source
stringlengths
3
92
c
stringlengths
26
2.25M
particlefilter.c
/** * @file ex_particle_OPENMP_seq.c * @author Michael Trotter & Matt Goodrum * @brief Particle filter implementation in C/OpenMP */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <sys/time.h> #include <time.h> // RISC-V VECTOR Version by Cristóbal Ramírez Lazo, "Barcelona 2019" #ifdef USE_RISCV_VECTOR #include "../../common/vector_defines.h" #endif //#include <omp.h> #include <limits.h> #define PI 3.1415926535897932 /** @var M value for Linear Congruential Generator (LCG); use GCC's value */ long M = INT_MAX; /** @var A value for LCG */ int A = 1103515245; /** @var C value for LCG */ int C = 12345; /***************************** *GET_TIME *returns a long int representing the time *****************************/ long long get_time() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec * 1000000) + tv.tv_usec; } // Returns the number of seconds elapsed between the two specified times float elapsed_time(long long start_time, long long end_time) { return (float) (end_time - start_time) / (1000 * 1000); } /** * Takes in a double and returns an integer that approximates to that double * @return if the mantissa < .5 => return value < input value; else return value > input value */ double roundDouble(double value){ int newValue = (int)(value); if(value - newValue < .5) return newValue; else return newValue++; } /** * Set values of the 3D array to a newValue if that value is equal to the testValue * @param testValue The value to be replaced * @param newValue The value to replace testValue with * @param array3D The image vector * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames */ void setIf(int testValue, int newValue, int * array3D, int * dimX, int * dimY, int * dimZ){ int x, y, z; for(x = 0; x < *dimX; x++){ for(y = 0; y < *dimY; y++){ for(z = 0; z < *dimZ; z++){ if(array3D[x * *dimY * *dimZ+y * *dimZ + z] == testValue) array3D[x * *dimY * *dimZ + y * *dimZ + z] = newValue; } } } } /** * Generates a uniformly distributed random number using the provided seed and GCC's settings for the Linear Congruential Generator (LCG) * @see http://en.wikipedia.org/wiki/Linear_congruential_generator * @note This function is thread-safe * @param seed The seed array * @param index The specific index of the seed to be advanced * @return a uniformly distributed number [0, 1) */ double randu(int * seed, int index) { int num = A*seed[index] + C; seed[index] = num % M; return fabs(seed[index]/((double) M)); } #ifdef USE_RISCV_VECTOR inline _MMR_f64 randu_vector(long int * seed, int index ,unsigned long int gvl) { /* _MMR_i64 xseed = _MM_LOAD_i64(&seed[index],gvl); _MMR_i64 xA = _MM_SET_i64(A,gvl); _MMR_i64 xC = _MM_SET_i64(C,gvl); _MMR_i64 xM = _MM_SET_i64(M,gvl); xseed = _MM_MUL_i64(xseed,xA,gvl); xseed = _MM_ADD_i64(xseed,xC,gvl); _MM_STORE_i64(&seed[index],_MM_REM_i64(xseed,xM,gvl),gvl); FENCE(); _MMR_f64 xResult; xResult = _MM_DIV_f64(_MM_VFCVT_F_X_f64(xseed,gvl),_MM_VFCVT_F_X_f64(xM,gvl),gvl); xResult = _MM_VFSGNJX_f64(xResult,xResult,gvl); return xResult; */ /* Esta parte del codigo deberia ser en 32 bits, pero las instrucciones de conversion aún no están disponibles, moviendo todo a 64 bits el resultado cambia ya que no se desborda, y las variaciones son muchas. */ double result[256]; int num[256]; //FENCE(); //double* result = (double*)malloc(gvl*sizeof(double)); //int* num = (int*)malloc(gvl*sizeof(int)); FENCE(); for(int x = index; x < index+gvl; x++){ num[x-index] = A*seed[x] + C; seed[x] = num[x-index] % M; result[x-index] = fabs(seed[x]/((double) M)); } _MMR_f64 xResult; xResult = _MM_LOAD_f64(&result[0],gvl); FENCE(); return xResult; } #endif // USE_RISCV_VECTOR /** * Generates a normally distributed random number using the Box-Muller transformation * @note This function is thread-safe * @param seed The seed array * @param index The specific index of the seed to be advanced * @return a double representing random number generated using the Box-Muller algorithm * @see http://en.wikipedia.org/wiki/Normal_distribution, section computing value for normal random distribution */ double randn(int * seed, int index){ /*Box-Muller algorithm*/ double u = randu(seed, index); double v = randu(seed, index); double cosine = cos(2*PI*v); double rt = -2*log(u); return sqrt(rt)*cosine; } #ifdef USE_RISCV_VECTOR static inline _MMR_f64 randn_vector(long int * seed, int index ,unsigned long int gvl){ /*Box-Muller algorithm*/ _MMR_f64 xU = randu_vector(seed,index,gvl); _MMR_f64 xV = randu_vector(seed,index,gvl); _MMR_f64 xCosine; _MMR_f64 xRt; xV = _MM_MUL_f64(_MM_SET_f64(PI*2.0,gvl),xV,gvl); xCosine =_MM_COS_f64(xV,gvl); FENCE(); xU = _MM_LOG_f64(xU,gvl); xRt = _MM_MUL_f64(_MM_SET_f64(-2.0,gvl),xU,gvl); return _MM_MUL_f64(_MM_SQRT_f64(xRt,gvl),xCosine,gvl); } #endif // USE_RISCV_VECTOR /** * Sets values of 3D matrix using randomly generated numbers from a normal distribution * @param array3D The video to be modified * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames * @param seed The seed array */ void addNoise(int * array3D, int * dimX, int * dimY, int * dimZ, int * seed){ int x, y, z; for(x = 0; x < *dimX; x++){ for(y = 0; y < *dimY; y++){ for(z = 0; z < *dimZ; z++){ array3D[x * *dimY * *dimZ + y * *dimZ + z] = array3D[x * *dimY * *dimZ + y * *dimZ + z] + (int)(5*randn(seed, 0)); } } } } /** * Fills a radius x radius matrix representing the disk * @param disk The pointer to the disk to be made * @param radius The radius of the disk to be made */ void strelDisk(int * disk, int radius) { int diameter = radius*2 - 1; int x, y; for(x = 0; x < diameter; x++){ for(y = 0; y < diameter; y++){ double distance = sqrt(pow((double)(x-radius+1),2) + pow((double)(y-radius+1),2)); if(distance < radius) disk[x*diameter + y] = 1; } } } /** * Dilates the provided video * @param matrix The video to be dilated * @param posX The x location of the pixel to be dilated * @param posY The y location of the pixel to be dilated * @param poxZ The z location of the pixel to be dilated * @param dimX The x dimension of the frame * @param dimY The y dimension of the frame * @param dimZ The number of frames * @param error The error radius */ void dilate_matrix(int * matrix, int posX, int posY, int posZ, int dimX, int dimY, int dimZ, int error) { int startX = posX - error; while(startX < 0) startX++; int startY = posY - error; while(startY < 0) startY++; int endX = posX + error; while(endX > dimX) endX--; int endY = posY + error; while(endY > dimY) endY--; int x,y; for(x = startX; x < endX; x++){ for(y = startY; y < endY; y++){ double distance = sqrt( pow((double)(x-posX),2) + pow((double)(y-posY),2) ); if(distance < error) matrix[x*dimY*dimZ + y*dimZ + posZ] = 1; } } } /** * Dilates the target matrix using the radius as a guide * @param matrix The reference matrix * @param dimX The x dimension of the video * @param dimY The y dimension of the video * @param dimZ The z dimension of the video * @param error The error radius to be dilated * @param newMatrix The target matrix */ void imdilate_disk(int * matrix, int dimX, int dimY, int dimZ, int error, int * newMatrix) { int x, y, z; for(z = 0; z < dimZ; z++){ for(x = 0; x < dimX; x++){ for(y = 0; y < dimY; y++){ if(matrix[x*dimY*dimZ + y*dimZ + z] == 1){ dilate_matrix(newMatrix, x, y, z, dimX, dimY, dimZ, error); } } } } } /** * Fills a 2D array describing the offsets of the disk object * @param se The disk object * @param numOnes The number of ones in the disk * @param neighbors The array that will contain the offsets * @param radius The radius used for dilation */ void getneighbors(int * se, int numOnes, double * neighbors, int radius){ int x, y; int neighY = 0; int center = radius - 1; int diameter = radius*2 -1; for(x = 0; x < diameter; x++){ for(y = 0; y < diameter; y++){ if(se[x*diameter + y]){ neighbors[neighY*2] = (int)(y - center); neighbors[neighY*2 + 1] = (int)(x - center); neighY++; } } } } /** * The synthetic video sequence we will work with here is composed of a * single moving object, circular in shape (fixed radius) * The motion here is a linear motion * the foreground intensity and the backgrounf intensity is known * the image is corrupted with zero mean Gaussian noise * @param I The video itself * @param IszX The x dimension of the video * @param IszY The y dimension of the video * @param Nfr The number of frames of the video * @param seed The seed array used for number generation */ void videoSequence(int * I, int IszX, int IszY, int Nfr, int * seed){ int k; int max_size = IszX*IszY*Nfr; /*get object centers*/ int x0 = (int)roundDouble(IszY/2.0); int y0 = (int)roundDouble(IszX/2.0); I[x0 *IszY *Nfr + y0 * Nfr + 0] = 1; /*move point*/ int xk, yk, pos; for(k = 1; k < Nfr; k++){ xk = abs(x0 + (k-1)); yk = abs(y0 - 2*(k-1)); pos = yk * IszY * Nfr + xk *Nfr + k; if(pos >= max_size) pos = 0; I[pos] = 1; } /*dilate matrix*/ int * newMatrix = (int *)malloc(sizeof(int)*IszX*IszY*Nfr); imdilate_disk(I, IszX, IszY, Nfr, 5, newMatrix); int x, y; for(x = 0; x < IszX; x++){ for(y = 0; y < IszY; y++){ for(k = 0; k < Nfr; k++){ I[x*IszY*Nfr + y*Nfr + k] = newMatrix[x*IszY*Nfr + y*Nfr + k]; } } } free(newMatrix); /*define background, add noise*/ setIf(0, 100, I, &IszX, &IszY, &Nfr); setIf(1, 228, I, &IszX, &IszY, &Nfr); /*add noise*/ addNoise(I, &IszX, &IszY, &Nfr, seed); } /** * Determines the likelihood sum based on the formula: SUM( (IK[IND] - 100)^2 - (IK[IND] - 228)^2)/ 100 * @param I The 3D matrix * @param ind The current ind array * @param numOnes The length of ind array * @return A double representing the sum */ double calcLikelihoodSum(int * I, int * ind, int numOnes){ double likelihoodSum = 0.0; int y; for(y = 0; y < numOnes; y++) likelihoodSum += (pow((I[ind[y]] - 100),2) - pow((I[ind[y]]-228),2))/50.0; return likelihoodSum; } /** * Finds the first element in the CDF that is greater than or equal to the provided value and returns that index * @note This function uses sequential search * @param CDF The CDF * @param lengthCDF The length of CDF * @param value The value to be found * @return The index of value in the CDF; if value is never found, returns the last index */ int findIndex(double * CDF, int lengthCDF, double value){ int index = -1; int x; // for(int a = 0; a < lengthCDF; a++) // { // printf("%f ",CDF[a]); // } // printf("\n"); // printf("CDF[x] >= value ,%f >= %f \n",CDF[0],value); for(x = 0; x < lengthCDF; x++){ if(CDF[x] >= value){ index = x; break; } } if(index == -1){ return lengthCDF-1; } return index; } /** * Finds the first element in the CDF that is greater than or equal to the provided value and returns that index * @note This function uses binary search before switching to sequential search * @param CDF The CDF * @param beginIndex The index to start searching from * @param endIndex The index to stop searching * @param value The value to find * @return The index of value in the CDF; if value is never found, returns the last index * @warning Use at your own risk; not fully tested */ int findIndexBin(double * CDF, int beginIndex, int endIndex, double value){ if(endIndex < beginIndex) return -1; int middleIndex = beginIndex + ((endIndex - beginIndex)/2); /*check the value*/ if(CDF[middleIndex] >= value) { /*check that it's good*/ if(middleIndex == 0) return middleIndex; else if(CDF[middleIndex-1] < value) return middleIndex; else if(CDF[middleIndex-1] == value) { while(middleIndex > 0 && CDF[middleIndex-1] == value) middleIndex--; return middleIndex; } } if(CDF[middleIndex] > value) return findIndexBin(CDF, beginIndex, middleIndex+1, value); return findIndexBin(CDF, middleIndex-1, endIndex, value); } /** * The implementation of the particle filter using OpenMP for many frames * @see http://openmp.org/wp/ * @note This function is designed to work with a video of several frames. In addition, it references a provided MATLAB function which takes the video, the objxy matrix and the x and y arrays as arguments and returns the likelihoods * @param I The video to be run * @param IszX The x dimension of the video * @param IszY The y dimension of the video * @param Nfr The number of frames * @param seed The seed array used for random number generation * @param Nparticles The number of particles to be used */ void particleFilter(int * I, int IszX, int IszY, int Nfr, int * seed, int Nparticles){ int max_size = IszX*IszY*Nfr; long long start = get_time(); //original particle centroid double xe = roundDouble(IszY/2.0); double ye = roundDouble(IszX/2.0); //expected object locations, compared to center int radius = 5; int diameter = radius*2 - 1; int * disk = (int *)malloc(diameter*diameter*sizeof(int)); strelDisk(disk, radius); int countOnes = 0; int x, y; for(x = 0; x < diameter; x++){ for(y = 0; y < diameter; y++){ if(disk[x*diameter + y] == 1) countOnes++; } } //printf("countOnes = %d \n",countOnes); // 69 double * objxy = (double *)malloc(countOnes*2*sizeof(double)); getneighbors(disk, countOnes, objxy, radius); long long get_neighbors = get_time(); printf("TIME TO GET NEIGHBORS TOOK: %f\n", elapsed_time(start, get_neighbors)); //initial weights are all equal (1/Nparticles) double * weights = (double *)malloc(sizeof(double)*Nparticles); //#pragma omp parallel for shared(weights, Nparticles) private(x) for(x = 0; x < Nparticles; x++){ weights[x] = 1/((double)(Nparticles)); } long long get_weights = get_time(); printf("TIME TO GET WEIGHTSTOOK: %f\n", elapsed_time(get_neighbors, get_weights)); //initial likelihood to 0.0 double * likelihood = (double *)malloc(sizeof(double)*Nparticles); double * arrayX = (double *)malloc(sizeof(double)*Nparticles); double * arrayY = (double *)malloc(sizeof(double)*Nparticles); double * xj = (double *)malloc(sizeof(double)*Nparticles); double * yj = (double *)malloc(sizeof(double)*Nparticles); double * CDF = (double *)malloc(sizeof(double)*Nparticles); double * u = (double *)malloc(sizeof(double)*Nparticles); int * ind = (int*)malloc(sizeof(int)*countOnes*Nparticles); //#pragma omp parallel for shared(arrayX, arrayY, xe, ye) private(x) for(x = 0; x < Nparticles; x++){ arrayX[x] = xe; arrayY[x] = ye; } int k; printf("TIME TO SET ARRAYS TOOK: %f\n", elapsed_time(get_weights, get_time())); int indX, indY; for(k = 1; k < Nfr; k++){ long long set_arrays = get_time(); //apply motion model //draws sample from motion model (random walk). The only prior information //is that the object moves 2x as fast as in the y direction //#pragma omp parallel for shared(arrayX, arrayY, Nparticles, seed) private(x) for(x = 0; x < Nparticles; x++){ arrayX[x] += 1 + 5*randn(seed, x); arrayY[x] += -2 + 2*randn(seed, x); } long long error = get_time(); printf("TIME TO SET ERROR TOOK: %f\n", elapsed_time(set_arrays, error)); //particle filter likelihood //#pragma omp parallel for shared(likelihood, I, arrayX, arrayY, objxy, ind) private(x, y, indX, indY) for(x = 0; x < Nparticles; x++){ //compute the likelihood: remember our assumption is that you know // foreground and the background image intensity distribution. // Notice that we consider here a likelihood ratio, instead of // p(z|x). It is possible in this case. why? a hometask for you. //calc ind for(y = 0; y < countOnes; y++){ indX = roundDouble(arrayX[x]) + objxy[y*2 + 1]; indY = roundDouble(arrayY[x]) + objxy[y*2]; ind[x*countOnes + y] = fabs(indX*IszY*Nfr + indY*Nfr + k); if(ind[x*countOnes + y] >= max_size) ind[x*countOnes + y] = 0; } likelihood[x] = 0; for(y = 0; y < countOnes; y++) likelihood[x] += (pow((I[ind[x*countOnes + y]] - 100),2) - pow((I[ind[x*countOnes + y]]-228),2))/50.0; likelihood[x] = likelihood[x]/((double) countOnes); } long long likelihood_time = get_time(); printf("TIME TO GET LIKELIHOODS TOOK: %f\n", elapsed_time(error, likelihood_time)); // update & normalize weights // using equation (63) of Arulampalam Tutorial //#pragma omp parallel for shared(Nparticles, weights, likelihood) private(x) for(x = 0; x < Nparticles; x++){ weights[x] = weights[x] * exp(likelihood[x]); } long long exponential = get_time(); printf("TIME TO GET EXP TOOK: %f\n", elapsed_time(likelihood_time, exponential)); double sumWeights = 0; //#pragma omp parallel for private(x) reduction(+:sumWeights) for(x = 0; x < Nparticles; x++){ sumWeights += weights[x]; } long long sum_time = get_time(); printf("TIME TO SUM WEIGHTS TOOK: %f\n", elapsed_time(exponential, sum_time)); //#pragma omp parallel for shared(sumWeights, weights) private(x) for(x = 0; x < Nparticles; x++){ weights[x] = weights[x]/sumWeights; } long long normalize = get_time(); printf("TIME TO NORMALIZE WEIGHTS TOOK: %f\n", elapsed_time(sum_time, normalize)); xe = 0; ye = 0; // estimate the object location by expected values //#pragma omp parallel for private(x) reduction(+:xe, ye) for(x = 0; x < Nparticles; x++){ xe += arrayX[x] * weights[x]; ye += arrayY[x] * weights[x]; } long long move_time = get_time(); printf("TIME TO MOVE OBJECT TOOK: %f\n", elapsed_time(normalize, move_time)); printf("XE: %lf\n", xe); printf("YE: %lf\n", ye); double distance = sqrt( pow((double)(xe-(int)roundDouble(IszY/2.0)),2) + pow((double)(ye-(int)roundDouble(IszX/2.0)),2) ); printf("%lf\n", distance); //display(hold off for now) //pause(hold off for now) //resampling CDF[0] = weights[0]; for(x = 1; x < Nparticles; x++){ CDF[x] = weights[x] + CDF[x-1]; } long long cum_sum = get_time(); printf("TIME TO CALC CUM SUM TOOK: %f\n", elapsed_time(move_time, cum_sum)); double u1 = (1/((double)(Nparticles)))*randu(seed, 0); //#pragma omp parallel for shared(u, u1, Nparticles) private(x) for(x = 0; x < Nparticles; x++){ u[x] = u1 + x/((double)(Nparticles)); } long long u_time = get_time(); printf("TIME TO CALC U TOOK: %f\n", elapsed_time(cum_sum, u_time)); int j, i; //#pragma omp parallel for shared(CDF, Nparticles, xj, yj, u, arrayX, arrayY) private(i, j) for(j = 0; j < Nparticles; j++){ i = findIndex(CDF, Nparticles, u[j]); if(i == -1) i = Nparticles-1; //printf("%d ", i); xj[j] = arrayX[i]; yj[j] = arrayY[i]; } //printf("\n"); long long xyj_time = get_time(); printf("TIME TO CALC NEW ARRAY X AND Y TOOK: %f\n", elapsed_time(u_time, xyj_time)); //#pragma omp parallel for shared(weights, Nparticles) private(x) for(x = 0; x < Nparticles; x++){ //reassign arrayX and arrayY arrayX[x] = xj[x]; arrayY[x] = yj[x]; weights[x] = 1/((double)(Nparticles)); } long long reset = get_time(); printf("TIME TO RESET WEIGHTS TOOK: %f\n", elapsed_time(xyj_time, reset)); } free(disk); free(objxy); free(weights); free(likelihood); free(xj); free(yj); free(arrayX); free(arrayY); free(CDF); free(u); free(ind); } #ifdef USE_RISCV_VECTOR void particleFilter_vector(int * I, int IszX, int IszY, int Nfr, int * seed, long int * seed_64, int Nparticles){ int max_size = IszX*IszY*Nfr; long long start = get_time(); //original particle centroid double xe = roundDouble(IszY/2.0); double ye = roundDouble(IszX/2.0); //expected object locations, compared to center int radius = 5; int diameter = radius*2 - 1; int * disk = (int *)malloc(diameter*diameter*sizeof(int)); strelDisk(disk, radius); int countOnes = 0; int x, y; for(x = 0; x < diameter; x++){ for(y = 0; y < diameter; y++){ if(disk[x*diameter + y] == 1) countOnes++; } } //printf("countOnes = %d \n",countOnes); // 69 double * objxy = (double *)malloc(countOnes*2*sizeof(double)); getneighbors(disk, countOnes, objxy, radius); long long get_neighbors = get_time(); printf("TIME TO GET NEIGHBORS TOOK: %f\n", elapsed_time(start, get_neighbors)); //initial weights are all equal (1/Nparticles) double * weights = (double *)malloc(sizeof(double)*Nparticles); //#pragma omp parallel for shared(weights, Nparticles) private(x) /* for(x = 0; x < Nparticles; x++){ weights[x] = 1/((double)(Nparticles)); }*/ // unsigned long int gvl = __builtin_epi_vsetvl(Nparticles, __epi_e64, __epi_m1); unsigned long int gvl = vsetvl_e64m1(Nparticles); //PLCT _MMR_f64 xweights = _MM_SET_f64(1.0/((double)(Nparticles)),gvl); for(x = 0; x < Nparticles; x=x+gvl){ // gvl = __builtin_epi_vsetvl(Nparticles-x, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles-x); //PLCT _MM_STORE_f64(&weights[x],xweights,gvl); } FENCE(); long long get_weights = get_time(); printf("TIME TO GET WEIGHTSTOOK: %f\n", elapsed_time(get_neighbors, get_weights)); //initial likelihood to 0.0 double * likelihood = (double *)malloc(sizeof(double)*Nparticles); double * arrayX = (double *)malloc(sizeof(double)*Nparticles); double * arrayY = (double *)malloc(sizeof(double)*Nparticles); double * xj = (double *)malloc(sizeof(double)*Nparticles); double * yj = (double *)malloc(sizeof(double)*Nparticles); double * CDF = (double *)malloc(sizeof(double)*Nparticles); double * u = (double *)malloc(sizeof(double)*Nparticles); int * ind = (int*)malloc(sizeof(int)*countOnes*Nparticles); /* //#pragma omp parallel for shared(arrayX, arrayY, xe, ye) private(x) for(x = 0; x < Nparticles; x++){ arrayX[x] = xe; arrayY[x] = ye; } */ // gvl = __builtin_epi_vsetvl(Nparticles, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles); //PLCT _MMR_f64 xArrayX = _MM_SET_f64(xe,gvl); _MMR_f64 xArrayY = _MM_SET_f64(ye,gvl); for(int i = 0; i < Nparticles; i=i+gvl){ // gvl = __builtin_epi_vsetvl(Nparticles-i, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles-i); //PLCT _MM_STORE_f64(&arrayX[i],xArrayX,gvl); _MM_STORE_f64(&arrayY[i],xArrayY,gvl); } FENCE(); _MMR_f64 xAux; int k; printf("TIME TO SET ARRAYS TOOK: %f\n", elapsed_time(get_weights, get_time())); int indX, indY; for(k = 1; k < Nfr; k++){ long long set_arrays = get_time(); //apply motion model //draws sample from motion model (random walk). The only prior information //is that the object moves 2x as fast as in the y direction // gvl = __builtin_epi_vsetvl(Nparticles, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles); //PLCT for(x = 0; x < Nparticles; x=x+gvl){ // gvl = __builtin_epi_vsetvl(Nparticles-x, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles-x); //PLCT xArrayX = _MM_LOAD_f64(&arrayX[x],gvl); FENCE(); xAux = randn_vector(seed_64, x,gvl); FENCE(); xAux = _MM_MUL_f64(xAux, _MM_SET_f64(5.0,gvl),gvl); xAux = _MM_ADD_f64(xAux, _MM_SET_f64(1.0,gvl),gvl); xArrayX = _MM_ADD_f64(xAux, xArrayX ,gvl); _MM_STORE_f64(&arrayX[x],xArrayX,gvl); xArrayY = _MM_LOAD_f64(&arrayY[x],gvl); FENCE(); xAux = randn_vector(seed_64, x,gvl); FENCE(); xAux = _MM_MUL_f64(xAux, _MM_SET_f64(2.0,gvl),gvl); xAux = _MM_ADD_f64(xAux, _MM_SET_f64(-2.0,gvl),gvl); xArrayY = _MM_ADD_f64(xAux, xArrayY ,gvl); _MM_STORE_f64(&arrayY[x],xArrayY,gvl); } FENCE(); /* //#pragma omp parallel for shared(arrayX, arrayY, Nparticles, seed) private(x) for(x = 0; x < Nparticles; x++){ arrayX[x] += 1 + 5*randn(seed, x); arrayY[x] += -2 + 2*randn(seed, x); } */ long long error = get_time(); printf("TIME TO SET ERROR TOOK: %f\n", elapsed_time(set_arrays, error)); //particle filter likelihood //#pragma omp parallel for shared(likelihood, I, arrayX, arrayY, objxy, ind) private(x, y, indX, indY) for(x = 0; x < Nparticles; x++){ //compute the likelihood: remember our assumption is that you know // foreground and the background image intensity distribution. // Notice that we consider here a likelihood ratio, instead of // p(z|x). It is possible in this case. why? a hometask for you. //calc ind for(y = 0; y < countOnes; y++){ indX = roundDouble(arrayX[x]) + objxy[y*2 + 1]; indY = roundDouble(arrayY[x]) + objxy[y*2]; ind[x*countOnes + y] = fabs(indX*IszY*Nfr + indY*Nfr + k); if(ind[x*countOnes + y] >= max_size) ind[x*countOnes + y] = 0; } likelihood[x] = 0; for(y = 0; y < countOnes; y++) likelihood[x] += (pow((I[ind[x*countOnes + y]] - 100),2) - pow((I[ind[x*countOnes + y]]-228),2))/50.0; likelihood[x] = likelihood[x]/((double) countOnes); } long long likelihood_time = get_time(); printf("TIME TO GET LIKELIHOODS TOOK: %f\n", elapsed_time(error, likelihood_time)); // update & normalize weights // using equation (63) of Arulampalam Tutorial //#pragma omp parallel for shared(Nparticles, weights, likelihood) private(x) for(x = 0; x < Nparticles; x++){ weights[x] = weights[x] * exp(likelihood[x]); } long long exponential = get_time(); printf("TIME TO GET EXP TOOK: %f\n", elapsed_time(likelihood_time, exponential)); double sumWeights = 0; //#pragma omp parallel for private(x) reduction(+:sumWeights) for(x = 0; x < Nparticles; x++){ sumWeights += weights[x]; } long long sum_time = get_time(); printf("TIME TO SUM WEIGHTS TOOK: %f\n", elapsed_time(exponential, sum_time)); //#pragma omp parallel for shared(sumWeights, weights) private(x) for(x = 0; x < Nparticles; x++){ weights[x] = weights[x]/sumWeights; } long long normalize = get_time(); printf("TIME TO NORMALIZE WEIGHTS TOOK: %f\n", elapsed_time(sum_time, normalize)); xe = 0; ye = 0; // estimate the object location by expected values //#pragma omp parallel for private(x) reduction(+:xe, ye) for(x = 0; x < Nparticles; x++){ xe += arrayX[x] * weights[x]; ye += arrayY[x] * weights[x]; } long long move_time = get_time(); printf("TIME TO MOVE OBJECT TOOK: %f\n", elapsed_time(normalize, move_time)); printf("XE: %lf\n", xe); printf("YE: %lf\n", ye); double distance = sqrt( pow((double)(xe-(int)roundDouble(IszY/2.0)),2) + pow((double)(ye-(int)roundDouble(IszX/2.0)),2) ); printf("%lf\n", distance); //display(hold off for now) //pause(hold off for now) //resampling CDF[0] = weights[0]; for(x = 1; x < Nparticles; x++){ CDF[x] = weights[x] + CDF[x-1]; } long long cum_sum = get_time(); printf("TIME TO CALC CUM SUM TOOK: %f\n", elapsed_time(move_time, cum_sum)); double u1 = (1/((double)(Nparticles)))*randu(seed, 0); //#pragma omp parallel for shared(u, u1, Nparticles) private(x) for(x = 0; x < Nparticles; x++){ u[x] = u1 + x/((double)(Nparticles)); } long long u_time = get_time(); printf("TIME TO CALC U TOOK: %f\n", elapsed_time(cum_sum, u_time)); int j, i; _MMR_MASK_i64 xComp; _MMR_i64 xMask; _MMR_f64 xCDF; _MMR_f64 xU; _MMR_i64 xArray; long int vector_complete; long int * locations = (long int *)malloc(sizeof(long int)*Nparticles); long int valid; // gvl = __builtin_epi_vsetvl(Nparticles, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles); //PLCT for(i = 0; i < Nparticles; i=i+gvl){ // gvl = __builtin_epi_vsetvl(Nparticles-i, __epi_e64, __epi_m1); gvl = vsetvl_e64m1(Nparticles-i); //PLCT vector_complete = 0; xMask = _MM_SET_i64(0,gvl); xArray = _MM_SET_i64(Nparticles-1,gvl); xU = _MM_LOAD_f64(&u[i],gvl); for(j = 0; j < Nparticles; j++){ xCDF = _MM_SET_f64(CDF[j],gvl); xComp = _MM_VFGE_f64(xCDF,xU,gvl); xComp = _MM_CAST_i1_i64(_MM_XOR_i64(_MM_CAST_i64_i1(xComp,gvl),xMask,gvl),gvl); valid = _MM_VMFIRST_i64(xComp,gvl); if(valid != -1) { xArray = _MM_MERGE_i64(xArray,_MM_SET_i64(j,gvl),xComp,gvl); xMask = _MM_OR_i64(_MM_CAST_i64_i1(xComp,gvl),xMask,gvl); vector_complete = _MM_VMPOPC_i64(_MM_CAST_i1_i64(xMask,gvl),gvl); } if(vector_complete == gvl){ break; } //FENCE(); } _MM_STORE_i64(&locations[i],xArray,gvl); } FENCE(); //for(i = 0; i < Nparticles; i++) { printf("%d ", locations[i]); } printf("\n"); //#pragma omp parallel for shared(CDF, Nparticles, xj, yj, u, arrayX, arrayY) private(i, j) for(j = 0; j < Nparticles; j++){ i = locations[j]; xj[j] = arrayX[i]; yj[j] = arrayY[i]; } // for(j = 0; j < Nparticles; j++){ printf("%lf ", xj[i]); } printf("\n"); // for(j = 0; j < Nparticles; j++){ printf("%lf ", yj[i]); } printf("\n"); long long xyj_time = get_time(); printf("TIME TO CALC NEW ARRAY X AND Y TOOK: %f\n", elapsed_time(u_time, xyj_time)); //#pragma omp parallel for shared(weights, Nparticles) private(x) for(x = 0; x < Nparticles; x++){ //reassign arrayX and arrayY arrayX[x] = xj[x]; arrayY[x] = yj[x]; weights[x] = 1/((double)(Nparticles)); } long long reset = get_time(); printf("TIME TO RESET WEIGHTS TOOK: %f\n", elapsed_time(xyj_time, reset)); } free(disk); free(objxy); free(weights); free(likelihood); free(xj); free(yj); free(arrayX); free(arrayY); free(CDF); free(u); free(ind); } #endif int main(int argc, char * argv[]){ char* usage = "openmp.out -x <dimX> -y <dimY> -z <Nfr> -np <Nparticles>"; //check number of arguments if(argc != 9) { printf("%s\n", usage); return 0; } //check args deliminators if( strcmp( argv[1], "-x" ) || strcmp( argv[3], "-y" ) || strcmp( argv[5], "-z" ) || strcmp( argv[7], "-np" ) ) { printf( "%s\n",usage ); return 0; } int IszX, IszY, Nfr, Nparticles; //converting a string to a integer if( sscanf( argv[2], "%d", &IszX ) == EOF ) { printf("ERROR: dimX input is incorrect"); return 0; } if( IszX <= 0 ) { printf("dimX must be > 0\n"); return 0; } //converting a string to a integer if( sscanf( argv[4], "%d", &IszY ) == EOF ) { printf("ERROR: dimY input is incorrect"); return 0; } if( IszY <= 0 ) { printf("dimY must be > 0\n"); return 0; } //converting a string to a integer if( sscanf( argv[6], "%d", &Nfr ) == EOF ) { printf("ERROR: Number of frames input is incorrect"); return 0; } if( Nfr <= 0 ) { printf("number of frames must be > 0\n"); return 0; } //converting a string to a integer if( sscanf( argv[8], "%d", &Nparticles ) == EOF ) { printf("ERROR: Number of particles input is incorrect"); return 0; } if( Nparticles <= 0 ) { printf("Number of particles must be > 0\n"); return 0; } //establish seed int * seed = (int *)malloc(sizeof(int)*Nparticles); int i; for(i = 0; i < Nparticles; i++) { seed[i] = time(0)*i; } //malloc matrix int * I = (int *)malloc(sizeof(int)*IszX*IszY*Nfr); // 128 * 128 * 10 = 163840 * sizeof(int) long long start = get_time(); //call video sequence videoSequence(I, IszX, IszY, Nfr, seed); long long endVideoSequence = get_time(); printf("VIDEO SEQUENCE TOOK %f\n", elapsed_time(start, endVideoSequence)); #ifdef USE_RISCV_VECTOR long int * seed_64 = (long int *)malloc(sizeof(long int)*Nparticles); for(i = 0; i < Nparticles; i++) { seed_64[i] = (long int)seed[i]; } //call particle filter particleFilter_vector(I, IszX, IszY, Nfr, seed,seed_64, Nparticles); #else //call particle filter particleFilter(I, IszX, IszY, Nfr, seed, Nparticles); #endif long long endParticleFilter = get_time(); printf("PARTICLE FILTER TOOK %f\n", elapsed_time(endVideoSequence, endParticleFilter)); printf("ENTIRE PROGRAM TOOK %f\n", elapsed_time(start, endParticleFilter)); free(seed); free(I); return 0; }
GB_unop__acos_fc64_fc64.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_fc64_fc64) // op(A') function: GB (_unop_tran__acos_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = cacos (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cacos (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = cacos (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ACOS || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__acos_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = cacos (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_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = cacos (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__acos_fc64_fc64) ( 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
arraymult.c
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <omp.h> #include "ctimer.h" void add (int A[], int B[], int C[], int N) { int i, carry, sum; carry = 0; for (i=0; i<N; i++) { sum = A[i] + B[i] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; C[i] = sum; } } void multiply_one_digit (int A[], int B[], int n, int N) { int i, carry; carry = 0; for (i=0; i<N; i++) { B[i] = n * A[i]; B[i] += carry; if (B[i] >= 10) { carry = B[i] / 10; B[i] %= 10; } else carry = 0; } } void shift_left (int A[], int n, int N) { int i; for (i=N-1; i>=n; i--) A[i] = A[i-n]; while (i >= 0) A[i--] = 0; } void multiply (int A[], int B[], int C[], int N) { int i, j, P[N]; for (i=0; i<N; i++) { multiply_one_digit (B, P, A[i], N); shift_left (P, i, N); add (C, P, C, N); } } main(int argc, char**argv) { // DECLARACION DE VARIABLES double t1,t2,tucpu,tscpu; int len1 = strlen(argv[1]); int len2 = strlen(argv[2]); int N = len1+len2; int A[N], B[N], C[N]; for(int i=0;i < N; i++){ A[i] = 0; B[i] = 0; C[i] = 0; } // RELLENADO DE MATRICES char k[len1]; strcpy(k, argv[1]); for(int i=0;i < len1; i++){ A[i] = k[len1-1-i] - '0'; } char l[len2]; strcpy(l, argv[2]); for(int i=0;i < len2; i++){ B[i] = l[len2-1-i] - '0'; } // SECUENCIAL ctimer(&t1,&tucpu,&tscpu); multiply(A,B,C,N); ctimer(&t2,&tucpu,&tscpu); printf("---SECUENCIAL---\n"); printf("A [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", A[loop]); printf("]\n"); printf("B [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", B[loop]); printf("]\nC [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", C[loop]); printf("]\n"); printf(" ------- \n"); printf("Tiempo %f segundos \n",(float) (t2-t1)); printf(" ------- \n"); // PARALELO printf("---PARALELO---\n"); printf("A [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", A[loop]); printf("]\n"); printf("B [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", B[loop]); printf("]\n"); omp_set_num_threads(4); int D[4*N]; int n, i, carry,j,sum, P[N], tid, nthreads; int E[N]; for(int i=0;i < N; i++) E[i] = 0; ctimer(&t1,&tucpu,&tscpu); #pragma omp parallel shared (B,A) private(i,n, carry, j, sum, P, tid) { nthreads = omp_get_num_threads(); for(i=0;i < N*nthreads; i++){ D[i] = 0; } #pragma omp barrier tid = omp_get_thread_num(); for (i=tid; i<len1; i=i+nthreads) { n = A[i]; carry = 0; for (j=0; j<N; j++) { P[j] = n * B[j]; P[j] += carry; if (P[j] >= 10) { carry = P[j] / 10; P[j] %= 10; } else carry = 0; } // SHIFT for (j=N-1; j>=i; j--) P[j] = P[j-i]; while (j >= 0) P[j--] = 0; // SUMA Y ACUMULACION EN D carry = 0; sum = 0; for (j=0; j<N; j++) { sum = D[tid*N+j] + P[j] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; D[tid*N+j] = sum; } } #pragma omp barrier /*if(tid==0){ printf("------------------------------\n"); printf("D%d [ ",tid); for(int loop = N-1; loop >= 0; loop--) printf("%d ", D[tid*N+loop]); printf("]\n"); } #pragma omp barrier if(tid==1){ printf("D%d [ ",tid); for(int loop = N-1; loop >= 0; loop--) printf("%d ", D[tid*N+loop]); printf("]\n"); } #pragma omp barrier if(tid==2){ printf("D%d [ ",tid); for(int loop = N-1; loop >= 0; loop--) printf("%d ", D[tid*N+loop]); printf("]\n"); } #pragma omp barrier if(tid==3){ printf("D%d [ ",tid); for(int loop = N-1; loop >= 0; loop--) printf("%d ", D[tid*N+loop]); printf("]\n"); printf("------------------------------\n"); }*/ // TRANSFERENCIA A E SUMANDO PARCIALES if(tid==0){ for(int k=0; k<nthreads;k++){ carry = 0; sum = 0; for (j=0; j<N; j++) { sum = E[j] + D[k*N+j] + carry; if (sum >= 10) { carry = 1; sum -= 10; } else carry = 0; E[j] = sum; } } } } ctimer(&t2,&tucpu,&tscpu); printf("C [ "); for(int loop = N-1; loop >= 0; loop--) printf("%d ", E[loop]); printf("]\n"); printf(" ------- \n"); printf("Tiempo %f segundos \n",(float) (t2-t1)); printf(" ------- \n"); }
linearFiltering-hessian.c
/************************************************************************* * linearFiltering-hessian.c - * * $Id$ * * Copyright (c) INRIA 2012, all rights reserved * * AUTHOR: * Gregoire Malandain (gregoire.malandain@inria.fr) * * CREATION DATE: * Wed Dec 26 22:52:20 CET 2012 * * ADDITIONS, CHANGES * */ /* WARNING, this file is not aimed to be computed * it is included from linearFiltering.c */ int gradientHessianGradient2D( void *bufferIn, bufferType typeIn, void *bufferOut, bufferType typeOut, int *bufferDims, int *borderLengths, typeFilteringCoefficients *theFilter ) { char *proc = "gradientHessianGradient2D"; size_t dimx, dimy, dimz; size_t sizeAuxBuf = 0; typeFilteringCoefficients filter[3]; float *theXX = NULL; float *theYY = NULL; float *theXY = NULL; float *theX = NULL; float *theY = NULL; float *theH = NULL; double g; long int i; dimx = bufferDims[0]; dimy = bufferDims[1]; dimz = bufferDims[2]; /* we could spare one buffer, but who cares? */ sizeAuxBuf = (size_t)5 * dimx*dimy*dimz; if ( typeOut != FLOAT || bufferIn == bufferOut ) sizeAuxBuf += dimx*dimy*dimz; /* allocation des buffers de calcul */ theXX = (float*)vtmalloc( sizeAuxBuf * sizeof(float), "theXX", proc ); if ( theXX == NULL ) { if ( _verbose_ > 0 ) fprintf( stderr, "%s: unable to allocate auxiliary buffer\n", proc ); return( -1 ); } sizeAuxBuf = dimx*dimy*dimz; theYY = theXY = theX = theY = theH = theXX; theYY += sizeAuxBuf; theXY += 2*sizeAuxBuf; theX += 3*sizeAuxBuf; theY += 4*sizeAuxBuf; if ( typeOut != FLOAT || bufferIn == bufferOut ) { theH += 5*sizeAuxBuf; } else { theH = (float*)bufferOut; } /* filtering */ filter[0] = theFilter[0]; filter[1] = theFilter[1]; filter[2] = theFilter[2]; /* smoothing along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_0; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theXX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute Y smoothing (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along X */ filter[0].derivative = DERIVATIVE_1; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXX, FLOAT, (void*)theX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute X 1st derivative (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along X */ filter[0].derivative = DERIVATIVE_2; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXX, FLOAT, (void*)theXX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute X 2nd derivative (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along X */ filter[0].derivative = DERIVATIVE_0; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theYY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute X smoothing (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_1; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYY, FLOAT, (void*)theY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute Y 1st derivative (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_2; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYY, FLOAT, (void*)theYY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute Y 2nd derivative (2D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along X and Y */ filter[0].derivative = DERIVATIVE_1; filter[1].derivative = DERIVATIVE_1; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theXY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute XY 2nd derivative (2D)\n", proc ); vtfree( theXX ); return( -1 ); } sizeAuxBuf = dimx*dimy*dimz; #ifdef _OPENMP #pragma omp parallel for private( g ) #endif for ( i = 0; i < (long int)sizeAuxBuf; i++ ) { theH[i] = theX[i] * ( theXX[i] * theX[i] + theXY[i] * theY[i] ) + theY[i] * ( theXY[i] * theX[i] + theYY[i] * theY[i] ); if ( 0 ) { g = theX[i] * theX[i] + theY[i] * theY[i]; if ( g > 1e-10 ) theH[i] /= g; } } if ( theH != bufferOut ) { if ( ConvertBuffer( theH, FLOAT, bufferOut, typeOut, sizeAuxBuf ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to convert buffer\n", proc ); vtfree( theXX ); return( -1 ); } } vtfree( theXX ); return( 1 ); } int gradientHessianGradient3D( void *bufferIn, bufferType typeIn, void *bufferOut, bufferType typeOut, int *bufferDims, int *borderLengths, typeFilteringCoefficients *theFilter ) { char *proc = "gradientHessianGradient3D"; size_t dimx, dimy, dimz; size_t sizeAuxBuf = 0; typeFilteringCoefficients filter[3]; float *theXX = NULL; float *theYY = NULL; float *theZZ = NULL; float *theXY = NULL; float *theXZ = NULL; float *theYZ = NULL; float *theX = NULL; float *theY = NULL; float *theZ = NULL; float *theH = NULL; double g; long int i; dimx = bufferDims[0]; dimy = bufferDims[1]; dimz = bufferDims[2]; /* we could spare one buffer, but who cares? */ sizeAuxBuf = (size_t)9 * dimx*dimy*dimz; if ( typeOut != FLOAT || bufferIn == bufferOut ) sizeAuxBuf += dimx*dimy*dimz; /* allocation des buffers de calcul */ theXX = (float*)vtmalloc( sizeAuxBuf * sizeof(float), "theXX", proc ); if ( theXX == NULL ) { if ( _verbose_ > 0 ) fprintf( stderr, "%s: unable to allocate auxiliary buffer\n", proc ); return( -1 ); } sizeAuxBuf = dimx*dimy*dimz; theYY = theZZ = theXY = theXZ = theYZ = theX = theY = theZ = theH = theXX; theYY += sizeAuxBuf; theZZ += 2*sizeAuxBuf; theXY += 3*sizeAuxBuf; theXZ += 4*sizeAuxBuf; theYZ += 5*sizeAuxBuf; theX += 6*sizeAuxBuf; theY += 7*sizeAuxBuf; theZ += 8*sizeAuxBuf; if ( typeOut != FLOAT || bufferIn == bufferOut ) { theH += 9*sizeAuxBuf; } else { theH = (float*)bufferOut; } /* filtering */ filter[0] = theFilter[0]; filter[1] = theFilter[1]; filter[2] = theFilter[2]; /* smoothing along Z */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = NODERIVATIVE; filter[2].derivative = DERIVATIVE_0; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theXY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (.,.,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_0; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXY, FLOAT, (void*)theXX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (.,0,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along X */ filter[0].derivative = DERIVATIVE_1; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXX, FLOAT, (void*)theX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (1,0,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along X */ filter[0].derivative = DERIVATIVE_2; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXX, FLOAT, (void*)theXX, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (2,0,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along X */ filter[0].derivative = DERIVATIVE_0; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXY, FLOAT, (void*)theYY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,.,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_1; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYY, FLOAT, (void*)theY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,1,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_2; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYY, FLOAT, (void*)theYY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,2,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along X and Y */ filter[0].derivative = DERIVATIVE_1; filter[1].derivative = DERIVATIVE_1; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXY, FLOAT, (void*)theXY, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (1,1,0) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along Z */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = NODERIVATIVE; filter[2].derivative = DERIVATIVE_1; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theYZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (.,.,1) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along Y */ filter[0].derivative = NODERIVATIVE; filter[1].derivative = DERIVATIVE_0; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYZ, FLOAT, (void*)theXZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (.,0,1) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along X */ filter[0].derivative = DERIVATIVE_0; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXZ, FLOAT, (void*)theZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,0,1) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 1st derivative along X */ filter[0].derivative = DERIVATIVE_1; filter[1].derivative = NODERIVATIVE; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theXZ, FLOAT, (void*)theXZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (1,0,1) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* smoothing along X, 1st derivative along Y */ filter[0].derivative = DERIVATIVE_0; filter[1].derivative = DERIVATIVE_1; filter[2].derivative = NODERIVATIVE; if ( separableLinearFiltering( (void*)theYZ, FLOAT, (void*)theYZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,1,1) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } /* 2nd derivative along Z */ filter[0].derivative = DERIVATIVE_0; filter[1].derivative = DERIVATIVE_0; filter[2].derivative = DERIVATIVE_2; if ( separableLinearFiltering( bufferIn, typeIn, (void*)theZZ, FLOAT, bufferDims, borderLengths, filter ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to compute (0,0,2) filtering (3D)\n", proc ); vtfree( theXX ); return( -1 ); } sizeAuxBuf = dimx*dimy*dimz; #ifdef _OPENMP #pragma omp parallel for private( g ) #endif for ( i = 0; i < (long int)sizeAuxBuf; i++ ) { theH[i] = theX[i] * ( theXX[i] * theX[i] + theXY[i] * theY[i] + theXZ[i] * theZ[i] ) + theY[i] * ( theXY[i] * theX[i] + theYY[i] * theY[i] + theYZ[i] * theZ[i] ) + theZ[i] * ( theXZ[i] * theX[i] + theYZ[i] * theY[i] + theZZ[i] * theZ[i] ); if ( 0 ) { g = theX[i] * theX[i] + theY[i] * theY[i] + theZ[i] * theZ[i]; if ( g > 1e-10 ) theH[i] /= g; } } if ( theH != bufferOut ) { if ( ConvertBuffer( theH, FLOAT, bufferOut, typeOut, sizeAuxBuf ) != 1 ) { if ( _verbose_ ) fprintf( stderr, "%s: unable to convert buffer\n", proc ); vtfree( theXX ); return( -1 ); } } vtfree( theXX ); return( 1 ); } int gradientHessianGradient( void *bufferIn, bufferType typeIn, void *bufferOut, bufferType typeOut, int *bufferDims, int *borderLengths, typeFilteringCoefficients *theFilter ) { if ( bufferDims[2] == 1 ) return( gradientHessianGradient2D( bufferIn, typeIn, bufferOut, typeOut, bufferDims, borderLengths, theFilter ) ); else return( gradientHessianGradient3D( bufferIn, typeIn, bufferOut, typeOut, bufferDims, borderLengths, theFilter ) ); }
mandelbrot.c
/* * mandelbrot.c: adaptive mesh refinement (AMR) * (c)2010-2018 Seiji Nishimura * $Id: mandelbrot.c,v 1.1.1.3 2018/09/11 00:00:00 seiji Exp seiji $ */ #include <math.h> #include <stdlib.h> #include <pixmap.h> #include <palette.h> #include <stdbool.h> // for adaptive mesh refinement #define MIN_GRID (0x01<<2) #define MAX_GRID (0x01<<8) #define ROUND(x) ((int) round(x)) #define MIN(x,y) (((x)<(y))?(x):(y)) #define MAX(x,y) (((x)>(y))?(x):(y)) // prototypes void colormap_init (pixel_t *, int); void draw_image (pixmap_t *, pixmap_t *, pixel_t *, int, double, double, double); void rough_sketch (pixmap_t *, pixel_t *, int, double, double, double); int mandelbrot (int, double, double); bool detect_edge (pixmap_t *, pixel_t *, int, int); bool equivalent_color(pixel_t, pixel_t); //====================================================================== int main(int argc, char **argv) { pixmap_t image, sketch; pixel_t colormap[ITER_MAX]; pixmap_create(&image , WIDTH, HEIGHT); pixmap_create(&sketch, WIDTH, HEIGHT); colormap_init(colormap, ITER_MAX); draw_image(&image, &sketch, colormap, ITER_MAX, CENTER_R, CENTER_I, RADIUS); pixmap_write_ppmfile(&image, "output.ppm"); pixmap_destroy(&sketch); pixmap_destroy(&image ); return EXIT_SUCCESS; } //---------------------------------------------------------------------- void colormap_init(pixel_t *colormap, int iter_max) { int colormap_mask = COLORMAP_CYCLE - 1; colormap[0] = pixel_set_rgb(0x00, 0x00, 0x00); for (int i = 1; i < iter_max; i++) #ifdef REVERSE_COLORMAP colormap[i] = palette(COLORMAP_TYPE, 0x00, colormap_mask, colormap_mask - (i & colormap_mask)); #else colormap[i] = palette(COLORMAP_TYPE, 0x00, colormap_mask, i & colormap_mask ); #endif return; } //---------------------------------------------------------------------- void draw_image(pixmap_t *image, pixmap_t *sketch, pixel_t *colormap, int iter_max, double c_r, double c_i, double radius) { // adaptive mesh refinement int iter_mask = iter_max - 1; int width, height; double d; pixmap_get_size(image, &width, &height); d = 2.0 * radius / MIN(width, height); rough_sketch(sketch, colormap, iter_max, c_r, c_i, radius); #pragma omp parallel for schedule(static,1) for (int xy = 0; xy < width * height; xy++) { int x = xy % width, y = xy / width; pixel_t pixel; if (detect_edge(sketch, &pixel, x, y)) { pixel_t average = pixel; int sum_r, sum_g, sum_b; sum_r = pixel_get_r(pixel); sum_g = pixel_get_g(pixel); sum_b = pixel_get_b(pixel); for (int ngrid = MIN_GRID; ngrid <= MAX_GRID; ngrid <<= 0x01) { pixel = average; for (int k = 1; k < ngrid * ngrid; k++) { // pixel refinement with AMR int m = k % ngrid, n = k / ngrid; if (((m | n) & 0x01) || // skip redundant points: (m % 2) != 0 || (n % 2) != 0 ngrid == MIN_GRID) { double p_r = c_r + d * ((x + (double) m / ngrid) - width / 2), p_i = c_i + d * (height / 2 - (y + (double) n / ngrid)); int iter = mandelbrot(iter_max, p_r, p_i); sum_r += pixel_get_r(colormap[iter & iter_mask]); sum_g += pixel_get_g(colormap[iter & iter_mask]); sum_b += pixel_get_b(colormap[iter & iter_mask]); } } average = pixel_set_rgb(ROUND((double) sum_r / (ngrid * ngrid)), ROUND((double) sum_g / (ngrid * ngrid)), ROUND((double) sum_b / (ngrid * ngrid))); if (equivalent_color(average, pixel)) break; } pixel = average; } pixmap_put_pixel(image, pixel, x, y); } return; } //---------------------------------------------------------------------- void rough_sketch(pixmap_t *sketch, pixel_t *colormap, int iter_max, double c_r, double c_i, double radius) { int iter_mask = iter_max - 1; int width, height; double d; pixmap_get_size(sketch, &width, &height); d = 2.0 * radius / MIN(width, height); #pragma omp parallel for schedule(static,1) for (int xy = 0; xy < width * height; xy++) { int x = xy % width, y = xy / width; double p_r = c_r + d * (x - width / 2), p_i = c_i + d * (height / 2 - y); int iter = mandelbrot(iter_max, p_r, p_i); pixmap_put_pixel(sketch, colormap[iter & iter_mask], x, y); } return; } //---------------------------------------------------------------------- int mandelbrot(int iter_max, double p_r, double p_i) { // kernel function (scalar version) int i; double z_r, z_i, work; z_r = p_r; z_i = p_i; work = 2.0 * z_r * z_i; for (i = 1; i < iter_max && (z_r *= z_r) + (z_i *= z_i) < 4.0; i++) { z_r += p_r - z_i ; z_i = p_i + work; work = 2.0 * z_r * z_i; } return i; } //---------------------------------------------------------------------- bool detect_edge(pixmap_t *pixmap, pixel_t *pixel, int x, int y) { int width, height; pixmap_get_size (pixmap, &width, &height); pixmap_get_pixel(pixmap, pixel, x, y); for (int j = MAX(0, y - 1); j <= MIN(height - 1, y + 1); j++) for (int i = MAX(0, x - 1); i <= MIN(width - 1, x + 1); i++) if (i != x || j != y) { pixel_t p; pixmap_get_pixel(pixmap, &p, i, j); if (!equivalent_color(*pixel, p)) return true; } return false; } //---------------------------------------------------------------------- bool equivalent_color(pixel_t p, pixel_t q) #ifdef USE_SAME_COLOR { return pixel_get_r(p) == pixel_get_r(q) && pixel_get_g(p) == pixel_get_g(q) && pixel_get_b(p) == pixel_get_b(q); } #else //...................................... { return 3 * abs(pixel_get_r(p) - pixel_get_r(q)) + 6 * abs(pixel_get_g(p) - pixel_get_g(q)) + 1 * abs(pixel_get_b(p) - pixel_get_b(q)) < 15; } #endif
omp_parallel_private.c
// RUN: %libomp-compile-and-run #include <stdio.h> #include <stdlib.h> #include "omp_testsuite.h" //static int sum1 = 789; int test_omp_parallel_private() { int sum, num_threads,sum1; int known_sum; sum = 0; num_threads = 0; #pragma omp parallel private(sum1) { int i; sum1 = 7; /*printf("sum1=%d\n",sum1);*/ #pragma omp for for (i = 1; i < 1000; i++) { sum1 = sum1 + i; } #pragma omp critical { sum = sum + sum1; num_threads++; } } known_sum = (999 * 1000) / 2 + 7 * num_threads; return (known_sum == sum); } int main() { int i; int num_failed=0; for(i = 0; i < REPETITIONS; i++) { if(!test_omp_parallel_private()) { num_failed++; } } return num_failed; }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * 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) /* 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, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][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] = 24; tile_size[1] = 24; tile_size[2] = 8; tile_size[3] = 512; 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); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.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 for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #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(1, "variable no-symmetry") #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(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
profile.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP RRRR OOO FFFFF IIIII L EEEEE % % P P R R O O F I L E % % PPPP RRRR O O FFF I L EEE % % P R R O O F I L E % % P R R OOO F IIIII LLLLL EEEEE % % % % % % MagickCore Image Profile Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 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/color.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/configure.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/linked-list.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/option-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/profile-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-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/utility.h" #if defined(MAGICKCORE_LCMS_DELEGATE) #if defined(MAGICKCORE_HAVE_LCMS_LCMS2_H) #include <wchar.h> #include <lcms/lcms2.h> #else #include <wchar.h> #include "lcms2.h" #endif #endif #if defined(MAGICKCORE_XML_DELEGATE) # if defined(MAGICKCORE_WINDOWS_SUPPORT) # if !defined(__MINGW32__) # include <win32config.h> # endif # endif # include <libxml/parser.h> # include <libxml/tree.h> #endif /* Forward declarations */ static MagickBooleanType SetImageProfileInternal(Image *,const char *,const StringInfo *, const MagickBooleanType,ExceptionInfo *); static void WriteTo8BimProfile(Image *,const char*,const StringInfo *); /* Typedef declarations */ struct _ProfileInfo { char *name; size_t length; unsigned char *info; size_t signature; }; typedef struct _CMSExceptionInfo { Image *image; ExceptionInfo *exception; } CMSExceptionInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneImageProfiles() clones one or more image profiles. % % The format of the CloneImageProfiles method is: % % MagickBooleanType CloneImageProfiles(Image *image, % const Image *clone_image) % % A description of each parameter follows: % % o image: the image. % % o clone_image: the clone image. % */ MagickExport MagickBooleanType CloneImageProfiles(Image *image, const Image *clone_image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(clone_image != (const Image *) NULL); assert(clone_image->signature == MagickCoreSignature); if (clone_image->profiles != (void *) NULL) { if (image->profiles != (void *) NULL) DestroyImageProfiles(image); image->profiles=CloneSplayTree((SplayTreeInfo *) clone_image->profiles, (void *(*)(void *)) ConstantString,(void *(*)(void *)) CloneStringInfo); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e l e t e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeleteImageProfile() deletes a profile from the image by its name. % % The format of the DeleteImageProfile method is: % % MagickBooleanTyupe DeleteImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport MagickBooleanType DeleteImageProfile(Image *image,const char *name) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return(MagickFalse); WriteTo8BimProfile(image,name,(StringInfo *) NULL); return(DeleteNodeFromSplayTree((SplayTreeInfo *) image->profiles,name)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImageProfiles() releases memory associated with an image profile map. % % The format of the DestroyProfiles method is: % % void DestroyImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImageProfiles(Image *image) { if (image->profiles != (SplayTreeInfo *) NULL) image->profiles=DestroySplayTree((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageProfile() gets a profile associated with an image by name. % % The format of the GetImageProfile method is: % % const StringInfo *GetImageProfile(const Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport const StringInfo *GetImageProfile(const Image *image, const char *name) { const StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); profile=(const StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t N e x t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNextImageProfile() gets the next profile name for an image. % % The format of the GetNextImageProfile method is: % % char *GetNextImageProfile(const Image *image) % % A description of each parameter follows: % % o hash_info: the hash info. % */ MagickExport char *GetNextImageProfile(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((char *) NULL); return((char *) GetNextKeyInSplayTree((SplayTreeInfo *) image->profiles)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P r o f i l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ProfileImage() associates, applies, or removes an ICM, IPTC, or generic % profile with / to / from an image. If the profile is NULL, it is removed % from the image otherwise added or applied. Use a name of '*' and a profile % of NULL to remove all profiles from the image. % % ICC and ICM profiles are handled as follows: If the image does not have % an associated color profile, the one you provide is associated with the % image and the image pixels are not transformed. Otherwise, the colorspace % transform defined by the existing and new profile are applied to the image % pixels and the new profile is associated with the image. % % The format of the ProfileImage method is: % % MagickBooleanType ProfileImage(Image *image,const char *name, % const void *datum,const size_t length,const MagickBooleanType clone) % % A description of each parameter follows: % % o image: the image. % % o name: Name of profile to add or remove: ICC, IPTC, or generic profile. % % o datum: the profile data. % % o length: the length of the profile. % % o clone: should be MagickFalse. % */ #if defined(MAGICKCORE_LCMS_DELEGATE) typedef struct _LCMSInfo { ColorspaceType colorspace; cmsUInt32Number type; size_t channels; cmsHPROFILE profile; int intent; double scale, translate; void **magick_restrict pixels; } LCMSInfo; #if LCMS_VERSION < 2060 static void* cmsGetContextUserData(cmsContext ContextID) { return(ContextID); } static cmsContext cmsCreateContext(void *magick_unused(Plugin),void *UserData) { magick_unreferenced(Plugin); return((cmsContext) UserData); } static void cmsSetLogErrorHandlerTHR(cmsContext magick_unused(ContextID), cmsLogErrorHandlerFunction Fn) { magick_unreferenced(ContextID); cmsSetLogErrorHandler(Fn); } static void cmsDeleteContext(cmsContext magick_unused(ContextID)) { magick_unreferenced(ContextID); } #endif static void **DestroyPixelThreadSet(void **pixels) { register ssize_t i; if (pixels == (void **) NULL) return((void **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (void *) NULL) pixels[i]=RelinquishMagickMemory(pixels[i]); pixels=(void **) RelinquishMagickMemory(pixels); return(pixels); } static void **AcquirePixelThreadSet(const size_t columns, const size_t channels,MagickBooleanType highres) { register ssize_t i; size_t number_threads; size_t size; void **pixels; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(void **) AcquireQuantumMemory(number_threads,sizeof(*pixels)); if (pixels == (void **) NULL) return((void **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); size=sizeof(double); if (highres == MagickFalse) size=sizeof(Quantum); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=AcquireQuantumMemory(columns,channels*size); if (pixels[i] == (void *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static cmsHTRANSFORM *DestroyTransformThreadSet(cmsHTRANSFORM *transform) { register ssize_t i; assert(transform != (cmsHTRANSFORM *) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (transform[i] != (cmsHTRANSFORM) NULL) cmsDeleteTransform(transform[i]); transform=(cmsHTRANSFORM *) RelinquishMagickMemory(transform); return(transform); } static cmsHTRANSFORM *AcquireTransformThreadSet(const LCMSInfo *source_info, const LCMSInfo *target_info,const cmsUInt32Number flags, cmsContext cms_context) { cmsHTRANSFORM *transform; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); transform=(cmsHTRANSFORM *) AcquireQuantumMemory(number_threads, sizeof(*transform)); if (transform == (cmsHTRANSFORM *) NULL) return((cmsHTRANSFORM *) NULL); (void) memset(transform,0,number_threads*sizeof(*transform)); for (i=0; i < (ssize_t) number_threads; i++) { transform[i]=cmsCreateTransformTHR(cms_context,source_info->profile, source_info->type,target_info->profile,target_info->type, target_info->intent,flags); if (transform[i] == (cmsHTRANSFORM) NULL) return(DestroyTransformThreadSet(transform)); } return(transform); } static void CMSExceptionHandler(cmsContext context,cmsUInt32Number severity, const char *message) { CMSExceptionInfo *cms_exception; ExceptionInfo *exception; Image *image; cms_exception=(CMSExceptionInfo *) cmsGetContextUserData(context); if (cms_exception == (CMSExceptionInfo *) NULL) return; exception=cms_exception->exception; if (exception == (ExceptionInfo *) NULL) return; image=cms_exception->image; if (image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s'","unknown context"); return; } if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(),"lcms: #%u, %s", severity,message != (char *) NULL ? message : "no message"); (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "UnableToTransformColorspace","`%s', %s (#%u)",image->filename, message != (char *) NULL ? message : "no message",severity); } static void TransformDoublePixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { #define GetLCMSPixel(source_info,pixel) \ (source_info->scale*QuantumScale*(pixel)+source_info->translate) #define SetLCMSPixel(target_info,pixel) \ ClampToQuantum(target_info->scale*QuantumRange*(pixel)+target_info->translate) register double *p; register ssize_t x; p=(double *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetLCMSPixel(source_info,GetPixelRed(image,q)); if (source_info->channels > 1) { *p++=GetLCMSPixel(source_info,GetPixelGreen(image,q)); *p++=GetLCMSPixel(source_info,GetPixelBlue(image,q)); } if (source_info->channels > 3) *p++=GetLCMSPixel(source_info,GetPixelBlack(image,q)); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(double *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,SetLCMSPixel(target_info,*p),q); else SetPixelRed(image,SetLCMSPixel(target_info,*p),q); p++; if (target_info->channels > 1) { SetPixelGreen(image,SetLCMSPixel(target_info,*p),q); p++; SetPixelBlue(image,SetLCMSPixel(target_info,*p),q); p++; } if (target_info->channels > 3) { SetPixelBlack(image,SetLCMSPixel(target_info,*p),q); p++; } q+=GetPixelChannels(image); } } static void TransformQuantumPixels(const int id,const Image* image, const LCMSInfo *source_info,const LCMSInfo *target_info, const cmsHTRANSFORM *transform,Quantum *q) { register Quantum *p; register ssize_t x; p=(Quantum *) source_info->pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { *p++=GetPixelRed(image,q); if (source_info->channels > 1) { *p++=GetPixelGreen(image,q); *p++=GetPixelBlue(image,q); } if (source_info->channels > 3) *p++=GetPixelBlack(image,q); q+=GetPixelChannels(image); } cmsDoTransform(transform[id],source_info->pixels[id], target_info->pixels[id],(unsigned int) image->columns); p=(Quantum *) target_info->pixels[id]; q-=GetPixelChannels(image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { if (target_info->channels == 1) SetPixelGray(image,*p++,q); else SetPixelRed(image,*p++,q); if (target_info->channels > 1) { SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); } if (target_info->channels > 3) SetPixelBlack(image,*p++,q); q+=GetPixelChannels(image); } } #endif static MagickBooleanType SetsRGBImageProfile(Image *image, ExceptionInfo *exception) { static unsigned char sRGBProfile[] = { 0x00, 0x00, 0x0c, 0x8c, 0x61, 0x72, 0x67, 0x6c, 0x02, 0x20, 0x00, 0x00, 0x6d, 0x6e, 0x74, 0x72, 0x52, 0x47, 0x42, 0x20, 0x58, 0x59, 0x5a, 0x20, 0x07, 0xde, 0x00, 0x01, 0x00, 0x06, 0x00, 0x16, 0x00, 0x0f, 0x00, 0x3a, 0x61, 0x63, 0x73, 0x70, 0x4d, 0x53, 0x46, 0x54, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x43, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf6, 0xd6, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0xd3, 0x2d, 0x61, 0x72, 0x67, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x01, 0x50, 0x00, 0x00, 0x00, 0x99, 0x63, 0x70, 0x72, 0x74, 0x00, 0x00, 0x01, 0xec, 0x00, 0x00, 0x00, 0x67, 0x64, 0x6d, 0x6e, 0x64, 0x00, 0x00, 0x02, 0x54, 0x00, 0x00, 0x00, 0x70, 0x64, 0x6d, 0x64, 0x64, 0x00, 0x00, 0x02, 0xc4, 0x00, 0x00, 0x00, 0x88, 0x74, 0x65, 0x63, 0x68, 0x00, 0x00, 0x03, 0x4c, 0x00, 0x00, 0x00, 0x0c, 0x76, 0x75, 0x65, 0x64, 0x00, 0x00, 0x03, 0x58, 0x00, 0x00, 0x00, 0x67, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x03, 0xc0, 0x00, 0x00, 0x00, 0x24, 0x6c, 0x75, 0x6d, 0x69, 0x00, 0x00, 0x03, 0xe4, 0x00, 0x00, 0x00, 0x14, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x03, 0xf8, 0x00, 0x00, 0x00, 0x24, 0x77, 0x74, 0x70, 0x74, 0x00, 0x00, 0x04, 0x1c, 0x00, 0x00, 0x00, 0x14, 0x62, 0x6b, 0x70, 0x74, 0x00, 0x00, 0x04, 0x30, 0x00, 0x00, 0x00, 0x14, 0x72, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00, 0x14, 0x67, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x58, 0x00, 0x00, 0x00, 0x14, 0x62, 0x58, 0x59, 0x5a, 0x00, 0x00, 0x04, 0x6c, 0x00, 0x00, 0x00, 0x14, 0x72, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x67, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x62, 0x54, 0x52, 0x43, 0x00, 0x00, 0x04, 0x80, 0x00, 0x00, 0x08, 0x0c, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3f, 0x73, 0x52, 0x47, 0x42, 0x20, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x28, 0x45, 0x71, 0x75, 0x69, 0x76, 0x61, 0x6c, 0x65, 0x6e, 0x74, 0x20, 0x74, 0x6f, 0x20, 0x77, 0x77, 0x77, 0x2e, 0x73, 0x72, 0x67, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x20, 0x31, 0x39, 0x39, 0x38, 0x20, 0x48, 0x50, 0x20, 0x70, 0x72, 0x6f, 0x66, 0x69, 0x6c, 0x65, 0x29, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x00, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x47, 0x72, 0x61, 0x65, 0x6d, 0x65, 0x20, 0x57, 0x2e, 0x20, 0x47, 0x69, 0x6c, 0x6c, 0x2e, 0x20, 0x52, 0x65, 0x6c, 0x65, 0x61, 0x73, 0x65, 0x64, 0x20, 0x69, 0x6e, 0x74, 0x6f, 0x20, 0x74, 0x68, 0x65, 0x20, 0x70, 0x75, 0x62, 0x6c, 0x69, 0x63, 0x20, 0x64, 0x6f, 0x6d, 0x61, 0x69, 0x6e, 0x2e, 0x20, 0x4e, 0x6f, 0x20, 0x57, 0x61, 0x72, 0x72, 0x61, 0x6e, 0x74, 0x79, 0x2c, 0x20, 0x55, 0x73, 0x65, 0x20, 0x61, 0x74, 0x20, 0x79, 0x6f, 0x75, 0x72, 0x20, 0x6f, 0x77, 0x6e, 0x20, 0x72, 0x69, 0x73, 0x6b, 0x2e, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x16, 0x49, 0x45, 0x43, 0x20, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x65, 0x63, 0x2e, 0x63, 0x68, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x49, 0x45, 0x43, 0x20, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x20, 0x44, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74, 0x20, 0x52, 0x47, 0x42, 0x20, 0x63, 0x6f, 0x6c, 0x6f, 0x75, 0x72, 0x20, 0x73, 0x70, 0x61, 0x63, 0x65, 0x20, 0x2d, 0x20, 0x73, 0x52, 0x47, 0x42, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x73, 0x69, 0x67, 0x20, 0x00, 0x00, 0x00, 0x00, 0x43, 0x52, 0x54, 0x20, 0x64, 0x65, 0x73, 0x63, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x45, 0x43, 0x36, 0x31, 0x39, 0x36, 0x36, 0x2d, 0x32, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x76, 0x69, 0x65, 0x77, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xa4, 0x7c, 0x00, 0x14, 0x5f, 0x30, 0x00, 0x10, 0xce, 0x02, 0x00, 0x03, 0xed, 0xb2, 0x00, 0x04, 0x13, 0x0a, 0x00, 0x03, 0x5c, 0x67, 0x00, 0x00, 0x00, 0x01, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4c, 0x0a, 0x3d, 0x00, 0x50, 0x00, 0x00, 0x00, 0x57, 0x1e, 0xb8, 0x6d, 0x65, 0x61, 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x8f, 0x00, 0x00, 0x00, 0x02, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf3, 0x51, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x16, 0xcc, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x6f, 0xa0, 0x00, 0x00, 0x38, 0xf5, 0x00, 0x00, 0x03, 0x90, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x97, 0x00, 0x00, 0xb7, 0x87, 0x00, 0x00, 0x18, 0xd9, 0x58, 0x59, 0x5a, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x24, 0x9f, 0x00, 0x00, 0x0f, 0x84, 0x00, 0x00, 0xb6, 0xc4, 0x63, 0x75, 0x72, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x0a, 0x00, 0x0f, 0x00, 0x14, 0x00, 0x19, 0x00, 0x1e, 0x00, 0x23, 0x00, 0x28, 0x00, 0x2d, 0x00, 0x32, 0x00, 0x37, 0x00, 0x3b, 0x00, 0x40, 0x00, 0x45, 0x00, 0x4a, 0x00, 0x4f, 0x00, 0x54, 0x00, 0x59, 0x00, 0x5e, 0x00, 0x63, 0x00, 0x68, 0x00, 0x6d, 0x00, 0x72, 0x00, 0x77, 0x00, 0x7c, 0x00, 0x81, 0x00, 0x86, 0x00, 0x8b, 0x00, 0x90, 0x00, 0x95, 0x00, 0x9a, 0x00, 0x9f, 0x00, 0xa4, 0x00, 0xa9, 0x00, 0xae, 0x00, 0xb2, 0x00, 0xb7, 0x00, 0xbc, 0x00, 0xc1, 0x00, 0xc6, 0x00, 0xcb, 0x00, 0xd0, 0x00, 0xd5, 0x00, 0xdb, 0x00, 0xe0, 0x00, 0xe5, 0x00, 0xeb, 0x00, 0xf0, 0x00, 0xf6, 0x00, 0xfb, 0x01, 0x01, 0x01, 0x07, 0x01, 0x0d, 0x01, 0x13, 0x01, 0x19, 0x01, 0x1f, 0x01, 0x25, 0x01, 0x2b, 0x01, 0x32, 0x01, 0x38, 0x01, 0x3e, 0x01, 0x45, 0x01, 0x4c, 0x01, 0x52, 0x01, 0x59, 0x01, 0x60, 0x01, 0x67, 0x01, 0x6e, 0x01, 0x75, 0x01, 0x7c, 0x01, 0x83, 0x01, 0x8b, 0x01, 0x92, 0x01, 0x9a, 0x01, 0xa1, 0x01, 0xa9, 0x01, 0xb1, 0x01, 0xb9, 0x01, 0xc1, 0x01, 0xc9, 0x01, 0xd1, 0x01, 0xd9, 0x01, 0xe1, 0x01, 0xe9, 0x01, 0xf2, 0x01, 0xfa, 0x02, 0x03, 0x02, 0x0c, 0x02, 0x14, 0x02, 0x1d, 0x02, 0x26, 0x02, 0x2f, 0x02, 0x38, 0x02, 0x41, 0x02, 0x4b, 0x02, 0x54, 0x02, 0x5d, 0x02, 0x67, 0x02, 0x71, 0x02, 0x7a, 0x02, 0x84, 0x02, 0x8e, 0x02, 0x98, 0x02, 0xa2, 0x02, 0xac, 0x02, 0xb6, 0x02, 0xc1, 0x02, 0xcb, 0x02, 0xd5, 0x02, 0xe0, 0x02, 0xeb, 0x02, 0xf5, 0x03, 0x00, 0x03, 0x0b, 0x03, 0x16, 0x03, 0x21, 0x03, 0x2d, 0x03, 0x38, 0x03, 0x43, 0x03, 0x4f, 0x03, 0x5a, 0x03, 0x66, 0x03, 0x72, 0x03, 0x7e, 0x03, 0x8a, 0x03, 0x96, 0x03, 0xa2, 0x03, 0xae, 0x03, 0xba, 0x03, 0xc7, 0x03, 0xd3, 0x03, 0xe0, 0x03, 0xec, 0x03, 0xf9, 0x04, 0x06, 0x04, 0x13, 0x04, 0x20, 0x04, 0x2d, 0x04, 0x3b, 0x04, 0x48, 0x04, 0x55, 0x04, 0x63, 0x04, 0x71, 0x04, 0x7e, 0x04, 0x8c, 0x04, 0x9a, 0x04, 0xa8, 0x04, 0xb6, 0x04, 0xc4, 0x04, 0xd3, 0x04, 0xe1, 0x04, 0xf0, 0x04, 0xfe, 0x05, 0x0d, 0x05, 0x1c, 0x05, 0x2b, 0x05, 0x3a, 0x05, 0x49, 0x05, 0x58, 0x05, 0x67, 0x05, 0x77, 0x05, 0x86, 0x05, 0x96, 0x05, 0xa6, 0x05, 0xb5, 0x05, 0xc5, 0x05, 0xd5, 0x05, 0xe5, 0x05, 0xf6, 0x06, 0x06, 0x06, 0x16, 0x06, 0x27, 0x06, 0x37, 0x06, 0x48, 0x06, 0x59, 0x06, 0x6a, 0x06, 0x7b, 0x06, 0x8c, 0x06, 0x9d, 0x06, 0xaf, 0x06, 0xc0, 0x06, 0xd1, 0x06, 0xe3, 0x06, 0xf5, 0x07, 0x07, 0x07, 0x19, 0x07, 0x2b, 0x07, 0x3d, 0x07, 0x4f, 0x07, 0x61, 0x07, 0x74, 0x07, 0x86, 0x07, 0x99, 0x07, 0xac, 0x07, 0xbf, 0x07, 0xd2, 0x07, 0xe5, 0x07, 0xf8, 0x08, 0x0b, 0x08, 0x1f, 0x08, 0x32, 0x08, 0x46, 0x08, 0x5a, 0x08, 0x6e, 0x08, 0x82, 0x08, 0x96, 0x08, 0xaa, 0x08, 0xbe, 0x08, 0xd2, 0x08, 0xe7, 0x08, 0xfb, 0x09, 0x10, 0x09, 0x25, 0x09, 0x3a, 0x09, 0x4f, 0x09, 0x64, 0x09, 0x79, 0x09, 0x8f, 0x09, 0xa4, 0x09, 0xba, 0x09, 0xcf, 0x09, 0xe5, 0x09, 0xfb, 0x0a, 0x11, 0x0a, 0x27, 0x0a, 0x3d, 0x0a, 0x54, 0x0a, 0x6a, 0x0a, 0x81, 0x0a, 0x98, 0x0a, 0xae, 0x0a, 0xc5, 0x0a, 0xdc, 0x0a, 0xf3, 0x0b, 0x0b, 0x0b, 0x22, 0x0b, 0x39, 0x0b, 0x51, 0x0b, 0x69, 0x0b, 0x80, 0x0b, 0x98, 0x0b, 0xb0, 0x0b, 0xc8, 0x0b, 0xe1, 0x0b, 0xf9, 0x0c, 0x12, 0x0c, 0x2a, 0x0c, 0x43, 0x0c, 0x5c, 0x0c, 0x75, 0x0c, 0x8e, 0x0c, 0xa7, 0x0c, 0xc0, 0x0c, 0xd9, 0x0c, 0xf3, 0x0d, 0x0d, 0x0d, 0x26, 0x0d, 0x40, 0x0d, 0x5a, 0x0d, 0x74, 0x0d, 0x8e, 0x0d, 0xa9, 0x0d, 0xc3, 0x0d, 0xde, 0x0d, 0xf8, 0x0e, 0x13, 0x0e, 0x2e, 0x0e, 0x49, 0x0e, 0x64, 0x0e, 0x7f, 0x0e, 0x9b, 0x0e, 0xb6, 0x0e, 0xd2, 0x0e, 0xee, 0x0f, 0x09, 0x0f, 0x25, 0x0f, 0x41, 0x0f, 0x5e, 0x0f, 0x7a, 0x0f, 0x96, 0x0f, 0xb3, 0x0f, 0xcf, 0x0f, 0xec, 0x10, 0x09, 0x10, 0x26, 0x10, 0x43, 0x10, 0x61, 0x10, 0x7e, 0x10, 0x9b, 0x10, 0xb9, 0x10, 0xd7, 0x10, 0xf5, 0x11, 0x13, 0x11, 0x31, 0x11, 0x4f, 0x11, 0x6d, 0x11, 0x8c, 0x11, 0xaa, 0x11, 0xc9, 0x11, 0xe8, 0x12, 0x07, 0x12, 0x26, 0x12, 0x45, 0x12, 0x64, 0x12, 0x84, 0x12, 0xa3, 0x12, 0xc3, 0x12, 0xe3, 0x13, 0x03, 0x13, 0x23, 0x13, 0x43, 0x13, 0x63, 0x13, 0x83, 0x13, 0xa4, 0x13, 0xc5, 0x13, 0xe5, 0x14, 0x06, 0x14, 0x27, 0x14, 0x49, 0x14, 0x6a, 0x14, 0x8b, 0x14, 0xad, 0x14, 0xce, 0x14, 0xf0, 0x15, 0x12, 0x15, 0x34, 0x15, 0x56, 0x15, 0x78, 0x15, 0x9b, 0x15, 0xbd, 0x15, 0xe0, 0x16, 0x03, 0x16, 0x26, 0x16, 0x49, 0x16, 0x6c, 0x16, 0x8f, 0x16, 0xb2, 0x16, 0xd6, 0x16, 0xfa, 0x17, 0x1d, 0x17, 0x41, 0x17, 0x65, 0x17, 0x89, 0x17, 0xae, 0x17, 0xd2, 0x17, 0xf7, 0x18, 0x1b, 0x18, 0x40, 0x18, 0x65, 0x18, 0x8a, 0x18, 0xaf, 0x18, 0xd5, 0x18, 0xfa, 0x19, 0x20, 0x19, 0x45, 0x19, 0x6b, 0x19, 0x91, 0x19, 0xb7, 0x19, 0xdd, 0x1a, 0x04, 0x1a, 0x2a, 0x1a, 0x51, 0x1a, 0x77, 0x1a, 0x9e, 0x1a, 0xc5, 0x1a, 0xec, 0x1b, 0x14, 0x1b, 0x3b, 0x1b, 0x63, 0x1b, 0x8a, 0x1b, 0xb2, 0x1b, 0xda, 0x1c, 0x02, 0x1c, 0x2a, 0x1c, 0x52, 0x1c, 0x7b, 0x1c, 0xa3, 0x1c, 0xcc, 0x1c, 0xf5, 0x1d, 0x1e, 0x1d, 0x47, 0x1d, 0x70, 0x1d, 0x99, 0x1d, 0xc3, 0x1d, 0xec, 0x1e, 0x16, 0x1e, 0x40, 0x1e, 0x6a, 0x1e, 0x94, 0x1e, 0xbe, 0x1e, 0xe9, 0x1f, 0x13, 0x1f, 0x3e, 0x1f, 0x69, 0x1f, 0x94, 0x1f, 0xbf, 0x1f, 0xea, 0x20, 0x15, 0x20, 0x41, 0x20, 0x6c, 0x20, 0x98, 0x20, 0xc4, 0x20, 0xf0, 0x21, 0x1c, 0x21, 0x48, 0x21, 0x75, 0x21, 0xa1, 0x21, 0xce, 0x21, 0xfb, 0x22, 0x27, 0x22, 0x55, 0x22, 0x82, 0x22, 0xaf, 0x22, 0xdd, 0x23, 0x0a, 0x23, 0x38, 0x23, 0x66, 0x23, 0x94, 0x23, 0xc2, 0x23, 0xf0, 0x24, 0x1f, 0x24, 0x4d, 0x24, 0x7c, 0x24, 0xab, 0x24, 0xda, 0x25, 0x09, 0x25, 0x38, 0x25, 0x68, 0x25, 0x97, 0x25, 0xc7, 0x25, 0xf7, 0x26, 0x27, 0x26, 0x57, 0x26, 0x87, 0x26, 0xb7, 0x26, 0xe8, 0x27, 0x18, 0x27, 0x49, 0x27, 0x7a, 0x27, 0xab, 0x27, 0xdc, 0x28, 0x0d, 0x28, 0x3f, 0x28, 0x71, 0x28, 0xa2, 0x28, 0xd4, 0x29, 0x06, 0x29, 0x38, 0x29, 0x6b, 0x29, 0x9d, 0x29, 0xd0, 0x2a, 0x02, 0x2a, 0x35, 0x2a, 0x68, 0x2a, 0x9b, 0x2a, 0xcf, 0x2b, 0x02, 0x2b, 0x36, 0x2b, 0x69, 0x2b, 0x9d, 0x2b, 0xd1, 0x2c, 0x05, 0x2c, 0x39, 0x2c, 0x6e, 0x2c, 0xa2, 0x2c, 0xd7, 0x2d, 0x0c, 0x2d, 0x41, 0x2d, 0x76, 0x2d, 0xab, 0x2d, 0xe1, 0x2e, 0x16, 0x2e, 0x4c, 0x2e, 0x82, 0x2e, 0xb7, 0x2e, 0xee, 0x2f, 0x24, 0x2f, 0x5a, 0x2f, 0x91, 0x2f, 0xc7, 0x2f, 0xfe, 0x30, 0x35, 0x30, 0x6c, 0x30, 0xa4, 0x30, 0xdb, 0x31, 0x12, 0x31, 0x4a, 0x31, 0x82, 0x31, 0xba, 0x31, 0xf2, 0x32, 0x2a, 0x32, 0x63, 0x32, 0x9b, 0x32, 0xd4, 0x33, 0x0d, 0x33, 0x46, 0x33, 0x7f, 0x33, 0xb8, 0x33, 0xf1, 0x34, 0x2b, 0x34, 0x65, 0x34, 0x9e, 0x34, 0xd8, 0x35, 0x13, 0x35, 0x4d, 0x35, 0x87, 0x35, 0xc2, 0x35, 0xfd, 0x36, 0x37, 0x36, 0x72, 0x36, 0xae, 0x36, 0xe9, 0x37, 0x24, 0x37, 0x60, 0x37, 0x9c, 0x37, 0xd7, 0x38, 0x14, 0x38, 0x50, 0x38, 0x8c, 0x38, 0xc8, 0x39, 0x05, 0x39, 0x42, 0x39, 0x7f, 0x39, 0xbc, 0x39, 0xf9, 0x3a, 0x36, 0x3a, 0x74, 0x3a, 0xb2, 0x3a, 0xef, 0x3b, 0x2d, 0x3b, 0x6b, 0x3b, 0xaa, 0x3b, 0xe8, 0x3c, 0x27, 0x3c, 0x65, 0x3c, 0xa4, 0x3c, 0xe3, 0x3d, 0x22, 0x3d, 0x61, 0x3d, 0xa1, 0x3d, 0xe0, 0x3e, 0x20, 0x3e, 0x60, 0x3e, 0xa0, 0x3e, 0xe0, 0x3f, 0x21, 0x3f, 0x61, 0x3f, 0xa2, 0x3f, 0xe2, 0x40, 0x23, 0x40, 0x64, 0x40, 0xa6, 0x40, 0xe7, 0x41, 0x29, 0x41, 0x6a, 0x41, 0xac, 0x41, 0xee, 0x42, 0x30, 0x42, 0x72, 0x42, 0xb5, 0x42, 0xf7, 0x43, 0x3a, 0x43, 0x7d, 0x43, 0xc0, 0x44, 0x03, 0x44, 0x47, 0x44, 0x8a, 0x44, 0xce, 0x45, 0x12, 0x45, 0x55, 0x45, 0x9a, 0x45, 0xde, 0x46, 0x22, 0x46, 0x67, 0x46, 0xab, 0x46, 0xf0, 0x47, 0x35, 0x47, 0x7b, 0x47, 0xc0, 0x48, 0x05, 0x48, 0x4b, 0x48, 0x91, 0x48, 0xd7, 0x49, 0x1d, 0x49, 0x63, 0x49, 0xa9, 0x49, 0xf0, 0x4a, 0x37, 0x4a, 0x7d, 0x4a, 0xc4, 0x4b, 0x0c, 0x4b, 0x53, 0x4b, 0x9a, 0x4b, 0xe2, 0x4c, 0x2a, 0x4c, 0x72, 0x4c, 0xba, 0x4d, 0x02, 0x4d, 0x4a, 0x4d, 0x93, 0x4d, 0xdc, 0x4e, 0x25, 0x4e, 0x6e, 0x4e, 0xb7, 0x4f, 0x00, 0x4f, 0x49, 0x4f, 0x93, 0x4f, 0xdd, 0x50, 0x27, 0x50, 0x71, 0x50, 0xbb, 0x51, 0x06, 0x51, 0x50, 0x51, 0x9b, 0x51, 0xe6, 0x52, 0x31, 0x52, 0x7c, 0x52, 0xc7, 0x53, 0x13, 0x53, 0x5f, 0x53, 0xaa, 0x53, 0xf6, 0x54, 0x42, 0x54, 0x8f, 0x54, 0xdb, 0x55, 0x28, 0x55, 0x75, 0x55, 0xc2, 0x56, 0x0f, 0x56, 0x5c, 0x56, 0xa9, 0x56, 0xf7, 0x57, 0x44, 0x57, 0x92, 0x57, 0xe0, 0x58, 0x2f, 0x58, 0x7d, 0x58, 0xcb, 0x59, 0x1a, 0x59, 0x69, 0x59, 0xb8, 0x5a, 0x07, 0x5a, 0x56, 0x5a, 0xa6, 0x5a, 0xf5, 0x5b, 0x45, 0x5b, 0x95, 0x5b, 0xe5, 0x5c, 0x35, 0x5c, 0x86, 0x5c, 0xd6, 0x5d, 0x27, 0x5d, 0x78, 0x5d, 0xc9, 0x5e, 0x1a, 0x5e, 0x6c, 0x5e, 0xbd, 0x5f, 0x0f, 0x5f, 0x61, 0x5f, 0xb3, 0x60, 0x05, 0x60, 0x57, 0x60, 0xaa, 0x60, 0xfc, 0x61, 0x4f, 0x61, 0xa2, 0x61, 0xf5, 0x62, 0x49, 0x62, 0x9c, 0x62, 0xf0, 0x63, 0x43, 0x63, 0x97, 0x63, 0xeb, 0x64, 0x40, 0x64, 0x94, 0x64, 0xe9, 0x65, 0x3d, 0x65, 0x92, 0x65, 0xe7, 0x66, 0x3d, 0x66, 0x92, 0x66, 0xe8, 0x67, 0x3d, 0x67, 0x93, 0x67, 0xe9, 0x68, 0x3f, 0x68, 0x96, 0x68, 0xec, 0x69, 0x43, 0x69, 0x9a, 0x69, 0xf1, 0x6a, 0x48, 0x6a, 0x9f, 0x6a, 0xf7, 0x6b, 0x4f, 0x6b, 0xa7, 0x6b, 0xff, 0x6c, 0x57, 0x6c, 0xaf, 0x6d, 0x08, 0x6d, 0x60, 0x6d, 0xb9, 0x6e, 0x12, 0x6e, 0x6b, 0x6e, 0xc4, 0x6f, 0x1e, 0x6f, 0x78, 0x6f, 0xd1, 0x70, 0x2b, 0x70, 0x86, 0x70, 0xe0, 0x71, 0x3a, 0x71, 0x95, 0x71, 0xf0, 0x72, 0x4b, 0x72, 0xa6, 0x73, 0x01, 0x73, 0x5d, 0x73, 0xb8, 0x74, 0x14, 0x74, 0x70, 0x74, 0xcc, 0x75, 0x28, 0x75, 0x85, 0x75, 0xe1, 0x76, 0x3e, 0x76, 0x9b, 0x76, 0xf8, 0x77, 0x56, 0x77, 0xb3, 0x78, 0x11, 0x78, 0x6e, 0x78, 0xcc, 0x79, 0x2a, 0x79, 0x89, 0x79, 0xe7, 0x7a, 0x46, 0x7a, 0xa5, 0x7b, 0x04, 0x7b, 0x63, 0x7b, 0xc2, 0x7c, 0x21, 0x7c, 0x81, 0x7c, 0xe1, 0x7d, 0x41, 0x7d, 0xa1, 0x7e, 0x01, 0x7e, 0x62, 0x7e, 0xc2, 0x7f, 0x23, 0x7f, 0x84, 0x7f, 0xe5, 0x80, 0x47, 0x80, 0xa8, 0x81, 0x0a, 0x81, 0x6b, 0x81, 0xcd, 0x82, 0x30, 0x82, 0x92, 0x82, 0xf4, 0x83, 0x57, 0x83, 0xba, 0x84, 0x1d, 0x84, 0x80, 0x84, 0xe3, 0x85, 0x47, 0x85, 0xab, 0x86, 0x0e, 0x86, 0x72, 0x86, 0xd7, 0x87, 0x3b, 0x87, 0x9f, 0x88, 0x04, 0x88, 0x69, 0x88, 0xce, 0x89, 0x33, 0x89, 0x99, 0x89, 0xfe, 0x8a, 0x64, 0x8a, 0xca, 0x8b, 0x30, 0x8b, 0x96, 0x8b, 0xfc, 0x8c, 0x63, 0x8c, 0xca, 0x8d, 0x31, 0x8d, 0x98, 0x8d, 0xff, 0x8e, 0x66, 0x8e, 0xce, 0x8f, 0x36, 0x8f, 0x9e, 0x90, 0x06, 0x90, 0x6e, 0x90, 0xd6, 0x91, 0x3f, 0x91, 0xa8, 0x92, 0x11, 0x92, 0x7a, 0x92, 0xe3, 0x93, 0x4d, 0x93, 0xb6, 0x94, 0x20, 0x94, 0x8a, 0x94, 0xf4, 0x95, 0x5f, 0x95, 0xc9, 0x96, 0x34, 0x96, 0x9f, 0x97, 0x0a, 0x97, 0x75, 0x97, 0xe0, 0x98, 0x4c, 0x98, 0xb8, 0x99, 0x24, 0x99, 0x90, 0x99, 0xfc, 0x9a, 0x68, 0x9a, 0xd5, 0x9b, 0x42, 0x9b, 0xaf, 0x9c, 0x1c, 0x9c, 0x89, 0x9c, 0xf7, 0x9d, 0x64, 0x9d, 0xd2, 0x9e, 0x40, 0x9e, 0xae, 0x9f, 0x1d, 0x9f, 0x8b, 0x9f, 0xfa, 0xa0, 0x69, 0xa0, 0xd8, 0xa1, 0x47, 0xa1, 0xb6, 0xa2, 0x26, 0xa2, 0x96, 0xa3, 0x06, 0xa3, 0x76, 0xa3, 0xe6, 0xa4, 0x56, 0xa4, 0xc7, 0xa5, 0x38, 0xa5, 0xa9, 0xa6, 0x1a, 0xa6, 0x8b, 0xa6, 0xfd, 0xa7, 0x6e, 0xa7, 0xe0, 0xa8, 0x52, 0xa8, 0xc4, 0xa9, 0x37, 0xa9, 0xa9, 0xaa, 0x1c, 0xaa, 0x8f, 0xab, 0x02, 0xab, 0x75, 0xab, 0xe9, 0xac, 0x5c, 0xac, 0xd0, 0xad, 0x44, 0xad, 0xb8, 0xae, 0x2d, 0xae, 0xa1, 0xaf, 0x16, 0xaf, 0x8b, 0xb0, 0x00, 0xb0, 0x75, 0xb0, 0xea, 0xb1, 0x60, 0xb1, 0xd6, 0xb2, 0x4b, 0xb2, 0xc2, 0xb3, 0x38, 0xb3, 0xae, 0xb4, 0x25, 0xb4, 0x9c, 0xb5, 0x13, 0xb5, 0x8a, 0xb6, 0x01, 0xb6, 0x79, 0xb6, 0xf0, 0xb7, 0x68, 0xb7, 0xe0, 0xb8, 0x59, 0xb8, 0xd1, 0xb9, 0x4a, 0xb9, 0xc2, 0xba, 0x3b, 0xba, 0xb5, 0xbb, 0x2e, 0xbb, 0xa7, 0xbc, 0x21, 0xbc, 0x9b, 0xbd, 0x15, 0xbd, 0x8f, 0xbe, 0x0a, 0xbe, 0x84, 0xbe, 0xff, 0xbf, 0x7a, 0xbf, 0xf5, 0xc0, 0x70, 0xc0, 0xec, 0xc1, 0x67, 0xc1, 0xe3, 0xc2, 0x5f, 0xc2, 0xdb, 0xc3, 0x58, 0xc3, 0xd4, 0xc4, 0x51, 0xc4, 0xce, 0xc5, 0x4b, 0xc5, 0xc8, 0xc6, 0x46, 0xc6, 0xc3, 0xc7, 0x41, 0xc7, 0xbf, 0xc8, 0x3d, 0xc8, 0xbc, 0xc9, 0x3a, 0xc9, 0xb9, 0xca, 0x38, 0xca, 0xb7, 0xcb, 0x36, 0xcb, 0xb6, 0xcc, 0x35, 0xcc, 0xb5, 0xcd, 0x35, 0xcd, 0xb5, 0xce, 0x36, 0xce, 0xb6, 0xcf, 0x37, 0xcf, 0xb8, 0xd0, 0x39, 0xd0, 0xba, 0xd1, 0x3c, 0xd1, 0xbe, 0xd2, 0x3f, 0xd2, 0xc1, 0xd3, 0x44, 0xd3, 0xc6, 0xd4, 0x49, 0xd4, 0xcb, 0xd5, 0x4e, 0xd5, 0xd1, 0xd6, 0x55, 0xd6, 0xd8, 0xd7, 0x5c, 0xd7, 0xe0, 0xd8, 0x64, 0xd8, 0xe8, 0xd9, 0x6c, 0xd9, 0xf1, 0xda, 0x76, 0xda, 0xfb, 0xdb, 0x80, 0xdc, 0x05, 0xdc, 0x8a, 0xdd, 0x10, 0xdd, 0x96, 0xde, 0x1c, 0xde, 0xa2, 0xdf, 0x29, 0xdf, 0xaf, 0xe0, 0x36, 0xe0, 0xbd, 0xe1, 0x44, 0xe1, 0xcc, 0xe2, 0x53, 0xe2, 0xdb, 0xe3, 0x63, 0xe3, 0xeb, 0xe4, 0x73, 0xe4, 0xfc, 0xe5, 0x84, 0xe6, 0x0d, 0xe6, 0x96, 0xe7, 0x1f, 0xe7, 0xa9, 0xe8, 0x32, 0xe8, 0xbc, 0xe9, 0x46, 0xe9, 0xd0, 0xea, 0x5b, 0xea, 0xe5, 0xeb, 0x70, 0xeb, 0xfb, 0xec, 0x86, 0xed, 0x11, 0xed, 0x9c, 0xee, 0x28, 0xee, 0xb4, 0xef, 0x40, 0xef, 0xcc, 0xf0, 0x58, 0xf0, 0xe5, 0xf1, 0x72, 0xf1, 0xff, 0xf2, 0x8c, 0xf3, 0x19, 0xf3, 0xa7, 0xf4, 0x34, 0xf4, 0xc2, 0xf5, 0x50, 0xf5, 0xde, 0xf6, 0x6d, 0xf6, 0xfb, 0xf7, 0x8a, 0xf8, 0x19, 0xf8, 0xa8, 0xf9, 0x38, 0xf9, 0xc7, 0xfa, 0x57, 0xfa, 0xe7, 0xfb, 0x77, 0xfc, 0x07, 0xfc, 0x98, 0xfd, 0x29, 0xfd, 0xba, 0xfe, 0x4b, 0xfe, 0xdc, 0xff, 0x6d, 0xff, 0xff }; StringInfo *profile; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (GetImageProfile(image,"icc") != (const StringInfo *) NULL) return(MagickFalse); profile=AcquireStringInfo(sizeof(sRGBProfile)); SetStringInfoDatum(profile,sRGBProfile); status=SetImageProfile(image,"icc",profile,exception); profile=DestroyStringInfo(profile); return(status); } MagickExport MagickBooleanType ProfileImage(Image *image,const char *name, const void *datum,const size_t length,ExceptionInfo *exception) { #define ProfileImageTag "Profile/Image" #ifndef TYPE_XYZ_8 #define TYPE_XYZ_8 (COLORSPACE_SH(PT_XYZ)|CHANNELS_SH(3)|BYTES_SH(1)) #endif #define ThrowProfileException(severity,tag,context) \ { \ if (cms_context != (cmsContext) NULL) \ cmsDeleteContext(cms_context); \ if (source_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(source_info.profile); \ if (target_info.profile != (cmsHPROFILE) NULL) \ (void) cmsCloseProfile(target_info.profile); \ ThrowBinaryException(severity,tag,context); \ } MagickBooleanType status; StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(name != (const char *) NULL); if ((datum == (const void *) NULL) || (length == 0)) { char *next; /* Delete image profile(s). */ ResetImageProfileIterator(image); for (next=GetNextImageProfile(image); next != (const char *) NULL; ) { if (IsOptionMember(next,name) != MagickFalse) { (void) DeleteImageProfile(image,next); ResetImageProfileIterator(image); } next=GetNextImageProfile(image); } return(MagickTrue); } /* Add a ICC, IPTC, or generic profile to the image. */ status=MagickTrue; profile=AcquireStringInfo((size_t) length); SetStringInfoDatum(profile,(unsigned char *) datum); if ((LocaleCompare(name,"icc") != 0) && (LocaleCompare(name,"icm") != 0)) status=SetImageProfile(image,name,profile,exception); else { const StringInfo *icc_profile; icc_profile=GetImageProfile(image,"icc"); if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { const char *value; value=GetImageProperty(image,"exif:ColorSpace",exception); (void) value; if (LocaleCompare(value,"1") != 0) (void) SetsRGBImageProfile(image,exception); value=GetImageProperty(image,"exif:InteroperabilityIndex",exception); if (LocaleCompare(value,"R98.") != 0) (void) SetsRGBImageProfile(image,exception); icc_profile=GetImageProfile(image,"icc"); } if ((icc_profile != (const StringInfo *) NULL) && (CompareStringInfo(icc_profile,profile) == 0)) { profile=DestroyStringInfo(profile); return(MagickTrue); } #if !defined(MAGICKCORE_LCMS_DELEGATE) (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn", "'%s' (LCMS)",image->filename); #else { cmsContext cms_context; CMSExceptionInfo cms_exception; LCMSInfo source_info, target_info; /* Transform pixel colors as defined by the color profiles. */ cms_exception.image=image; cms_exception.exception=exception; cms_context=cmsCreateContext(NULL,&cms_exception); if (cms_context == (cmsContext) NULL) ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); cmsSetLogErrorHandlerTHR(cms_context,CMSExceptionHandler); source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(profile),(cmsUInt32Number) GetStringInfoLength(profile)); if (source_info.profile == (cmsHPROFILE) NULL) { cmsDeleteContext(cms_context); ThrowBinaryException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } if ((cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass) && (icc_profile == (StringInfo *) NULL)) status=SetImageProfile(image,name,profile,exception); else { CacheView *image_view; cmsColorSpaceSignature signature; cmsHTRANSFORM *magick_restrict transform; cmsUInt32Number flags; #if !defined(MAGICKCORE_HDRI_SUPPORT) const char *artifact; #endif MagickBooleanType highres; MagickOffsetType progress; ssize_t y; target_info.profile=(cmsHPROFILE) NULL; if (icc_profile != (StringInfo *) NULL) { target_info.profile=source_info.profile; source_info.profile=cmsOpenProfileFromMemTHR(cms_context, GetStringInfoDatum(icc_profile), (cmsUInt32Number) GetStringInfoLength(icc_profile)); if (source_info.profile == (cmsHPROFILE) NULL) ThrowProfileException(ResourceLimitError, "ColorspaceColorProfileMismatch",name); } highres=MagickTrue; #if !defined(MAGICKCORE_HDRI_SUPPORT) artifact=GetImageArtifact(image,"profile:highres-transform"); if (IsStringFalse(artifact) != MagickFalse) highres=MagickFalse; #endif if (highres != MagickFalse) { source_info.scale=1.0; source_info.translate=0.0; } source_info.colorspace=sRGBColorspace; source_info.channels=3; switch (cmsGetColorSpace(source_info.profile)) { case cmsSigCmykData: { source_info.colorspace=CMYKColorspace; source_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; source_info.scale=100.0; } break; } case cmsSigGrayData: { source_info.colorspace=GRAYColorspace; source_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif source_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { source_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { source_info.type=(cmsUInt32Number) TYPE_Lab_DBL; source_info.scale=100.0; source_info.translate=(-0.5); } break; } case cmsSigRgbData: { source_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif source_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { source_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif source_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } signature=cmsGetPCS(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) signature=cmsGetColorSpace(target_info.profile); if (highres != MagickFalse) { target_info.scale=1.0; target_info.translate=0.0; } target_info.channels=3; switch (signature) { case cmsSigCmykData: { target_info.colorspace=CMYKColorspace; target_info.channels=4; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_CMYK_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_CMYK_DBL; target_info.scale=0.01; } break; } case cmsSigGrayData: { target_info.colorspace=GRAYColorspace; target_info.channels=1; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_GRAY_16; else #endif target_info.type=(cmsUInt32Number) TYPE_GRAY_DBL; break; } case cmsSigLabData: { target_info.colorspace=LabColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_Lab_16; else #endif { target_info.type=(cmsUInt32Number) TYPE_Lab_DBL; target_info.scale=0.01; target_info.translate=0.5; } break; } case cmsSigRgbData: { target_info.colorspace=sRGBColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_RGB_16; else #endif target_info.type=(cmsUInt32Number) TYPE_RGB_DBL; break; } case cmsSigXYZData: { target_info.colorspace=XYZColorspace; #if (MAGICKCORE_QUANTUM_DEPTH == 8) if (highres == MagickFalse) target_info.type=(cmsUInt32Number) TYPE_XYZ_8; else #elif (MAGICKCORE_QUANTUM_DEPTH == 16) if (highres == MagickFalse) source_info.type=(cmsUInt32Number) TYPE_XYZ_16; else #endif target_info.type=(cmsUInt32Number) TYPE_XYZ_DBL; break; } default: ThrowProfileException(ImageError, "ColorspaceColorProfileMismatch",name); } switch (image->rendering_intent) { case AbsoluteIntent: { target_info.intent=INTENT_ABSOLUTE_COLORIMETRIC; break; } case PerceptualIntent: { target_info.intent=INTENT_PERCEPTUAL; break; } case RelativeIntent: { target_info.intent=INTENT_RELATIVE_COLORIMETRIC; break; } case SaturationIntent: { target_info.intent=INTENT_SATURATION; break; } default: { target_info.intent=INTENT_PERCEPTUAL; break; } } flags=cmsFLAGS_HIGHRESPRECALC; #if defined(cmsFLAGS_BLACKPOINTCOMPENSATION) if (image->black_point_compensation != MagickFalse) flags|=cmsFLAGS_BLACKPOINTCOMPENSATION; #endif transform=AcquireTransformThreadSet(&source_info,&target_info, flags,cms_context); if (transform == (cmsHTRANSFORM *) NULL) ThrowProfileException(ImageError,"UnableToCreateColorTransform", name); /* Transform image as dictated by the source & target image profiles. */ source_info.pixels=AcquirePixelThreadSet(image->columns, source_info.channels,highres); target_info.pixels=AcquirePixelThreadSet(image->columns, target_info.channels,highres); if ((source_info.pixels == (void **) NULL) || (target_info.pixels == (void **) NULL)) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); ThrowProfileException(ResourceLimitError, "MemoryAllocationFailed",image->filename); } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if (source_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(source_info.profile); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); return(MagickFalse); } if (target_info.colorspace == CMYKColorspace) (void) SetImageColorspace(image,target_info.colorspace,exception); progress=0; 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++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register Quantum *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } if (highres != MagickFalse) TransformDoublePixels(id,image,&source_info,&target_info,transform,q); else TransformQuantumPixels(id,image,&source_info,&target_info,transform,q); 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 atomic #endif progress++; proceed=SetImageProgress(image,ProfileImageTag,progress, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); (void) SetImageColorspace(image,target_info.colorspace,exception); switch (signature) { case cmsSigRgbData: { image->type=image->alpha_trait == UndefinedPixelTrait ? TrueColorType : TrueColorAlphaType; break; } case cmsSigCmykData: { image->type=image->alpha_trait == UndefinedPixelTrait ? ColorSeparationType : ColorSeparationAlphaType; break; } case cmsSigGrayData: { image->type=image->alpha_trait == UndefinedPixelTrait ? GrayscaleType : GrayscaleAlphaType; break; } default: break; } target_info.pixels=DestroyPixelThreadSet(target_info.pixels); source_info.pixels=DestroyPixelThreadSet(source_info.pixels); transform=DestroyTransformThreadSet(transform); if ((status != MagickFalse) && (cmsGetDeviceClass(source_info.profile) != cmsSigLinkClass)) status=SetImageProfile(image,name,profile,exception); if (target_info.profile != (cmsHPROFILE) NULL) (void) cmsCloseProfile(target_info.profile); } (void) cmsCloseProfile(source_info.profile); cmsDeleteContext(cms_context); } #endif } profile=DestroyStringInfo(profile); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m o v e I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemoveImageProfile() removes a named profile from the image and returns its % value. % % The format of the RemoveImageProfile method is: % % void *RemoveImageProfile(Image *image,const char *name) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name. % */ MagickExport StringInfo *RemoveImageProfile(Image *image,const char *name) { StringInfo *profile; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return((StringInfo *) NULL); WriteTo8BimProfile(image,name,(StringInfo *) NULL); profile=(StringInfo *) RemoveNodeFromSplayTree((SplayTreeInfo *) image->profiles,name); return(profile); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e s e t P r o f i l e I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetImageProfileIterator() resets the image profile iterator. Use it in % conjunction with GetNextImageProfile() to iterate over all the profiles % associated with an image. % % The format of the ResetImageProfileIterator method is: % % ResetImageProfileIterator(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void ResetImageProfileIterator(const Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->profiles == (SplayTreeInfo *) NULL) return; ResetSplayTreeIterator((SplayTreeInfo *) image->profiles); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t I m a g e P r o f i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageProfile() adds a named profile to the image. If a profile with the % same name already exists, it is replaced. This method differs from the % ProfileImage() method in that it does not apply CMS color profiles. % % The format of the SetImageProfile method is: % % MagickBooleanType SetImageProfile(Image *image,const char *name, % const StringInfo *profile) % % A description of each parameter follows: % % o image: the image. % % o name: the profile name, for example icc, exif, and 8bim (8bim is the % Photoshop wrapper for iptc profiles). % % o profile: A StringInfo structure that contains the named profile. % */ static void *DestroyProfile(void *profile) { return((void *) DestroyStringInfo((StringInfo *) profile)); } static inline const unsigned char *ReadResourceByte(const unsigned char *p, unsigned char *quantum) { *quantum=(*p++); return(p); } static inline const unsigned char *ReadResourceLong(const unsigned char *p, unsigned int *quantum) { *quantum=(unsigned int) (*p++) << 24; *quantum|=(unsigned int) (*p++) << 16; *quantum|=(unsigned int) (*p++) << 8; *quantum|=(unsigned int) (*p++); return(p); } static inline const unsigned char *ReadResourceShort(const unsigned char *p, unsigned short *quantum) { *quantum=(unsigned short) (*p++) << 8; *quantum|=(unsigned short) (*p++); return(p); } static inline void WriteResourceLong(unsigned char *p, const unsigned int quantum) { unsigned char buffer[4]; buffer[0]=(unsigned char) (quantum >> 24); buffer[1]=(unsigned char) (quantum >> 16); buffer[2]=(unsigned char) (quantum >> 8); buffer[3]=(unsigned char) quantum; (void) memcpy(p,buffer,4); } static void WriteTo8BimProfile(Image *image,const char *name, const StringInfo *profile) { const unsigned char *datum, *q; register const unsigned char *p; size_t length; StringInfo *profile_8bim; ssize_t count; unsigned char length_byte; unsigned int value; unsigned short id, profile_id; if (LocaleCompare(name,"icc") == 0) profile_id=0x040f; else if (LocaleCompare(name,"iptc") == 0) profile_id=0x0404; else if (LocaleCompare(name,"xmp") == 0) profile_id=0x0424; else return; profile_8bim=(StringInfo *) GetValueFromSplayTree((SplayTreeInfo *) image->profiles,"8bim"); if (profile_8bim == (StringInfo *) NULL) return; datum=GetStringInfoDatum(profile_8bim); length=GetStringInfoLength(profile_8bim); for (p=datum; p < (datum+length-16); ) { q=p; if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((count & 0x01) != 0) count++; if ((count < 0) || (p > (datum+length-count)) || (count > (ssize_t) length)) break; if (id != profile_id) p+=count; else { size_t extent, offset; ssize_t extract_extent; StringInfo *extract_profile; extract_extent=0; extent=(datum+length)-(p+count); if (profile == (StringInfo *) NULL) { offset=(q-datum); extract_profile=AcquireStringInfo(offset+extent); (void) memcpy(extract_profile->datum,datum,offset); } else { offset=(p-datum); extract_extent=profile->length; if ((extract_extent & 0x01) != 0) extract_extent++; extract_profile=AcquireStringInfo(offset+extract_extent+extent); (void) memcpy(extract_profile->datum,datum,offset-4); WriteResourceLong(extract_profile->datum+offset-4,(unsigned int) profile->length); (void) memcpy(extract_profile->datum+offset, profile->datum,profile->length); } (void) memcpy(extract_profile->datum+offset+extract_extent, p+count,extent); (void) AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString("8bim"),CloneStringInfo(extract_profile)); extract_profile=DestroyStringInfo(extract_profile); break; } } } static void GetProfilesFromResourceBlock(Image *image, const StringInfo *resource_block,ExceptionInfo *exception) { const unsigned char *datum; register const unsigned char *p; size_t length; ssize_t count; StringInfo *profile; unsigned char length_byte; unsigned int value; unsigned short id; datum=GetStringInfoDatum(resource_block); length=GetStringInfoLength(resource_block); for (p=datum; p < (datum+length-16); ) { if (LocaleNCompare((char *) p,"8BIM",4) != 0) break; p+=4; p=ReadResourceShort(p,&id); p=ReadResourceByte(p,&length_byte); p+=length_byte; if (((length_byte+1) & 0x01) != 0) p++; if (p > (datum+length-4)) break; p=ReadResourceLong(p,&value); count=(ssize_t) value; if ((p > (datum+length-count)) || (count > (ssize_t) length) || (count < 0)) break; switch (id) { case 0x03ed: { unsigned int resolution; unsigned short units; /* Resolution. */ if (count < 10) break; p=ReadResourceLong(p,&resolution); image->resolution.x=((double) resolution)/65536.0; p=ReadResourceShort(p,&units)+2; p=ReadResourceLong(p,&resolution)+4; image->resolution.y=((double) resolution)/65536.0; /* Values are always stored as pixels per inch. */ if ((ResolutionType) units != PixelsPerCentimeterResolution) image->units=PixelsPerInchResolution; else { image->units=PixelsPerCentimeterResolution; image->resolution.x/=2.54; image->resolution.y/=2.54; } break; } case 0x0404: { /* IPTC Profile */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"iptc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x040c: { /* Thumbnail. */ p+=count; break; } case 0x040f: { /* ICC Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"icc",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0422: { /* EXIF Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"exif",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } case 0x0424: { /* XMP Profile. */ profile=AcquireStringInfo(count); SetStringInfoDatum(profile,p); (void) SetImageProfileInternal(image,"xmp",profile,MagickTrue, exception); profile=DestroyStringInfo(profile); p+=count; break; } default: { p+=count; break; } } if ((count & 0x01) != 0) p++; } } #if defined(MAGICKCORE_XML_DELEGATE) static MagickBooleanType ValidateXMPProfile(const StringInfo *profile) { xmlDocPtr document; /* Parse XML profile. */ document=xmlReadMemory((const char *) GetStringInfoDatum(profile),(int) GetStringInfoLength(profile),"xmp.xml",NULL,XML_PARSE_NOERROR | XML_PARSE_NOWARNING); if (document == (xmlDocPtr) NULL) return(MagickFalse); xmlFreeDoc(document); return(MagickTrue); } #else static MagickBooleanType ValidateXMPProfile(const StringInfo *profile) { return(MagickFalse); } #endif static MagickBooleanType SetImageProfileInternal(Image *image,const char *name, const StringInfo *profile,const MagickBooleanType recursive, ExceptionInfo *exception) { char key[MagickPathExtent]; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((LocaleCompare(name,"xmp") == 0) && (ValidateXMPProfile(profile) == MagickFalse)) { (void) ThrowMagickException(exception,GetMagickModule(),ImageWarning, "CorruptImageProfile","`%s'",name); return(MagickTrue); } if (image->profiles == (SplayTreeInfo *) NULL) image->profiles=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, DestroyProfile); (void) CopyMagickString(key,name,MagickPathExtent); LocaleLower(key); status=AddValueToSplayTree((SplayTreeInfo *) image->profiles, ConstantString(key),CloneStringInfo(profile)); if (status != MagickFalse) { if (LocaleCompare(name,"8bim") == 0) GetProfilesFromResourceBlock(image,profile,exception); else if (recursive == MagickFalse) WriteTo8BimProfile(image,name,profile); } return(status); } MagickExport MagickBooleanType SetImageProfile(Image *image,const char *name, const StringInfo *profile,ExceptionInfo *exception) { return(SetImageProfileInternal(image,name,profile,MagickFalse,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c I m a g e P r o f i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImageProfiles() synchronizes image properties with the image profiles. % Currently we only support updating the EXIF resolution and orientation. % % The format of the SyncImageProfiles method is: % % MagickBooleanType SyncImageProfiles(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static inline int ReadProfileByte(unsigned char **p,size_t *length) { int c; if (*length < 1) return(EOF); c=(int) (*(*p)++); (*length)--; return(c); } static inline signed short ReadProfileShort(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned short value; if (endian == LSBEndian) { value=(unsigned short) buffer[1] << 8; value|=(unsigned short) buffer[0]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } value=(unsigned short) buffer[0] << 8; value|=(unsigned short) buffer[1]; quantum.unsigned_value=value & 0xffff; return(quantum.signed_value); } static inline signed int ReadProfileLong(const EndianType endian, unsigned char *buffer) { union { unsigned int unsigned_value; signed int signed_value; } quantum; unsigned int value; if (endian == LSBEndian) { value=(unsigned int) buffer[3] << 24; value|=(unsigned int) buffer[2] << 16; value|=(unsigned int) buffer[1] << 8; value|=(unsigned int) buffer[0]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } value=(unsigned int) buffer[0] << 24; value|=(unsigned int) buffer[1] << 16; value|=(unsigned int) buffer[2] << 8; value|=(unsigned int) buffer[3]; quantum.unsigned_value=value & 0xffffffff; return(quantum.signed_value); } static inline signed int ReadProfileMSBLong(unsigned char **p,size_t *length) { signed int value; if (*length < 4) return(0); value=ReadProfileLong(MSBEndian,*p); (*length)-=4; *p+=4; return(value); } static inline signed short ReadProfileMSBShort(unsigned char **p, size_t *length) { signed short value; if (*length < 2) return(0); value=ReadProfileShort(MSBEndian,*p); (*length)-=2; *p+=2; return(value); } static inline void WriteProfileLong(const EndianType endian, const size_t value,unsigned char *p) { unsigned char buffer[4]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); buffer[2]=(unsigned char) (value >> 16); buffer[3]=(unsigned char) (value >> 24); (void) memcpy(p,buffer,4); return; } buffer[0]=(unsigned char) (value >> 24); buffer[1]=(unsigned char) (value >> 16); buffer[2]=(unsigned char) (value >> 8); buffer[3]=(unsigned char) value; (void) memcpy(p,buffer,4); } static void WriteProfileShort(const EndianType endian, const unsigned short value,unsigned char *p) { unsigned char buffer[2]; if (endian == LSBEndian) { buffer[0]=(unsigned char) value; buffer[1]=(unsigned char) (value >> 8); (void) memcpy(p,buffer,2); return; } buffer[0]=(unsigned char) (value >> 8); buffer[1]=(unsigned char) value; (void) memcpy(p,buffer,2); } static MagickBooleanType Sync8BimProfile(Image *image,StringInfo *profile) { size_t length; ssize_t count; unsigned char *p; unsigned short id; length=GetStringInfoLength(profile); p=GetStringInfoDatum(profile); while (length != 0) { if (ReadProfileByte(&p,&length) != 0x38) continue; if (ReadProfileByte(&p,&length) != 0x42) continue; if (ReadProfileByte(&p,&length) != 0x49) continue; if (ReadProfileByte(&p,&length) != 0x4D) continue; if (length < 7) return(MagickFalse); id=ReadProfileMSBShort(&p,&length); count=(ssize_t) ReadProfileByte(&p,&length); if ((count >= (ssize_t) length) || (count < 0)) return(MagickFalse); p+=count; length-=count; if ((*p & 0x01) == 0) (void) ReadProfileByte(&p,&length); count=(ssize_t) ReadProfileMSBLong(&p,&length); if ((count > (ssize_t) length) || (count < 0)) return(MagickFalse); if ((id == 0x3ED) && (count == 16)) { if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x*2.54* 65536.0),p); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.x* 65536.0),p); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+4); if (image->units == PixelsPerCentimeterResolution) WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y*2.54* 65536.0),p+8); else WriteProfileLong(MSBEndian,(unsigned int) (image->resolution.y* 65536.0),p+8); WriteProfileShort(MSBEndian,(unsigned short) image->units,p+12); } p+=count; length-=count; } return(MagickTrue); } MagickBooleanType SyncExifProfile(Image *image,StringInfo *profile) { #define MaxDirectoryStack 16 #define EXIF_DELIMITER "\n" #define EXIF_NUM_FORMATS 12 #define TAG_EXIF_OFFSET 0x8769 #define TAG_INTEROP_OFFSET 0xa005 typedef struct _DirectoryInfo { unsigned char *directory; size_t entry; } DirectoryInfo; DirectoryInfo directory_stack[MaxDirectoryStack]; EndianType endian; size_t entry, length, number_entries; SplayTreeInfo *exif_resources; ssize_t id, level, offset; static int format_bytes[] = {0, 1, 1, 2, 4, 8, 1, 1, 2, 4, 8, 4, 8}; unsigned char *directory, *exif; /* Set EXIF resolution tag. */ length=GetStringInfoLength(profile); exif=GetStringInfoDatum(profile); if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); if ((id != 0x4949) && (id != 0x4D4D)) { while (length != 0) { if (ReadProfileByte(&exif,&length) != 0x45) continue; if (ReadProfileByte(&exif,&length) != 0x78) continue; if (ReadProfileByte(&exif,&length) != 0x69) continue; if (ReadProfileByte(&exif,&length) != 0x66) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; if (ReadProfileByte(&exif,&length) != 0x00) continue; break; } if (length < 16) return(MagickFalse); id=(ssize_t) ReadProfileShort(LSBEndian,exif); } endian=LSBEndian; if (id == 0x4949) endian=LSBEndian; else if (id == 0x4D4D) endian=MSBEndian; else return(MagickFalse); if (ReadProfileShort(endian,exif+2) != 0x002a) return(MagickFalse); /* This the offset to the first IFD. */ offset=(ssize_t) ReadProfileLong(endian,exif+4); if ((offset < 0) || ((size_t) offset >= length)) return(MagickFalse); directory=exif+offset; level=0; entry=0; exif_resources=NewSplayTree((int (*)(const void *,const void *)) NULL, (void *(*)(void *)) NULL,(void *(*)(void *)) NULL); do { if (level > 0) { level--; directory=directory_stack[level].directory; entry=directory_stack[level].entry; } if ((directory < exif) || (directory > (exif+length-2))) break; /* Determine how many entries there are in the current IFD. */ number_entries=ReadProfileShort(endian,directory); for ( ; entry < number_entries; entry++) { int components; register unsigned char *p, *q; size_t number_bytes; ssize_t format, tag_value; q=(unsigned char *) (directory+2+(12*entry)); if (q > (exif+length-12)) break; /* corrupt EXIF */ if (GetValueFromSplayTree(exif_resources,q) == q) break; (void) AddValueToSplayTree(exif_resources,q,q); tag_value=(ssize_t) ReadProfileShort(endian,q); format=(ssize_t) ReadProfileShort(endian,q+2); if ((format < 0) || ((format-1) >= EXIF_NUM_FORMATS)) break; components=(int) ReadProfileLong(endian,q+4); if (components < 0) break; /* corrupt EXIF */ number_bytes=(size_t) components*format_bytes[format]; if ((ssize_t) number_bytes < components) break; /* prevent overflow */ if (number_bytes <= 4) p=q+8; else { /* The directory entry contains an offset. */ offset=(ssize_t) ReadProfileLong(endian,q+8); if ((offset < 0) || ((size_t) (offset+number_bytes) > length)) continue; if (~length < number_bytes) continue; /* prevent overflow */ p=(unsigned char *) (exif+offset); } switch (tag_value) { case 0x011a: { (void) WriteProfileLong(endian,(size_t) (image->resolution.x+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x011b: { (void) WriteProfileLong(endian,(size_t) (image->resolution.y+0.5),p); if (number_bytes == 8) (void) WriteProfileLong(endian,1UL,p+4); break; } case 0x0112: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) image->orientation,p); break; } (void) WriteProfileShort(endian,(unsigned short) image->orientation, p); break; } case 0x0128: { if (number_bytes == 4) { (void) WriteProfileLong(endian,(size_t) (image->units+1),p); break; } (void) WriteProfileShort(endian,(unsigned short) (image->units+1),p); break; } default: break; } if ((tag_value == TAG_EXIF_OFFSET) || (tag_value == TAG_INTEROP_OFFSET)) { offset=(ssize_t) ReadProfileLong(endian,p); if (((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=directory; entry++; directory_stack[level].entry=entry; level++; directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; if ((directory+2+(12*number_entries)) > (exif+length)) break; offset=(ssize_t) ReadProfileLong(endian,directory+2+(12* number_entries)); if ((offset != 0) && ((size_t) offset < length) && (level < (MaxDirectoryStack-2))) { directory_stack[level].directory=exif+offset; directory_stack[level].entry=0; level++; } } break; } } } while (level > 0); exif_resources=DestroySplayTree(exif_resources); return(MagickTrue); } MagickPrivate MagickBooleanType SyncImageProfiles(Image *image) { MagickBooleanType status; StringInfo *profile; status=MagickTrue; profile=(StringInfo *) GetImageProfile(image,"8BIM"); if (profile != (StringInfo *) NULL) if (Sync8BimProfile(image,profile) == MagickFalse) status=MagickFalse; profile=(StringInfo *) GetImageProfile(image,"EXIF"); if (profile != (StringInfo *) NULL) if (SyncExifProfile(image,profile) == MagickFalse) status=MagickFalse; return(status); }
GB_AxB_colscale_template.c
//------------------------------------------------------------------------------ // GB_AxB_colscale_template: C=A*D where D is a square diagonal matrix //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // This template is not used If C is iso, since all that is needed is to create // C as a shallow-copy of the pattern of A. // A and C can be jumbled. D cannot, but it is a diagonal matrix so it is // never jumbled. { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (GB_JUMBLED_OK (C)) ; ASSERT (GB_JUMBLED_OK (A)) ; ASSERT (!GB_JUMBLED (D)) ; ASSERT (!C->iso) ; //-------------------------------------------------------------------------- // get C, A, and D //-------------------------------------------------------------------------- const int64_t *restrict Ap = A->p ; const int64_t *restrict Ah = A->h ; #if !GB_A_IS_PATTERN const GB_ATYPE *restrict Ax = (GB_ATYPE *) A->x ; #endif #if !GB_B_IS_PATTERN const GB_BTYPE *restrict Dx = (GB_BTYPE *) D->x ; #endif const int64_t avlen = A->vlen ; const bool A_iso = A->iso ; const bool D_iso = D->iso ; const int64_t *restrict kfirst_Aslice = A_ek_slicing ; const int64_t *restrict klast_Aslice = A_ek_slicing + A_ntasks ; const int64_t *restrict pstart_Aslice = A_ek_slicing + A_ntasks * 2 ; //-------------------------------------------------------------------------- // C=A*D //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(A_nthreads) schedule(dynamic,1) for (tid = 0 ; tid < A_ntasks ; tid++) { // if kfirst > klast then task tid does no work at all int64_t kfirst = kfirst_Aslice [tid] ; int64_t klast = klast_Aslice [tid] ; //---------------------------------------------------------------------- // C(:,kfirst:klast) = A(:,kfirst:klast)*D(kfirst:klast,kfirst:klast) //---------------------------------------------------------------------- for (int64_t k = kfirst ; k <= klast ; k++) { //------------------------------------------------------------------ // find the part of A(:,k) and C(:,k) to be operated on by this task //------------------------------------------------------------------ int64_t j = GBH (Ah, k) ; int64_t pA_start, pA_end ; GB_get_pA (&pA_start, &pA_end, tid, k, kfirst, klast, pstart_Aslice, Ap, avlen) ; //------------------------------------------------------------------ // C(:,j) = A(:,j)*D(j,j) //------------------------------------------------------------------ GB_GETB (djj, Dx, j, D_iso) ; // djj = D (j,j) GB_PRAGMA_SIMD_VECTORIZE for (int64_t p = pA_start ; p < pA_end ; p++) { GB_GETA (aij, Ax, p, A_iso) ; // aij = A(i,j) GB_BINOP (GB_CX (p), aij, djj, 0, 0) ; // C(i,j) = aij * djj } } } }
conv_dw_k5_k7_kernel_arm.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. */ /* * Copyright (c) 2020, OPEN AI LAB * Author: haoluo@openailab.com */ #ifndef __CONV_DW_K5_K7_KERNEL_ARM_H_ #define __CONV_DW_K5_K7_KERNEL_ARM_H_ #include <stdio.h> #include <arm_neon.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> void dw_k5s1(float*, float*, float*, float*, int, int, int); static float elem_activation(float tmp, int type) { if (type == 0) { if (tmp < 0.0f) tmp = 0; if (type > 0) tmp = tmp < type ? tmp : type; } return tmp; } static float32x4_t vector_activation(float32x4_t tmp, int type) { if (type == 0) { float32x4_t zero = vdupq_n_f32(0.0); tmp = vmaxq_f32(tmp, zero); if (type > 0) { float32x4_t max = vdupq_n_f32(( float )type); tmp = vminq_f32(tmp, max); } } return tmp; } void depthwise_conv_k5s1(float* input, float* weight, float* bias, float* output, int input_h, int input_w, int channel, int output_h, int output_w, int pad0, int pad1, int activation, int num_thread) { int input_h_pad = input_h + pad0 + pad1; int input_w_pad = input_w + pad0 + pad1; int no_pad = pad0 == 0 && pad1 == 0; if (!no_pad) // have pad { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < channel; c++) { /* pad */ float* input_buf = ( float* )malloc(sizeof(float) * input_h_pad * input_w_pad + 128); float* input_tmp = input_buf; float* input_c = input + c * input_h * input_w; memset(input_tmp, 0, sizeof(float) * (input_w_pad * pad0 + pad0)); input_tmp += input_w_pad * pad0 + pad0; for (int h = 0; h < input_h; h++) { memcpy(input_tmp, input_c + h * input_w, sizeof(float) * input_w); input_tmp += input_w; memset(input_tmp, 0, sizeof(float) * (pad0 + pad1)); input_tmp += pad0 + pad1; } memset(input_tmp, 0, sizeof(float) * (input_w_pad * pad1 - pad0)); /* process convdw5x5s1 */ float* weight_cur = weight + c * 25; float* output_cur = output + c * output_h * output_w; if (bias) dw_k5s1(input_buf, weight_cur, bias + c, output_cur, output_h, output_w, activation); else dw_k5s1(input_buf, weight_cur, NULL, output_cur, output_h, output_w, activation); /* free input temp buffer */ free(input_buf); } } else { #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < channel; c++) { float* input_cur = input + c * input_h * input_w; float* weight_cur = weight + c * 25; // kernel_w * kernel_h is 5 * 5 = 25 float* output_cur = output + c * output_h * output_w; dw_k5s1(input_cur, weight_cur, bias + c, output_cur, output_h, output_w, activation); } } } void depthwise_conv_k5s2(float* input_buf, float* weight_buf, float* bias, float* output_buf, int input_h, int input_w, int channel, int output_h, int output_w, int activation, int num_thread) { int input_hw = input_h * input_w; int output_hw = output_h * output_w; int h_remain = input_h & 0x1; int w_remain = input_w & 0x1; int mid_h = output_h - 2; int mid_w = output_w - 2; int mid_w_block = mid_w & -4; #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < channel; c++) { int w, h; float* input_buf_c = input_buf + c * input_hw; float* output_buf_c = output_buf + c * output_hw; float* weight_buf_c = weight_buf + c * 25; float bias_c = bias ? bias[c] : 0; float tmp = bias_c; tmp += weight_buf_c[12] * input_buf_c[0]; tmp += weight_buf_c[13] * input_buf_c[1]; tmp += weight_buf_c[14] * input_buf_c[2]; tmp += weight_buf_c[17] * input_buf_c[input_w]; tmp += weight_buf_c[18] * input_buf_c[input_w + 1]; tmp += weight_buf_c[19] * input_buf_c[input_w + 2]; tmp += weight_buf_c[22] * input_buf_c[input_w * 2]; tmp += weight_buf_c[23] * input_buf_c[input_w * 2 + 1]; tmp += weight_buf_c[24] * input_buf_c[input_w * 2 + 2]; output_buf_c[0] = elem_activation(tmp, activation); for (w = 0; w < mid_w_block; w += 4) { float32x4_t sum0 = vdupq_n_f32(bias_c); float32x4_t line2_0 = vld1q_f32(input_buf_c + 2 * w); float32x4_t line2_1 = vld1q_f32(input_buf_c + 2 * w + 4); float32x4_t line2_2 = vld1q_f32(input_buf_c + 2 * w + 8); float32x4x2_t line2_01 = vuzpq_f32(line2_0, line2_1); float32x4x2_t line2_12 = vuzpq_f32(line2_1, line2_2); float32x4_t input2_2 = vextq_f32(line2_01.val[0], line2_2, 1); float32x4_t input2_3 = vextq_f32(line2_0, line2_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[10]), line2_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[11]), line2_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[12]), input2_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[13]), input2_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[14]), line2_12.val[0]); float32x4_t line3_0 = vld1q_f32(input_buf_c + input_w + 2 * w); float32x4_t line3_1 = vld1q_f32(input_buf_c + input_w + 2 * w + 4); float32x4_t line3_2 = vld1q_f32(input_buf_c + input_w + 2 * w + 8); float32x4x2_t line3_01 = vuzpq_f32(line3_0, line3_1); float32x4x2_t line3_12 = vuzpq_f32(line3_1, line3_2); float32x4_t input3_2 = vextq_f32(line3_01.val[0], line3_2, 1); float32x4_t input3_3 = vextq_f32(line3_0, line3_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[15]), line3_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[16]), line3_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[17]), input3_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[18]), input3_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[19]), line3_12.val[0]); float32x4_t line4_0 = vld1q_f32(input_buf_c + input_w * 2 + 2 * w); float32x4_t line4_1 = vld1q_f32(input_buf_c + input_w * 2 + 2 * w + 4); float32x4_t line4_2 = vld1q_f32(input_buf_c + input_w * 2 + 2 * w + 8); float32x4x2_t line4_01 = vuzpq_f32(line4_0, line4_1); float32x4x2_t line4_12 = vuzpq_f32(line4_1, line4_2); float32x4_t input4_2 = vextq_f32(line4_01.val[0], line4_2, 1); float32x4_t input4_3 = vextq_f32(line4_0, line4_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[20]), line4_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[21]), line4_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[22]), input4_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[23]), input4_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[24]), line4_12.val[0]); sum0 = vector_activation(sum0, activation); vst1q_f32(output_buf_c + w + 1, sum0); } for (w = mid_w_block; w < mid_w; w++) { tmp = bias_c; tmp += weight_buf_c[10] * input_buf_c[2 * w]; tmp += weight_buf_c[11] * input_buf_c[2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[2 * w + 3]; tmp += weight_buf_c[14] * input_buf_c[2 * w + 4]; tmp += weight_buf_c[15] * input_buf_c[input_w + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w + 2 * w + 3]; tmp += weight_buf_c[19] * input_buf_c[input_w + 2 * w + 4]; tmp += weight_buf_c[20] * input_buf_c[input_w * 2 + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * 2 + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * 2 + 2 * w + 2]; tmp += weight_buf_c[23] * input_buf_c[input_w * 2 + 2 * w + 3]; tmp += weight_buf_c[24] * input_buf_c[input_w * 2 + 2 * w + 4]; output_buf_c[w + 1] = elem_activation(tmp, activation); } if (w_remain) { tmp = bias_c; tmp += weight_buf_c[10] * input_buf_c[2 * w]; tmp += weight_buf_c[11] * input_buf_c[2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[2 * w + 2]; tmp += weight_buf_c[15] * input_buf_c[input_w + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w + 2 * w + 2]; tmp += weight_buf_c[20] * input_buf_c[input_w * 2 + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * 2 + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * 2 + 2 * w + 2]; output_buf_c[w + 1] = elem_activation(tmp, activation); } else { tmp = bias_c; tmp += weight_buf_c[10] * input_buf_c[2 * w]; tmp += weight_buf_c[11] * input_buf_c[2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[2 * w + 3]; tmp += weight_buf_c[15] * input_buf_c[input_w + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w + 2 * w + 3]; tmp += weight_buf_c[20] * input_buf_c[input_w * 2 + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * 2 + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * 2 + 2 * w + 2]; tmp += weight_buf_c[23] * input_buf_c[input_w * 2 + 2 * w + 3]; output_buf_c[w + 1] = elem_activation(tmp, activation); } // mid height for (h = 0; h < mid_h; h++) { tmp = bias_c; tmp += weight_buf_c[2] * input_buf_c[input_w * 2 * h]; tmp += weight_buf_c[3] * input_buf_c[input_w * 2 * h + 1]; tmp += weight_buf_c[4] * input_buf_c[input_w * 2 * h + 2]; tmp += weight_buf_c[7] * input_buf_c[input_w * (2 * h + 1)]; tmp += weight_buf_c[8] * input_buf_c[input_w * (2 * h + 1) + 1]; tmp += weight_buf_c[9] * input_buf_c[input_w * (2 * h + 1) + 2]; tmp += weight_buf_c[12] * input_buf_c[input_w * (2 * h + 2)]; tmp += weight_buf_c[13] * input_buf_c[input_w * (2 * h + 2) + 1]; tmp += weight_buf_c[14] * input_buf_c[input_w * (2 * h + 2) + 2]; tmp += weight_buf_c[17] * input_buf_c[input_w * (2 * h + 3)]; tmp += weight_buf_c[18] * input_buf_c[input_w * (2 * h + 3) + 1]; tmp += weight_buf_c[19] * input_buf_c[input_w * (2 * h + 3) + 2]; tmp += weight_buf_c[22] * input_buf_c[input_w * (2 * h + 4)]; tmp += weight_buf_c[23] * input_buf_c[input_w * (2 * h + 4) + 1]; tmp += weight_buf_c[24] * input_buf_c[input_w * (2 * h + 4) + 2]; output_buf_c[output_w * (h + 1)] = elem_activation(tmp, activation); for (w = 0; w < mid_w_block; w += 4) { float32x4_t sum0 = vdupq_n_f32(bias_c); float32x4_t line0_0 = vld1q_f32(input_buf_c + input_w * 2 * h + 2 * w); float32x4_t line0_1 = vld1q_f32(input_buf_c + input_w * 2 * h + 2 * w + 4); float32x4_t line0_2 = vld1q_f32(input_buf_c + input_w * 2 * h + 2 * w + 8); float32x4x2_t line0_01 = vuzpq_f32(line0_0, line0_1); float32x4x2_t line0_12 = vuzpq_f32(line0_1, line0_2); float32x4_t input0_2 = vextq_f32(line0_01.val[0], line0_2, 1); float32x4_t input0_3 = vextq_f32(line0_0, line0_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[0]), line0_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[1]), line0_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[2]), input0_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[3]), input0_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[4]), line0_12.val[0]); float32x4_t line1_0 = vld1q_f32(input_buf_c + input_w * (2 * h + 1) + 2 * w); float32x4_t line1_1 = vld1q_f32(input_buf_c + input_w * (2 * h + 1) + 2 * w + 4); float32x4_t line1_2 = vld1q_f32(input_buf_c + input_w * (2 * h + 1) + 2 * w + 8); float32x4x2_t line1_01 = vuzpq_f32(line1_0, line1_1); float32x4x2_t line1_12 = vuzpq_f32(line1_1, line1_2); float32x4_t input1_2 = vextq_f32(line1_01.val[0], line1_2, 1); float32x4_t input1_3 = vextq_f32(line1_0, line1_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[5]), line1_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[6]), line1_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[7]), input1_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[8]), input1_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[9]), line1_12.val[0]); float32x4_t line2_0 = vld1q_f32(input_buf_c + input_w * (2 * h + 2) + 2 * w); float32x4_t line2_1 = vld1q_f32(input_buf_c + input_w * (2 * h + 2) + 2 * w + 4); float32x4_t line2_2 = vld1q_f32(input_buf_c + input_w * (2 * h + 2) + 2 * w + 8); float32x4x2_t line2_01 = vuzpq_f32(line2_0, line2_1); float32x4x2_t line2_12 = vuzpq_f32(line2_1, line2_2); float32x4_t input2_2 = vextq_f32(line2_01.val[0], line2_2, 1); float32x4_t input2_3 = vextq_f32(line2_0, line2_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[10]), line2_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[11]), line2_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[12]), input2_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[13]), input2_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[14]), line2_12.val[0]); float32x4_t line3_0 = vld1q_f32(input_buf_c + input_w * (2 * h + 3) + 2 * w); float32x4_t line3_1 = vld1q_f32(input_buf_c + input_w * (2 * h + 3) + 2 * w + 4); float32x4_t line3_2 = vld1q_f32(input_buf_c + input_w * (2 * h + 3) + 2 * w + 8); float32x4x2_t line3_01 = vuzpq_f32(line3_0, line3_1); float32x4x2_t line3_12 = vuzpq_f32(line3_1, line3_2); float32x4_t input3_2 = vextq_f32(line3_01.val[0], line3_2, 1); float32x4_t input3_3 = vextq_f32(line3_0, line3_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[15]), line3_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[16]), line3_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[17]), input3_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[18]), input3_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[19]), line3_12.val[0]); float32x4_t line4_0 = vld1q_f32(input_buf_c + input_w * (2 * h + 4) + 2 * w); float32x4_t line4_1 = vld1q_f32(input_buf_c + input_w * (2 * h + 4) + 2 * w + 4); float32x4_t line4_2 = vld1q_f32(input_buf_c + input_w * (2 * h + 4) + 2 * w + 8); float32x4x2_t line4_01 = vuzpq_f32(line4_0, line4_1); float32x4x2_t line4_12 = vuzpq_f32(line4_1, line4_2); float32x4_t input4_2 = vextq_f32(line4_01.val[0], line4_2, 1); float32x4_t input4_3 = vextq_f32(line4_0, line4_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[20]), line4_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[21]), line4_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[22]), input4_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[23]), input4_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[24]), line4_12.val[0]); sum0 = vector_activation(sum0, activation); vst1q_f32(output_buf_c + output_w * (h + 1) + w + 1, sum0); } for (w = mid_w_block; w < mid_w; w++) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * 2 * h + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * 2 * h + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * 2 * h + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * 2 * h + 2 * w + 3]; tmp += weight_buf_c[4] * input_buf_c[input_w * 2 * h + 2 * w + 4]; tmp += weight_buf_c[5] * input_buf_c[input_w * (2 * h + 1) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 3]; tmp += weight_buf_c[9] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 4]; tmp += weight_buf_c[10] * input_buf_c[input_w * (2 * h + 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 3]; tmp += weight_buf_c[14] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 4]; tmp += weight_buf_c[15] * input_buf_c[input_w * (2 * h + 3) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 3]; tmp += weight_buf_c[19] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 4]; tmp += weight_buf_c[20] * input_buf_c[input_w * (2 * h + 4) + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 2]; tmp += weight_buf_c[23] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 3]; tmp += weight_buf_c[24] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 4]; output_buf_c[output_w * (h + 1) + w + 1] = elem_activation(tmp, activation); } if (w_remain) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * 2 * h + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * 2 * h + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * 2 * h + 2 * w + 2]; tmp += weight_buf_c[5] * input_buf_c[input_w * (2 * h + 1) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 2]; tmp += weight_buf_c[10] * input_buf_c[input_w * (2 * h + 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 2]; tmp += weight_buf_c[15] * input_buf_c[input_w * (2 * h + 3) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 2]; tmp += weight_buf_c[20] * input_buf_c[input_w * (2 * h + 4) + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 2]; output_buf_c[output_w * (h + 2) - 1] = elem_activation(tmp, activation); } else { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * 2 * h + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * 2 * h + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * 2 * h + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * 2 * h + 2 * w + 3]; tmp += weight_buf_c[5] * input_buf_c[input_w * (2 * h + 1) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (2 * h + 1) + 2 * w + 3]; tmp += weight_buf_c[10] * input_buf_c[input_w * (2 * h + 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (2 * h + 2) + 2 * w + 3]; tmp += weight_buf_c[15] * input_buf_c[input_w * (2 * h + 3) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w * (2 * h + 3) + 2 * w + 3]; tmp += weight_buf_c[20] * input_buf_c[input_w * (2 * h + 4) + 2 * w]; tmp += weight_buf_c[21] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 1]; tmp += weight_buf_c[22] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 2]; tmp += weight_buf_c[23] * input_buf_c[input_w * (2 * h + 4) + 2 * w + 3]; output_buf_c[output_w * (h + 2) - 1] = elem_activation(tmp, activation); } } if (h_remain) { tmp = bias_c; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 3)]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 3) + 1]; tmp += weight_buf_c[4] * input_buf_c[input_w * (input_h - 3) + 2]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 2)]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 2) + 1]; tmp += weight_buf_c[9] * input_buf_c[input_w * (input_h - 2) + 2]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 1)]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 1) + 1]; tmp += weight_buf_c[14] * input_buf_c[input_w * (input_h - 1) + 2]; output_buf_c[output_w * (output_h - 1)] = elem_activation(tmp, activation); for (w = 0; w < mid_w_block; w += 4) { float32x4_t sum0 = vdupq_n_f32(bias_c); float32x4_t line0_0 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w); float32x4_t line0_1 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w + 4); float32x4_t line0_2 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w + 8); float32x4x2_t line0_01 = vuzpq_f32(line0_0, line0_1); float32x4x2_t line0_12 = vuzpq_f32(line0_1, line0_2); float32x4_t input0_2 = vextq_f32(line0_01.val[0], line0_2, 1); float32x4_t input0_3 = vextq_f32(line0_0, line0_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[0]), line0_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[1]), line0_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[2]), input0_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[3]), input0_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[4]), line0_12.val[0]); float32x4_t line1_0 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w); float32x4_t line1_1 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w + 4); float32x4_t line1_2 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w + 8); float32x4x2_t line1_01 = vuzpq_f32(line1_0, line1_1); float32x4x2_t line1_12 = vuzpq_f32(line1_1, line1_2); float32x4_t input1_2 = vextq_f32(line1_01.val[0], line1_2, 1); float32x4_t input1_3 = vextq_f32(line1_0, line1_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[5]), line1_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[6]), line1_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[7]), input1_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[8]), input1_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[9]), line1_12.val[0]); float32x4_t line2_0 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w); float32x4_t line2_1 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w + 4); float32x4_t line2_2 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w + 8); float32x4x2_t line2_01 = vuzpq_f32(line2_0, line2_1); float32x4x2_t line2_12 = vuzpq_f32(line2_1, line2_2); float32x4_t input2_2 = vextq_f32(line2_01.val[0], line2_2, 1); float32x4_t input2_3 = vextq_f32(line2_0, line2_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[10]), line2_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[11]), line2_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[12]), input2_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[13]), input2_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[14]), line2_12.val[0]); sum0 = vector_activation(sum0, activation); vst1q_f32(output_buf_c + output_w * (output_h - 1) + w + 1, sum0); } for (w = mid_w_block; w < mid_w; w++) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 3) + 2 * w + 3]; tmp += weight_buf_c[4] * input_buf_c[input_w * (input_h - 3) + 2 * w + 4]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 2) + 2 * w + 3]; tmp += weight_buf_c[9] * input_buf_c[input_w * (input_h - 2) + 2 * w + 4]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 1) + 2 * w + 3]; tmp += weight_buf_c[14] * input_buf_c[input_w * (input_h - 1) + 2 * w + 4]; output_buf_c[output_w * (output_h - 1) + w + 1] = elem_activation(tmp, activation); } if (w_remain) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; output_buf_c[output_hw - 1] = elem_activation(tmp, activation); } else { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 3) + 2 * w + 3]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 2) + 2 * w + 3]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 1) + 2 * w + 3]; output_buf_c[output_hw - 1] = elem_activation(tmp, activation); } } else { tmp = bias_c; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 4)]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 4) + 1]; tmp += weight_buf_c[4] * input_buf_c[input_w * (input_h - 4) + 2]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 3)]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 3) + 1]; tmp += weight_buf_c[9] * input_buf_c[input_w * (input_h - 3) + 2]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 2)]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 2) + 1]; tmp += weight_buf_c[14] * input_buf_c[input_w * (input_h - 2) + 2]; tmp += weight_buf_c[17] * input_buf_c[input_w * (input_h - 1)]; tmp += weight_buf_c[18] * input_buf_c[input_w * (input_h - 1) + 1]; tmp += weight_buf_c[19] * input_buf_c[input_w * (input_h - 1) + 2]; output_buf_c[output_w * (output_h - 1)] = elem_activation(tmp, activation); for (w = 0; w < mid_w_block; w += 4) { float32x4_t sum0 = vdupq_n_f32(bias_c); float32x4_t line0_0 = vld1q_f32(input_buf_c + input_w * (input_h - 4) + 2 * w); float32x4_t line0_1 = vld1q_f32(input_buf_c + input_w * (input_h - 4) + 2 * w + 4); float32x4_t line0_2 = vld1q_f32(input_buf_c + input_w * (input_h - 4) + 2 * w + 8); float32x4x2_t line0_01 = vuzpq_f32(line0_0, line0_1); float32x4x2_t line0_12 = vuzpq_f32(line0_1, line0_2); float32x4_t input0_2 = vextq_f32(line0_01.val[0], line0_2, 1); float32x4_t input0_3 = vextq_f32(line0_0, line0_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[0]), line0_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[1]), line0_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[2]), input0_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[3]), input0_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[4]), line0_12.val[0]); float32x4_t line1_0 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w); float32x4_t line1_1 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w + 4); float32x4_t line1_2 = vld1q_f32(input_buf_c + input_w * (input_h - 3) + 2 * w + 8); float32x4x2_t line1_01 = vuzpq_f32(line1_0, line1_1); float32x4x2_t line1_12 = vuzpq_f32(line1_1, line1_2); float32x4_t input1_2 = vextq_f32(line1_01.val[0], line1_2, 1); float32x4_t input1_3 = vextq_f32(line1_0, line1_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[5]), line1_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[6]), line1_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[7]), input1_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[8]), input1_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[9]), line1_12.val[0]); float32x4_t line2_0 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w); float32x4_t line2_1 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w + 4); float32x4_t line2_2 = vld1q_f32(input_buf_c + input_w * (input_h - 2) + 2 * w + 8); float32x4x2_t line2_01 = vuzpq_f32(line2_0, line2_1); float32x4x2_t line2_12 = vuzpq_f32(line2_1, line2_2); float32x4_t input2_2 = vextq_f32(line2_01.val[0], line2_2, 1); float32x4_t input2_3 = vextq_f32(line2_0, line2_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[10]), line2_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[11]), line2_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[12]), input2_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[13]), input2_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[14]), line2_12.val[0]); float32x4_t line3_0 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w); float32x4_t line3_1 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w + 4); float32x4_t line3_2 = vld1q_f32(input_buf_c + input_w * (input_h - 1) + 2 * w + 8); float32x4x2_t line3_01 = vuzpq_f32(line3_0, line3_1); float32x4x2_t line3_12 = vuzpq_f32(line3_1, line3_2); float32x4_t input3_2 = vextq_f32(line3_01.val[0], line3_2, 1); float32x4_t input3_3 = vextq_f32(line3_0, line3_12.val[1], 3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[15]), line3_01.val[0]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[16]), line3_01.val[1]); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[17]), input3_2); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[18]), input3_3); sum0 = vmlaq_f32(sum0, vdupq_n_f32(weight_buf_c[19]), line3_12.val[0]); sum0 = vector_activation(sum0, activation); vst1q_f32(output_buf_c + output_w * (output_h - 1) + w + 1, sum0); } for (w = mid_w_block; w < mid_w; w++) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 4) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 4) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 4) + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 4) + 2 * w + 3]; tmp += weight_buf_c[4] * input_buf_c[input_w * (input_h - 4) + 2 * w + 4]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 3) + 2 * w + 3]; tmp += weight_buf_c[9] * input_buf_c[input_w * (input_h - 3) + 2 * w + 4]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 2) + 2 * w + 3]; tmp += weight_buf_c[14] * input_buf_c[input_w * (input_h - 2) + 2 * w + 4]; tmp += weight_buf_c[15] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w * (input_h - 1) + 2 * w + 3]; tmp += weight_buf_c[19] * input_buf_c[input_w * (input_h - 1) + 2 * w + 4]; output_buf_c[output_w * (output_h - 1) + w + 1] = elem_activation(tmp, activation); } if (w_remain) { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 4) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 4) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 4) + 2 * w + 2]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[15] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; output_buf_c[output_hw - 1] = elem_activation(tmp, activation); } else { tmp = bias_c; tmp += weight_buf_c[0] * input_buf_c[input_w * (input_h - 4) + 2 * w]; tmp += weight_buf_c[1] * input_buf_c[input_w * (input_h - 4) + 2 * w + 1]; tmp += weight_buf_c[2] * input_buf_c[input_w * (input_h - 4) + 2 * w + 2]; tmp += weight_buf_c[3] * input_buf_c[input_w * (input_h - 4) + 2 * w + 3]; tmp += weight_buf_c[5] * input_buf_c[input_w * (input_h - 3) + 2 * w]; tmp += weight_buf_c[6] * input_buf_c[input_w * (input_h - 3) + 2 * w + 1]; tmp += weight_buf_c[7] * input_buf_c[input_w * (input_h - 3) + 2 * w + 2]; tmp += weight_buf_c[8] * input_buf_c[input_w * (input_h - 3) + 2 * w + 3]; tmp += weight_buf_c[10] * input_buf_c[input_w * (input_h - 2) + 2 * w]; tmp += weight_buf_c[11] * input_buf_c[input_w * (input_h - 2) + 2 * w + 1]; tmp += weight_buf_c[12] * input_buf_c[input_w * (input_h - 2) + 2 * w + 2]; tmp += weight_buf_c[13] * input_buf_c[input_w * (input_h - 2) + 2 * w + 3]; tmp += weight_buf_c[15] * input_buf_c[input_w * (input_h - 1) + 2 * w]; tmp += weight_buf_c[16] * input_buf_c[input_w * (input_h - 1) + 2 * w + 1]; tmp += weight_buf_c[17] * input_buf_c[input_w * (input_h - 1) + 2 * w + 2]; tmp += weight_buf_c[18] * input_buf_c[input_w * (input_h - 1) + 2 * w + 3]; output_buf_c[output_hw - 1] = elem_activation(tmp, activation); } } } } void depthwise_conv_k7s1(float* input, float* weight, float* bias, float* output, int input_h, int input_w, int channel, int output_h, int output_w, int activation, int num_thread) { int channel_size = input_h * input_w; int mid_w = input_w - 6; int mid_block = mid_w >> 2; int mid_h = input_h - 6; int w = 0; // #pragma omp parallel for num_threads(num_thread) for (int c = 0; c < channel; c++) { float tmp0, tmp1, tmp2; float* input_1 = input + c * channel_size; float* input_2 = input_1 + input_w; float* input_3 = input_1 + input_w * 2; float* input_4 = input_1 + input_w * 3; float* input_5 = input_1 + input_w * 4; float* input_6 = input_1 + input_w * 5; float* input_7 = input_1 + input_w * 6; float* output_buf = output + c * channel_size; float* output_buf_1 = output_buf + output_w; float* output_buf_2 = output_buf_1 + output_w; float* weight_buf = weight + c * 49; float bias_c = bias ? bias[c] : 0; float32x4_t kernel_0_3 = vld1q_f32(weight_buf); float32x4_t kernel_4_7 = vld1q_f32(weight_buf + 4); float32x4_t kernel_8_11 = vld1q_f32(weight_buf + 8); float32x4_t kernel_12_15 = vld1q_f32(weight_buf + 12); float32x4_t kernel_16_19 = vld1q_f32(weight_buf + 16); float32x4_t kernel_20_23 = vld1q_f32(weight_buf + 20); float32x4_t kernel_24_27 = vld1q_f32(weight_buf + 24); float32x4_t kernel_28_31 = vld1q_f32(weight_buf + 28); float32x4_t kernel_32_35 = vld1q_f32(weight_buf + 32); float32x4_t kernel_36_39 = vld1q_f32(weight_buf + 36); float32x4_t kernel_40_43 = vld1q_f32(weight_buf + 40); float32x4_t kernel_44_47 = vld1q_f32(weight_buf + 44); float32x4_t kernel_48_51 = vld1q_f32(weight_buf + 48); float32x4_t line1 = vld1q_f32(input_1); float32x4_t line2 = vld1q_f32(input_2); float32x4_t line3 = vld1q_f32(input_3); float32x4_t line4 = vld1q_f32(input_4); float32x4_t line5 = vld1q_f32(input_5); float32x4_t line6 = vld1q_f32(input_6); float32x4_t kernel_10_13 = vextq_f32(kernel_8_11, kernel_12_15, 2); float32x4_t kernel_17_20 = vextq_f32(kernel_16_19, kernel_20_23, 1); float32x4_t kernel_31_34 = vextq_f32(kernel_28_31, kernel_32_35, 3); float32x4_t kernel_38_41 = vextq_f32(kernel_36_39, kernel_40_43, 2); float32x4_t kernel_45_48 = vextq_f32(kernel_44_47, kernel_48_51, 1); float32x4_t line1_1 = vld1q_f32(input_1 + 4); float32x4_t line2_1 = vld1q_f32(input_2 + 4); float32x4_t line3_1 = vld1q_f32(input_3 + 4); float32x4_t line4_1 = vld1q_f32(input_4 + 4); float32x4_t line5_1 = vld1q_f32(input_5 + 4); float32x4_t line6_1 = vld1q_f32(input_6 + 4); /* top start1 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_31_34); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_38_41); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_45_48); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_10_13); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_17_20); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_24_27); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_31_34); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_38_41); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_45_48); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } float32x4_t kernel_9_12 = vextq_f32(kernel_8_11, kernel_12_15, 1); float32x4_t kernel_23_26 = vextq_f32(kernel_20_23, kernel_24_27, 3); float32x4_t kernel_30_33 = vextq_f32(kernel_28_31, kernel_32_35, 2); float32x4_t kernel_37_40 = vextq_f32(kernel_36_39, kernel_40_43, 1); /* top start2 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_23_26); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_30_33); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_37_40); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_44_47); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += weight_buf[27] * input_1[4]; tmp0 += weight_buf[34] * input_2[4]; tmp0 += weight_buf[41] * input_3[4]; tmp0 += weight_buf[48] * input_4[4]; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_16_19); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_23_26); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_30_33); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_37_40); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_44_47); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; tmp1 += weight_buf[20] * input_1[4]; tmp1 += weight_buf[27] * input_2[4]; tmp1 += weight_buf[34] * input_3[4]; tmp1 += weight_buf[41] * input_4[4]; tmp1 += weight_buf[48] * input_5[4]; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_9_12); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_16_19); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_23_26); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_30_33); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_37_40); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_44_47); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; tmp2 += weight_buf[13] * input_1[4]; tmp2 += weight_buf[20] * input_2[4]; tmp2 += weight_buf[27] * input_3[4]; tmp2 += weight_buf[34] * input_4[4]; tmp2 += weight_buf[41] * input_5[4]; tmp2 += weight_buf[48] * input_6[4]; *output_buf_2++ = elem_activation(tmp2, activation); } float32x4_t kernel_15_18 = vextq_f32(kernel_12_15, kernel_16_19, 3); float32x4_t kernel_22_25 = vextq_f32(kernel_20_23, kernel_24_27, 2); float32x4_t kernel_29_32 = vextq_f32(kernel_28_31, kernel_32_35, 1); float32x4_t kernel_43_46 = vextq_f32(kernel_40_43, kernel_44_47, 3); /* top start3 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_36_39); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_43_46); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_15_18); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_22_25); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_29_32); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_36_39); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_43_46); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line1_1), vget_high_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_24_27)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_31_34)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_38_41)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_45_48)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_8_11); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_15_18); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_22_25); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_29_32); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_36_39); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_43_46); float32x2_t tmp_2_2 = vadd_f32(vget_low_f32(tmp_4_2), vget_high_f32(tmp_4_2)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line1_1), vget_high_f32(kernel_10_13)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line2_1), vget_high_f32(kernel_17_20)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line3_1), vget_high_f32(kernel_24_27)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line4_1), vget_high_f32(kernel_31_34)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line5_1), vget_high_f32(kernel_38_41)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line6_1), vget_high_f32(kernel_45_48)); tmp2 = vget_lane_f32(tmp_2_2, 0) + vget_lane_f32(tmp_2_2, 1) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } float32x4_t line1_2; float32x4_t line2_2; float32x4_t line3_2; float32x4_t line4_2; float32x4_t line5_2; float32x4_t line6_2; /* top mid */ for (w = 0; w < mid_block; w++) { line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); float32x4_t tmp_4_1 = vdupq_n_f32(bias_c); float32x4_t tmp_4_2 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1, vget_low_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line1, vget_high_f32(kernel_12_15), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line1, vget_high_f32(kernel_4_7), 1); float32x4_t tmp = vextq_f32(line1, line1_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_12_15), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line1, line1_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line1, line1_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_8_11), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1_1, vget_low_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line1_1, vget_high_f32(kernel_16_19), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line1_1, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line1_1, line1_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line1_1, line1_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_20_23), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_12_15), 1); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2, vget_low_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line2, vget_low_f32(kernel_20_23), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line2, vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line2, line2_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line2, line2_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line2, line2_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2_1, vget_low_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line2_1, vget_low_f32(kernel_24_27), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line2_1, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line2_1, line2_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line2_1, line2_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_20_23), 0); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3, vget_high_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line3, vget_low_f32(kernel_28_31), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line3, vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line3, line3_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line3, line3_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line3, line3_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3_1, vget_high_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line3_1, vget_low_f32(kernel_32_35), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line3_1, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line3_1, line3_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line3_1, line3_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_24_27), 1); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4, vget_high_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line4, vget_high_f32(kernel_32_35), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line4, vget_low_f32(kernel_28_31), 0); tmp = vextq_f32(line4, line4_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_36_39), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_28_31), 1); tmp = vextq_f32(line4, line4_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_36_39), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_28_31), 0); tmp = vextq_f32(line4, line4_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4_1, vget_high_f32(kernel_44_47), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line4_1, vget_high_f32(kernel_36_39), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line4_1, vget_low_f32(kernel_32_35), 0); tmp = vextq_f32(line4_1, line4_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_40_43), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_32_35), 1); tmp = vextq_f32(line4_1, line4_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_40_43), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_32_35), 0); /* line5 */ tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line5, vget_high_f32(kernel_40_43), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line5, vget_high_f32(kernel_32_35), 1); tmp = vextq_f32(line5, line5_1, 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_40_43), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_36_39), 0); tmp = vextq_f32(line5, line5_1, 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_44_47), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_36_39), 1); tmp = vextq_f32(line5, line5_1, 3); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_44_47), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line5_1, vget_high_f32(kernel_44_47), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line5_1, vget_high_f32(kernel_36_39), 1); tmp = vextq_f32(line5_1, line5_2, 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_44_47), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_40_43), 0); tmp = vextq_f32(line5_1, line5_2, 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_40_43), 1); /* line6 */ tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line6, vget_high_f32(kernel_40_43), 0); tmp = vextq_f32(line6, line6_1, 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_40_43), 1); tmp = vextq_f32(line6, line6_1, 2); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_44_47), 0); tmp = vextq_f32(line6, line6_1, 3); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_44_47), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line6_1, vget_high_f32(kernel_44_47), 0); tmp = vextq_f32(line6_1, line6_2, 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_44_47), 1); tmp = vextq_f32(line6_1, line6_2, 2); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_0 = vector_activation(tmp_4_0, activation); tmp_4_1 = vector_activation(tmp_4_1, activation); tmp_4_2 = vector_activation(tmp_4_2, activation); vst1q_f32(output_buf, tmp_4_0); vst1q_f32(output_buf_1, tmp_4_1); vst1q_f32(output_buf_2, tmp_4_2); output_buf += 4; output_buf_1 += 4; output_buf_2 += 4; line1 = line1_1; line2 = line2_1; line3 = line3_1; line4 = line4_1; line5 = line5_1; line6 = line6_1; line1_1 = line1_2; line2_1 = line2_2; line3_1 = line3_2; line4_1 = line4_2; line5_1 = line5_2; line6_1 = line6_2; } float32x4_t zero = vdupq_n_f32(0.0); float32x4_t kernel_7_10 = vextq_f32(kernel_4_7, kernel_8_11, 3); float32x4_t kernel_14_17 = vextq_f32(kernel_12_15, kernel_16_19, 2); float32x4_t kernel_21_24 = vextq_f32(kernel_20_23, kernel_24_27, 1); float32x4_t kernel_35_38 = vextq_f32(kernel_32_35, kernel_36_39, 3); float32x4_t kernel_42_45 = vextq_f32(kernel_40_43, kernel_44_47, 2); line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); for (w = mid_block * 4; w < mid_w; w++) { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_42_45); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_21_24); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_28_31); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_35_38); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_42_45); float32x4_t tmp = vextq_f32(zero, line1_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_17_20); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_10_13); tmp = vextq_f32(zero, line2_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_31_34); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_24_27); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_17_20); tmp = vextq_f32(zero, line3_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_38_41); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_31_34); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_24_27); tmp = vextq_f32(zero, line4_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_45_48); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_38_41); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_31_34); tmp = vextq_f32(zero, line5_1, 3); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_45_48); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_38_41); tmp = vextq_f32(zero, line6_1, 3); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); *output_buf_1++ = elem_activation(tmp1, activation); *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_2, 1); line2_1 = vextq_f32(line2_1, line2_2, 1); line3_1 = vextq_f32(line3_1, line3_2, 1); line4_1 = vextq_f32(line4_1, line4_2, 1); line5_1 = vextq_f32(line5_1, line5_2, 1); line6_1 = vextq_f32(line6_1, line6_2, 1); } /* top end1 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_37_40)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_44_47)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_42_45); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line1_1), vget_high_f32(kernel_16_19)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_23_26)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_30_33)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_37_40)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_44_47)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_21_24); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_28_31); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_35_38); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_42_45); float32x2_t tmp_2_2 = vadd_f32(vget_low_f32(tmp_4_2), vget_high_f32(tmp_4_2)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line1_1), vget_high_f32(kernel_9_12)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line2_1), vget_high_f32(kernel_16_19)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line3_1), vget_high_f32(kernel_23_26)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line4_1), vget_high_f32(kernel_30_33)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line5_1), vget_high_f32(kernel_37_40)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line6_1), vget_high_f32(kernel_44_47)); tmp2 = vget_lane_f32(tmp_2_2, 0) + vget_lane_f32(tmp_2_2, 1) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); } /* top end2 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += vgetq_lane_f32(line1_1, 0) * weight_buf[25]; tmp0 += vgetq_lane_f32(line2_1, 0) * weight_buf[32]; tmp0 += vgetq_lane_f32(line3_1, 0) * weight_buf[39]; tmp0 += vgetq_lane_f32(line4_1, 0) * weight_buf[46]; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_42_45); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; tmp1 += vgetq_lane_f32(line1_1, 0) * weight_buf[18]; tmp1 += vgetq_lane_f32(line2_1, 0) * weight_buf[25]; tmp1 += vgetq_lane_f32(line3_1, 0) * weight_buf[32]; tmp1 += vgetq_lane_f32(line4_1, 0) * weight_buf[39]; tmp1 += vgetq_lane_f32(line5_1, 0) * weight_buf[46]; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_21_24); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_28_31); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_35_38); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_42_45); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; tmp2 += vgetq_lane_f32(line1_1, 0) * weight_buf[11]; tmp2 += vgetq_lane_f32(line2_1, 0) * weight_buf[18]; tmp2 += vgetq_lane_f32(line3_1, 0) * weight_buf[25]; tmp2 += vgetq_lane_f32(line4_1, 0) * weight_buf[32]; tmp2 += vgetq_lane_f32(line5_1, 0) * weight_buf[39]; tmp2 += vgetq_lane_f32(line6_1, 0) * weight_buf[46]; *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); } /* top end3 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_42_45); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line1, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line2, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line3, kernel_21_24); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_28_31); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_35_38); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_42_45); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } float32x4_t kernel_1_4 = vextq_f32(kernel_0_3, kernel_4_7, 1); float32x4_t kernel_2_5 = vextq_f32(kernel_0_3, kernel_4_7, 2); float32x4_t kernel_3_6 = vextq_f32(kernel_0_3, kernel_4_7, 3); output_buf += output_w * 2; float32x4_t line7; float32x4_t line7_1; float32x4_t line7_2; /* mid */ for (int h = 0; h < mid_h; h++) { input_1 = input + c * channel_size + h * input_w; input_2 = input_1 + input_w; input_3 = input_2 + input_w; input_4 = input_3 + input_w; input_5 = input_4 + input_w; input_6 = input_5 + input_w; input_7 = input_6 + input_w; line1 = vld1q_f32(input_1); line2 = vld1q_f32(input_2); line3 = vld1q_f32(input_3); line4 = vld1q_f32(input_4); line5 = vld1q_f32(input_5); line6 = vld1q_f32(input_6); line7 = vld1q_f32(input_7); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line1_1 = vld1q_f32(input_1 + 4); line2_1 = vld1q_f32(input_2 + 4); line3_1 = vld1q_f32(input_3 + 4); line4_1 = vld1q_f32(input_4 + 4); line5_1 = vld1q_f32(input_5 + 4); line6_1 = vld1q_f32(input_6 + 4); line7_1 = vld1q_f32(input_7 + 4); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_2_5); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_9_12); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_16_19); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_23_26); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_30_33); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_37_40); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_44_47); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += vgetq_lane_f32(line1_1, 0) * weight_buf[6]; tmp0 += vgetq_lane_f32(line2_1, 0) * weight_buf[13]; tmp0 += vgetq_lane_f32(line3_1, 0) * weight_buf[20]; tmp0 += vgetq_lane_f32(line4_1, 0) * weight_buf[27]; tmp0 += vgetq_lane_f32(line5_1, 0) * weight_buf[34]; tmp0 += vgetq_lane_f32(line6_1, 0) * weight_buf[41]; tmp0 += vgetq_lane_f32(line7_1, 0) * weight_buf[48]; *output_buf++ = elem_activation(tmp0, activation); } { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_1_4); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_8_11); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_15_18); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_36_39); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_43_46); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line7_1), vget_high_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } for (w = 0; w < mid_block; w++) { line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); line7_2 = vld1q_f32(input_7 + 8 + 4 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1, vget_low_f32(kernel_0_3), 0); float32x4_t tmp = vextq_f32(line1, line1_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line1, line1_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line1, line1_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1_1, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line1_1, line1_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line1_1, line1_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_4_7), 0); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2, vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line2, line2_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line2, line2_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line2, line2_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2_1, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line2_1, line2_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line2_1, line2_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 1); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3, vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line3, line3_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line3, line3_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line3, line3_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3_1, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line3_1, line3_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line3_1, line3_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_20_23), 0); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4, vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line4, line4_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line4, line4_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line4, line4_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4_1, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line4_1, line4_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line4_1, line4_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); /* line5 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line5, vget_low_f32(kernel_28_31), 0); tmp = vextq_f32(line5, line5_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp = vextq_f32(line5, line5_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp = vextq_f32(line5, line5_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line5_1, vget_low_f32(kernel_32_35), 0); tmp = vextq_f32(line5_1, line5_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp = vextq_f32(line5_1, line5_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); /* line6 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line6, vget_high_f32(kernel_32_35), 1); tmp = vextq_f32(line6, line6_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp = vextq_f32(line6, line6_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp = vextq_f32(line6, line6_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line6_1, vget_high_f32(kernel_36_39), 1); tmp = vextq_f32(line6_1, line6_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp = vextq_f32(line6_1, line6_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); /* line7 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line7, vget_high_f32(kernel_40_43), 0); tmp = vextq_f32(line7, line7_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_40_43), 1); tmp = vextq_f32(line7, line7_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 0); tmp = vextq_f32(line7, line7_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line7_1, vget_high_f32(kernel_44_47), 0); tmp = vextq_f32(line7_1, line7_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 1); tmp = vextq_f32(line7_1, line7_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_0 = vector_activation(tmp_4_0, activation); vst1q_f32(output_buf, tmp_4_0); output_buf += 4; line1 = line1_1; line2 = line2_1; line3 = line3_1; line4 = line4_1; line5 = line5_1; line6 = line6_1; line7 = line7_1; line1_1 = line1_2; line2_1 = line2_2; line3_1 = line3_2; line4_1 = line4_2; line5_1 = line5_2; line6_1 = line6_2; line7_1 = line7_2; } line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); line7_2 = vld1q_f32(input_7 + 8 + 4 * w); for (w = mid_block * 4; w < mid_w; w++) { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); float32x4_t tmp = vextq_f32(zero, line1_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_3_6); tmp = vextq_f32(zero, line2_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_10_13); tmp = vextq_f32(zero, line3_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_17_20); tmp = vextq_f32(zero, line4_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_24_27); tmp = vextq_f32(zero, line5_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_31_34); tmp = vextq_f32(zero, line6_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_38_41); tmp = vextq_f32(zero, line7_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line7 = vextq_f32(line7, line7_1, 1); line1_1 = vextq_f32(line1_1, line1_2, 1); line2_1 = vextq_f32(line2_1, line2_2, 1); line3_1 = vextq_f32(line3_1, line3_2, 1); line4_1 = vextq_f32(line4_1, line4_2, 1); line5_1 = vextq_f32(line5_1, line5_2, 1); line6_1 = vextq_f32(line6_1, line6_2, 1); line7_1 = vextq_f32(line7_1, line7_2, 1); } { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_2_5)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_9_12)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_16_19)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_37_40)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line7_1), vget_high_f32(kernel_44_47)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line7 = vextq_f32(line7, line7_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); line7_1 = vextq_f32(line7_1, line7_1, 1); } { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += vgetq_lane_f32(line1_1, 0) * weight_buf[4]; tmp0 += vgetq_lane_f32(line2_1, 0) * weight_buf[11]; tmp0 += vgetq_lane_f32(line3_1, 0) * weight_buf[18]; tmp0 += vgetq_lane_f32(line4_1, 0) * weight_buf[25]; tmp0 += vgetq_lane_f32(line5_1, 0) * weight_buf[32]; tmp0 += vgetq_lane_f32(line6_1, 0) * weight_buf[39]; tmp0 += vgetq_lane_f32(line7_1, 0) * weight_buf[46]; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line7 = vextq_f32(line7, line7_1, 1); } { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } } /* bottom start1 */ input_1 = input + c * channel_size + input_w * (input_h - 6); input_2 = input_1 + input_w; input_3 = input_2 + input_w; input_4 = input_3 + input_w; input_5 = input_4 + input_w; input_6 = input_5 + input_w; line1 = vld1q_f32(input_1); line2 = vld1q_f32(input_2); line3 = vld1q_f32(input_3); line4 = vld1q_f32(input_4); line5 = vld1q_f32(input_5); line6 = vld1q_f32(input_6); output_buf_1 = output_buf + input_w; output_buf_2 = output_buf_1 + input_w; { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_38_41); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_3_6); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_31_34); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_3_6); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_10_13); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_17_20); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_24_27); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } line1_1 = vld1q_f32(input_1 + 4); line2_1 = vld1q_f32(input_2 + 4); line3_1 = vld1q_f32(input_3 + 4); line4_1 = vld1q_f32(input_4 + 4); line5_1 = vld1q_f32(input_5 + 4); line6_1 = vld1q_f32(input_6 + 4); /* bottom start2 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_2_5); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_9_12); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_16_19); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_23_26); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_30_33); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_37_40); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += vgetq_lane_f32(line1_1, 0) * weight_buf[6]; tmp0 += vgetq_lane_f32(line2_1, 0) * weight_buf[13]; tmp0 += vgetq_lane_f32(line3_1, 0) * weight_buf[20]; tmp0 += vgetq_lane_f32(line4_1, 0) * weight_buf[27]; tmp0 += vgetq_lane_f32(line5_1, 0) * weight_buf[34]; tmp0 += vgetq_lane_f32(line6_1, 0) * weight_buf[41]; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_2_5); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_9_12); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_16_19); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_23_26); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_30_33); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; tmp1 += vgetq_lane_f32(line2_1, 0) * weight_buf[6]; tmp1 += vgetq_lane_f32(line3_1, 0) * weight_buf[13]; tmp1 += vgetq_lane_f32(line4_1, 0) * weight_buf[20]; tmp1 += vgetq_lane_f32(line5_1, 0) * weight_buf[27]; tmp1 += vgetq_lane_f32(line6_1, 0) * weight_buf[34]; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_2_5); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_9_12); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_16_19); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_23_26); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; tmp2 += vgetq_lane_f32(line3_1, 0) * weight_buf[6]; tmp2 += vgetq_lane_f32(line4_1, 0) * weight_buf[13]; tmp2 += vgetq_lane_f32(line5_1, 0) * weight_buf[20]; tmp2 += vgetq_lane_f32(line6_1, 0) * weight_buf[27]; *output_buf_2++ = elem_activation(tmp2, activation); } /* bottom start3 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_1_4); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_8_11); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_15_18); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_36_39); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_38_41)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_1_4); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_8_11); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_15_18); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_22_25); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_29_32); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_3_6)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_10_13)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_24_27)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_31_34)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_1_4); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_8_11); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_15_18); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_22_25); float32x2_t tmp_2_2 = vadd_f32(vget_low_f32(tmp_4_2), vget_high_f32(tmp_4_2)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line3_1), vget_high_f32(kernel_3_6)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line4_1), vget_high_f32(kernel_10_13)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line5_1), vget_high_f32(kernel_17_20)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line6_1), vget_high_f32(kernel_24_27)); tmp2 = vget_lane_f32(tmp_2_2, 0) + vget_lane_f32(tmp_2_2, 1) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } /* bottom mid */ for (w = 0; w < mid_block; w++) { line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); float32x4_t tmp_4_1 = vdupq_n_f32(bias_c); float32x4_t tmp_4_2 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1, vget_low_f32(kernel_0_3), 0); float32x4_t tmp = vextq_f32(line1, line1_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line1, line1_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line1, line1_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line1_1, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line1_1, line1_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line1_1, line1_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_4_7), 0); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2, vget_high_f32(kernel_4_7), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line2, vget_low_f32(kernel_0_3), 0); tmp = vextq_f32(line2, line2_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line2, line2_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line2, line2_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_0_3), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line2_1, vget_high_f32(kernel_8_11), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line2_1, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line2_1, line2_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line2_1, line2_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_4_7), 0); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3, vget_high_f32(kernel_12_15), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line3, vget_high_f32(kernel_4_7), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line3, vget_low_f32(kernel_0_3), 0); tmp = vextq_f32(line3, line3_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_12_15), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line3, line3_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line3, line3_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_8_11), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_0_3), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line3_1, vget_high_f32(kernel_16_19), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line3_1, vget_high_f32(kernel_8_11), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line3_1, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line3_1, line3_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line3_1, line3_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_4_7), 0); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4, vget_low_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line4, vget_high_f32(kernel_12_15), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line4, vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line4, line4_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_12_15), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line4, line4_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line4, line4_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_8_11), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line4_1, vget_low_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line4_1, vget_high_f32(kernel_16_19), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line4_1, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line4_1, line4_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line4_1, line4_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_20_23), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_12_15), 1); /* line5 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line5, vget_low_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line5, vget_low_f32(kernel_20_23), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line5, vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line5, line5_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line5, line5_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line5, line5_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line5_1, vget_low_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line5_1, vget_low_f32(kernel_24_27), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line5_1, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line5_1, line5_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line5_1, line5_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_20_23), 0); /* line6 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line6, vget_high_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line6, vget_low_f32(kernel_28_31), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line6, vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line6, line6_1, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line6, line6_1, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line6, line6_1, 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line6_1, vget_high_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line6_1, vget_low_f32(kernel_32_35), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, line6_1, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line6_1, line6_2, 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line6_1, line6_2, 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_2 = vmlaq_lane_f32(tmp_4_2, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_0 = vector_activation(tmp_4_0, activation); vst1q_f32(output_buf, tmp_4_0); output_buf += 4; tmp_4_1 = vector_activation(tmp_4_1, activation); vst1q_f32(output_buf_1, tmp_4_1); output_buf_1 += 4; tmp_4_2 = vector_activation(tmp_4_2, activation); vst1q_f32(output_buf_2, tmp_4_2); output_buf_2 += 4; line1 = line1_1; line2 = line2_1; line3 = line3_1; line4 = line4_1; line5 = line5_1; line6 = line6_1; line1_1 = line1_2; line2_1 = line2_2; line3_1 = line3_2; line4_1 = line4_2; line5_1 = line5_2; line6_1 = line6_2; } line1_2 = vld1q_f32(input_1 + 8 + 4 * w); line2_2 = vld1q_f32(input_2 + 8 + 4 * w); line3_2 = vld1q_f32(input_3 + 8 + 4 * w); line4_2 = vld1q_f32(input_4 + 8 + 4 * w); line5_2 = vld1q_f32(input_5 + 8 + 4 * w); line6_2 = vld1q_f32(input_6 + 8 + 4 * w); for (w = mid_block * 4; w < mid_w; w++) { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_28_31); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_0_3); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_21_24); float32x4_t tmp = vextq_f32(zero, line1_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_3_6); tmp = vextq_f32(zero, line2_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_3_6); tmp = vextq_f32(zero, line3_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_10_13); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_3_6); tmp = vextq_f32(zero, line4_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_17_20); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_10_13); tmp = vextq_f32(zero, line5_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_31_34); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_24_27); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_17_20); tmp = vextq_f32(zero, line6_1, 3); tmp_4_0 = vmlaq_f32(tmp_4_0, tmp, kernel_38_41); tmp_4_1 = vmlaq_f32(tmp_4_1, tmp, kernel_31_34); tmp_4_2 = vmlaq_f32(tmp_4_2, tmp, kernel_24_27); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_2, 1); line2_1 = vextq_f32(line2_1, line2_2, 1); line3_1 = vextq_f32(line3_1, line3_2, 1); line4_1 = vextq_f32(line4_1, line4_2, 1); line5_1 = vextq_f32(line5_1, line5_2, 1); line6_1 = vextq_f32(line6_1, line6_2, 1); } /* bottom end1 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_2_5)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_9_12)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_16_19)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_37_40)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_28_31); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_2_5)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_9_12)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_16_19)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_23_26)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_30_33)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_0_3); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_21_24); float32x2_t tmp_2_2 = vadd_f32(vget_low_f32(tmp_4_2), vget_high_f32(tmp_4_2)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line3_1), vget_high_f32(kernel_2_5)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line4_1), vget_high_f32(kernel_9_12)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line5_1), vget_high_f32(kernel_16_19)); tmp_2_2 = vmla_f32(tmp_2_2, vget_low_f32(line6_1), vget_high_f32(kernel_23_26)); tmp2 = vget_lane_f32(tmp_2_2, 0) + vget_lane_f32(tmp_2_2, 1) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); } /* bottom end2 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; tmp0 += vgetq_lane_f32(line1_1, 0) * weight_buf[4]; tmp0 += vgetq_lane_f32(line2_1, 0) * weight_buf[11]; tmp0 += vgetq_lane_f32(line3_1, 0) * weight_buf[18]; tmp0 += vgetq_lane_f32(line4_1, 0) * weight_buf[25]; tmp0 += vgetq_lane_f32(line5_1, 0) * weight_buf[32]; tmp0 += vgetq_lane_f32(line6_1, 0) * weight_buf[39]; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_28_31); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; tmp1 += vgetq_lane_f32(line2_1, 0) * weight_buf[4]; tmp1 += vgetq_lane_f32(line3_1, 0) * weight_buf[11]; tmp1 += vgetq_lane_f32(line4_1, 0) * weight_buf[18]; tmp1 += vgetq_lane_f32(line5_1, 0) * weight_buf[25]; tmp1 += vgetq_lane_f32(line6_1, 0) * weight_buf[32]; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_0_3); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_21_24); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; tmp2 += vgetq_lane_f32(line3_1, 0) * weight_buf[4]; tmp2 += vgetq_lane_f32(line4_1, 0) * weight_buf[11]; tmp2 += vgetq_lane_f32(line5_1, 0) * weight_buf[18]; tmp2 += vgetq_lane_f32(line6_1, 0) * weight_buf[25]; *output_buf_2++ = elem_activation(tmp2, activation); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); } /* bottom end3 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line2, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_28_31); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); float32x4_t tmp_4_2 = vmulq_f32(line3, kernel_0_3); tmp_4_2 = vmlaq_f32(tmp_4_2, line4, kernel_7_10); tmp_4_2 = vmlaq_f32(tmp_4_2, line5, kernel_14_17); tmp_4_2 = vmlaq_f32(tmp_4_2, line6, kernel_21_24); tmp2 = vgetq_lane_f32(tmp_4_2, 0) + vgetq_lane_f32(tmp_4_2, 1) + vgetq_lane_f32(tmp_4_2, 2) + vgetq_lane_f32(tmp_4_2, 3) + bias_c; *output_buf_2++ = elem_activation(tmp2, activation); } } } void depthwise_conv_k7s2(float* input, float* weight, float* bias, float* output, int input_h, int input_w, int channel, int output_h, int output_w, int activation, int num_thread) { int input_hw = input_h * input_w; int output_hw = output_h * output_w; int mid_w = output_w - 3; int mid_h = output_h - 3; int remain_h = input_h & 0x1; int remain_w = input_w & 0x1; if (remain_h) mid_h--; if (remain_w) mid_w--; int mid_block = mid_w >> 2; int w = 0; //#pragma omp parallel for num_threads(num_thread) for (int c = 0; c < channel; c++) { float tmp0, tmp1; float* output_buf = output + c * output_hw; float* output_buf_1 = output_buf + output_w; float* weight_buf = weight + c * 49; float bias_c = bias ? bias[c] : 0; float* input_1 = input + c * input_hw; float* input_2 = input_1 + input_w; float* input_3 = input_2 + input_w; float* input_4 = input_3 + input_w; float* input_5 = input_4 + input_w; float* input_6 = input_5 + input_w; float32x4_t kernel_0_3 = vld1q_f32(weight_buf); float32x4_t kernel_4_7 = vld1q_f32(weight_buf + 4); float32x4_t kernel_8_11 = vld1q_f32(weight_buf + 8); float32x4_t kernel_12_15 = vld1q_f32(weight_buf + 12); float32x4_t kernel_16_19 = vld1q_f32(weight_buf + 16); float32x4_t kernel_20_23 = vld1q_f32(weight_buf + 20); float32x4_t kernel_24_27 = vld1q_f32(weight_buf + 24); float32x4_t kernel_28_31 = vld1q_f32(weight_buf + 28); float32x4_t kernel_32_35 = vld1q_f32(weight_buf + 32); float32x4_t kernel_36_39 = vld1q_f32(weight_buf + 36); float32x4_t kernel_40_43 = vld1q_f32(weight_buf + 40); float32x4_t kernel_44_47 = vld1q_f32(weight_buf + 44); float32x4_t kernel_48_51 = vld1q_f32(weight_buf + 48); float32x4_t line1 = vld1q_f32(input_1); float32x4_t line2 = vld1q_f32(input_2); float32x4_t line3 = vld1q_f32(input_3); float32x4_t line4 = vld1q_f32(input_4); float32x4_t line5 = vld1q_f32(input_5); float32x4_t line6 = vld1q_f32(input_6); float32x4_t kernel_10_13 = vextq_f32(kernel_8_11, kernel_12_15, 2); float32x4_t kernel_17_20 = vextq_f32(kernel_16_19, kernel_20_23, 1); float32x4_t kernel_31_34 = vextq_f32(kernel_28_31, kernel_32_35, 3); float32x4_t kernel_38_41 = vextq_f32(kernel_36_39, kernel_40_43, 2); float32x4_t kernel_45_48 = vextq_f32(kernel_44_47, kernel_48_51, 1); /* top left1 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_31_34); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_38_41); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_45_48); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } float32x4_t line1_1 = vld1q_f32(input_1 + 4); float32x4_t line2_1 = vld1q_f32(input_2 + 4); float32x4_t line3_1 = vld1q_f32(input_3 + 4); float32x4_t line4_1 = vld1q_f32(input_4 + 4); float32x4_t line5_1 = vld1q_f32(input_5 + 4); float32x4_t line6_1 = vld1q_f32(input_6 + 4); float32x4_t kernel_15_18 = vextq_f32(kernel_12_15, kernel_16_19, 3); float32x4_t kernel_22_25 = vextq_f32(kernel_20_23, kernel_24_27, 2); float32x4_t kernel_29_32 = vextq_f32(kernel_28_31, kernel_32_35, 1); float32x4_t kernel_43_46 = vextq_f32(kernel_40_43, kernel_44_47, 3); /* top left2 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_36_39); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_43_46); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_8_11); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_15_18); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_22_25); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_29_32); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_36_39); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_43_46); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line1_1), vget_high_f32(kernel_10_13)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_24_27)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_31_34)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_38_41)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_45_48)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } /* top mid */ float32x4x2_t line_1_01 = vuzpq_f32(line1, line1_1); float32x4x2_t line_2_01 = vuzpq_f32(line2, line2_1); float32x4x2_t line_3_01 = vuzpq_f32(line3, line3_1); float32x4x2_t line_4_01 = vuzpq_f32(line4, line4_1); float32x4x2_t line_5_01 = vuzpq_f32(line5, line5_1); float32x4x2_t line_6_01 = vuzpq_f32(line6, line6_1); for (w = 0; w < mid_block; w++) { float32x4x2_t line_1_23 = vld2q_f32(input_1 + 8 + 8 * w); float32x4x2_t line_2_23 = vld2q_f32(input_2 + 8 + 8 * w); float32x4x2_t line_3_23 = vld2q_f32(input_3 + 8 + 8 * w); float32x4x2_t line_4_23 = vld2q_f32(input_4 + 8 + 8 * w); float32x4x2_t line_5_23 = vld2q_f32(input_5 + 8 + 8 * w); float32x4x2_t line_6_23 = vld2q_f32(input_6 + 8 + 8 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); float32x4_t tmp_4_1 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_1_01.val[1], vget_low_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_1_01.val[1], vget_high_f32(kernel_4_7), 1); float32x4_t tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_8_11), 0); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 1); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_2_01.val[1], vget_low_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_2_01.val[1], vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 1); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_20_23), 0); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_3_01.val[1], vget_high_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_3_01.val[1], vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 0); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 1); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_4_01.val[1], vget_high_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_4_01.val[1], vget_low_f32(kernel_28_31), 0); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_28_31), 1); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 0); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_28_31), 1); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_32_35), 0); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_32_35), 1); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_32_35), 0); /* line5 */ tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_5_01.val[1], vget_high_f32(kernel_32_35), 1); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_36_39), 0); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_36_39), 1); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_36_39), 0); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_36_39), 1); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 3); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_40_43), 0); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 3); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_40_43), 1); /* line6 */ tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_6_01.val[1], vget_high_f32(kernel_40_43), 0); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_40_43), 1); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_44_47), 0); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_44_47), 1); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 2); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_44_47), 0); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 3); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_44_47), 1); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 3); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_0 = vector_activation(tmp_4_0, activation); tmp_4_1 = vector_activation(tmp_4_1, activation); vst1q_f32(output_buf, tmp_4_0); vst1q_f32(output_buf_1, tmp_4_1); output_buf += 4; output_buf_1 += 4; line_1_01 = line_1_23; line_2_01 = line_2_23; line_3_01 = line_3_23; line_4_01 = line_4_23; line_5_01 = line_5_23; line_6_01 = line_6_23; } line_1_01 = vzipq_f32(line_1_01.val[0], line_1_01.val[1]); line_2_01 = vzipq_f32(line_2_01.val[0], line_2_01.val[1]); line_3_01 = vzipq_f32(line_3_01.val[0], line_3_01.val[1]); line_4_01 = vzipq_f32(line_4_01.val[0], line_4_01.val[1]); line_5_01 = vzipq_f32(line_5_01.val[0], line_5_01.val[1]); line_6_01 = vzipq_f32(line_6_01.val[0], line_6_01.val[1]); line1 = line_1_01.val[0]; line1_1 = line_1_01.val[1]; line2 = line_2_01.val[0]; line2_1 = line_2_01.val[1]; line3 = line_3_01.val[0]; line3_1 = line_3_01.val[1]; line4 = line_4_01.val[0]; line4_1 = line_4_01.val[1]; line5 = line_5_01.val[0]; line5_1 = line_5_01.val[1]; line6 = line_6_01.val[0]; line6_1 = line_6_01.val[1]; float32x4_t kernel_7_10 = vextq_f32(kernel_4_7, kernel_8_11, 3); float32x4_t kernel_14_17 = vextq_f32(kernel_12_15, kernel_16_19, 2); float32x4_t kernel_21_24 = vextq_f32(kernel_20_23, kernel_24_27, 1); float32x4_t kernel_35_38 = vextq_f32(kernel_32_35, kernel_36_39, 3); float32x4_t kernel_42_45 = vextq_f32(kernel_40_43, kernel_44_47, 2); float32x4_t zero = vdupq_n_f32(0.0); float32x4_t kernel_0789 = vextq_f32(zero, kernel_7_10, 3); float32x4_t kernel_0141516 = vextq_f32(zero, kernel_14_17, 3); float32x4_t kernel_0212223 = vextq_f32(zero, kernel_21_24, 3); float32x4_t kernel_0282930 = vextq_f32(zero, kernel_28_31, 3); float32x4_t kernel_0353637 = vextq_f32(zero, kernel_35_38, 3); float32x4_t kernel_0424344 = vextq_f32(zero, kernel_42_45, 3); for (w = mid_block * 4; w < mid_w; w++) { float32x4_t line1_2 = vld1q_f32(input_1 + 8 + 2 * w); float32x4_t line2_2 = vld1q_f32(input_2 + 8 + 2 * w); float32x4_t line3_2 = vld1q_f32(input_3 + 8 + 2 * w); float32x4_t line4_2 = vld1q_f32(input_4 + 8 + 2 * w); float32x4_t line5_2 = vld1q_f32(input_5 + 8 + 2 * w); float32x4_t line6_2 = vld1q_f32(input_6 + 8 + 2 * w); float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0353637); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0424344); tmp_4_0 = vmlaq_f32(tmp_4_0, line1_1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line2_1, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line3_1, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line4_1, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_0789); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_0141516); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_0212223); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_0282930); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_0353637); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_0424344); tmp_4_1 = vmlaq_f32(tmp_4_1, line1_1, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, line2_1, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line3_1, kernel_24_27); tmp_4_1 = vmlaq_f32(tmp_4_1, line4_1, kernel_31_34); tmp_4_1 = vmlaq_f32(tmp_4_1, line5_1, kernel_38_41); tmp_4_1 = vmlaq_f32(tmp_4_1, line6_1, kernel_45_48); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); line1_1 = vextq_f32(line1_1, line1_2, 2); line2_1 = vextq_f32(line2_1, line2_2, 2); line3_1 = vextq_f32(line3_1, line3_2, 2); line4_1 = vextq_f32(line4_1, line4_2, 2); line5_1 = vextq_f32(line5_1, line5_2, 2); line6_1 = vextq_f32(line6_1, line6_2, 2); } /* top right */ if (remain_w) { float32x4_t kernel_9_12 = vextq_f32(kernel_8_11, kernel_12_15, 1); float32x4_t kernel_23_26 = vextq_f32(kernel_20_23, kernel_24_27, 3); float32x4_t kernel_30_33 = vextq_f32(kernel_28_31, kernel_32_35, 2); float32x4_t kernel_37_40 = vextq_f32(kernel_36_39, kernel_40_43, 1); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_37_40)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_44_47)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_42_45); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line1_1), vget_high_f32(kernel_9_12)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_high_f32(kernel_16_19)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_23_26)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_30_33)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_37_40)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_44_47)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_21_24); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_28_31); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_35_38); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_42_45); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } } else { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0353637); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0424344); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_low_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_low_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_low_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line1, kernel_0789); tmp_4_1 = vmlaq_f32(tmp_4_1, line2, kernel_0141516); tmp_4_1 = vmlaq_f32(tmp_4_1, line3, kernel_0212223); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_0282930); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_0353637); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_0424344); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line1_1), vget_low_f32(kernel_10_13)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line2_1), vget_low_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_low_f32(kernel_24_27)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_low_f32(kernel_31_34)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_low_f32(kernel_38_41)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_low_f32(kernel_45_48)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } float* input_7; output_buf = output_buf_1; float32x4_t kernel_3_6 = vextq_f32(kernel_0_3, kernel_4_7, 3); float32x4_t kernel_1_4 = vextq_f32(kernel_0_3, kernel_4_7, 1); float32x4_t kernel_0012 = vextq_f32(zero, kernel_0_3, 3); /* mid */ for (int h = 0; h < mid_h; h++) { input_1 = input + c * input_hw + input_w * (1 + 2 * h); input_2 = input_1 + input_w; input_3 = input_2 + input_w; input_4 = input_3 + input_w; input_5 = input_4 + input_w; input_6 = input_5 + input_w; input_7 = input_6 + input_w; line1 = vld1q_f32(input_1); line2 = vld1q_f32(input_2); line3 = vld1q_f32(input_3); line4 = vld1q_f32(input_4); line5 = vld1q_f32(input_5); line6 = vld1q_f32(input_6); float32x4_t line7 = vld1q_f32(input_7); /* mid left 1 */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line1_1 = vld1q_f32(input_1 + 4); line2_1 = vld1q_f32(input_2 + 4); line3_1 = vld1q_f32(input_3 + 4); line4_1 = vld1q_f32(input_4 + 4); line5_1 = vld1q_f32(input_5 + 4); line6_1 = vld1q_f32(input_6 + 4); /* mid left 2 */ float32x4_t line7_1 = vld1q_f32(input_7 + 4); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_1_4); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_8_11); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_15_18); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_36_39); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_43_46); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line7_1), vget_high_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line_1_01 = vuzpq_f32(line1, line1_1); line_2_01 = vuzpq_f32(line2, line2_1); line_3_01 = vuzpq_f32(line3, line3_1); line_4_01 = vuzpq_f32(line4, line4_1); line_5_01 = vuzpq_f32(line5, line5_1); line_6_01 = vuzpq_f32(line6, line6_1); float32x4x2_t line_7_01 = vuzpq_f32(line7, line7_1); /* mid mid */ for (w = 0; w < mid_block; w++) { float32x4x2_t line_1_23 = vld2q_f32(input_1 + 8 + 8 * w); float32x4x2_t line_2_23 = vld2q_f32(input_2 + 8 + 8 * w); float32x4x2_t line_3_23 = vld2q_f32(input_3 + 8 + 8 * w); float32x4x2_t line_4_23 = vld2q_f32(input_4 + 8 + 8 * w); float32x4x2_t line_5_23 = vld2q_f32(input_5 + 8 + 8 * w); float32x4x2_t line_6_23 = vld2q_f32(input_6 + 8 + 8 * w); float32x4x2_t line_7_23 = vld2q_f32(input_7 + 8 + 8 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_1_01.val[1], vget_low_f32(kernel_0_3), 0); float32x4_t tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_4_7), 0); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_2_01.val[1], vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 1); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_3_01.val[1], vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_20_23), 0); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_4_01.val[1], vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); /* line5 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_5_01.val[1], vget_low_f32(kernel_28_31), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); /* line6 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_6_01.val[1], vget_high_f32(kernel_32_35), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); /* line7 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_7_01.val[1], vget_high_f32(kernel_40_43), 0); tmp = vextq_f32(line_7_01.val[0], line_7_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_40_43), 1); tmp = vextq_f32(line_7_01.val[1], line_7_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 0); tmp = vextq_f32(line_7_01.val[0], line_7_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_44_47), 1); tmp = vextq_f32(line_7_01.val[1], line_7_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 0); tmp = vextq_f32(line_7_01.val[0], line_7_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_44_47), 1); tmp = vextq_f32(line_7_01.val[1], line_7_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_48_51), 0); tmp_4_0 = vector_activation(tmp_4_0, activation); vst1q_f32(output_buf, tmp_4_0); output_buf += 4; line_1_01 = line_1_23; line_2_01 = line_2_23; line_3_01 = line_3_23; line_4_01 = line_4_23; line_5_01 = line_5_23; line_6_01 = line_6_23; line_7_01 = line_7_23; } line_1_01 = vzipq_f32(line_1_01.val[0], line_1_01.val[1]); line_2_01 = vzipq_f32(line_2_01.val[0], line_2_01.val[1]); line_3_01 = vzipq_f32(line_3_01.val[0], line_3_01.val[1]); line_4_01 = vzipq_f32(line_4_01.val[0], line_4_01.val[1]); line_5_01 = vzipq_f32(line_5_01.val[0], line_5_01.val[1]); line_6_01 = vzipq_f32(line_6_01.val[0], line_6_01.val[1]); line_7_01 = vzipq_f32(line_7_01.val[0], line_7_01.val[1]); line1 = line_1_01.val[0]; line1_1 = line_1_01.val[1]; line2 = line_2_01.val[0]; line2_1 = line_2_01.val[1]; line3 = line_3_01.val[0]; line3_1 = line_3_01.val[1]; line4 = line_4_01.val[0]; line4_1 = line_4_01.val[1]; line5 = line_5_01.val[0]; line5_1 = line_5_01.val[1]; line6 = line_6_01.val[0]; line6_1 = line_6_01.val[1]; line7 = line_7_01.val[0]; line7_1 = line_7_01.val[1]; for (w = mid_block * 4; w < mid_w; w++) { float32x4_t line1_2 = vld1q_f32(input_1 + 8 + 2 * w); float32x4_t line2_2 = vld1q_f32(input_2 + 8 + 2 * w); float32x4_t line3_2 = vld1q_f32(input_3 + 8 + 2 * w); float32x4_t line4_2 = vld1q_f32(input_4 + 8 + 2 * w); float32x4_t line5_2 = vld1q_f32(input_5 + 8 + 2 * w); float32x4_t line6_2 = vld1q_f32(input_6 + 8 + 2 * w); float32x4_t line7_2 = vld1q_f32(input_7 + 8 + 2 * w); float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_0353637); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_0424344); tmp_4_0 = vmlaq_f32(tmp_4_0, line1_1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2_1, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3_1, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4_1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5_1, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6_1, kernel_38_41); tmp_4_0 = vmlaq_f32(tmp_4_0, line7_1, kernel_45_48); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); line7 = vextq_f32(line7, line7_1, 2); line1_1 = vextq_f32(line1_1, line1_2, 2); line2_1 = vextq_f32(line2_1, line2_2, 2); line3_1 = vextq_f32(line3_1, line3_2, 2); line4_1 = vextq_f32(line4_1, line4_2, 2); line5_1 = vextq_f32(line5_1, line5_2, 2); line6_1 = vextq_f32(line6_1, line6_2, 2); line7_1 = vextq_f32(line7_1, line7_2, 2); } /* mid right */ if (remain_w) { float32x4_t kernel_9_12 = vextq_f32(kernel_8_11, kernel_12_15, 1); float32x4_t kernel_23_26 = vextq_f32(kernel_20_23, kernel_24_27, 3); float32x4_t kernel_30_33 = vextq_f32(kernel_28_31, kernel_32_35, 2); float32x4_t kernel_37_40 = vextq_f32(kernel_36_39, kernel_40_43, 1); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line7 = vextq_f32(line7, line7_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); line7_1 = vextq_f32(line7_1, line7_1, 1); float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_4_7)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_9_12)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_16_19)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_37_40)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line7_1), vget_high_f32(kernel_44_47)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); line7 = vextq_f32(line7, line7_1, 2); tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_42_45); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } else { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_0353637); tmp_4_0 = vmlaq_f32(tmp_4_0, line7, kernel_0424344); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_low_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_low_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_low_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_low_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_low_f32(kernel_38_41)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line7_1), vget_low_f32(kernel_45_48)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } } /* bottom */ if (remain_h) { output_buf_1 = output_buf + output_w; input_1 = input + c * input_hw + (input_h - 6) * input_w; input_2 = input_1 + input_w; input_3 = input_2 + input_w; input_4 = input_3 + input_w; input_5 = input_4 + input_w; input_6 = input_5 + input_w; line1 = vld1q_f32(input_1); line2 = vld1q_f32(input_2); line3 = vld1q_f32(input_3); line4 = vld1q_f32(input_4); line5 = vld1q_f32(input_5); line6 = vld1q_f32(input_6); /* bottom 1 left */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_38_41); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_3_6); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_24_27); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } line1_1 = vld1q_f32(input_1 + 4); line2_1 = vld1q_f32(input_2 + 4); line3_1 = vld1q_f32(input_3 + 4); line4_1 = vld1q_f32(input_4 + 4); line5_1 = vld1q_f32(input_5 + 4); line6_1 = vld1q_f32(input_6 + 4); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_1_4); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_8_11); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_15_18); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_29_32); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_36_39); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_38_41)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_1_4); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_8_11); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_15_18); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_22_25); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_high_f32(kernel_3_6)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_10_13)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_24_27)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } line_1_01 = vuzpq_f32(line1, line1_1); line_2_01 = vuzpq_f32(line2, line2_1); line_3_01 = vuzpq_f32(line3, line3_1); line_4_01 = vuzpq_f32(line4, line4_1); line_5_01 = vuzpq_f32(line5, line5_1); line_6_01 = vuzpq_f32(line6, line6_1); /* bottom 1 mid */ for (w = 0; w < mid_block; w++) { float32x4x2_t line_1_23 = vld2q_f32(input_1 + 8 + 8 * w); float32x4x2_t line_2_23 = vld2q_f32(input_2 + 8 + 8 * w); float32x4x2_t line_3_23 = vld2q_f32(input_3 + 8 + 8 * w); float32x4x2_t line_4_23 = vld2q_f32(input_4 + 8 + 8 * w); float32x4x2_t line_5_23 = vld2q_f32(input_5 + 8 + 8 * w); float32x4x2_t line_6_23 = vld2q_f32(input_6 + 8 + 8 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); float32x4_t tmp_4_1 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_1_01.val[1], vget_low_f32(kernel_0_3), 0); float32x4_t tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_4_7), 0); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_2_01.val[1], vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 1); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_3_01.val[1], vget_high_f32(kernel_12_15), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_3_01.val[1], vget_low_f32(kernel_0_3), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_12_15), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_0_3), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_4_7), 0); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_4_01.val[1], vget_low_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_4_01.val[1], vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_8_11), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_12_15), 1); /* line5 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_5_01.val[1], vget_low_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_5_01.val[1], vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_16_19), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_20_23), 0); /* line6 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_6_01.val[1], vget_high_f32(kernel_32_35), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, line_6_01.val[1], vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_36_39), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line_6_01.val[0], line_6_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 0); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line_6_01.val[1], line_6_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_40_43), 1); tmp_4_1 = vmlaq_lane_f32(tmp_4_1, tmp, vget_high_f32(kernel_24_27), 1); tmp_4_0 = vector_activation(tmp_4_0, activation); vst1q_f32(output_buf, tmp_4_0); output_buf += 4; tmp_4_1 = vector_activation(tmp_4_1, activation); vst1q_f32(output_buf_1, tmp_4_1); output_buf_1 += 4; line_1_01 = line_1_23; line_2_01 = line_2_23; line_3_01 = line_3_23; line_4_01 = line_4_23; line_5_01 = line_5_23; line_6_01 = line_6_23; } line_1_01 = vzipq_f32(line_1_01.val[0], line_1_01.val[1]); line_2_01 = vzipq_f32(line_2_01.val[0], line_2_01.val[1]); line_3_01 = vzipq_f32(line_3_01.val[0], line_3_01.val[1]); line_4_01 = vzipq_f32(line_4_01.val[0], line_4_01.val[1]); line_5_01 = vzipq_f32(line_5_01.val[0], line_5_01.val[1]); line_6_01 = vzipq_f32(line_6_01.val[0], line_6_01.val[1]); line1 = line_1_01.val[0]; line1_1 = line_1_01.val[1]; line2 = line_2_01.val[0]; line2_1 = line_2_01.val[1]; line3 = line_3_01.val[0]; line3_1 = line_3_01.val[1]; line4 = line_4_01.val[0]; line4_1 = line_4_01.val[1]; line5 = line_5_01.val[0]; line5_1 = line_5_01.val[1]; line6 = line_6_01.val[0]; line6_1 = line_6_01.val[1]; for (w = mid_block * 4; w < mid_w; w++) { float32x4_t line1_2 = vld1q_f32(input_1 + 8 + 2 * w); float32x4_t line2_2 = vld1q_f32(input_2 + 8 + 2 * w); float32x4_t line3_2 = vld1q_f32(input_3 + 8 + 2 * w); float32x4_t line4_2 = vld1q_f32(input_4 + 8 + 2 * w); float32x4_t line5_2 = vld1q_f32(input_5 + 8 + 2 * w); float32x4_t line6_2 = vld1q_f32(input_6 + 8 + 2 * w); float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_0353637); tmp_4_0 = vmlaq_f32(tmp_4_0, line1_1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2_1, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3_1, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4_1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5_1, kernel_31_34); tmp_4_0 = vmlaq_f32(tmp_4_0, line6_1, kernel_38_41); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_0012); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_0789); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_0141516); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_0212223); tmp_4_1 = vmlaq_f32(tmp_4_1, line3_1, kernel_3_6); tmp_4_1 = vmlaq_f32(tmp_4_1, line4_1, kernel_10_13); tmp_4_1 = vmlaq_f32(tmp_4_1, line5_1, kernel_17_20); tmp_4_1 = vmlaq_f32(tmp_4_1, line6_1, kernel_24_27); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); line1_1 = vextq_f32(line1_1, line1_2, 2); line2_1 = vextq_f32(line2_1, line2_2, 2); line3_1 = vextq_f32(line3_1, line3_2, 2); line4_1 = vextq_f32(line4_1, line4_2, 2); line5_1 = vextq_f32(line5_1, line5_2, 2); line6_1 = vextq_f32(line6_1, line6_2, 2); } /* bottom 1 right */ if (remain_w) { float32x4_t kernel_9_12 = vextq_f32(kernel_8_11, kernel_12_15, 1); float32x4_t kernel_23_26 = vextq_f32(kernel_20_23, kernel_24_27, 3); float32x4_t kernel_30_33 = vextq_f32(kernel_28_31, kernel_32_35, 2); float32x4_t kernel_37_40 = vextq_f32(kernel_36_39, kernel_40_43, 1); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line6 = vextq_f32(line6, line6_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); line6_1 = vextq_f32(line6_1, line6_1, 1); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_4_7)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_9_12)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_16_19)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_30_33)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_high_f32(kernel_37_40)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_21_24); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_low_f32(kernel_4_7)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_high_f32(kernel_9_12)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_high_f32(kernel_16_19)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_high_f32(kernel_23_26)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line6 = vextq_f32(line6, line6_1, 2); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_35_38); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_0_3); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_7_10); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_14_17); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_21_24); tmp1 = vgetq_lane_f32(tmp_4_1, 0) + vgetq_lane_f32(tmp_4_1, 1) + vgetq_lane_f32(tmp_4_1, 2) + vgetq_lane_f32(tmp_4_1, 3) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } } else { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line6, kernel_0353637); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_low_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_low_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_low_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_low_f32(kernel_31_34)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line6_1), vget_low_f32(kernel_38_41)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); float32x4_t tmp_4_1 = vmulq_f32(line3, kernel_0012); tmp_4_1 = vmlaq_f32(tmp_4_1, line4, kernel_0789); tmp_4_1 = vmlaq_f32(tmp_4_1, line5, kernel_0141516); tmp_4_1 = vmlaq_f32(tmp_4_1, line6, kernel_0212223); float32x2_t tmp_2_1 = vadd_f32(vget_low_f32(tmp_4_1), vget_high_f32(tmp_4_1)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line3_1), vget_low_f32(kernel_3_6)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line4_1), vget_low_f32(kernel_10_13)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line5_1), vget_low_f32(kernel_17_20)); tmp_2_1 = vmla_f32(tmp_2_1, vget_low_f32(line6_1), vget_low_f32(kernel_24_27)); tmp1 = vget_lane_f32(tmp_2_1, 0) + vget_lane_f32(tmp_2_1, 1) + bias_c; *output_buf_1++ = elem_activation(tmp1, activation); } } else { input_1 = input + c * input_hw + (input_h - 5) * input_w; input_2 = input_1 + input_w; input_3 = input_2 + input_w; input_4 = input_3 + input_w; input_5 = input_4 + input_w; line1 = vld1q_f32(input_1); line2 = vld1q_f32(input_2); line3 = vld1q_f32(input_3); line4 = vld1q_f32(input_4); line5 = vld1q_f32(input_5); /* bottom 0 left */ { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_31_34); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line1_1 = vld1q_f32(input_1 + 4); line2_1 = vld1q_f32(input_2 + 4); line3_1 = vld1q_f32(input_3 + 4); line4_1 = vld1q_f32(input_4 + 4); line5_1 = vld1q_f32(input_5 + 4); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_1_4); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_8_11); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_15_18); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_22_25); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_29_32); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_high_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_31_34)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line_1_01 = vuzpq_f32(line1, line1_1); line_2_01 = vuzpq_f32(line2, line2_1); line_3_01 = vuzpq_f32(line3, line3_1); line_4_01 = vuzpq_f32(line4, line4_1); line_5_01 = vuzpq_f32(line5, line5_1); /* bottom 0 mid */ for (w = 0; w < mid_block; w++) { float32x4x2_t line_1_23 = vld2q_f32(input_1 + 8 + 8 * w); float32x4x2_t line_2_23 = vld2q_f32(input_2 + 8 + 8 * w); float32x4x2_t line_3_23 = vld2q_f32(input_3 + 8 + 8 * w); float32x4x2_t line_4_23 = vld2q_f32(input_4 + 8 + 8 * w); float32x4x2_t line_5_23 = vld2q_f32(input_5 + 8 + 8 * w); float32x4_t tmp_4_0 = vdupq_n_f32(bias_c); /* line1 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_1_01.val[1], vget_low_f32(kernel_0_3), 0); float32x4_t tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_0_3), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 0); tmp = vextq_f32(line_1_01.val[0], line_1_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_4_7), 1); tmp = vextq_f32(line_1_01.val[1], line_1_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_4_7), 0); /* line2 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_2_01.val[1], vget_high_f32(kernel_4_7), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_8_11), 1); tmp = vextq_f32(line_2_01.val[0], line_2_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 0); tmp = vextq_f32(line_2_01.val[1], line_2_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_12_15), 1); /* line3 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_3_01.val[1], vget_high_f32(kernel_12_15), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_12_15), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_16_19), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 0); tmp = vextq_f32(line_3_01.val[0], line_3_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_16_19), 1); tmp = vextq_f32(line_3_01.val[1], line_3_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_20_23), 0); /* line4 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_4_01.val[1], vget_low_f32(kernel_20_23), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_20_23), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_24_27), 1); tmp = vextq_f32(line_4_01.val[0], line_4_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 0); tmp = vextq_f32(line_4_01.val[1], line_4_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_24_27), 1); /* line5 */ tmp_4_0 = vmlaq_lane_f32(tmp_4_0, line_5_01.val[1], vget_low_f32(kernel_28_31), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_28_31), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 1); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_28_31), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 2); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 0); tmp = vextq_f32(line_5_01.val[0], line_5_23.val[0], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_low_f32(kernel_32_35), 1); tmp = vextq_f32(line_5_01.val[1], line_5_23.val[1], 3); tmp_4_0 = vmlaq_lane_f32(tmp_4_0, tmp, vget_high_f32(kernel_32_35), 0); tmp_4_0 = vector_activation(tmp_4_0, activation); vst1q_f32(output_buf, tmp_4_0); output_buf += 4; line_1_01 = line_1_23; line_2_01 = line_2_23; line_3_01 = line_3_23; line_4_01 = line_4_23; line_5_01 = line_5_23; } line_1_01 = vzipq_f32(line_1_01.val[0], line_1_01.val[1]); line_2_01 = vzipq_f32(line_2_01.val[0], line_2_01.val[1]); line_3_01 = vzipq_f32(line_3_01.val[0], line_3_01.val[1]); line_4_01 = vzipq_f32(line_4_01.val[0], line_4_01.val[1]); line_5_01 = vzipq_f32(line_5_01.val[0], line_5_01.val[1]); line1 = line_1_01.val[0]; line1_1 = line_1_01.val[1]; line2 = line_2_01.val[0]; line2_1 = line_2_01.val[1]; line3 = line_3_01.val[0]; line3_1 = line_3_01.val[1]; line4 = line_4_01.val[0]; line4_1 = line_4_01.val[1]; line5 = line_5_01.val[0]; line5_1 = line_5_01.val[1]; for (w = mid_block * 4; w < mid_w; w++) { float32x4_t line1_2 = vld1q_f32(input_1 + 8 + 2 * w); float32x4_t line2_2 = vld1q_f32(input_2 + 8 + 2 * w); float32x4_t line3_2 = vld1q_f32(input_3 + 8 + 2 * w); float32x4_t line4_2 = vld1q_f32(input_4 + 8 + 2 * w); float32x4_t line5_2 = vld1q_f32(input_5 + 8 + 2 * w); float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); tmp_4_0 = vmlaq_f32(tmp_4_0, line1_1, kernel_3_6); tmp_4_0 = vmlaq_f32(tmp_4_0, line2_1, kernel_10_13); tmp_4_0 = vmlaq_f32(tmp_4_0, line3_1, kernel_17_20); tmp_4_0 = vmlaq_f32(tmp_4_0, line4_1, kernel_24_27); tmp_4_0 = vmlaq_f32(tmp_4_0, line5_1, kernel_31_34); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); line1_1 = vextq_f32(line1_1, line1_2, 2); line2_1 = vextq_f32(line2_1, line2_2, 2); line3_1 = vextq_f32(line3_1, line3_2, 2); line4_1 = vextq_f32(line4_1, line4_2, 2); line5_1 = vextq_f32(line5_1, line5_2, 2); } /* bottom 0 right */ if (remain_w) { float32x4_t kernel_9_12 = vextq_f32(kernel_8_11, kernel_12_15, 1); float32x4_t kernel_23_26 = vextq_f32(kernel_20_23, kernel_24_27, 3); float32x4_t kernel_30_33 = vextq_f32(kernel_28_31, kernel_32_35, 2); line1 = vextq_f32(line1, line1_1, 1); line2 = vextq_f32(line2, line2_1, 1); line3 = vextq_f32(line3, line3_1, 1); line4 = vextq_f32(line4, line4_1, 1); line5 = vextq_f32(line5, line5_1, 1); line1_1 = vextq_f32(line1_1, line1_1, 1); line2_1 = vextq_f32(line2_1, line2_1, 1); line3_1 = vextq_f32(line3_1, line3_1, 1); line4_1 = vextq_f32(line4_1, line4_1, 1); line5_1 = vextq_f32(line5_1, line5_1, 1); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_4_7)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_high_f32(kernel_9_12)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_high_f32(kernel_16_19)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_high_f32(kernel_23_26)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_high_f32(kernel_30_33)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } line1 = vextq_f32(line1, line1_1, 2); line2 = vextq_f32(line2, line2_1, 2); line3 = vextq_f32(line3, line3_1, 2); line4 = vextq_f32(line4, line4_1, 2); line5 = vextq_f32(line5, line5_1, 2); { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0_3); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_7_10); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_14_17); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_21_24); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_28_31); tmp0 = vgetq_lane_f32(tmp_4_0, 0) + vgetq_lane_f32(tmp_4_0, 1) + vgetq_lane_f32(tmp_4_0, 2) + vgetq_lane_f32(tmp_4_0, 3) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } } else { float32x4_t tmp_4_0 = vmulq_f32(line1, kernel_0012); tmp_4_0 = vmlaq_f32(tmp_4_0, line2, kernel_0789); tmp_4_0 = vmlaq_f32(tmp_4_0, line3, kernel_0141516); tmp_4_0 = vmlaq_f32(tmp_4_0, line4, kernel_0212223); tmp_4_0 = vmlaq_f32(tmp_4_0, line5, kernel_0282930); float32x2_t tmp_2_0 = vadd_f32(vget_low_f32(tmp_4_0), vget_high_f32(tmp_4_0)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line1_1), vget_low_f32(kernel_3_6)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line2_1), vget_low_f32(kernel_10_13)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line3_1), vget_low_f32(kernel_17_20)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line4_1), vget_low_f32(kernel_24_27)); tmp_2_0 = vmla_f32(tmp_2_0, vget_low_f32(line5_1), vget_low_f32(kernel_31_34)); tmp0 = vget_lane_f32(tmp_2_0, 0) + vget_lane_f32(tmp_2_0, 1) + bias_c; *output_buf++ = elem_activation(tmp0, activation); } } } } #endif
global.h
#ifndef GLOBAL_H #define GLOBAL_H #pragma omp declare target extern int * device_arr; #pragma omp end declare target #endif
t000.c
#include<stdint.h> #include<stdlib.h> #include<stdio.h> #include<omp.h> typedef struct {int64_t nteam; int64_t nthread;} tinfo; int main(int argc, char **argv) { tinfo *t = malloc(sizeof(tinfo)); t->nteam = -1; t->nthread = -1; #pragma omp target teams map(t[0:1]) { #pragma omp parallel { if(omp_get_team_num() == 0 && omp_get_thread_num() == 0){ t->nteam = omp_get_num_teams(); t->nthread = omp_get_num_threads(); } } } printf("nteam: %ld nthread: %ld\n", t->nteam, t->nthread); int ret = 0; if(t->nteam <= 0 || t->nthread <= 0) ret = 1; free(t); return ret; }
kmp_set_dispatch_buf.c
// RUN: %libomp-compile && %libomp-run 7 // RUN: %libomp-run 0 && %libomp-run -1 // RUN: %libomp-run 1 && %libomp-run 2 && %libomp-run 5 // RUN: %libomp-compile -DMY_SCHEDULE=guided && %libomp-run 7 // RUN: %libomp-run 1 && %libomp-run 2 && %libomp-run 5 // UNSUPPORTED: clang-11, clang-12 #include <stdio.h> #include <omp.h> #include <stdlib.h> #include <limits.h> #include "omp_testsuite.h" #define INCR 7 #define MY_MAX 200 #define MY_MIN -200 #ifndef MY_SCHEDULE # define MY_SCHEDULE dynamic #endif int num_disp_buffers, num_loops; int a, b, a_known_value, b_known_value; int test_kmp_set_disp_num_buffers() { int success = 1; a = 0; b = 0; // run many small dynamic loops to stress the dispatch buffer system #pragma omp parallel { int i,j; for (j = 0; j < num_loops; j++) { #pragma omp for schedule(MY_SCHEDULE) nowait for (i = MY_MIN; i < MY_MAX; i+=INCR) { #pragma omp atomic a++; } #pragma omp for schedule(MY_SCHEDULE) nowait for (i = MY_MAX; i >= MY_MIN; i-=INCR) { #pragma omp atomic b++; } } } // detect failure if (a != a_known_value || b != b_known_value) { success = 0; printf("a = %d (should be %d), b = %d (should be %d)\n", a, a_known_value, b, b_known_value); } return success; } int main(int argc, char** argv) { int i,j; int num_failed=0; if (argc != 2) { fprintf(stderr, "usage: %s num_disp_buffers\n", argv[0]); exit(1); } // set the number of dispatch buffers num_disp_buffers = atoi(argv[1]); kmp_set_disp_num_buffers(num_disp_buffers); // figure out the known values to compare with calculated result a_known_value = 0; b_known_value = 0; // if specified to use bad num_disp_buffers set num_loops // to something reasonable if (num_disp_buffers <= 0) num_loops = 10; else num_loops = num_disp_buffers*10; for (j = 0; j < num_loops; j++) { for (i = MY_MIN; i < MY_MAX; i+=INCR) a_known_value++; for (i = MY_MAX; i >= MY_MIN; i-=INCR) b_known_value++; } for(i = 0; i < REPETITIONS; i++) { if(!test_kmp_set_disp_num_buffers()) { num_failed++; } } if (num_failed == 0) printf("passed\n"); else printf("failed %d\n", num_failed); return num_failed; }
FullMatrix.h
/*! * @file FullMatrix.h * @author Michal Merta * @date July 5, 2013 * @brief Header file for the FullMatrix class * */ #ifndef FULLMATRIX_H #define FULLMATRIX_H #include <cstring> #include <vector> #include "Matrix.h" #include "SparseMatrix.h" #include "Macros.h" #if N_MIC > 0 #pragma offload_attribute( push, target( mic ) ) #endif #include "BLAS_LAPACK_wrapper.h" #if N_MIC > 0 #pragma offload_attribute( pop ) #endif namespace bem4i { /*! * Class representing a full matrix * * The matrix is stored in a column-major order. * Matrix operations are performed by calling the BLAS/LAPACK routines. * */ template<class LO, class SC> class FullMatrix : public Matrix<LO, SC>, Offloadable { typedef typename GetType<LO, SC>::SCVT SCVT; friend class FullMatrix<LO, SCVT>; friend class FullMatrix<LO, std::complex<SCVT> >; public: //! default constructor FullMatrix( ); //! copy constructor FullMatrix( const FullMatrix& orig ); /*! * Constructor allocating a full matrix * * @param[in] nRows number of rows * @param[in] nCols number of columns * @param[in] zeroOut (optional) whether to set all matrix elements to zero * @param[in] allocWork (optional) whether to allocate working space for BLAS/LAPACK */ FullMatrix( LO nRows, LO nCols, bool zeroOut = true, bool allocWork = true ); /*! * Constructor taking an user preallocated array with matrix data * * @param[in] nRows number of rows * @param[in] nCols number of columns * @param[in] data pointer to an array representing matrix entries * @param[in] allocWork (optional) whether to allocate working space for BLAS/LAPACK */ FullMatrix( LO nRows, LO nCols, SC * data, bool allocWork = true ); //! destructor virtual ~FullMatrix( ); //! deletes matrix values and allocates new resized matrix void resize( LO nRows, LO nCols, bool zeroOut = true ); void copy( FullMatrix<LO, SC> & copy ) const; void copyToComplex( FullMatrix< LO, std::complex< SCVT > > & copy ) const; //! returns an (m,n) element of a matrix inline SC get( LO m, LO n ) const { return data[n * this->nRows + m]; } //! sets the (m,n) element to the value of val inline void set( LO m, LO n, SC val ) { data[n * this->nRows + m] = val; } //! adds val to the (m,n) element inline void add( LO m, LO n, SC val ) { data[n * this->nRows + m] += val; } inline void addAtomic( LO m, LO n, SC val ) { #pragma omp atomic update data[n * this->nRows + m] += val; } //! sets all elements to the value of val inline void setAll( SC val ) { SC *p = this->data, *last = this->data + this->nRows * this->nCols; while ( p != last ) *( p++ ) = val; } /*! * Sums values specified by input array to the subset of matrix * * @param[in] rows indices of rows * @param[in] cols indices of cols * @param[in] mat input matrix */ void addToPositions( std::vector<LO> const & rows, std::vector<LO> const & cols, FullMatrix<LO, SC> const & mat ); void addToPositionsAtomic( std::vector<LO> const & rows, std::vector<LO> const & cols, FullMatrix<LO, SC> const & mat ); /*! * Sums values specified by input array to the subset of matrix to positions * (i, j, v) - i specified by rows, j by Cols * * @param[in] rows indices of rows * @param[in] cols indices of cols * @param[in] values input values */ void addToPositions( std::vector<LO> const & rows, std::vector<LO> const & cols, std::vector<SC> const & values ); //! copies a column of a matrix into a <em>user-preallocated</em> array void getCol( LO idx, SC * outCol ) const; //! copies a row of a matrix into a <em>user-preallocated</em> array void getRow( LO idx, SC * outCol ) const; //! scales all values of matrix by alpha void scale( SC alpha ); //! performs in-place conjugation void conjugate( ); //! computes 1-norm of a matrix SC norm1( ) const; //! computes Frobenius norm of a matrix SC normFro( ); //! computes Inf-norm of a matrix SC normI( ); /*! * @brief Matrix-matrix addition * * Computes the sum this = this + alpha*A * @param A * @param alpha */ void add( FullMatrix<LO, SC> &A, SC alpha = 1.0 ); /*! * @brief Matrix-matrix addition * * Computes the sum this = this + alpha*A * @param A * @param alpha */ void add( SparseMatrix<LO, SC, Eigen::ColMajor> &A, SC alpha = 1.0 ); /*! * @brief Matrix-matrix multiplication * * Computes a sum this = beta*this + alpha*A*B * @param A * @param B * @param alpha * @param beta */ void multiply( FullMatrix<LO, SC> &A, FullMatrix<LO, SC> &B, bool transA = false, bool transB = false, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Matrix-matrix multiplication * * Computes a sum this = beta*this + alpha*A*B * @param A * @param B * @param alpha * @param beta */ void multiply( FullMatrix<LO, SC> &A, SparseMatrix<LO, SC, Eigen::ColMajor> &B, bool transA = false, bool transB = false, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Matrix-matrix multiplication * * Computes a sum this = beta*this + alpha*A*B * @param A * @param B * @param alpha * @param beta */ void multiply( SparseMatrix<LO, SC, Eigen::ColMajor> &A, FullMatrix<LO, SC> &B, bool transA = false, bool transB = false, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Matrix-matrix multiplication * * Computes a sum this = beta*this + alpha*A(1:nRows, 1:nCols)*B(1:nCols, :) * @param A * @param B * @param alpha * @param beta */ void multiply( FullMatrix<LO, SC> &A, FullMatrix<LO, SC> &B, LO ARows, LO ACols, LO BRows, LO BCols, bool transA, bool transB, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Performs a matrix-vector multiplication * * Computes y = beta*y + alpha*this*x * @param A * @param x * @param y * @param alpha * @param beta */ virtual void apply( Vector<LO, SC> const & x, Vector<LO, SC> & y, bool transA = false, SC alpha = 1.0, SC beta = 0.0 ); void applyMIC( Vector<LO, SC> const & x, Vector<LO, SC> & y, bool transA = false, SC alpha = 1.0, SC beta = 0.0, int device = 0 ); /*! * @brief Performs a matrix-vector multiplication using submatrix * * Computes y = beta*y + alpha*this(1:ARows, 1:ACols)*x * @param A * @param x * @param y * @param ARows * @param ACols * @param alpha * @param beta */ void applySubmatrix( Vector<LO, SC> const &x, Vector<LO, SC> &y, LO ARows, LO ACols, bool transA = false, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Performs a matrix-vector multiplication on a subvector * * Computes y(indicesY) = this*x(indicesX) * @param A * @param x * @param y */ void apply( Vector<LO, SC> const &x, std::vector<LO>& indicesX, Vector<LO, SC> &y, std::vector<LO> &indicesY, bool transA = false, SC alpha = 1.0, SC beta = 0.0 ); /*! * @brief Solves a system of linear equations using LU decomposition * * Solves the system this*x = rhs. WARNING: The original matrix is * overwritten by its factors! * @param x on input: right-hand side, on output: result */ void LUSolve( Vector<LO, SC> & x, LO nRhs = 1 ); /*! * @brief Solves a system of linear equations using Choleski decomposition * * Solves the system this*x = rhs. WARNING: The original matrix is * overwritten by its factors! * @param x on input: right-hand side, on output: result */ void CholeskiSolve( Vector<LO, SC> & x, LO nRhs = 1 ); /*! * @brief Solves a system of linear equations using LU decomposition * * Solves the system this*x = rhs. WARNING: The original matrix is * overwritten by its factors! * @param x on input: right-hand side, rhs given by columns of x */ void LUSolve( FullMatrix<LO, SC> & x, LO nRhs = 0 ); /*! * @brief Solves a system of linear equations using Choleski decomposition * * Solves the system this*x = rhs. WARNING: The original matrix is * overwritten by its factors! * @param x on input: right-hand side, rhs given by columns of x */ void CholeskiSolve( FullMatrix<LO, SC> & x, LO nRhs = 0 ); /*! * @brief Solves a system with upper triangular matrix by backward substitution * * Solves the system this*x = rhs. WARNING: The original matrix is * overwritten by its factors! * @param x on input: right-hand side, on output: resul * @param nRhs number of right-hand sides * @param n dimension of a system matrix this(1:n, 1:n), if 0 => n = this.nRows */ void backward( Vector<LO, SC> & x, LO nRhs = 1, LO n = 0 ); /*! * @brief Computes eigenvectors and eigenvalues of symmetric real matrix * * todo: Not implemented for complex matrices! * @param[in,out] eigenvectors array of eigenvectors * @param[in,out] eigenvalues array of eigenvalues */ void eigs( SC * eigenvectors, SC * eigenvalues ); /*! * @brief Computes the Schur decompositin of a Hessenberg matrix * * Computes decomposition of this matrxi into H = Z T Z**H. The input matrix * must be of Hessenberg form. * * WARNING: May rewrite the original matrix * * @param[in, out] Z reference to the full matrix Z from Schur decomposition * @param[out] eigs pointer to user preallocated array to store * eigenvalues */ void schurOfHessenberg( FullMatrix<LO, SC> & Z, std::complex<SCVT> * eigs ); //! prints the matrix void print( std::ostream & stream = std::cout ) const; /*! * @brief Returns a pointer to the array of data. Use with caution! * * * @param[in, out] data */ inline SC * getData( ) const { return data; } // void setFactReuseOn( ) { // this->reuseFact = true; // } void xferToMIC( int device = 0 ) const { #if N_MIC > 0 const SCVT * data = reinterpret_cast < SCVT * > ( this->data ); const SCVT * work = reinterpret_cast < SCVT * > ( this->work ); int mult = 1; if ( !std::is_same< SC, SCVT >::value ) mult = 2; LO nRows = this->nRows; LO nCols = this->nCols; #pragma omp target enter data device( device ) \ map( to : data[ 0 : mult * nRows * nCols ] ) \ map( to : work[ 0 : mult * nRows ] ) #endif } void xferToHost( int device = 0 ) const { #if N_MIC > 0 const SCVT * data = reinterpret_cast < SCVT * > ( this->data ); int mult = 1; if ( !std::is_same< SC, SCVT >::value ) mult = 2; LO nRows = this->nRows; LO nCols = this->nCols; #pragma omp target update device( device ) \ from( data[ 0 : mult * nRows * nCols ] ) #endif } void updateMIC( int device = 0 ) const { #if N_MIC > 0 const SCVT * data = reinterpret_cast < SCVT * > ( this->data ); const SCVT * work = reinterpret_cast < SCVT * > ( this->work ); int mult = 1; if ( !std::is_same< SC, SCVT >::value ) mult = 2; LO nRows = this->nRows; LO nCols = this->nCols; #pragma omp target update device( device ) \ to( data[ 0 : mult * nRows * nCols ] ) #endif } void deleteMIC( int device = 0 ) const { #if N_MIC > 0 const SCVT * data = reinterpret_cast < SCVT * > ( this->data ); const SCVT * work = reinterpret_cast < SCVT * > ( this->work ); #pragma omp target exit data device( device ) \ map( delete : data ) \ map( delete : work ) #endif } private: //! 1D array with matrix data in column-major order SC * data; /*! * @brief auxiliary workspace for some LAPACK routines * * Note, that some LAPACK routines may need more allocated space. */ mutable SC * work; //! whether the destructor should delete array with data bool deleteData; //! whether the matrix has been factorized for LAPACK LU solve already // bool factorized; //! pivoting info from LU factorization // int * ipiv; // bool reuseFact; }; } // include .cpp file to overcome linking problems due to templates #include "FullMatrix.cpp" #endif /* FULLMATRIX_H */
parallel_string.h
/* Header ini adalah kumpulan fungsi string.h yang dibutuhkan oleh kelompok kami dan beberapa dimodifikasi menjadi versi paralel jika memungkinkan. */ #ifndef PARALLEL_STRING #define PARALLEL_STRING #include <omp.h> //Fungsi strlen. Tidak bisa diparalelkan. int my_strlen(const unsigned char * string) { register int i; for (i = 0; string[i] != '\0'; i++); return i; } //Fungsi strcpy yang diubah menjadi paralel void my_strcpy(unsigned char * destination, const unsigned char * source) { //parameter ketiga beda register int i, size_source = my_strlen(source); #pragma omp parallel for for (i = 0; i < size_source; i++) { destination[i] = source[i]; } destination[size_source] = '\0'; } //Fungsi strcat yang diubah menjadi paralel void my_strcat(unsigned char * destination, const unsigned char * source) { register int i; register int size_source = my_strlen(source); register int size_destination = my_strlen(destination); register int size_keduanya = size_source + size_destination; #pragma omp parallel for for (i = size_destination; i < size_keduanya; i++) { destination[i] = source[i - size_destination]; } destination[size_keduanya] = '\0'; } //Fungsi strcmp yang diubah menjadi paralel int my_strcmp(const unsigned char * str1, const unsigned char * str2) { register int i, flag = 1; register int len_str1 = my_strlen(str1); #pragma omp parallel for shared(flag) for (i = 0; i < len_str1; i++) { if (str1[i] != str2[i]) { #pragma omp critical flag = 0; } } return !flag; } /* Fungsi strcasecmp, tetapi dapat digunakan jika kata yang dicari tidak persis. Contohnya, ada "facebook.com", tetapi dengan mencari "Book" dapat ditemukan. */ int my_strcasestr(const unsigned char * string, const unsigned char * toFind) { register int slen = my_strlen(string); register int tFlen = my_strlen(toFind); register int found = 0, s, t; if (slen >= tFlen) { for (s = 0, t = 0; s < slen; s++) { do { if (string[s] == toFind[t] || string[s] == toFind[t] + 32 || string[s] + 32 == toFind[t]) { if (++found == tFlen) return 0; s++; t++; } else { s -= found; found = 0; t = 0; } } while (found); } return 1; } else return -1; } #endif //PARALLEL_STRING
update_values_x_bsr.c
#include "alphasparse/kernel.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(ALPHA_SPMAT_BSR *A, const ALPHA_INT nvalues, const ALPHA_INT *indx, const ALPHA_INT *indy, ALPHA_Number *values) { ALPHA_INT num_thread = alpha_get_thread_num(); ALPHA_INT find = 0; #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) reduction(+:find) #endif for(ALPHA_INT i = 0; i < nvalues; i++) { ALPHA_INT row = indx[i]; ALPHA_INT col = indy[i]; ALPHA_INT bs = A->block_size; ALPHA_INT block_row = row / bs; ALPHA_INT block_col = col / bs; ALPHA_INT block_row_inside = row % bs; ALPHA_INT block_col_inside = col % bs; for(ALPHA_INT ai = A->rows_start[block_row]; ai < A->rows_end[block_row]; ai++) { const ALPHA_INT ac = A->col_indx[ai]; if(ac == block_col) { ALPHA_INT idx = 0; if(A->block_layout == ALPHA_SPARSE_LAYOUT_ROW_MAJOR) idx = ai * bs * bs + block_row_inside * bs + block_col_inside; else idx = ai * bs * bs + block_row_inside + block_col_inside * bs; A->values[idx] = values[i]; find ++; break; } } } if(find) return ALPHA_SPARSE_STATUS_SUCCESS; else return ALPHA_SPARSE_STATUS_INVALID_VALUE; }
mesh-amit.c
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <complex.h> #include <sys/types.h> #include <time.h> #include <fftw3.h> #include "globalvars.h" #include "sharedvars.h" #include "prototype.h" #include "mesh.h" /*****************************************************************************/ void init_normal_beads (double normal[NTRIANGLE_MAX][3], double nrm[beads][3], int ipart) { double wx[beads], wy[beads], wz[beads]; int i; int i1,i2,i3; int itriangle; double norm; /* Initialize weights for the global solution */ for(i=0;i<beads;i++) { wx[i]=0.0; wy[i]=0.0; wz[i]=0.0; } /* Store weights for the global calculation */ /* Also used for computing the area weighted normal average for each bead */ for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; wx[i1] += area[ipart][itriangle]/3.0*normal[itriangle][0]; wx[i2] += area[ipart][itriangle]/3.0*normal[itriangle][0]; wx[i3] += area[ipart][itriangle]/3.0*normal[itriangle][0]; wy[i1] += area[ipart][itriangle]/3.0*normal[itriangle][1]; wy[i2] += area[ipart][itriangle]/3.0*normal[itriangle][1]; wy[i3] += area[ipart][itriangle]/3.0*normal[itriangle][1]; wz[i1] += area[ipart][itriangle]/3.0*normal[itriangle][2]; wz[i2] += area[ipart][itriangle]/3.0*normal[itriangle][2]; wz[i3] += area[ipart][itriangle]/3.0*normal[itriangle][2]; normal_t[ipart][itriangle][0] = normal[itriangle][0]; normal_t[ipart][itriangle][1] = normal[itriangle][1]; normal_t[ipart][itriangle][2] = normal[itriangle][2]; } /*Computing the area weighted normal average for each bead */ for(i=0;i<beads;i++) { norm = wx[i]*wx[i] + wy[i]*wy[i] + wz[i]*wz[i]; norm = sqrt(norm); nrm[i][0] = wx[i]/norm; nrm[i][1] = wy[i]/norm; nrm[i][2] = wz[i]/norm; } } /*****************************************************************************/ void compute_normal_curvature (double nrm[beads][3], double curv[beads], double xb[beads][3], int beads_to_beads[beads][6]) { int i,j,k; int ibead,jbead; int i1,i2,i3; int itriangle; double norm; double xneigh[6][3]; double x_tr[6][3]; double Ct[3][3]; double u[3],Q[3][3]; double xp[3],yp[3],zp[3]; double A1[5][5],brhs1[5],rdist1[5]; double A2[6][6],brhs2[6],rdist2[6]; int INFO, N, NRHS, IPIV[6],LDA, LDB, M, RANK; int LWORK=50; double WORK[50]; double RCOND=1E-10; double S[5]; double nrm_l[3],nrm_g[3]; double error; FILE *fp; /*fp = fopen("nrm.txt","w+"); for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { fprintf(fp,"%E\t",nrm[ibead][i]); } fprintf(fp,"\n"); } fclose(fp);*/ /* First for the first 12 vertices with coordination number 5 */ for(ibead=0;ibead<12;ibead++) { /* store coordinates of the connected beads relative to ibead */ for(i=0;i<5;i++) { jbead = beads_to_beads[ibead][i]; for(j=0;j<3;j++) { xneigh[i][j] = xb[jbead][j]-xb[ibead][j]; } } do { /* Store local z axis coordinates in global frame */ zp[0] = nrm[ibead][0]; zp[1] = nrm[ibead][1]; zp[2] = nrm[ibead][2]; /* find the rotation matrix: Use householder's algorithm */ if (fabs(zp[2]-1) > 1E-10) { u[0] = 0.0 - zp[0]; u[1] = 0.0 - zp[1]; u[2] = 1.0 - zp[2]; norm = sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]); /* normalize */ u[0] = u[0]/norm; u[1] = u[1]/norm; u[2] = u[2]/norm; /* Find the Q matrix */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0 - 2.0*u[i]*u[j]; } else { Q[i][j] = -2.0*u[i]*u[j]; } } } } else // no rotation necessary Q=I { for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0; } else { Q[i][j] = 0.0; } } } } /* find coordinates of the local x axis in global system = Q^T*(1,0,0) */ xp[0] = Q[0][0]; xp[1] = Q[1][0]; xp[2] = Q[2][0]; /* find yp = z * x*/ cross_product(zp,xp,yp); /* compute the coordinate transformation matrix: C^T */ for(i=0;i<3;i++) { Ct[0][i] = xp[i]; Ct[1][i] = yp[i]; Ct[2][i] = zp[i]; } /* transform coordinates of neighboring beads to local coordinates */ for(i=0;i<5;i++) { for(j=0;j<3;j++) { x_tr[i][j] = 0.0; for(k=0;k<3;k++) { x_tr[i][j] += Ct[j][k]*xneigh[i][k]; } } } /* Find the distance from the center */ for(i=0;i<5;i++) { rdist1[i] = sqrt(x_tr[i][0]*x_tr[i][0] + x_tr[i][1]*x_tr[i][1] + x_tr[i][2]*x_tr[i][2]); } /* build the A matrix, store in fortran column major format */ for(i=0;i<5;i++) { A1[0][i] = x_tr[i][0]/rdist1[i]; A1[1][i] = x_tr[i][1]/rdist1[i]; A1[2][i] = x_tr[i][0]*x_tr[i][0]/rdist1[i]; A1[3][i] = x_tr[i][0]*x_tr[i][1]/rdist1[i]; A1[4][i] = x_tr[i][1]*x_tr[i][1]/rdist1[i]; brhs1[i] = x_tr[i][2]/rdist1[i]; } /* Solve using dgesv */ N=5;NRHS=1;LDA=5;LDB=5; dgesv_(&N,&NRHS,A1,&LDA,IPIV,brhs1,&LDB,&INFO); /* find new normal in local coordinates */ norm = sqrt(1.0 + brhs1[0]*brhs1[0] + brhs1[1]*brhs1[1]); nrm_l[0] = -brhs1[0]/norm; nrm_l[1] = -brhs1[1]/norm; nrm_l[2] = 1.0/norm; /* transform to global coordinates */ for(i=0;i<3;i++) { nrm_g[i]=0.0; for(j=0;j<3;j++) { nrm_g[i] += Ct[j][i]*nrm_l[j]; } } /* find error */ error=0.0; for(i=0;i<3;i++) { error += pow(zp[i]-nrm_g[i],2); } error = sqrt(error); /* store in normal array */ for(i=0;i<3;i++) { nrm[ibead][i] = nrm_g[i]; } } while (error > 1E-3); /* store curvature */ curv[ibead] = -brhs1[2] - brhs1[4]; // printf("%d\t%E\n",ibead,curv[ibead]); } /* Remaining vertices with coordination number 6 */ for(ibead=12;ibead<beads;ibead++) { /* store coordinates of the connected beads relative to ibead */ for(i=0;i<6;i++) { jbead = beads_to_beads[ibead][i]; for(j=0;j<3;j++) { xneigh[i][j] = xb[jbead][j]-xb[ibead][j]; } } do { /* Store zp axis coordinates */ zp[0] = nrm[ibead][0]; zp[1] = nrm[ibead][1]; zp[2] = nrm[ibead][2]; if (fabs(zp[2]-1) > 1E-10) { u[0] = 0.0 - zp[0]; u[1] = 0.0 - zp[1]; u[2] = 1.0 - zp[2]; norm = sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]); /* normalize */ u[0] = u[0]/norm; u[1] = u[1]/norm; u[2] = u[2]/norm; /* Find the Q matrix */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0 - 2.0*u[i]*u[j]; } else { Q[i][j] = -2.0*u[i]*u[j]; } } } } else // no rotation necessary Q=I { for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0; } else { Q[i][j] = 0.0; } } } } /* find coordinates of xp axis in global system */ xp[0] = Q[0][0]; xp[1] = Q[1][0]; xp[2] = Q[2][0]; /* find yp = z * x*/ cross_product(zp,xp,yp); /* compute the coordinate transformation matrix: C^T */ for(i=0;i<3;i++) { Ct[0][i] = xp[i]; Ct[1][i] = yp[i]; Ct[2][i] = zp[i]; } /* transform coordinates of neighboring beads to local coordinates */ for(i=0;i<6;i++) { for(j=0;j<3;j++) { x_tr[i][j] = 0.0; for(k=0;k<3;k++) { x_tr[i][j] += Ct[j][k]*xneigh[i][k]; } } } /* Find the distance from the center */ for(i=0;i<6;i++) { rdist2[i] = sqrt(x_tr[i][0]*x_tr[i][0] + x_tr[i][1]*x_tr[i][1] + x_tr[i][2]*x_tr[i][2]); } /* build the A matrix, store in fortran column major format */ for(i=0;i<6;i++) { A2[0][i] = x_tr[i][0]/rdist2[i]; A2[1][i] = x_tr[i][1]/rdist2[i]; A2[2][i] = x_tr[i][0]*x_tr[i][0]/rdist2[i]; A2[3][i] = x_tr[i][0]*x_tr[i][1]/rdist2[i]; A2[4][i] = x_tr[i][1]*x_tr[i][1]/rdist2[i]; brhs2[i] = x_tr[i][2]/rdist2[i]; } /* Solve using dgelss */ M=6;N=5;NRHS=1;LDA=M;LDB=M; dgelss_(&M,&N,&NRHS,A2,&LDA,brhs2,&LDB,S,&RCOND,&RANK,WORK,&LWORK,&INFO); /* find new normal in local coordinates */ norm = sqrt(1.0 + brhs2[0]*brhs2[0] + brhs2[1]*brhs2[1]); nrm_l[0] = -brhs2[0]/norm; nrm_l[1] = -brhs2[1]/norm; nrm_l[2] = 1.0/norm; /* transform to global coordinates */ for(i=0;i<3;i++) { nrm_g[i]=0.0; for(j=0;j<3;j++) { nrm_g[i] += Ct[j][i]*nrm_l[j]; } } /* find error */ error=0.0; for(i=0;i<3;i++) { error += pow(zp[i]-nrm_g[i],2); } error = sqrt(error); /* store in normal array */ for(i=0;i<3;i++) { nrm[ibead][i] = nrm_g[i]; } } while (error > 1E-3); /* store curvature */ curv[ibead] = -brhs2[2] - brhs2[4]; // printf("%d\t%E\n",ibead,curv[ibead]); } /*fp = fopen("nrm1.txt","w+"); for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { fprintf(fp,"%E\t",nrm[ibead][i]); } fprintf(fp,"\n"); } fclose(fp); exit(0);*/ } /*****************************************************************************/ /*------------------------------------------------------------- * Computes the solid angle subtended by a triangle at * one of its own vertex (see ieee transactions of biomedical * engineering, 45, 980, 1998) - *------------------------------------------------------------*/ void solid_angle(double *Omega, double x1[3],double x2[3], double x3[3], double n[3]) { int i,j,k; double pi; double x[3],y[3]; double z[3]; double ndotx,ndoty,ndotz,xdoty; double xm,ym; double nr,dr; pi = 4.0*atan(1.0); /* find sides of the triangle relative to the origin vertex */ for(i=0;i<3;i++) { x[i]=x2[i]-x1[i]; y[i]=x3[i]-x1[i]; } cross_product(x,y,z); xm = sqrt(dot_product(3,x,x)); ym = sqrt(dot_product(3,y,y)); ndotx = dot_product(3,n,x); ndoty = dot_product(3,n,y); ndotz = dot_product(3,n,z); xdoty = dot_product(3,x,y); nr = -2.0*ndotz*(ndotx*ym + ndoty*xm); dr = pow(xm*ym + xdoty,2) - pow(ndotx*ym + ndoty*xm,2) + pow(ndotz,2); *Omega = atan(nr/dr); } /******************************************************************************/ /*----------------------------------------------------------------------------------- uin = coefficient of the Green's function uout = output of the double layer integral -------------------------------------------------------------------------------------*/ void prvec_double_layer(double xb[npart][beads][3],double uin[npart][beads][3], double nrm[npart][beads][3], double ub[npart][beads][3]) { int i,j,k,ibead; int itriangle,jtriangle; double xi[3]; int i1,i2,i3; double u[3],u1[3]; double w[npart][beads]; double uxf[nx][ny][nz], uyf[nx][ny][nz], uzf[nx][ny][nz],pf[nx][ny][nz]; double ubc1[nx][ny][3], ubc2[nx][ny][3]; double gaussx[nx][ny][nz],gaussy[nx][ny][nz],gaussz[nx][ny][nz],gaussz_p[nx][ny][nz]; FILE *fp; char name[20]; double fb[beads][3]; double sigma_g[nx][ny][nz][3][3]; double pi; double uint[beads][3]; int ix,iy,iz; double dx,dy; int member; int ipart,jpart; double Omega; double dudx[nx][ny][nz],dudy[nx][ny][nz],dudz[nx][ny][nz]; double dvdx[nx][ny][nz],dvdy[nx][ny][nz],dvdz[nx][ny][nz]; double dwdx[nx][ny][nz],dwdy[nx][ny][nz],dwdz[nx][ny][nz]; pi = 4.0*atan(1.0); /* Mesh size */ dx = Lx/nx; dy = Ly/ny; /* Initialize velocity to zero */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<beads;i++) { for(j=0;j<3;j++) { ub[ipart][i][j]=0.0; } } } /* Initialize weights for the global solution */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<beads;i++) { w[ipart][i]=0.0; } } /* Store weights for the global calculation */ for(ipart=0;ipart<npart;ipart++) { for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; w[ipart][i1] += area[ipart][itriangle]/3.0; w[ipart][i2] += area[ipart][itriangle]/3.0; w[ipart][i3] += area[ipart][itriangle]/3.0; } } #if (OMP == 1) omp_set_num_threads(NTHREADS); #endif /* Sum contribution from the self element at each of the nodes*/ /* Also find the weight for each node for the global solution computaiton */ #if (npart > 1) #if (OMP == 1) #pragma omp parallel for private(ipart,jpart,ibead,j,itriangle,jtriangle,xi,i1,i2,i3,member,u,Omega) #endif #endif for(ipart=0;ipart<npart;ipart++) { #if (npart == 1) #if (OMP == 1) #pragma omp parallel for private(jpart,ibead,j,itriangle,jtriangle,xi,i1,i2,i3,member,u,Omega) #endif #endif for(ibead=0;ibead<beads;ibead++) { /* Store position of the field point */ for(i=0;i<3;i++) { xi[i] = xb[ipart][ibead][i]; } /* compute velocity at this point due to all triangular elements */ for(itriangle=0;itriangle<triangle_count[ipart][ibead];itriangle++) { jpart = triangle_list[ipart][ibead][itriangle][0]; jtriangle = triangle_list[ipart][ibead][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // printf("%lf\n",area[triangle_list[ibead][itriangle]]); if (ibead == i1 && jpart == ipart) { member=1; } else if (ibead == i2 && jpart == ipart) { i2=i1; i1 = ibead; member=1; } else if (ibead == i3 && jpart == ipart) { i3=i1; i1=ibead; member=1; } /* Perform the integration */ if (member==0) { integrate5(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2],uin[jpart][i3], u,alpha,nrm[ipart][ibead]); } else { if (SOLID_ANGLE == 1) { /* compute solid angle */ solid_angle(&Omega,xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],nrm[ipart][ibead]); integrate5c(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1], uin[jpart][i2],uin[jpart][i3],u,alpha,normal_t[ipart][jtriangle],Omega); } else { /* using normal of the triangle as the normal of ibead, this makes it non-singular */ integrate5a(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2], uin[jpart][i3],u,alpha,nrm[ipart][ibead],normal_t[ipart][jtriangle]); } } /* Sum to total velocity */ for(i=0;i<3;i++) { ub[ipart][ibead][i] += u[i]; } } } } /*----------------------- Global Solution Calculation ------------------------------*/ /*----- Boundary Conditions ---- */ /* Initialize */ for(i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<3;k++) { ubc1[i][j][k]=0.0; ubc2[i][j][k]=0.0; } } } /* set ubc = - u_l for poiseuille flow */ /* Top plate */ #if (OMP == 1) #pragma omp parallel for private(ix,iy,xi,itriangle,jpart,jtriangle,i1,i2,i3,member,u) #endif for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = Lz; for(itriangle=0;itriangle<triangle_count_t[ix][iy];itriangle++) { jpart = triangle_list_t[ix][iy][itriangle][0]; jtriangle = triangle_list_t[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2],uin[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2],uin[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc2[ix][iy][i] -= u[i]/8/pi; } } } } /* Bottom plate */ #if (OMP == 1) #pragma omp parallel for private(ix,iy,xi,itriangle,jpart,jtriangle,i1,i2,i3,member,u) #endif for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = 0.0; for(itriangle=0;itriangle<triangle_count_b[ix][iy];itriangle++) { jpart = triangle_list_b[ix][iy][itriangle][0]; jtriangle = triangle_list_b[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2],uin[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,uin[jpart][i1],uin[jpart][i2],uin[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc1[ix][iy][i] -= u[i]/8/pi; } } } } /* Distribute density to mesh */ /* Initialize mesh force density */ for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { for(iz=0;iz<nz;iz++) { gaussx[ix][iy][iz] = 0.0; gaussy[ix][iy][iz] = 0.0; gaussz[ix][iy][iz] = 0.0; gaussz_p[ix][iy][iz] = 0.0; } } } for(ipart=0;ipart<npart;ipart++) { distribute_density(xb[ipart],uin[ipart],gaussx,gaussy,gaussz,gaussz_p,w[ipart],alpha,xz); } /* solve for the velocity and pressure at the mesh points */ global_velocity_inhomogeneous(gaussx,gaussy,gaussz,gaussz_p,ubc1,ubc2,uxf,uyf,uzf,pf, dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz, xxi,cz, u1H,v1H,w1H,dwdz1H,dudz1H,dvdz1H,p1H, u2H,v2H,w2H,dwdz2H,dudz2H,dvdz2H,p2H); /* Compute the global stress tensor at the mesh points */ #if (STRESS_HI == 1) compute_global_stress_tensor_spectral(dudx,dudy,dudz,dvdx,dvdy,dvdz, dwdx,dwdy,dwdz,pf,sigma_g); #else compute_global_stress_tensor(uxf,uyf,uzf,pf,sigma_g,xz); #endif /* Store first column of sigma in uxf, uyf, uzf to interpolate */ for (i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<nz;k++) { uxf[i][j][k] = sigma_g[i][j][k][0][0]; uyf[i][j][k] = sigma_g[i][j][k][1][0]; uzf[i][j][k] = sigma_g[i][j][k][2][0]; } } } /* Interpolate velocity from the mesh to the bead position: store in uint */ for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { uint[ibead][i]=0.0; } } #if (INTERP == 2) interpolate2(xb[ipart],uint,uxf,uyf,uzf,xz); #else interpolate4(xb[ipart],uint,uxf,uyf,uzf,xz); #endif /* multiply by nrm[ibead][0] */ for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { ub[ipart][ibead][i] += uint[ibead][i]*nrm[ipart][ibead][0]; } } } /* Store second column of sigma in uxf, uyf, uzf to interpolate */ for (i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<nz;k++) { uxf[i][j][k] = sigma_g[i][j][k][0][1]; uyf[i][j][k] = sigma_g[i][j][k][1][1]; uzf[i][j][k] = sigma_g[i][j][k][2][1]; } } } /* Interpolate velocity from the mesh to the bead position: store in uint */ for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { uint[ibead][i]=0.0; } } #if (INTERP == 2) interpolate2(xb[ipart],uint,uxf,uyf,uzf,xz); #else interpolate4(xb[ipart],uint,uxf,uyf,uzf,xz); #endif /* multiply by nrm[ibead][1] */ for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { ub[ipart][ibead][i] += uint[ibead][i]*nrm[ipart][ibead][1]; } } } /* Store third column of sigma in uxf, uyf, uzf to interpolate */ for(i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<nz;k++) { uxf[i][j][k] = sigma_g[i][j][k][0][2]; uyf[i][j][k] = sigma_g[i][j][k][1][2]; uzf[i][j][k] = sigma_g[i][j][k][2][2]; } } } /* Interpolate velocity from the mesh to the bead position: store in uint */ for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { uint[ibead][i]=0.0; } } #if (INTERP == 2) interpolate2(xb[ipart],uint,uxf,uyf,uzf,xz); #else interpolate4(xb[ipart],uint,uxf,uyf,uzf,xz); #endif /* multiply by nrm[ibead][2] */ for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { ub[ipart][ibead][i] += uint[ibead][i]*nrm[ipart][ibead][2]; } } } } /******************************************************************************/ void prvec(double xb[npart][beads][3], double fb[npart][beads][3], double ub[npart][beads][3], double nrm_b[npart][beads][3]) { int i,j,k; int ibead,itriangle,jtriangle; double xi[3]; double r1; int i1,i2,i3; double pi; double u[3]; int member; double weights[npart][beads]; double uxf[nx][ny][nz], uyf[nx][ny][nz], uzf[nx][ny][nz], pf[nx][ny][nz]; double ubc1[nx][ny][3], ubc2[nx][ny][3]; double gaussx[nx][ny][nz],gaussy[nx][ny][nz],gaussz[nx][ny][nz],gaussz_p[nx][ny][nz]; double dudx[nx][ny][nz],dudy[nx][ny][nz],dudz[nx][ny][nz]; double dvdx[nx][ny][nz],dvdy[nx][ny][nz],dvdz[nx][ny][nz]; double dwdx[nx][ny][nz],dwdy[nx][ny][nz],dwdz[nx][ny][nz]; FILE *fp; char name[20]; int ix,iy,iz; double dx,dy; int ipart,jpart; double fn,f1[3],f2[3],f3[3]; pi = 4.0*atan(1.0); /* Mesh size */ dx = Lx/nx; dy = Ly/ny; /* Initialize velocity to zero */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<beads;i++) { for(j=0;j<3;j++) { ub[ipart][i][j]=0.0; } } } #if (OMP == 1) omp_set_num_threads(NTHREADS); #endif /* Contribution from local force density */ #if (npart > 1) #if (OMP == 1) #pragma omp parallel for private(ipart,jpart,ibead,j,itriangle,jtriangle,xi,i1,i2,i3,member,u) #endif #endif for(ipart=0;ipart<npart;ipart++) { #if (npart == 1) #if (OMP == 1) #pragma omp parallel for private(jpart,ibead,j,itriangle,jtriangle,xi,i1,i2,i3,member,u) #endif #endif for(ibead=0;ibead<beads;ibead++) { for(j=0;j<3;j++) { xi[j] = xb[ipart][ibead][j]; } #if (SING_SUBT == 1) fn = fb[ipart][ibead][0]*nrm_b[ipart][ibead][0] + fb[ipart][ibead][1]*nrm_b[ipart][ibead][1] + fb[ipart][ibead][2]*nrm_b[ipart][ibead][2]; #endif for(itriangle=0;itriangle<triangle_count[ipart][ibead];itriangle++) { jpart = triangle_list[ipart][ibead][itriangle][0]; jtriangle = triangle_list[ipart][ibead][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // printf("%lf\n",area[triangle_list[ibead][itriangle]]); if (ibead == i1 && ipart == jpart) { member=1; } else if (ibead == i2 && jpart == ipart) { i2=i1; i1 = ibead; member=1; } else if (ibead == i3 && jpart == ipart) { i3=i1; i1=ibead; member=1; } #if (SING_SUBT == 0 ) if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } #else for(j=0;j<3;j++) { f1[j] = fb[jpart][i1][j] - fn*normal_t[jpart][jtriangle][j]; f2[j] = fb[jpart][i2][j] - fn*normal_t[jpart][jtriangle][j]; f3[j] = fb[jpart][i3][j] - fn*normal_t[jpart][jtriangle][j]; } if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,f1,f2,f3,u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,f1,f2,f3,u,alpha); } #endif for(i=0;i<3;i++) { ub[ipart][ibead][i] += u[i]; } } } } /* fp = fopen("U.txt","w+"); for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { fprintf(fp,"%d\t%E\t%E\t%E\n",ibead,ub[ipart][ibead][0],ub[ipart][ibead][0],ub[ipart][ibead][0]); } } fclose(fp); exit(0);*/ // return; /*---------------- Global solution calculation -----------------*/ /*----- Boundary Conditions ---- */ /* Initialize */ for(i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<3;k++) { ubc1[i][j][k]=0.0; ubc2[i][j][k]=0.0; } } } /* set ubc = - u_l for poiseuille flow */ /* Top plate */ #if (OMP == 1) #pragma omp parallel for private(ix,iy,xi,itriangle,jpart,jtriangle,i1,i2,i3,member,u) #endif for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = Lz; for(itriangle=0;itriangle<triangle_count_t[ix][iy];itriangle++) { jpart = triangle_list_t[ix][iy][itriangle][0]; jtriangle = triangle_list_t[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc2[ix][iy][i] -= u[i]/8/pi; } } } } /* bottom plate */ #if (OMP == 1) #pragma omp parallel for private(ix,iy,xi,itriangle,jpart,jtriangle,i1,i2,i3,member,u) #endif for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = 0.0; for(itriangle=0;itriangle<triangle_count_b[ix][iy];itriangle++) { jpart = triangle_list_b[ix][iy][itriangle][0]; jtriangle = triangle_list_b[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc1[ix][iy][i] -= u[i]/8/pi; } } } } /* Find weights for the global solution */ /* Initialize weights for the global solution */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<beads;i++) { weights[ipart][i]=0.0; } } for(ipart=0;ipart<npart;ipart++) { for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; /* Store weights for the global calculation */ weights[ipart][i1] += area[ipart][itriangle]/3.0; weights[ipart][i2] += area[ipart][itriangle]/3.0; weights[ipart][i3] += area[ipart][itriangle]/3.0; } } /* Distribute density to mesh */ /* Initialize mesh force density */ for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { for(iz=0;iz<nz;iz++) { gaussx[ix][iy][iz] = 0.0; gaussy[ix][iy][iz] = 0.0; gaussz[ix][iy][iz] = 0.0; gaussz_p[ix][iy][iz] = 0.0; } } } for(ipart=0;ipart<npart;ipart++) { distribute_density(xb[ipart],fb[ipart],gaussx,gaussy,gaussz,gaussz_p,weights[ipart],alpha,xz); } /* printf("Here\n"); fp =fopen("rho.txt","w+"); for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { for(iz=0;iz<nz;iz++) { fprintf(fp,"%E\t%E\t%E\t%E\n",gaussx[ix][iy][iz],gaussy[ix][iy][iz],gaussz[ix][iy][iz],gaussz_p[ix][iy][iz]); } } } fclose(fp); */ /* solve for the velocity and pressure at the mesh points */ global_velocity_inhomogeneous(gaussx,gaussy,gaussz,gaussz_p,ubc1,ubc2,uxf,uyf,uzf,pf, dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz, xxi,cz, u1H,v1H,w1H,dwdz1H,dudz1H,dvdz1H,p1H, u2H,v2H,w2H,dwdz2H,dudz2H,dvdz2H,p2H); /* fp =fopen("Vel.txt","w+"); for(iz=0;iz<nz;iz++) { fprintf(fp,"%E\t%E\t%E\t%E\n",xz[iz],uxf[nx/3][ny/3][iz],uyf[nx/3][ny/3][iz],uzf[nx/3][ny/3][iz]); } fclose(fp); exit(0); */ /* Interpolate velocity from the mesh to the bead position */ for(ipart=0;ipart<npart;ipart++) { #if (INTERP == 2) interpolate2(xb[ipart],ub[ipart],uxf,uyf,uzf,xz); #else interpolate4(xb[ipart],ub[ipart],uxf,uyf,uzf,xz); #endif } /*fp = fopen("U.txt","w+"); for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { fprintf(fp,"%d\t%E\t%E\t%E\n",ibead,ub[ipart][ibead][0],ub[ipart][ibead][1],ub[ipart][ibead][2]); } } fclose(fp); exit(0);*/ } /*------------------------------------------------------------------ Find the particle pairs which overlap or violate the minimum gap specification -------------------------------------------------------------------*/ void find_overlaps_gap(double xb[npart][beads][3], double nrm_b[npart][beads][3],int overlap_pairs[npart][npart], double min_gap[npart][npart],int *overlaps) { int ipart,jpart; int ibead,jbead; int i,j; double xi[3],xj[3]; double x,y,z,r; double xc,yc,zc; double dotp; *overlaps=0; for(ipart=0;ipart<npart;ipart++) { for(jpart=0;jpart<npart;jpart++) { overlap_pairs[ipart][jpart]=0; min_gap[ipart][jpart]=GAP_MIN; } } for(i=0;i<ovp_pair_count;i++) { ipart = ovp_list[i][0]; ibead = ovp_list[i][1]; jpart = ovp_list[i][2]; jbead = ovp_list[i][3]; for(j=0;j<3;j++) { xi[j] = xb[ipart][ibead][j]; xj[j] = xb[jpart][jbead][j]; } // difference vector x = xi[0]-xj[0]; y = xi[1]-xj[1]; z = xi[2]-xj[2]; /* correct for periodicity */ x = x - Lx*floor(x/Lx+0.5); y = y - Ly*floor(y/Ly+0.5); r = sqrt(x*x+y*y+z*z); /* find dot_product to check overlap */ dotp = (x*nrm_b[jpart][jbead][0] + y*nrm_b[jpart][jbead][1] + z*nrm_b[jpart][jbead][2])/r; if (dotp < 0.0) // overlaps { overlap_pairs[ipart][jpart]=1; overlap_pairs[jpart][ipart]=1; if ( -r < min_gap[ipart][jpart]) { min_gap[ipart][jpart]=-r; min_gap[jpart][ipart]=-r; } *overlaps = *overlaps + 1; } else if (r < GAP_MIN) { overlap_pairs[ipart][jpart]=1; overlap_pairs[jpart][ipart]=1; if ( r < min_gap[ipart][jpart]) { min_gap[ipart][jpart]=r; min_gap[jpart][ipart]=r; } *overlaps = *overlaps + 1; } } } /*------------------------------------------------------------------ Find the particle pairs which overlap or violate the minimum gap specification -------------------------------------------------------------------*/ void find_repulsive_force(double xcm[npart][3],int overlap_pairs[npart][npart], double min_gap[npart][npart], double FR[npart][3]) { int ipart,jpart; int i,j; double xi[3],xj[3]; double x,y,z,r; double num_min_gap=0.005; // numerical minimum gap double gap; double sign_x,sign_y; /* Initialize repulsive force to zero */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { FR[ipart][i]=0.0; } } for(ipart=0;ipart<npart-1;ipart++) { for(jpart=ipart+1;jpart<npart;jpart++) { if (overlap_pairs[ipart][jpart] != 0) { for(i=0;i<3;i++) { xi[i] = xcm[ipart][i]; xj[i] = xcm[jpart][i]; } // difference vector x = xi[0]-xj[0]; y = xi[1]-xj[1]; z = xi[2]-xj[2]; r = sqrt(x*x+y*y+z*z); gap = min_gap[ipart][jpart]; /* set a numerical minimum gap */ if (gap < num_min_gap) { gap = num_min_gap; } /* correct for periodicity */ if (fabs(x) > Lx/2) { sign_x = -1.0; } else { sign_x = 1.0; } if (fabs(y) > Ly/2) { sign_y = -1.0; } else { sign_y = 1.0; } FR[jpart][0] = (1.0 - GAP_MIN/gap)*x/r*sign_x; FR[jpart][1] = (1.0 - GAP_MIN/gap)*y/r*sign_y; FR[jpart][2] = (1.0 - GAP_MIN/gap)*z/r; FR[ipart][0] = -FR[jpart][0]; FR[ipart][1] = -FR[jpart][1]; FR[ipart][2] = -FR[jpart][2]; } } } } /* ------------------------------------------------------------------- * pushes the particle apart without rotating them to correct the * overlaps --------------------------------------------------------------------*/ void correct_overlaps(double xb[npart][beads][3], double nrm_b[npart][beads][3], double xcm[npart][3]) { int ipart,ibead,jpart; int i,j; int overlaps,overlaps0; double FR[npart][3]; int overlap_pairs[npart][npart]; double min_gap[npart][npart]; double xcm_new[npart][3]; double REX=0.001; int itr_count=0; FILE *fp; do { /* find the minimum gap violations */ find_overlaps_gap(xb,nrm_b,overlap_pairs,min_gap, &overlaps); if (itr_count == 0) { overlaps0 = overlaps; /* set overlap indicator */ for(ipart=0;ipart<npart;ipart++) { overlap_indicator[ipart]=0; for(jpart=0;jpart<npart;jpart++) { overlap_indicator[ipart] += overlap_pairs[ipart][jpart]; } } } if (overlaps == 0 || itr_count > 1000) { break; } else { #if (PRINT==1) printf("Number of overlaps = %d\t initial = %d\t iteration count = %d\n ",overlaps,overlaps0,itr_count); #endif } /* find the repsulsive force */ find_repulsive_force(xcm,overlap_pairs,min_gap,FR); /* move the particles */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { xcm_new[ipart][i] = xcm[ipart][i] + REX*FR[ipart][i]; } } /* find new xb */ for(ipart=0;ipart<npart;ipart++) { for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { xb[ipart][ibead][i] = xb[ipart][ibead][i] + (xcm_new[ipart][i] - xcm[ipart][i]); } } } /* update center of mass */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { xcm[ipart][i] = xcm_new[ipart][i]; } } itr_count++; } while (1); fp = fopen("overlap.txt","a+"); fprintf(fp,"%d\t%d\t%d\n ",overlaps,overlaps0,itr_count); fclose(fp); } /*----------------------------------------------------------------------------------- -------------------------------------------------------------------------------------*/ void compute_total_grid_vel(double xb[npart][beads][3], double fb[npart][beads][3], int psteps) { int i,j,k; int ibead,itriangle,jtriangle; double xi[3]; double r1; int i1,i2,i3; double pi; double u[3]; int member; double weights[npart][beads]; double uxf[nx][ny][nz], uyf[nx][ny][nz], uzf[nx][ny][nz],pf[nx][ny][nz]; double ubc1[nx][ny][3], ubc2[nx][ny][3]; double gaussx[nx][ny][nz],gaussy[nx][ny][nz],gaussz[nx][ny][nz],gaussz_p[nx][ny][nz]; FILE *fp; char name[20]; int ix,iy,iz; double dx,dy,dz; int ipart,jpart; double dudx[nx][ny][nz],dudy[nx][ny][nz],dudz[nx][ny][nz]; double dvdx[nx][ny][nz],dvdy[nx][ny][nz],dvdz[nx][ny][nz]; double dwdx[nx][ny][nz],dwdy[nx][ny][nz],dwdz[nx][ny][nz]; pi = 4.0*atan(1.0); /* Mesh size */ dx = Lx/nx; dy = Ly/ny; dz = Lz/(nz-1.0); #if (OMP == 1) omp_set_num_threads(NTHREADS); #endif /*---------------- Global solution calculation -----------------*/ /*----- Boundary Conditions ---- */ /* Initialize */ for(i=0;i<nx;i++) { for(j=0;j<ny;j++) { for(k=0;k<3;k++) { ubc1[i][j][k]=0.0; ubc2[i][j][k]=0.0; } } } /* set ubc = - u_l for poiseuille flow */ /* Top plate */ for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = Lz; for(itriangle=0;itriangle<triangle_count_t[ix][iy];itriangle++) { jpart = triangle_list_t[ix][iy][itriangle][0]; jtriangle = triangle_list_t[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc2[ix][iy][i] -= u[i]/8/pi; } } } } /* bottom plate */ for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = 0.0; for(itriangle=0;itriangle<triangle_count_b[ix][iy];itriangle++) { jpart = triangle_list_b[ix][iy][itriangle][0]; jtriangle = triangle_list_b[ix][iy][itriangle][1]; i1 = triangle[jtriangle][0]; i2 = triangle[jtriangle][1]; i3 = triangle[jtriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } else { integrate1(xb[jpart][i1],xb[jpart][i2],xb[jpart][i3],xi,fb[jpart][i1],fb[jpart][i2],fb[jpart][i3],u,alpha); } for(i=0;i<3;i++) { ubc1[ix][iy][i] -= u[i]/8/pi; } } } } /* Find weights for the global solution */ /* Initialize weights for the global solution */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<beads;i++) { weights[ipart][i]=0.0; } } for(ipart=0;ipart<npart;ipart++) { for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; /* Store weights for the global calculation */ weights[ipart][i1] += area[ipart][itriangle]/3.0; weights[ipart][i2] += area[ipart][itriangle]/3.0; weights[ipart][i3] += area[ipart][itriangle]/3.0; } } /* Distribute density to mesh */ /* Initialize mesh force density */ for(ix=0;ix<nx;ix++) { for(iy=0;iy<ny;iy++) { for(iz=0;iz<nz;iz++) { gaussx[ix][iy][iz] = 0.0; gaussy[ix][iy][iz] = 0.0; gaussz[ix][iy][iz] = 0.0; gaussz_p[ix][iy][iz] = 0.0; } } } for(ipart=0;ipart<npart;ipart++) { distribute_density(xb[ipart],fb[ipart],gaussx,gaussy,gaussz,gaussz_p,weights[ipart],alpha,xz); } /* solve for the velocity and pressure at the mesh points */ /* solve for the velocity and pressure at the mesh points */ global_velocity_inhomogeneous(gaussx,gaussy,gaussz,gaussz_p,ubc1,ubc2,uxf,uyf,uzf,pf, dudx,dudy,dudz,dvdx,dvdy,dvdz,dwdx,dwdy,dwdz, xxi,cz, u1H,v1H,w1H,dwdz1H,dudz1H,dvdz1H,p1H, u2H,v2H,w2H,dwdz2H,dudz2H,dvdz2H,p2H); /* Add local contribution to the velocity at grid points: doing in an umoptimized fashion, as this is for test purposes only */ #if (OMP == 1) #pragma omp parallel for private(ix,iy,iz,xi,itriangle,ipart,i1,i2,i3,member,u) #endif for(ix=0;ix<nx;ix++) { for(iy=ny/2;iy<ny/2+1;iy++) // midplane only { for(iz=0;iz<nz;iz++) { xi[0] = ix*dx; xi[1] = iy*dy; xi[2] = iz*dz; for(ipart=0;ipart<npart;ipart++) { for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; member=0; // performing non-singular integral as of now if (member == 1) { integrate2(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xi,fb[ipart][i1],fb[ipart][i2],fb[ipart][i3],u,alpha); } else { integrate1(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xi,fb[ipart][i1],fb[ipart][i2],fb[ipart][i3],u,alpha); } /* sum to grid velocity array */ uxf[ix][iy][iz] -= u[0]/8/pi; uyf[ix][iy][iz] -= u[1]/8/pi; uzf[ix][iy][iz] -= u[2]/8/pi; } } } } } if (CONDOR==0) { sprintf(name,"output/vel_grid_%03d.vtk",psteps); } else { sprintf(name,"vel_grid_%03d.vtk",psteps); } fp = fopen(name,"w+"); for(ix=0;ix<nx;ix++) { for(iz=0;iz<nz;iz++) { fprintf(fp,"%E\t%E\t%E\t%E\t%E\t%E\n",ix*dx,ny/2*dy,iz*dz,uxf[ix][ny/2][iz],uyf[ix][ny/2][iz],uzf[ix][ny/2][iz]); } } fclose(fp); } /*------------------------------------------------------------ Computes initial volume ------------------------------------------------------------*/ void compute_vol(double xb[beads][3], double xcm[3], double nrm[beads][3], double *Vol0, int ipart) { int itriangle; int i1,i2,i3; /*------- Volume averaged velocity inside the capsule----------- */ for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; // normal of beads //integrate_vol(xb[i1],xb[i2],xb[i3],xcm,nrm[i1],nrm[i2],nrm[i3],Vol0); // normal of triangel integrate_vol(xb[i1],xb[i2],xb[i3],xcm,normal_t[ipart][itriangle],normal_t[ipart][itriangle], normal_t[ipart][itriangle],Vol0); } } /*----------------------------------------------*/ /* -------- randomly rotates the swimmers ------ */ /*----------------------------------------------*/ void rand_rotate(double xb[npart][beads][3], double xcm0[npart][3]) { int i,j,k,ipart; double Qrot[3][3],urot[3],norm_rot,xrot[3],xrotn[3]; /* apply a random rotation */ srand(time(NULL)); for(ipart=0;ipart<npart;ipart++) { urot[0]= 1.0;//rand(); urot[1]= 0.0;//rand(); urot[2]= 1.0;//rand(); norm_rot = sqrt(urot[0]*urot[0]+urot[1]*urot[1]+urot[2]*urot[2]); urot[0] = urot[0]/norm_rot; urot[1] = urot[1]/norm_rot; urot[2] = urot[2]/norm_rot; for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Qrot[i][j] = 1.0-2.0*urot[i]*urot[j]; } else { Qrot[i][j]=-2.0*urot[i]*urot[j]; } } } for(i=0;i<beads;i++) { for(j=0;j<3;j++) { xrot[j] = xb[ipart][i][j] - xcm0[ipart][j]; } for(j=0;j<3;j++) { xrotn[j]=0.0; for(k=0;k<3;k++) { xrotn[j] += Qrot[j][k]*xrot[k]; } } for(j=0;j<3;j++) { xb[ipart][i][j] = xcm0[ipart][j] + xrotn[j]; } } } } /*------------------------------------------------------- */ /* -------- rotates the swimmers by directed angle------ */ /*--------------------------------------------------------*/ void dir_rotate(double xb[npart][beads][3], double xcm0[npart][3], double theta_rot) { int i,j,k,ipart; double Qrot[3][3],theta,pi,xrot[3],xrotn[3]; pi = 4.0*atan(1.0); /* apply a random rotation */ // srand(time(NULL)); theta = pi*(theta_rot/180); //printf("theta = %E\t cos = %E\t THETA_rot = %E\n",theta,cos(theta),theta_rot); for(ipart=0;ipart<npart;ipart++) { //urot[0]= 1.0;//rand(); //urot[1]= 0.0;//rand(); //urot[2]= 1.0;//rand(); //norm_rot = sqrt(urot[0]*urot[0]+urot[1]*urot[1]+urot[2]*urot[2]); //urot[0] = urot[0]/norm_rot; //urot[1] = urot[1]/norm_rot; //urot[2] = urot[2]/norm_rot; //for(i=0;i<3;i++) //{ //for(j=0;j<3;j++) //{ //if (i==j) //{ //Qrot[i][j] = 1.0-2.0*urot[i]*urot[j]; //} //else //{ //Qrot[i][j]=-2.0*urot[i]*urot[j]; //} //} //} /* First rotation by 90 about z-axis and theta about x-axis */ //Qrot[0][0] = 1; //Qrot[0][1] = 0; //Qrot[0][2] = 0; //Qrot[1][0] = 0; //Qrot[1][1] = cos(theta); //Qrot[1][2] = -sin(theta); //Qrot[2][0] = 0; //Qrot[2][1] = sin(theta); //Qrot[2][2] = cos(theta); /* First rotation by 90 about z-axis and theta about y-axis(commented part) */ Qrot[0][0] = cos(theta); Qrot[0][1] = 0; Qrot[0][2] = sin(theta); Qrot[1][0] = 0; Qrot[1][1] = 1; Qrot[1][2] = 0; Qrot[2][0] = -sin(theta); Qrot[2][1] = 0; Qrot[2][2] = cos(theta); for(i=0;i<beads;i++) { for(j=0;j<3;j++) { xrot[j] = xb[ipart][i][j] - xcm0[ipart][j]; } for(j=0;j<3;j++) { xrotn[j]=0.0; for(k=0;k<3;k++) { xrotn[j] += Qrot[j][k]*xrot[k]; } } for(j=0;j<3;j++) { xb[ipart][i][j] = xcm0[ipart][j] + xrotn[j]; } } } } /*----------------------------------------------------------------------------------- // rotates so as to make ibead=0 on the -ve z-axis -------------------------------------------------------------------------------------*/ void rotate_z_align(double xb[beads][3],double xcm[3]) { int i,j,k; int ibead; double norm; double u[3],Q[3][3],zp[3]; double xb_rot[beads][3]; /* find the displacement wrt to the center of mass */ for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { xb_rot[ibead][i] = xb[ibead][i] - xcm[i]; } } /* Store ibead=0 as the z-axis in the old frame of reference */ zp[0] = xb_rot[0][0]; zp[1] = xb_rot[0][1]; zp[2] = xb_rot[0][2]; /* find the rotation matrix: Use householder's algorithm */ if (fabs(zp[2]-1) > 1E-10) { u[0] = 0.0 - zp[0]; u[1] = 0.0 - zp[1]; u[2] = 1.0 - zp[2]; norm = sqrt(u[0]*u[0]+u[1]*u[1]+u[2]*u[2]); /* normalize */ u[0] = u[0]/norm; u[1] = u[1]/norm; u[2] = u[2]/norm; /* Find the Q matrix */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0 - 2.0*u[i]*u[j]; } else { Q[i][j] = -2.0*u[i]*u[j]; } } } } else // no rotation necessary Q=I { for(i=0;i<3;i++) { for(j=0;j<3;j++) { if (i==j) { Q[i][j] = 1.0; } else { Q[i][j] = 0.0; } } } } /* transform the coordinates */ for(ibead=0;ibead<beads;ibead++) { for(i=0;i<3;i++) { xb[ibead][i] = xcm[i]; for(j=0;j<3;j++) { xb[ibead][i] += Q[i][j]*xb_rot[ibead][j]; } } } } /*---------------------------------------------------------------*/ /*---- Computes the particle contribution to the stress tensor ---*/ /*---------------------------------------------------------------*/ void compute_bulk_stress_tensor(double xb[npart][beads][3],double xcm[npart][3], double fm[npart][beads][3],double ub[npart][beads][3],double nrm[npart][beads][3], double Sigma[npart][3][3],double Sigma_g[3][3],double Sigma_g1[3][3], double Sigma_g2[3][3],double Vcell, double viscr[npart], double Stime) { int i,j,k,ibead,ipart; int itriangle; int i1,i2,i3; double S12,N1,N2; double S12a,N1a,N2a; double S12b,N1b,N2b; int npart1,npart2; FILE *fp; char name[20]; double ndensity; npart2 = NRATIO*npart; npart1 = npart - npart2; /* Initialize */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma_g[i][j]=0.0; Sigma_g1[i][j]=0.0; Sigma_g2[i][j]=0.0; } } /*------- Particle's contribution to bulk stress tensor----------- */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma[ipart][i][j]=0.0; } } for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; // normal of beads // integrate_stress(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xcm[ipart],ub[ipart][i1],ub[ipart][i2], // ub[ipart][i3],nrm[ipart][i1],nrm[ipart][i2],nrm[ipart][i3],fm[ipart][i1], // fm[ipart][i2],fm[ipart][i3],Sigma[ipart],viscr[ipart]); // normal of triangle integrate_stress(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xcm[ipart],ub[ipart][i1],ub[ipart][i2], ub[ipart][i3],normal_t[ipart][itriangle],normal_t[ipart][itriangle],normal_t[ipart][itriangle], fm[ipart][i1], fm[ipart][i2],fm[ipart][i3],Sigma[ipart],viscr[ipart]); } } /* find the particle's contribution to bulk stress */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma_g[i][j] += Sigma[ipart][i][j]; } } } /* find the particle's contribution to bulk stress: Ist type */ for(ipart=0;ipart<npart1;ipart++) { for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma_g1[i][j] += Sigma[ipart][i][j]; } } } /* find the particle's contribution to bulk stress: 2nd type */ for(ipart=npart1;ipart<npart;ipart++) { for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma_g2[i][j] += Sigma[ipart][i][j]; } } } /* Volume averaged contribution */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { Sigma_g[i][j]=Sigma_g[i][j]/Vcell; Sigma_g1[i][j]=Sigma_g1[i][j]/Vcell*npart/npart1; if (npart2 > 0) { Sigma_g2[i][j]=Sigma_g2[i][j]/Vcell*npart/npart2; } } } S12 = 0.5*(Sigma_g[0][2]+Sigma_g[2][0]); // xy N1 = Sigma_g[0][0]-Sigma_g[2][2]; // xx - yy N2 = Sigma_g[2][2]-Sigma_g[1][1]; // yy - zz S12a = 0.5*(Sigma_g1[0][2]+Sigma_g1[2][0]); N1a = Sigma_g1[0][0]-Sigma_g1[2][2]; N2a = Sigma_g1[2][2]-Sigma_g1[1][1]; if (npart2 > 0) { S12b = 0.5*(Sigma_g2[0][2]+Sigma_g2[2][0]); N1b = Sigma_g2[0][0]-Sigma_g2[2][2]; N2b = Sigma_g2[2][2]-Sigma_g2[1][1]; } /* print */ if (CONDOR == 1) { fp = fopen("Stress.txt","a+"); } else { fp = fopen("output/Stress.txt","a+"); } if(npart2 > 0) { fprintf(fp,"%E %E %E\t%E %E %E\t%E %E %E\n",S12,N1,N2,S12a,N1a,N2a,S12b,N1b,N2b); } else { fprintf(fp,"%E %E %E\t%E %E %E\n",S12,N1,N2,S12a,N1a,N2a); } fclose(fp); if (PRINT == 1) { printf("S12 = %E\t N1 = %E\t N2 = %E\n",S12,N1,N2); printf("S12a = %E\t N1a = %E\t N2a = %E\n",S12a,N1a,N2a); if (npart2>0) { printf("S12b = %E\t N1b = %E\t N2b= %E\n",S12b,N1b,N2b); } } /* print per particle stress tensor */ ndensity = npart/Vcell; for(ipart=0;ipart<npart;ipart++) { if (CONDOR==1) { sprintf(name,"stress_%03d.txt",ipart); } else { sprintf(name,"output/stress_%03d.txt",ipart); } S12 = 0.5*(Sigma[ipart][0][2]+Sigma[ipart][2][0]); // xy N1 = Sigma[ipart][0][0]-Sigma[ipart][2][2]; // xx - yy N2 = Sigma[ipart][2][2]-Sigma[ipart][1][1]; // yy - zz fp = fopen(name,"a+"); fprintf(fp,"%E\t%E\t%E\n",S12*ndensity,N1*ndensity,N2*ndensity); fclose(fp); } } /*-------------------------------------------------------------------------------------*/ /* ----- Computes volume averaged velocity and rate of rotation of particles ---------*/ /*-------------------------------------------------------------------------------------*/ void volume_avg_u_omega(double ub[npart][beads][3],double nrm[npart][beads][3], double xcm[npart][3],double xb[npart][beads][3],double Stime) { int i,j,k,ibead,ipart; int itriangle; int i1,i2,i3; double pi; double uvol[npart][3],uvolw[npart]; double xcm_v[npart][3]; double Omega[3][3],omega[npart][3]; int epsilon[3][3][3]; double x1[3],x2[3],x3[3]; FILE *fp; char name[20]; pi = 4.0*atan(1.0); /* set permutation operator */ for(i=0;i<3;i++) { for(j=0;j<3;j++) { for(k=0;k<3;k++) { if(i==j || i==k || j==k) { epsilon[i][j][k]=0; } else { if(i==0) { if(j==1) { epsilon[i][j][k]=1; } else { epsilon[i][j][k]=-1; } } if(i==1) { if(j==2) { epsilon[i][j][k]=1; } else { epsilon[i][j][k]=-1; } } if(i==2) { if(j==0) { epsilon[i][j][k]=1; } else { epsilon[i][j][k]=-1; } } } } } } /*------- Volume averaged velocity and rotation inside the capsule----------- */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { uvol[ipart][i]=0.0; for(j=0;j<3;j++) { Omega[i][j]=0.0; } } uvolw[ipart]=0.0; for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; // normal of beads //integrate_trans_vol(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xcm[ipart],ub[ipart][i1],ub[ipart][i2],ub[ipart][i3],nrm[ipart][i1],nrm[ipart][i2],nrm[ipart][i3],uvol[ipart],Omega,&uvolw[ipart]); // normal of triangle integrate_trans_vol(xb[ipart][i1],xb[ipart][i2],xb[ipart][i3],xcm[ipart],ub[ipart][i1],ub[ipart][i2],ub[ipart][i3],normal_t[ipart][itriangle],normal_t[ipart][itriangle],normal_t[ipart][itriangle],uvol[ipart],Omega,&uvolw[ipart]); } /* volume averaged velocity */ for(i=0;i<3;i++) { uvol[ipart][i] = uvol[ipart][i]/uvolw[ipart]; } /* volume averaged rotation rate */ for(i=0;i<3;i++) { omega[ipart][i]=0.0; for(j=0;j<3;j++) { for(k=0;k<3;k++) { omega[ipart][i] += 0.5*epsilon[i][j][k]*Omega[j][k]; } } } } /*------- Volume averaged center of mass of the capsule----------- */ for(ipart=0;ipart<npart;ipart++) { for(i=0;i<3;i++) { xcm_v[ipart][i]=0.0; } for(itriangle=0;itriangle<ntriangles;itriangle++) { i1 = triangle[itriangle][0]; i2 = triangle[itriangle][1]; i3 = triangle[itriangle][2]; for(i=0;i<3;i++) { x1[i] = xb[ipart][i1][i] - xcm[ipart][i]; x2[i] = xb[ipart][i2][i] - xcm[ipart][i]; x3[i] = xb[ipart][i3][i] - xcm[ipart][i]; } // normal at beads //integrate_rsq_vol(x1,x2,x3,nrm[ipart][i1],nrm[ipart][i2],nrm[ipart][i3],xcm_v[ipart]); // normal of triangle integrate_rsq_vol(x1,x2,x3,normal_t[ipart][itriangle], normal_t[ipart][itriangle],normal_t[ipart][itriangle],xcm_v[ipart]); } for(i=0;i<3;i++) { xcm_v[ipart][i] = xcm_v[ipart][i]/uvolw[ipart] + xcm[ipart][i]; } } if(PRINT==1) { if (npart==1) { printf("Volume average U: %E\t%E\t%E\n",uvol[0][0],uvol[0][1],uvol[0][2]); printf("Vol avg CM: %E\t%E\t%E\n",xcm_v[0][0],xcm_v[0][1],xcm_v[0][2]); printf("Volume = %E\n",uvolw[0]/4/pi*3); } } for(ipart=0;ipart<npart;ipart++) { if (CONDOR==1) { sprintf(name,"pos_vel_%03d.txt",ipart); } else { sprintf(name,"output/pos_vel_%03d.txt",ipart); } fp = fopen(name,"a+"); fprintf(fp,"%E\t",Stime); #if (DETAILED==1) fprintf(fp,"%E\t%E\t%E\t",xcm_v[ipart][0],xcm_v[ipart][1],xcm_v[ipart][2]); fprintf(fp,"%E\t%E\t%E\t",uvol[ipart][0],uvol[ipart][1],uvol[ipart][2]); fprintf(fp,"%E\t%E\t%E\n",omega[ipart][0],omega[ipart][1],omega[ipart][2]); #else //fprintf(fp,"%E\t%E\t%E\n",xcm_v[ipart][0],xcm_v[ipart][1],xcm_v[ipart][2]); fprintf(fp,"%E\t%E\t%E\n",uvol[ipart][0],uvol[ipart][1],uvol[ipart][2]); #endif fclose(fp); } } /*----------------------------------------------------------------------------------- Find Taylor deformation parameter -------------------------------------------------------------------------------------*/ void deformation_parameter(double xb[beads][3],double xcm[3],double Le[3], double thetae[2],double phie[2]) { int i,j; double max=-100,min=100; double dist; double x,y,z; for(i=0;i<beads;i++) { x = xb[i][0]-xcm[0]; y = xb[i][1]-xcm[1]; z = xb[i][2]-xcm[2]; dist = sqrt(x*x+y*y+z*z); if (dist < min) { min = dist; Le[0] = dist; thetae[0] = acos(y/dist); phie[0] = atan(z/x); } if (dist > max) { max = dist; Le[1] = dist; thetae[1] = acos(y/dist); phie[1] = atan(z/x); } } } /*----------------------------------------------------------------------------------- Find Taylor deformation parameter using mass moment of inertia tensor -------------------------------------------------------------------------------------*/ void mmoi_deformation_parameter(double xb[beads][3], double xcm0[3], double DD[2], double Stime, int ipart, int print) { int i, j, k, ii, jj, kk; double mmoi[3][3],delta[3][3], xcm[3]; double dxij[3], dxjk[3], dxik[3]; double xcm_to_cm[3], normal[3], v[3]; double rij,rjk,rik,s,area_l,norm,theta_cm_to_cm, r2; int N, LDA, LWORK, INFO; double eigenv[3]; double* work; double wkopt; double lmax, lmin, lmid, pi; FILE *fp; char name[20]; pi = 4*atan2(1,1); for(i=0;i<3;i++) { for(j=0;j<3;j++) { mmoi[i][j] = 0.0; delta[i][j] = 0.0; } } for(i=0;i<3;i++) { delta[i][i] = 1.0; } for(i=0;i<ntriangles;i++) { for(j=0;j<3;j++) { dxij[j] = xb[triangle[i][1]][j]-xb[triangle[i][0]][j]; dxjk[j] = xb[triangle[i][2]][j]-xb[triangle[i][1]][j]; dxik[j] = xb[triangle[i][0]][j]-xb[triangle[i][2]][j]; } rij = sqrt(dot_product(3,dxij,dxij)); rjk = sqrt(dot_product(3,dxjk,dxjk)); rik = sqrt(dot_product(3,dxik,dxik)); s = 0.5*(rij+rjk+rik); area_l = sqrt(s*(s-rij)*(s-rjk)*(s-rik)); /* center of mass of the triangle */ for(j=0;j<3;j++) { xcm[j] = (xb[triangle[i][0]][j] + xb[triangle[i][1]][j] + xb[triangle[i][2]][j])/3.0; } cross_product(dxij, dxjk, normal); norm = sqrt(dot_product(3,normal,normal)); for(j=0;j<3;j++) { normal[j] = normal[j]/norm; } for(j=0;j<3;j++) { xcm_to_cm[j] = xcm0[j] - xcm[j]; } norm = sqrt(dot_product(3,xcm_to_cm,xcm_to_cm)); for(j=0;j<3;j++) { xcm_to_cm[j] = xcm_to_cm[j]/norm; } theta_cm_to_cm = acos(dot_product(3,normal,xcm_to_cm)); if(theta_cm_to_cm < pi/2.0) { for(j=0;j<3;j++) { normal[j] = -normal[j]; } } for(j=0;j<3;j++) { v[j] = xcm[j] - xcm0[j]; } r2 = dot_product(3,v,v); for(ii=0;ii<3;ii++) { for(jj=0;jj<3;jj++) { for(kk=0;kk<3;kk++) { mmoi[ii][jj] += (r2*v[kk]*delta[ii][jj] - v[ii]*v[jj]*v[kk])*normal[kk]*area_l; } } } } mmoi[1][0] = 0.0; mmoi[2][0] = 0.0; mmoi[2][1] = 0.0; N=3;LDA=3;LWORK=-1; dsyev_( "V", "L", &N, mmoi, &LDA, eigenv, &wkopt, &LWORK, &INFO ); LWORK = (int)wkopt; printf("%d",LWORK); work = (double*)malloc( LWORK*sizeof(double) ); /* Solve eigenproblem */ dsyev_( "V", "L", &N, mmoi, &LDA, eigenv, work, &LWORK, &INFO ); /* Check for convergence */ if( INFO > 0 ) { printf( "The algorithm failed to compute eigenvalues.\n" ); exit( 1 ); } //kaiser(mmoi, 3, 3, eigenv, trace, sume, ier); lmax = sqrt(eigenv[2]+eigenv[1]-eigenv[0]); lmin = sqrt(eigenv[1]+eigenv[0]-eigenv[2]); lmid = sqrt(eigenv[0]+eigenv[2]-eigenv[1]); DD[0] = (lmax-lmin)/(lmax+lmin); DD[1] = atan(mmoi[0][2]/mmoi[0][0]); /* Print Eigenvalues and Eigenvectors */ if (PRINT == 1 || print == 1) { if (CONDOR==1) { sprintf(name,"Eigenval_vector.txt"); } else { sprintf(name,"output/Eigenval_vector.txt"); } fp=fopen(name,"a+"); fprintf(fp,"%lf\t%d\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\t%lf\n",Stime,ipart,eigenv[0],eigenv[1],eigenv[2], mmoi[0][0],mmoi[0][1],mmoi[0][2],mmoi[1][0],mmoi[1][1],mmoi[1][2],mmoi[2][0],mmoi[2][1],mmoi[2][2]); fclose(fp); } } /*----------------------------------------------------------------------------------- find area weighted center of mass of the body -------------------------------------------------------------------------------------*/ void compute_center_mass_area(double xb[beads][3], double xcm0[3]) { int i,j; double xcm[3],xcm_to_cm[3]; double dxij[3],dxjk[3],dxik[3]; double rij,rjk,rik,s,theta_cm_to_cm; double area_sum=0.0; double area_l; for(i=0;i<3;i++) { xcm0[i]=0.0; } for(i=0;i<ntriangles;i++) { for(j=0;j<3;j++) { dxij[j] = xb[triangle[i][1]][j]-xb[triangle[i][0]][j]; dxjk[j] = xb[triangle[i][2]][j]-xb[triangle[i][1]][j]; dxik[j] = xb[triangle[i][0]][j]-xb[triangle[i][2]][j]; } rij = sqrt(dot_product(3,dxij,dxij)); rjk = sqrt(dot_product(3,dxjk,dxjk)); rik = sqrt(dot_product(3,dxik,dxik)); s = 0.5*(rij+rjk+rik); area_l = sqrt(s*(s-rij)*(s-rjk)*(s-rik)); area_sum += area_l; /* center of mass of the triangle */ for(j=0;j<3;j++) { xcm[j] = (xb[triangle[i][0]][j] + xb[triangle[i][1]][j] + xb[triangle[i][2]][j])/3.0; } /* sum to center of mass of the body */ for(j=0;j<3;j++) { xcm0[j] += xcm[j]*area_l; } } /* Find CM */ for(j=0;j<3;j++) { xcm0[j] = xcm0[j]/area_sum; } if(PRINT==1) { if (npart == 1) { printf("xcm=%lf\tycm=%lf\tzcm=%lf\trad=%lf\n",xcm0[0],xcm0[1],xcm0[2],sqrt(area_sum/4/3.14)); } } } /*----------------------------------------------------------------------------------- computes the traction at nodes due to the imposed flow:finf -------------------------------------------------------------------------------------*/ void compute_finf(double finf[beads][3],double xb[beads][3],double nrm[beads][3]) { int ibead; double pi; double U0; double gdot=GDOT; /* Compute the stress tensor and then traction at each node */ if (SHEAR==0) { /* set U0=centerline velocity */ U0 = gdot*Lz/4.0; for(ibead=0;ibead<beads;ibead++) { finf[ibead][0] = 8*U0*xb[ibead][0]/Lz/Lz*nrm[ibead][0] + 4*U0/Lz*(1-2*xb[ibead][2]/Lz)*nrm[ibead][2]; finf[ibead][1] = 8*U0*xb[ibead][0]/Lz/Lz*nrm[ibead][1]; finf[ibead][2] = 8*U0*xb[ibead][0]/Lz/Lz*nrm[ibead][2] + 4*U0/Lz*(1-2*xb[ibead][2]/Lz)*nrm[ibead][0]; } } else { for(ibead=0;ibead<beads;ibead++) { finf[ibead][0] = gdot*nrm[ibead][2]; finf[ibead][1] = 0.0; finf[ibead][2] = gdot*nrm[ibead][0]; } } } /*--------------------------------------------------*/ /* sets the viscosity ratio and membrane stiffness */ /*-------------------------------------------------*/ void set_viscr(double viscr[npart], double krbc_r[npart]) { int ipart; double randr; int npart1,npart2; npart2 = NRATIO*npart; npart1 = npart - npart2; /* set viscosity ratio */ if (LAMBDA == 1) { for(ipart=0;ipart<npart;ipart++) { viscr[ipart]=1.0; } } else { for(ipart=0;ipart<npart1;ipart++) { viscr[ipart]=LAMBDA1; } for(ipart=npart1;ipart<npart;ipart++) { viscr[ipart]=LAMBDA2; } } /* set membrane shear modulus */ for(ipart=0;ipart<npart1;ipart++) { krbc_r[ipart] = 1.0; } for(ipart=npart1;ipart<npart;ipart++) { krbc_r[ipart] = KRBC_R; } }
pi-v10.c
/* * Compute pi by approximating the area under the curve f(x) = 4 / (1 + x*x) * between 0 and 1. * * parallel version using OpenMP */ #include <stdio.h> #include <stdlib.h> #include <omp.h> /* OpenMP */ #if _DEBUG_ #define _DEBUG_ 1 #else #define _DEBUG_ 0 #include "extrae_user_events.h" #define PROGRAM 1000 #define PI_COMPUTATION 1 #define END 0 #endif int main(int argc, char *argv[]) { double x, sum=0.0, pi=0.0; #if _DEBUG_ double start,end; #endif int i; const char Usage[] = "Usage: pi <num_steps> (try 1000000000)\n"; if (argc < 2) { fprintf(stderr, Usage); exit(1); } int num_steps = atoi(argv[1]); double step = 1.0/(double) num_steps; #if _DEBUG_ start= omp_get_wtime(); #else Extrae_event (PROGRAM, PI_COMPUTATION); #endif /* do computation -- using all available threads */ // WARNING : correct code #pragma omp parallel private(i,x) reduction(+:sum) { #if _DEBUG_ int id = omp_get_thread_num(); #endif #pragma omp for schedule(dynamic,1000) for (i=0; i < num_steps; i++) { x = (i+0.5)*step; sum += 4.0/(1.0+x*x); #if _DEBUG_ printf("thread id:%d it:%d\n",id,i); #endif } } pi = step * sum; #if _DEBUG_ end = omp_get_wtime(); printf("Wall clock execution time = %.9f seconds\n", end-start); #else Extrae_event (PROGRAM, END); #endif /* print results */ printf("Value of pi = %12.10f\n", pi); return EXIT_SUCCESS; }
TensorNode.h
#ifndef TENSOR_NODE_H #define TENSOR_NODE_H #include <complex> #include <vector> #include <map> #include <exception> #include <stdlib.h> #include "Core/Utilities/QPandaNamespace.h" #include "Core/Utilities/Tools/QPandaException.h" using std::map; using std::complex; using std::vector; using std::exception; using std::pair; typedef float qdata_t; typedef size_t qsize_t; typedef complex<qdata_t> qcomplex_data_t; typedef vector<qcomplex_data_t> qstate_t; typedef vector<pair<qsize_t, qsize_t>> qubit_vector_t; class Edge; typedef map<size_t, Edge> EdgeMap; struct Mask { size_t first_maks; size_t second_maks; }; typedef struct Mask mask_t; class ComplexTensor { public: ~ComplexTensor(); int getRank() const; qcomplex_data_t getElem(size_t num); void mulElem(size_t, qcomplex_data_t); friend ComplexTensor matrixMultiplication(const ComplexTensor &matrix_left, const ComplexTensor &matrix_right); void dimIncrement(size_t) ; void getSubTensor(size_t num,int value); void dimDecrement(size_t num) ; void swap(qsize_t, qsize_t); qcomplex_data_t *get_tensor(); ComplexTensor & operator * (ComplexTensor &); // ComplexTensor operator + (ComplexTensor &); ComplexTensor& operator = (const ComplexTensor &); ComplexTensor(const ComplexTensor& old) :m_rank(old.m_rank) { auto size = 1ull << old.m_rank; m_tensor = (qcomplex_data_t *)calloc(size, sizeof(qcomplex_data_t)); if (nullptr == m_tensor) { QCERR("calloc_fail"); throw QPanda::calloc_fail(); } #pragma omp parallel for for (long long i = 0; i < size; i++) { m_tensor[i] = old.m_tensor[i]; } } ComplexTensor(int rank, qstate_t & tensor) :m_rank(rank) { auto size = 1ull << rank; m_tensor = (qcomplex_data_t *)calloc(size, sizeof(qcomplex_data_t)); if (nullptr == m_tensor) { QCERR("calloc_fail"); throw QPanda::calloc_fail(); } #pragma omp parallel for for (long long i = 0; i < size; i++) { m_tensor[i] = tensor[i]; } } ComplexTensor(int rank, qcomplex_data_t * tensor) :m_rank(rank) { auto size = 1ull << rank; m_tensor = (qcomplex_data_t *)calloc(size, sizeof(qcomplex_data_t)); if (nullptr == m_tensor) { QCERR("calloc_fail"); throw QPanda::calloc_fail(); } #pragma omp parallel for for (long long i = 0; i < size; i++) { m_tensor[i] = tensor[i]; } } private: ComplexTensor(); int m_rank; qcomplex_data_t * m_tensor; }; inline ComplexTensor::~ComplexTensor() { free(m_tensor); //m_tensor = nullptr; } class VerticeMatrix; class QuantumProgMap; class Edge { public: inline Edge(qsize_t qubit_count, ComplexTensor &tensor, vector<pair<qsize_t, qsize_t>> &contect_vertice) noexcept : m_tensor(tensor), m_contect_vertice(contect_vertice), m_qubit_count(qubit_count) { } ~Edge() {}; inline Edge(const Edge & old) : m_tensor(old.getComplexTensor()), m_qubit_count(old.m_qubit_count), m_contect_vertice(old.m_contect_vertice) { } void earseContectVertice(qsize_t qubit, size_t num); qsize_t getQubitCount()const noexcept; void premultiplication(Edge &); bool mergeEdge(Edge & ); void dimDecrementbyValue(qsize_t ,qsize_t, int value); void dimDecrement(qsize_t qubit, qsize_t num); void dimIncrementByEdge(Edge &); void getEdgeMap(Edge &, size_t *); void mul(Edge&, size_t * ); void swapByEdge(Edge &); int getRank() const noexcept; ComplexTensor getComplexTensor() const noexcept; qcomplex_data_t getElem(VerticeMatrix &vertice); void setComplexTensor( ComplexTensor &) noexcept; vector<pair<qsize_t, qsize_t>> getContectVertice() const noexcept; void setContectVerticeVector(const qubit_vector_t &) noexcept; void setContectVertice(qsize_t qubit, qsize_t src_num, qsize_t des_num); private: qsize_t m_qubit_count; ComplexTensor m_tensor; qubit_vector_t m_contect_vertice; }; class Vertice { public: inline Vertice(int value, vector<qsize_t> &contect_edge) noexcept :m_contect_edge(contect_edge), m_value(value) {} inline Vertice() : m_value(-1) {} ~Vertice() { } inline Vertice operator = (const Vertice & old) { m_value = old.getValue(); auto temp = old.m_contect_edge; m_contect_edge.resize(0); for (auto aiter : temp) { m_contect_edge.push_back(aiter); } return *this; } inline Vertice(const Vertice & old) { m_value = old.getValue(); auto temp = old.m_contect_edge; m_contect_edge.resize(0); for (auto aiter : temp) { m_contect_edge.push_back(aiter); } } vector<qsize_t> & getContectEdge() noexcept; void addContectEdge(qsize_t) noexcept; void setContectEdge(qsize_t, qsize_t); void setContectEdgebyID(qsize_t id, qsize_t value); void deleteContectEdge(qsize_t); int getValue() const noexcept; void setValue(int) noexcept; private: vector<qsize_t> m_contect_edge; int m_value; }; typedef map<qsize_t, Vertice> vertice_map_t; typedef vector<vertice_map_t> vertice_matrix_t; class VerticeMatrix { public: VerticeMatrix(); VerticeMatrix(const VerticeMatrix &); VerticeMatrix operator = (const VerticeMatrix &); qsize_t getQubitCount() const; qsize_t getVerticeCount() const; void subVerticeCount(); qsize_t addVertice(qsize_t); qsize_t addVertice(qsize_t, qsize_t); qsize_t addVertice(qsize_t,qsize_t, Vertice &); int getVerticeValue(qsize_t, qsize_t); qsize_t getEmptyVertice(); void setVerticeValue(qsize_t, qsize_t, int); void initVerticeMatrix(qsize_t); map<qsize_t, Vertice>::iterator deleteVertice(qsize_t, qsize_t); qsize_t getQubitVerticeLastID(qsize_t); vector<qsize_t> & getContectEdge(qsize_t, qsize_t); vertice_matrix_t::iterator begin()noexcept; vertice_matrix_t::iterator end()noexcept; vertice_matrix_t::iterator getQubitMapIter(qsize_t qubit)noexcept; vertice_map_t::iterator getQubitMapIterBegin(qsize_t qubit); vertice_map_t::iterator getQubitMapIterEnd(qsize_t qubit); vertice_map_t::iterator getVertice(qsize_t, qsize_t); void addContectEdge(qsize_t, qsize_t, qsize_t); void changeContectEdge(qsize_t, qsize_t, qsize_t,qsize_t); void deleteContectEdge(qsize_t, qsize_t, qsize_t); void clearVertice() noexcept; bool isEmpty() noexcept; void clear() noexcept; ~VerticeMatrix(); private: qsize_t m_qubit_count; qsize_t m_vertice_count; vector<map<qsize_t, Vertice>> m_vertice_matrix; }; class QuantumProgMap { private: VerticeMatrix * m_vertice_matrix; EdgeMap * m_edge_map; size_t m_qubit_num; public: QuantumProgMap() { m_vertice_matrix = new VerticeMatrix(); m_edge_map = new EdgeMap; } ~QuantumProgMap() { delete m_vertice_matrix; delete m_edge_map; } inline QuantumProgMap(const QuantumProgMap & old) { m_vertice_matrix = new VerticeMatrix(*(old.m_vertice_matrix)); m_edge_map = new EdgeMap(*(old.m_edge_map)); } inline VerticeMatrix * getVerticeMatrix() { return m_vertice_matrix; } inline void setQubitNum(size_t num) { m_qubit_num = num; } inline bool isEmptyQProg() { return ((m_vertice_matrix->isEmpty()) || (m_edge_map->empty()) || (m_qubit_num == 0)); } inline size_t getQubitNum() { return m_qubit_num; } inline EdgeMap * getEdgeMap() { return m_edge_map; } inline void clearVerticeValue() noexcept { m_vertice_matrix->clearVertice(); } inline void clear() noexcept { m_vertice_matrix->clear(); m_edge_map->clear(); m_qubit_num = 0;; } qsize_t getVerticeCount() const; }; #endif // !TENSOR_NODE_H
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * 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) /* 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, m, 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]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][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] = 4; tile_size[3] = 64; 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); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.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 for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(max(1,ceild(8*t2-Nz+9,4)),t1+1);t3<=min(floord(4*Nt+Ny-9,4),floord(4*t1+Ny-1,4));t3++) { for (t4=max(max(ceild(t1-14,16),ceild(8*t2-Nz-51,64)),ceild(4*t3-Ny-51,64));t4<=min(min(floord(4*Nt+Nx-9,64),floord(4*t1+Nx-1,64)),floord(4*t3+Nx-9,64));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(4*t3-Ny+5,4)),ceild(64*t4-Nx+5,4)),t1);t5<=min(min(min(Nt-1,t1+1),t3-1),16*t4+14);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=4*t3;t7<=min(4*t3+3,4*t5+Ny-5);t7++) { lbv=max(64*t4,4*t5+4); ubv=min(64*t4+63,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ 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, "variable axis-symmetric") #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(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
kernel_cos.c
/*! @copyright (c) 2017 King Abdullah University of Science and * Technology (KAUST). All rights reserved. * * STARS-H is a software package, provided by King Abdullah * University of Science and Technology (KAUST) * * @generate NDIM -> n 1 2 3 4 * Generate different functions for different dimensions. This hack improves * performance in certain cases. Value 'n' stands for general case, whereas all * other values correspond to static values of dimensionality. * During code generation step, each appearance of @NDIM (including this one) * will be replace by proposed values. If you want to use this file outside * STARS-H, simply do substitutions yourself. * * @file src/applications/electrodynamics/kernel_cos.c * @version 0.3.0 * @author Aleksandr Mikhalev * @date 2017-11-07 */ #include "common.h" #include "starsh.h" #include "starsh-electrodynamics.h" // If dimensionality is static #if (@NDIM != n) //! Replace variable ndim with static integer value #define ndim @NDIM #endif void starsh_eddata_block_cos_kernel_@NDIMd(int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, void *row_data, void *col_data, void *result, int ld) //! Helmholtz cos for @NDIM-dimensional electrodynamics problem. /*! Fills matrix \f$ A \f$ with values * \f[ * A_{ij} = \frac{cos(k r_{ij})}{r_{ij}}, * \f] * \f$ r_{ij} \f$ is a distance between \f$i\f$-th and \f$j\f$-th spatial * points and \f$ k \f$ is a wave number. No memory is allocated in this * function! * * @param[in] nrows: Number of rows of \f$ A \f$. * @param[in] ncols: Number of columns of \f$ A \f$. * @param[in] irow: Array of row indexes. * @param[in] icol: Array of column indexes. * @param[in] row_data: Pointer to physical data (@ref STARSH_eddata object). * @param[in] col_data: Pointer to physical data (@ref STARSH_eddata object). * @param[out] result: Pointer to memory of \f$ A \f$. * @param[in] ld: Leading dimension of `result`. * @sa starsh_eddata_block_cos_kernel_1d(), * starsh_eddata_block_cos_kernel_2d(), * starsh_eddata_block_cos_kernel_3d(), * starsh_eddata_block_cos_kernel_4d(), * starsh_eddata_block_cos_kernel_nd(). * @ingroup app-electrodynamics-kernels * */ { int i, j, k; STARSH_eddata *data1 = row_data; STARSH_eddata *data2 = col_data; double tmp, dist; // Read parameters // If dimensionality is not static #if (@NDIM == n) int ndim = data1->particles.ndim; #endif // Get coordinates STARSH_int count1 = data1->particles.count; STARSH_int count2 = data2->particles.count; double *x1[ndim], *x2[ndim]; double wave_k = data1->k; double diag = data1->diag; x1[0] = data1->particles.point; x2[0] = data2->particles.point; //#pragma omp simd for(i = 1; i < ndim; i++) { x1[i] = x1[0]+i*count1; x2[i] = x2[0]+i*count2; } double *x1_cur, *x2_cur; double *buffer = result; // Fill column-major matrix //#pragma omp simd for(j = 0; j < ncols; j++) { for(i = 0; i < nrows; i++) { dist = 0.0; for(k = 0; k < ndim; k++) { tmp = x1[k][irow[i]]-x2[k][icol[j]]; dist += tmp*tmp; } if(dist == 0) buffer[j*(size_t)ld+i] = diag; else { dist = sqrt(dist); buffer[j*(size_t)ld+i] = cos(wave_k*dist)/dist; } } } } void starsh_eddata_block_cos_kernel_@NDIMd_simd(int nrows, int ncols, STARSH_int *irow, STARSH_int *icol, void *row_data, void *col_data, void *result, int ld) //! Helmholtz cos for @NDIM-dimensional electrodynamics problem. /*! Fills matrix \f$ A \f$ with values * \f[ * A_{ij} = \frac{cos(k r_{ij})}{r_{ij}}, * \f] * \f$ r_{ij} \f$ is a distance between \f$i\f$-th and \f$j\f$-th spatial * points and \f$ k \f$ is a wave number. No memory is allocated in this * function! * * Uses SIMD instructions. * * @param[in] nrows: Number of rows of \f$ A \f$. * @param[in] ncols: Number of columns of \f$ A \f$. * @param[in] irow: Array of row indexes. * @param[in] icol: Array of column indexes. * @param[in] row_data: Pointer to physical data (@ref STARSH_eddata object). * @param[in] col_data: Pointer to physical data (@ref STARSH_eddata object). * @param[out] result: Pointer to memory of \f$ A \f$. * @param[in] ld: Leading dimension of `result`. * @sa starsh_eddata_block_cos_kernel_1d_simd(), * starsh_eddata_block_cos_kernel_2d_simd(), * starsh_eddata_block_cos_kernel_3d_simd(), * starsh_eddata_block_cos_kernel_4d_simd(), * starsh_eddata_block_cos_kernel_nd_simd(). * @ingroup app-electrodynamics-kernels * */ { int i, j, k; STARSH_eddata *data1 = row_data; STARSH_eddata *data2 = col_data; double tmp, dist; // Read parameters // If dimensionality is not static #if (@NDIM == n) int ndim = data1->particles.ndim; #endif // Get coordinates STARSH_int count1 = data1->particles.count; STARSH_int count2 = data2->particles.count; double *x1[ndim], *x2[ndim]; double wave_k = data1->k; double diag = data1->diag; x1[0] = data1->particles.point; x2[0] = data2->particles.point; #pragma omp simd for(i = 1; i < ndim; i++) { x1[i] = x1[0]+i*count1; x2[i] = x2[0]+i*count2; } double *x1_cur, *x2_cur; double *buffer = result; // Fill column-major matrix #pragma omp simd for(j = 0; j < ncols; j++) { for(i = 0; i < nrows; i++) { dist = 0.0; for(k = 0; k < ndim; k++) { tmp = x1[k][irow[i]]-x2[k][icol[j]]; dist += tmp*tmp; } if(dist == 0) buffer[j*(size_t)ld+i] = diag; else { dist = sqrt(dist); buffer[j*(size_t)ld+i] = cos(wave_k*dist)/dist; } } } }
broadcast_reduce_customized-inl.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. */ /*! * Copyright (c) 2015-2017 by Contributors * \file broadcast_reduce_customized-inl.h * \brief CPU-specific Function definition of broadcast and reduce operators */ #ifndef MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_ #define MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_ #include "../../tensor/broadcast_reduce-inl.h" namespace mxnet { namespace op { namespace broadcast { using namespace mshadow; template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, OType *small, const Shape<ndim>& bshape, const Shape<ndim>& sshape, const Shape<ndim>& rshape, const Shape<ndim>& rstride, Reducer* reducer) { Shape<ndim> coord = unravel(idx, sshape); index_t j = ravel(coord, bshape); AType val, residual; reducer->SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { coord = unravel(k, rshape); reducer->Reduce(val, AType(OP::Map(big[j + dot(coord, rstride)])), residual); } reducer->Finalize(val, residual); assign(&small[idx], addto, OType(val)); } #ifdef __CUDACC__ #include "broadcast_reduce_customized-inl.cuh" #include "../../tensor/broadcast_reduce-inl.cuh" #else template<typename Reducer, int ndim, typename AType, typename DType, typename OType, typename OP> void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto, const DType *big, OType *small, const Shape<ndim> bshape, const Shape<ndim> sshape, const Shape<ndim> rshape, const Shape<ndim> rstride, Reducer* reducer) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign_wr<Reducer, ndim, AType, DType, OType, OP>(idx, M, addto, big, small, bshape, sshape, rshape, rstride, reducer); } } template <typename Reducer, int ndim, typename DType, typename OP, bool safe_acc = false> void ReduceWithReducer(Stream<cpu>* s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big, Reducer* reducer) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(), M = rshape.Size(); if (!safe_acc) { seq_reduce_compute_wr<Reducer, ndim, DType, DType, DType, OP>( N, M, req == kAddTo, big.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer); } else { MXNET_ACC_TYPE_SWITCH(mshadow::DataType<DType>::kFlag, DataType, AType, { typedef typename std::conditional<safe_acc, AType, DataType>::type AccType; MSHADOW_TYPE_SWITCH_WITH_BOOL(small.type_flag_, OType, { typedef typename std::conditional<safe_acc, OType, DataType>::type OutType; seq_reduce_compute_wr<Reducer, ndim, AccType, DataType, OutType, OP>( N, M, req == kAddTo, big.dptr<DataType>(), small.dptr<OutType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, reducer); }); }); } } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> MSHADOW_XINLINE void seq_reduce_assign_wr(const index_t idx, const size_t M, const bool addto, const DType* __restrict big, const DType* __restrict lhs, const DType* __restrict rhs, DType *small, const Shape<ndim>& big_shape, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0, const Shape<ndim>& small_shape, const Shape<ndim>& rshape, const Shape<ndim>& lhs_shape, const Shape<ndim>& rhs_shape, const Shape<ndim>& rstride, const Shape<ndim>& lhs_stride, const Shape<ndim>& rhs_stride, Reducer* reducer) { Shape<ndim> coord = unravel(idx, small_shape); const index_t idx_big0 = ravel(coord, big_shape); const index_t idx_lhs0 = ravel(coord, lhs_shape0); const index_t idx_rhs0 = ravel(coord, rhs_shape0); DType val, residual; reducer->SetInitValue(val, residual); for (size_t k = 0; k < M; ++k) { Shape<ndim> coord_big = unravel(k, rshape); index_t idx_big = idx_big0 + dot(coord_big, rstride); Shape<ndim> coord_lhs = unravel(k, lhs_shape); index_t idx_lhs = idx_lhs0 + dot(coord_lhs, lhs_stride); Shape<ndim> coord_rhs = unravel(k, rhs_shape); index_t idx_rhs = idx_rhs0 + dot(coord_rhs, rhs_stride); reducer->Reduce(val, OP1::Map(big[idx_big], OP2::Map(lhs[idx_lhs], rhs[idx_rhs])), residual); } reducer->Finalize(val, residual); assign(&small[idx], addto, val); } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void seq_reduce_compute_wr(const size_t N, const size_t M, const bool addto, const DType *big, const DType *lhs, const DType *rhs, DType *small, const Shape<ndim> big_shape, const Shape<ndim> small_shape, const Shape<ndim> rshape, const Shape<ndim> rstride, const Shape<ndim> lhs_shape, const Shape<ndim> lhs_stride, const Shape<ndim> rhs_shape, const Shape<ndim> rhs_stride, const Shape<ndim>& lhs_shape0, const Shape<ndim>& rhs_shape0, Reducer* reducer) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t idx = 0; idx < static_cast<index_t>(N); ++idx) { seq_reduce_assign_wr<Reducer, ndim, DType, OP1, OP2>(idx, M, addto, big, lhs, rhs, small, big_shape, lhs_shape0, rhs_shape0, small_shape, rshape, lhs_shape, rhs_shape, rstride, lhs_stride, rhs_stride, reducer); } } template<typename Reducer, int ndim, typename DType, typename OP1, typename OP2> void ReduceWithReducer(Stream<cpu> *s, const TBlob& small, const OpReqType req, const Tensor<cpu, 1, char>& workspace, const TBlob& big, const TBlob& lhs, const TBlob& rhs, Reducer* reducer) { if (req == kNullOp) return; Shape<ndim> rshape, rstride; diff(small.shape_.get<ndim>(), big.shape_.get<ndim>(), &rshape, &rstride); size_t N = small.shape_.Size(); size_t M = rshape.Size(); Shape<ndim> lhs_shape, lhs_stride; diff(small.shape_.get<ndim>(), lhs.shape_.get<ndim>(), &lhs_shape, &lhs_stride); Shape<ndim> rhs_shape, rhs_stride; diff(small.shape_.get<ndim>(), rhs.shape_.get<ndim>(), &rhs_shape, &rhs_stride); seq_reduce_compute_wr<Reducer, ndim, DType, OP1, OP2>( N, M, req == kAddTo, big.dptr<DType>(), lhs.dptr<DType>(), rhs.dptr<DType>(), small.dptr<DType>(), big.shape_.get<ndim>(), small.shape_.get<ndim>(), rshape, rstride, lhs_shape, lhs_stride, rhs_shape, rhs_stride, lhs.shape_.get<ndim>(), rhs.shape_.get<ndim>(), reducer); } #endif } // namespace broadcast } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_NUMPY_LINALG_BROADCAST_REDUCE_CUSTOMIZED_INL_H_
Interp1PrimFifthOrderHCWENOChar.c
/*! @file Interp1PrimFifthOrderHCWENOChar.c @author Debojyoti Ghosh @brief Characteristic-based hybrid compact-WENO5 Scheme */ #include <stdio.h> #include <basic.h> #include <arrayfunctions.h> #include <mathfunctions.h> #include <interpolation.h> #include <tridiagLU.h> #include <mpivars.h> #include <hypar.h> #ifdef with_omp #include <omp.h> #endif #undef _MINIMUM_GHOSTS_ /*! \def _MINIMUM_GHOSTS_ * Minimum number of ghost points required for this interpolation * method. */ #define _MINIMUM_GHOSTS_ 3 /*! @brief 5th order hybrid compact-WENO reconstruction (characteristic-based) on a uniform grid Computes the interpolated values of the first primitive of a function \f${\bf f}\left({\bf u}\right)\f$ at the interfaces from the cell-centered values of the function using the fifth hybrid compact-WENO order scheme on a uniform grid. The reconstruction is carried out in terms of \f{equation}{ \alpha^k = {\bf l}_k \cdot {\bf f},\ k=1,\cdots,n, \f} which is the \f$k\f$-th characteristic quantity, and \f${\bf l}_k\f$ is the \f$k\f$-th left eigenvector, \f${\bf r}_k\f$ is the \f$k\f$-th right eigenvector, and \f$n\f$ is #HyPar::nvars. The block tridiagonal system is solved using blocktridiagLU() (see also #TridiagLU, tridiagLU.h). The final interpolated function is computed from the interpolated characteristic quantities as: \f{equation}{ \hat{\bf f}_{j+1/2} = \sum_{k=1}^n \alpha^k_{j+1/2} {\bf r}_k \f} See the references below for details of the hybrid compact-WENO scheme. \b Implementation \b Notes: + This method assumes a uniform grid in the spatial dimension corresponding to the interpolation. + The method described above corresponds to a left-biased interpolation. The corresponding right-biased interpolation can be obtained by reflecting the equations about interface j+1/2. + The WENO weights are computed in WENOFifthOrderCalculateWeightsChar(). + The left and right eigenvectors are computed at an averaged quantity at j+1/2. Thus, this function requires functions to compute the average state, and the left and right eigenvectors. These are provided by the physical model through - #HyPar::GetLeftEigenvectors() - #HyPar::GetRightEigenvectors() - #HyPar::AveragingFunction() If these functions are not provided by the physical model, then a characteristic-based interpolation cannot be used. + The function computes the interpolant for the entire grid in one call. It loops over all the grid lines along the interpolation direction and carries out the 1D interpolation along these grid lines. + Location of cell-centers and cell interfaces along the spatial dimension of the interpolation is shown in the following figure: @image html chap1_1Ddomain.png @image latex chap1_1Ddomain.eps width=0.9\textwidth \b Function \b arguments: Argument | Type | Explanation --------- | --------- | --------------------------------------------- fI | double* | Array to hold the computed interpolant at the grid interfaces. This array must have the same layout as the solution, but with \b no \b ghost \b points. Its size should be the same as u in all dimensions, except dir (the dimension along which to interpolate) along which it should be larger by 1 (number of interfaces is 1 more than the number of interior cell centers). fC | double* | Array with the cell-centered values of the flux function \f${\bf f}\left({\bf u}\right)\f$. This array must have the same layout and size as the solution, \b with \b ghost \b points. u | double* | The solution array \f${\bf u}\f$ (with ghost points). If the interpolation is characteristic based, this is needed to compute the eigendecomposition. For a multidimensional problem, the layout is as follows: u is a contiguous 1D array of size (nvars*dim[0]*dim[1]*...*dim[D-1]) corresponding to the multi-dimensional solution, with the following ordering - nvars, dim[0], dim[1], ..., dim[D-1], where nvars is the number of solution components (#HyPar::nvars), dim is the local size (#HyPar::dim_local), D is the number of spatial dimensions. x | double* | The grid array (with ghost points). This is used only by non-uniform-grid interpolation methods. For multidimensional problems, the layout is as follows: x is a contiguous 1D array of size (dim[0]+dim[1]+...+dim[D-1]), with the spatial coordinates along dim[0] stored from 0,...,dim[0]-1, the spatial coordinates along dim[1] stored along dim[0],...,dim[0]+dim[1]-1, and so forth. upw | int | Upwinding direction: if positive, a left-biased interpolant will be computed; if negative, a right-biased interpolant will be computed. If the interpolation method is central, then this has no effect. dir | int | Spatial dimension along which to interpolate (eg: 0 for 1D; 0 or 1 for 2D; 0,1 or 2 for 3D) s | void* | Solver object of type #HyPar: the following variables are needed - #HyPar::ghosts, #HyPar::ndims, #HyPar::nvars, #HyPar::dim_local. m | void* | MPI object of type #MPIVariables: this is needed only by compact interpolation method that need to solve a global implicit system across MPI ranks. uflag | int | A flag indicating if the function being interpolated \f${\bf f}\f$ is the solution itself \f${\bf u}\f$ (if 1, \f${\bf f}\left({\bf u}\right) \equiv {\bf u}\f$). \b Reference: + Pirozzoli, S., Conservative Hybrid Compact-WENO Schemes for Shock-Turbulence Interaction, J. Comput. Phys., 178 (1), 2002, pp. 81-117, http://dx.doi.org/10.1006/jcph.2002.7021 + Ren, Y.-X., Liu, M., Zhang, H., A characteristic-wise hybrid compact-WENO scheme for solving hyperbolic conservation laws, J. Comput. Phys., 192 (2), 2003, pp. 365-386, */ int Interp1PrimFifthOrderHCWENOChar( double *fI, /*!< Array of interpolated function values at the interfaces */ double *fC, /*!< Array of cell-centered values of the function \f${\bf f}\left({\bf u}\right)\f$ */ double *u, /*!< Array of cell-centered values of the solution \f${\bf u}\f$ */ double *x, /*!< Grid coordinates */ int upw, /*!< Upwind direction (left or right biased) */ int dir, /*!< Spatial dimension along which to interpolation */ void *s, /*!< Object of type #HyPar containing solver-related variables */ void *m, /*!< Object of type #MPIVariables containing MPI-related variables */ int uflag /*!< Flag to indicate if \f$f(u) \equiv u\f$, i.e, if the solution is being reconstructed */ ) { HyPar *solver = (HyPar*) s; MPIVariables *mpi = (MPIVariables*) m; CompactScheme *compact= (CompactScheme*) solver->compact; WENOParameters *weno = (WENOParameters*) solver->interp; TridiagLU *lu = (TridiagLU*) solver->lusolver; int sys,Nsys,d,v,k; _DECLARE_IERR_; int ghosts = solver->ghosts; int ndims = solver->ndims; int nvars = solver->nvars; int *dim = solver->dim_local; /* define some constants */ static const double one_half = 1.0/2.0; static const double one_third = 1.0/3.0; static const double one_sixth = 1.0/6.0; double *ww1, *ww2, *ww3; ww1 = weno->w1 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir]; ww2 = weno->w2 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir]; ww3 = weno->w3 + (upw < 0 ? 2*weno->size : 0) + (uflag ? weno->size : 0) + weno->offset[dir]; /* create index and bounds for the outer loop, i.e., to loop over all 1D lines along dimension "dir" */ int indexC[ndims], indexI[ndims], index_outer[ndims], bounds_outer[ndims], bounds_inter[ndims]; _ArrayCopy1D_(dim,bounds_outer,ndims); bounds_outer[dir] = 1; _ArrayCopy1D_(dim,bounds_inter,ndims); bounds_inter[dir] += 1; /* calculate total number of block tridiagonal systems to solve */ _ArrayProduct1D_(bounds_outer,ndims,Nsys); /* allocate arrays for the averaged state, eigenvectors and characteristic interpolated f */ double R[nvars*nvars], L[nvars*nvars], uavg[nvars]; /* Allocate arrays for tridiagonal system */ double *A = compact->A; double *B = compact->B; double *C = compact->C; double *F = compact->R; #pragma omp parallel for schedule(auto) default(shared) private(sys,d,v,k,R,L,uavg,index_outer,indexC,indexI) for (sys=0; sys<Nsys; sys++) { _ArrayIndexnD_(ndims,sys,bounds_outer,index_outer,0); _ArrayCopy1D_(index_outer,indexC,ndims); _ArrayCopy1D_(index_outer,indexI,ndims); for (indexI[dir] = 0; indexI[dir] < dim[dir]+1; indexI[dir]++) { int qm1,qm2,qm3,qp1,qp2; if (upw > 0) { indexC[dir] = indexI[dir]-3; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm3); indexC[dir] = indexI[dir]-2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm2); indexC[dir] = indexI[dir]-1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm1); indexC[dir] = indexI[dir] ; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp1); indexC[dir] = indexI[dir]+1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp2); } else { indexC[dir] = indexI[dir]+2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm3); indexC[dir] = indexI[dir]+1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm2); indexC[dir] = indexI[dir] ; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qm1); indexC[dir] = indexI[dir]-1; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp1); indexC[dir] = indexI[dir]-2; _ArrayIndex1D_(ndims,dim,indexC,ghosts,qp2); } int p; /* 1D index of the interface */ _ArrayIndex1D_(ndims,bounds_inter,indexI,0,p); /* find averaged state at this interface */ IERR solver->AveragingFunction(uavg,&u[nvars*qm1],&u[nvars*qp1],solver->physics); CHECKERR(ierr); /* Get the left and right eigenvectors */ IERR solver->GetLeftEigenvectors (uavg,L,solver->physics,dir); CHECKERR(ierr); IERR solver->GetRightEigenvectors (uavg,R,solver->physics,dir); CHECKERR(ierr); for (v=0; v<nvars; v++) { /* calculate the characteristic flux components along this characteristic */ double fm3, fm2, fm1, fp1, fp2; fm3 = fm2 = fm1 = fp1 = fp2 = 0; for (k = 0; k < nvars; k++) { fm3 += L[v*nvars+k] * fC[qm3*nvars+k]; fm2 += L[v*nvars+k] * fC[qm2*nvars+k]; fm1 += L[v*nvars+k] * fC[qm1*nvars+k]; fp1 += L[v*nvars+k] * fC[qp1*nvars+k]; fp2 += L[v*nvars+k] * fC[qp2*nvars+k]; } /* Candidate stencils and their optimal weights*/ double f1, f2, f3; if ( ((mpi->ip[dir] == 0 ) && (indexI[dir] == 0 )) || ((mpi->ip[dir] == mpi->iproc[dir]-1) && (indexI[dir] == dim[dir])) ) { /* Use WENO5 at the physical boundaries */ f1 = (2*one_sixth)*fm3 - (7.0*one_sixth)*fm2 + (11.0*one_sixth)*fm1; f2 = (-one_sixth)*fm2 + (5.0*one_sixth)*fm1 + (2*one_sixth)*fp1; f3 = (2*one_sixth)*fm1 + (5*one_sixth)*fp1 - (one_sixth)*fp2; } else { /* HCWENO5 at the interior points */ f1 = (one_sixth) * (fm2 + 5*fm1); f2 = (one_sixth) * (5*fm1 + fp1); f3 = (one_sixth) * (fm1 + 5*fp1); } /* calculate WENO weights */ double w1,w2,w3; w1 = *(ww1+p*nvars+v); w2 = *(ww2+p*nvars+v); w3 = *(ww3+p*nvars+v); /* calculate the hybridization parameter */ double sigma; if ( ((mpi->ip[dir] == 0 ) && (indexI[dir] == 0 )) || ((mpi->ip[dir] == mpi->iproc[dir]-1) && (indexI[dir] == dim[dir])) ) { /* Standard WENO at physical boundaries */ sigma = 0.0; } else { double cuckoo, df_jm12, df_jp12, df_jp32, r_j, r_jp1, r_int; cuckoo = (0.9*weno->rc / (1.0-0.9*weno->rc)) * weno->xi * weno->xi; df_jm12 = fm1 - fm2; df_jp12 = fp1 - fm1; df_jp32 = fp2 - fp1; r_j = (absolute(2*df_jp12*df_jm12)+cuckoo)/(df_jp12*df_jp12+df_jm12*df_jm12+cuckoo); r_jp1 = (absolute(2*df_jp32*df_jp12)+cuckoo)/(df_jp32*df_jp32+df_jp12*df_jp12+cuckoo); r_int = min(r_j, r_jp1); sigma = min((r_int/weno->rc), 1.0); } if (upw > 0) { for (k=0; k<nvars; k++) { A[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (one_half*sigma) * L[v*nvars+k]; B[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (1.0) * L[v*nvars+k]; C[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (one_sixth*sigma) * L[v*nvars+k]; } } else { for (k=0; k<nvars; k++) { C[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (one_half*sigma) * L[v*nvars+k]; B[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (1.0) * L[v*nvars+k]; A[(Nsys*indexI[dir]+sys)*nvars*nvars+v*nvars+k] = (one_sixth*sigma) * L[v*nvars+k]; } } double fWENO, fCompact; fWENO = w1*f1 + w2*f2 + w3*f3; fCompact = one_sixth * (one_third*fm2 + 19.0*one_third*fm1 + 10.0*one_third*fp1); F[(Nsys*indexI[dir]+sys)*nvars+v] = sigma*fCompact + (1.0-sigma)*fWENO; } } } #ifdef serial /* Solve the tridiagonal system */ IERR blocktridiagLU(A,B,C,F,dim[dir]+1,Nsys,nvars,lu,NULL); CHECKERR(ierr); #else /* Solve the tridiagonal system */ /* all processes except the last will solve without the last interface to avoid overlap */ if (mpi->ip[dir] != mpi->iproc[dir]-1) { IERR blocktridiagLU(A,B,C,F,dim[dir] ,Nsys,nvars,lu,&mpi->comm[dir]); CHECKERR(ierr); } else { IERR blocktridiagLU(A,B,C,F,dim[dir]+1,Nsys,nvars,lu,&mpi->comm[dir]); CHECKERR(ierr); } /* Now get the solution to the last interface from the next proc */ double *sendbuf = compact->sendbuf; double *recvbuf = compact->recvbuf; MPI_Request req[2] = {MPI_REQUEST_NULL,MPI_REQUEST_NULL}; if (mpi->ip[dir]) for (d=0; d<Nsys*nvars; d++) sendbuf[d] = F[d]; if (mpi->ip[dir] != mpi->iproc[dir]-1) MPI_Irecv(recvbuf,Nsys*nvars,MPI_DOUBLE,mpi->ip[dir]+1,214,mpi->comm[dir],&req[0]); if (mpi->ip[dir]) MPI_Isend(sendbuf,Nsys*nvars,MPI_DOUBLE,mpi->ip[dir]-1,214,mpi->comm[dir],&req[1]); MPI_Waitall(2,&req[0],MPI_STATUS_IGNORE); if (mpi->ip[dir] != mpi->iproc[dir]-1) for (d=0; d<Nsys*nvars; d++) F[d+Nsys*nvars*dim[dir]] = recvbuf[d]; #endif /* save the solution to fI */ #pragma omp parallel for schedule(auto) default(shared) private(sys,d,v,k,R,L,uavg,index_outer,indexC,indexI) for (sys=0; sys<Nsys; sys++) { _ArrayIndexnD_(ndims,sys,bounds_outer,index_outer,0); _ArrayCopy1D_(index_outer,indexI,ndims); for (indexI[dir] = 0; indexI[dir] < dim[dir]+1; indexI[dir]++) { int p; _ArrayIndex1D_(ndims,bounds_inter,indexI,0,p); _ArrayCopy1D_((F+sys*nvars+Nsys*nvars*indexI[dir]),(fI+nvars*p),nvars); } } return(0); }
irbuilder_unroll_partial_heuristic_runtime_for.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=51 -x c -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics // REQUIRES: x86-registered-target #ifndef HEADER #define HEADER double sind(double); // CHECK-LABEL: define {{.*}}@unroll_partial_heuristic_runtime_for( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[N_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[B_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[C_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[D_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[E_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[OFFSET_ADDR:.+]] = alloca float, align 4 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32 %[[N:.+]], i32* %[[N_ADDR]], align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store float* %[[B:.+]], float** %[[B_ADDR]], align 8 // CHECK-NEXT: store float* %[[C:.+]], float** %[[C_ADDR]], align 8 // CHECK-NEXT: store float* %[[D:.+]], float** %[[D_ADDR]], align 8 // CHECK-NEXT: store float* %[[E:.+]], float** %[[E_ADDR]], align 8 // CHECK-NEXT: store float %[[OFFSET:.+]], float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: store i32 0, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 1 // CHECK-NEXT: store i32* %[[N_ADDR]], i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP2:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[TMP2]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: %[[TMP4:.+]] = udiv i32 %[[DOTCOUNT]], 4 // CHECK-NEXT: %[[TMP5:.+]] = urem i32 %[[DOTCOUNT]], 4 // CHECK-NEXT: %[[TMP6:.+]] = icmp ne i32 %[[TMP5]], 0 // CHECK-NEXT: %[[TMP7:.+]] = zext i1 %[[TMP6]] to i32 // CHECK-NEXT: %[[OMP_FLOOR0_TRIPCOUNT:.+]] = add nuw i32 %[[TMP4]], %[[TMP7]] // CHECK-NEXT: br label %[[OMP_FLOOR0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_PREHEADER]]: // CHECK-NEXT: store i32 0, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP8:.+]] = sub i32 %[[OMP_FLOOR0_TRIPCOUNT]], 1 // CHECK-NEXT: store i32 %[[TMP8]], i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]], i32 1, i32 0) // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[TMP11:.+]] = sub i32 %[[TMP10]], %[[TMP9]] // CHECK-NEXT: %[[TMP12:.+]] = add i32 %[[TMP11]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_HEADER]]: // CHECK-NEXT: %[[OMP_FLOOR0_IV:.+]] = phi i32 [ 0, %[[OMP_FLOOR0_PREHEADER]] ], [ %[[OMP_FLOOR0_NEXT:.+]], %[[OMP_FLOOR0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_FLOOR0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_COND]]: // CHECK-NEXT: %[[OMP_FLOOR0_CMP:.+]] = icmp ult i32 %[[OMP_FLOOR0_IV]], %[[TMP12]] // CHECK-NEXT: br i1 %[[OMP_FLOOR0_CMP]], label %[[OMP_FLOOR0_BODY:.+]], label %[[OMP_FLOOR0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_BODY]]: // CHECK-NEXT: %[[TMP13:.+]] = add i32 %[[OMP_FLOOR0_IV]], %[[TMP9]] // CHECK-NEXT: %[[TMP14:.+]] = icmp eq i32 %[[TMP13]], %[[OMP_FLOOR0_TRIPCOUNT]] // CHECK-NEXT: %[[TMP15:.+]] = select i1 %[[TMP14]], i32 %[[TMP5]], i32 4 // CHECK-NEXT: br label %[[OMP_TILE0_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_PREHEADER]]: // CHECK-NEXT: br label %[[OMP_TILE0_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_HEADER]]: // CHECK-NEXT: %[[OMP_TILE0_IV:.+]] = phi i32 [ 0, %[[OMP_TILE0_PREHEADER]] ], [ %[[OMP_TILE0_NEXT:.+]], %[[OMP_TILE0_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_TILE0_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_COND]]: // CHECK-NEXT: %[[OMP_TILE0_CMP:.+]] = icmp ult i32 %[[OMP_TILE0_IV]], %[[TMP15]] // CHECK-NEXT: br i1 %[[OMP_TILE0_CMP]], label %[[OMP_TILE0_BODY:.+]], label %[[OMP_TILE0_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_BODY]]: // CHECK-NEXT: %[[TMP16:.+]] = mul nuw i32 4, %[[TMP13]] // CHECK-NEXT: %[[TMP17:.+]] = add nuw i32 %[[TMP16]], %[[OMP_TILE0_IV]] // CHECK-NEXT: br label %[[OMP_LOOP_BODY:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[TMP17]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP18:.+]] = load float*, float** %[[B_ADDR]], align 8 // CHECK-NEXT: %[[TMP19:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = sext i32 %[[TMP19]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP18]], i64 %[[IDXPROM]] // CHECK-NEXT: %[[TMP20:.+]] = load float, float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: %[[CONV:.+]] = fpext float %[[TMP20]] to double // CHECK-NEXT: %[[CALL:.+]] = call double @sind(double noundef %[[CONV]]) // CHECK-NEXT: %[[TMP21:.+]] = load float*, float** %[[C_ADDR]], align 8 // CHECK-NEXT: %[[TMP22:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM2:.+]] = sext i32 %[[TMP22]] to i64 // CHECK-NEXT: %[[ARRAYIDX3:.+]] = getelementptr inbounds float, float* %[[TMP21]], i64 %[[IDXPROM2]] // CHECK-NEXT: %[[TMP23:.+]] = load float, float* %[[ARRAYIDX3]], align 4 // CHECK-NEXT: %[[CONV4:.+]] = fpext float %[[TMP23]] to double // CHECK-NEXT: %[[MUL:.+]] = fmul double %[[CALL]], %[[CONV4]] // CHECK-NEXT: %[[TMP24:.+]] = load float*, float** %[[D_ADDR]], align 8 // CHECK-NEXT: %[[TMP25:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM5:.+]] = sext i32 %[[TMP25]] to i64 // CHECK-NEXT: %[[ARRAYIDX6:.+]] = getelementptr inbounds float, float* %[[TMP24]], i64 %[[IDXPROM5]] // CHECK-NEXT: %[[TMP26:.+]] = load float, float* %[[ARRAYIDX6]], align 4 // CHECK-NEXT: %[[CONV7:.+]] = fpext float %[[TMP26]] to double // CHECK-NEXT: %[[MUL8:.+]] = fmul double %[[MUL]], %[[CONV7]] // CHECK-NEXT: %[[TMP27:.+]] = load float*, float** %[[E_ADDR]], align 8 // CHECK-NEXT: %[[TMP28:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM9:.+]] = sext i32 %[[TMP28]] to i64 // CHECK-NEXT: %[[ARRAYIDX10:.+]] = getelementptr inbounds float, float* %[[TMP27]], i64 %[[IDXPROM9]] // CHECK-NEXT: %[[TMP29:.+]] = load float, float* %[[ARRAYIDX10]], align 4 // CHECK-NEXT: %[[CONV11:.+]] = fpext float %[[TMP29]] to double // CHECK-NEXT: %[[MUL12:.+]] = fmul double %[[MUL8]], %[[CONV11]] // CHECK-NEXT: %[[TMP30:.+]] = load float, float* %[[OFFSET_ADDR]], align 4 // CHECK-NEXT: %[[CONV13:.+]] = fpext float %[[TMP30]] to double // CHECK-NEXT: %[[ADD:.+]] = fadd double %[[MUL12]], %[[CONV13]] // CHECK-NEXT: %[[TMP31:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP32:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM14:.+]] = sext i32 %[[TMP32]] to i64 // CHECK-NEXT: %[[ARRAYIDX15:.+]] = getelementptr inbounds float, float* %[[TMP31]], i64 %[[IDXPROM14]] // CHECK-NEXT: %[[TMP33:.+]] = load float, float* %[[ARRAYIDX15]], align 4 // CHECK-NEXT: %[[CONV16:.+]] = fpext float %[[TMP33]] to double // CHECK-NEXT: %[[ADD17:.+]] = fadd double %[[CONV16]], %[[ADD]] // CHECK-NEXT: %[[CONV18:.+]] = fptrunc double %[[ADD17]] to float // CHECK-NEXT: store float %[[CONV18]], float* %[[ARRAYIDX15]], align 4 // CHECK-NEXT: br label %[[OMP_TILE0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_INC]]: // CHECK-NEXT: %[[OMP_TILE0_NEXT]] = add nuw i32 %[[OMP_TILE0_IV]], 1 // CHECK-NEXT: br label %[[OMP_TILE0_HEADER]], !llvm.loop ![[LOOP3:[0-9]+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_EXIT]]: // CHECK-NEXT: br label %[[OMP_TILE0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_TILE0_AFTER]]: // CHECK-NEXT: br label %[[OMP_FLOOR0_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_INC]]: // CHECK-NEXT: %[[OMP_FLOOR0_NEXT]] = add nuw i32 %[[OMP_FLOOR0_IV]], 1 // CHECK-NEXT: br label %[[OMP_FLOOR0_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_EXIT]]: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]]) // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM19:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM19]]) // CHECK-NEXT: br label %[[OMP_FLOOR0_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_FLOOR0_AFTER]]: // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } void unroll_partial_heuristic_runtime_for(int n, float *a, float *b, float *c, float *d, float *e, float offset) { #pragma omp for #pragma omp unroll partial for (int i = 0; i < n; i++) { a[i] += sind(b[i]) * c[i] * d[i] * e[i] + offset; } } #endif // HEADER // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 1 // CHECK-NEXT: %[[TMP5:.+]] = load i32*, i32** %[[TMP4]], align 8 // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[TMP5]], align 4 // CHECK-NEXT: store i32 %[[TMP6]], i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 1, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp slt i32 %[[TMP7]], %[[TMP8]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[TMP10:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub nsw i32 %[[TMP9]], %[[TMP10]] // CHECK-NEXT: %[[TMP11:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub i32 %[[TMP11]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB1]] // CHECK-NEXT: %[[TMP12:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[TMP12]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP13:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP13]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 1, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 51} // CHECK: ![[META2:[0-9]+]] = // CHECK: ![[LOOP3]] = distinct !{![[LOOP3]], ![[LOOPPROP4:[0-9]+]], ![[LOOPPROP5:[0-9]+]]} // CHECK: ![[LOOPPROP4]] = !{!"llvm.loop.unroll.enable"} // CHECK: ![[LOOPPROP5]] = !{!"llvm.loop.unroll.count", i32 4}
threshold.c
/* Copyright 2014. The Regents of the University of California. * Copyright 2015-2017. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2013-2017 Martin Uecker <martin.uecker@med.uni-goettingen.de> * 2015-2016 Jon Tamir <jtamir@eecs.berkeley.edu> * 2015 Frank Ong <frankong@berkeley.edu> */ #include <stdbool.h> #include <complex.h> #include "num/flpmath.h" #include "num/multind.h" #include "num/init.h" #include "num/ops_p.h" #include "iter/prox.h" #include "iter/thresh.h" #include "misc/mmio.h" #include "misc/misc.h" #include "misc/debug.h" #include "misc/opts.h" #include "lowrank/lrthresh.h" #include "linops/waveop.h" #include "dfwavelet/prox_dfwavelet.h" // FIXME: lowrank interface should not be coupled to mri.h -- it should take D as an input #ifndef DIMS #define DIMS 16 #endif // FIXME: consider moving this to a more accessible location? static void wthresh(unsigned int D, const long dims[D], float lambda, unsigned int flags, complex float* out, const complex float* in) { long minsize[D]; md_singleton_dims(D, minsize); long course_scale[3] = MD_INIT_ARRAY(3, 16); md_copy_dims(3, minsize, course_scale); unsigned int wflags = 7; // FIXME for (unsigned int i = 0; i < 3; i++) if (dims[i] < minsize[i]) wflags = MD_CLEAR(wflags, i); long strs[D]; md_calc_strides(D, strs, dims, CFL_SIZE); const struct linop_s* w = linop_wavelet_create(D, wflags, dims, strs, minsize, false); const struct operator_p_s* p = prox_unithresh_create(D, w, lambda, flags); operator_p_apply(p, 1., D, dims, out, D, dims, in); operator_p_free(p); } static void lrthresh(unsigned int D, const long dims[D], int llrblk, float lambda, unsigned int flags, complex float* out, const complex float* in) { long blkdims[MAX_LEV][D]; int levels = llr_blkdims(blkdims, ~flags, dims, llrblk); UNUSED(levels); const struct operator_p_s* p = lrthresh_create(dims, false, ~flags, (const long (*)[])blkdims, lambda, false, false, false); operator_p_apply(p, 1., D, dims, out, D, dims, in); operator_p_free(p); } static void dfthresh(unsigned int D, const long dims[D], float lambda, complex float* out, const complex float* in) { long minsize[D]; md_singleton_dims(D, minsize); long coarse_scale[3] = MD_INIT_ARRAY(3, 16); md_min_dims(3, ~0u, minsize, dims, coarse_scale); complex float res[3]; res[0] = 1.; res[1] = 1.; res[2] = 1.; assert(3 == dims[TE_DIM]); const struct operator_p_s* p = prox_dfwavelet_create(dims, minsize, res, TE_DIM, lambda, false); operator_p_apply(p, 1., D, dims, out, D, dims, in); operator_p_free(p); } static void hard_thresh(unsigned int D, const long dims[D], float lambda, complex float* out, const complex float* in) { long size = md_calc_size(DIMS, dims); #pragma omp parallel for for (long i = 0; i < size; i++) out[i] = (cabsf(in[i]) > lambda) ? in[i] : 0.; } static void binary_thresh(unsigned int D, const long dims[D], float lambda, complex float* out, const complex float* in) { long size = md_calc_size(DIMS, dims); #pragma omp parallel for for (long i = 0; i < size; i++) out[i] = (cabsf(in[i]) > lambda) ? 1. : 0.; } static const char help_str[] = "Perform (soft) thresholding with parameter lambda."; int main_threshold(int argc, char* argv[argc]) { float lambda = 0.; const char* in_file = NULL; const char* out_file = NULL; struct arg_s args[] = { ARG_FLOAT(true, &lambda, "lambda"), ARG_INFILE(true, &in_file, "input"), ARG_OUTFILE(true, &out_file, "output"), }; unsigned int flags = 0; enum th_type { NONE, WAV, LLR, DFW, MPDFW, HARD, BINARY } th_type = NONE; int llrblk = 8; const struct opt_s opts[] = { OPT_SELECT('H', enum th_type, &th_type, HARD, "hard thresholding"), OPT_SELECT('W', enum th_type, &th_type, WAV, "daubechies wavelet soft-thresholding"), OPT_SELECT('L', enum th_type, &th_type, LLR, "locally low rank soft-thresholding"), OPT_SELECT('D', enum th_type, &th_type, DFW, "divergence-free wavelet soft-thresholding"), OPT_SELECT('B', enum th_type, &th_type, BINARY, "thresholding with binary output"), OPT_UINT('j', &flags, "bitmask", "joint soft-thresholding"), OPT_INT('b', &llrblk, "blocksize", "locally low rank block size"), }; cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts); num_init(); const int N = DIMS; long dims[N]; complex float* idata = load_cfl(in_file, N, dims); complex float* odata = create_cfl(out_file, N, dims); switch (th_type) { case WAV: wthresh(N, dims, lambda, flags, odata, idata); break; case LLR: lrthresh(N, dims, llrblk, lambda, flags, odata, idata); break; case DFW: dfthresh(N, dims, lambda, odata, idata); break; case HARD: hard_thresh(N, dims, lambda, odata, idata); break; case BINARY: binary_thresh(N, dims, lambda, odata, idata); break; default: md_zsoftthresh(N, dims, lambda, flags, odata, idata); } unmap_cfl(N, dims, idata); unmap_cfl(N, dims, odata); return 0; }
add_sparse_gradient.h
/* * Copyright 1999-2017 Alibaba Group. * * 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 XDL_CORE_OPS_ADD_SPARSE_GRADIENT_H_ #define XDL_CORE_OPS_ADD_SPARSE_GRADIENT_H_ #include <omp.h> #include "xdl/core/framework/op_kernel.h" #include "xdl/core/framework/op_registry.h" #include "xdl/core/lib/atomic.h" #include "xdl/core/backend/device_singleton.h" namespace xdl { struct Indice { unsigned int i; unsigned int j; Indice(size_t i, size_t j) : i(i), j(j) {} }; template <typename T, typename I> void HostAddSparse(const std::vector<Tensor>& in_grads, const std::vector<Tensor>& in_ids, Tensor* out_grads, Tensor* out_ids) { size_t count = 0; std::vector<std::vector<Indice>> indices_vec; bool is_hash64 = (in_ids[0].Shape().Size() == 1); if (is_hash64) { std::unordered_map<I, size_t> uniq_map; for (size_t i = 0; i < in_ids.size(); ++i) { size_t n = in_ids[i].Shape()[0]; I* pid = in_ids[i].Raw<I>(); for (size_t j = 0; j < n; ++j) { auto iter = uniq_map.insert(std::make_pair(pid[j], count)); if (iter.second) { ++count; indices_vec.push_back(std::vector<Indice>{Indice(i, j)}); } else { indices_vec[iter.first->second].push_back(Indice(i, j)); } } } } else { auto hash_fn = [](const std::pair<I, I>& id) { size_t x = std::hash<I>()(id.first); size_t y = std::hash<I>()(id.second); x = ((x & 0xAAAAAAAAAAAAAAAAL) >> 1) + ((x & 0x5555555555555555L) << 1); y = ((y & 0xCCCCCCCCCCCCCCCCL) >> 2) + ((y & 0x3333333333333333L) << 2); return x ^ y; }; auto equal_fn = [](const std::pair<I, I>& lhs, const std::pair<I, I>& rhs) { return lhs.first == rhs.first && lhs.second == rhs.second; }; std::unordered_map<std::pair<I, I>, size_t, decltype(hash_fn), decltype(equal_fn)> uniq_map(0, hash_fn, equal_fn); for (size_t i = 0; i < in_ids.size(); ++i) { size_t n = in_ids[i].Shape()[0]; I* pid = in_ids[i].Raw<I>(); for (size_t j = 0; j < n; ++j) { auto iter = uniq_map.insert(std::make_pair(std::make_pair(pid[j*2], pid[j*2+1]), count)); if (iter.second) { ++count; indices_vec.push_back(std::vector<Indice>{Indice(i, j)}); } else { indices_vec[iter.first->second].push_back(Indice(i, j)); } } } } TensorShape id_shape = in_ids[0].Shape(); id_shape.Set(0, count); *out_ids = Tensor(DeviceSingleton::CpuInstance(), id_shape, in_ids[0].Type()); I* pid_out = out_ids->Raw<I>(); size_t eb_dim = in_grads[0].Shape()[1]; TensorShape uniq_shape({count, eb_dim}); *out_grads = Tensor(DeviceSingleton::CpuInstance(), uniq_shape, in_grads[0].Type()); T* puniq = out_grads->Raw<T>(); #pragma omp parallel for for (size_t c = 0; c < count; ++c) { const std::vector<Indice>& indices = indices_vec[c]; size_t s = 0; const unsigned int i = indices[s].i, j = indices[s].j; if (is_hash64) { pid_out[c] = in_ids[i].Raw<I>()[j]; } else { pid_out[c*2] = in_ids[i].Raw<I>()[j*2]; pid_out[c*2+1] = in_ids[i].Raw<I>()[j*2+1]; } T* p = puniq + c*eb_dim; T* pgrad = in_grads[i].Raw<T>() + j*eb_dim; memcpy(p, pgrad, eb_dim * sizeof(T)); //for (size_t k = 0; k < eb_dim; ++k) p[k] = pgrad[k]; for (s = 1; s < indices.size(); ++s) { T* pgrad = in_grads[indices[s].i].Raw<T>() + indices[s].j*eb_dim; for (size_t k = 0; k < eb_dim; ++k) { p[k] += pgrad[k]; } } } } } // namespace xdl #endif // XDL_CORE_OPS_ADD_SPARSE_GRADIENT_H_
GradientStrengthImageFilter.h
/* * MIT License * * Copyright (c) 2018-2019 Benjamin Köhler * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #pragma once #ifndef BK_GRADIENTSTRENGTHIMAGEFILTER_H #define BK_GRADIENTSTRENGTHIMAGEFILTER_H #include <bkMath/functions/list_grid_id_conversion.h> #ifdef BK_EMIT_PROGRESS #include <bk/Progress> #include <bk/Localization> #endif namespace bk { class GradientStrengthImageFilter { //==================================================================================================== //===== DEFINITIONS //==================================================================================================== using self_type = GradientStrengthImageFilter; //==================================================================================================== //===== CONSTRUCTORS & DESTRUCTOR //==================================================================================================== public: /// @{ -------------------------------------------------- CTOR constexpr GradientStrengthImageFilter() = default; constexpr GradientStrengthImageFilter(const self_type&) = default; constexpr GradientStrengthImageFilter(self_type&&) noexcept = default; /// @} /// @{ -------------------------------------------------- DTOR ~GradientStrengthImageFilter() = default; /// @} //==================================================================================================== //===== SETTER //==================================================================================================== /// @{ -------------------------------------------------- OPERATOR = [[maybe_unused]] constexpr auto operator=(const self_type& other) -> self_type& = default; [[maybe_unused]] constexpr auto operator=(self_type&& other) noexcept -> self_type& = default; /// @} //==================================================================================================== //===== FUNCTIONS //==================================================================================================== /// @{ -------------------------------------------------- APPLY template<typename TImage> [[nodiscard]] static typename TImage::template self_template_type<double> apply(const TImage& img) { #ifdef BK_EMIT_PROGRESS bk::Progress& prog = bk_progress.emplace_task(10 + img.num_values(), ___("Gradient strength filter")); #endif typename TImage::template self_template_type<double> res; res.set_size(img.size()); #ifdef BK_EMIT_PROGRESS prog.increment(10); #endif #pragma omp parallel for for (unsigned int i = 0; i < img.num_values(); ++i) { res[i] = img.gradient_strength(bk::list_to_grid_id(img.size(), i)); #ifdef BK_EMIT_PROGRESS #pragma omp critical(filter_gradient_strength) { prog.increment(1); } #endif } #ifdef BK_EMIT_PROGRESS prog.set_finished(); #endif return res; } /// @} }; // class GradientStrengthImageFilter } // namespace bk #endif //BK_GRADIENTSTRENGTHIMAGEFILTER_H
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-2020 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/accelerate-private.h" #include "MagickCore/annotate.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/fx-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resample.h" #include "MagickCore/resample-private.h" #include "MagickCore/resize.h" #include "MagickCore/resource_.h" #include "MagickCore/splay-tree.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/transform.h" #include "MagickCore/transform-private.h" #include "MagickCore/utility.h" /* Typedef declarations. */ typedef enum { BitwiseAndAssignmentOperator = 0xd9U, BitwiseOrAssignmentOperator, LeftShiftAssignmentOperator, RightShiftAssignmentOperator, PowerAssignmentOperator, ModuloAssignmentOperator, PlusAssignmentOperator, SubtractAssignmentOperator, MultiplyAssignmentOperator, DivideAssignmentOperator, IncrementAssignmentOperator, DecrementAssignmentOperator, LeftShiftOperator, RightShiftOperator, LessThanEqualOperator, GreaterThanEqualOperator, EqualOperator, NotEqualOperator, LogicalAndOperator, LogicalOrOperator, ExponentialNotation } FxOperator; 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 *images,const char *expression, % ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o expression: the expression. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate FxInfo *AcquireFxInfo(const Image *images,const char *expression, ExceptionInfo *exception) { const Image *next; FxInfo *fx_info; register ssize_t i; unsigned char fx_op[2]; fx_info=(FxInfo *) AcquireCriticalMemory(sizeof(*fx_info)); (void) memset(fx_info,0,sizeof(*fx_info)); fx_info->exception=AcquireExceptionInfo(); fx_info->images=images; fx_info->colors=NewSplayTree(CompareSplayTreeString,RelinquishMagickMemory, RelinquishMagickMemory); 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,exception); i++; } fx_info->random_info=AcquireRandomInfo(); fx_info->expression=ConstantString(expression); fx_info->file=stderr; /* Convert compound to simple operators. */ fx_op[1]='\0'; *fx_op=(unsigned char) BitwiseAndAssignmentOperator; (void) SubstituteString(&fx_info->expression,"&=",(char *) fx_op); *fx_op=(unsigned char) BitwiseOrAssignmentOperator; (void) SubstituteString(&fx_info->expression,"|=",(char *) fx_op); *fx_op=(unsigned char) LeftShiftAssignmentOperator; (void) SubstituteString(&fx_info->expression,"<<=",(char *) fx_op); *fx_op=(unsigned char) RightShiftAssignmentOperator; (void) SubstituteString(&fx_info->expression,">>=",(char *) fx_op); *fx_op=(unsigned char) PowerAssignmentOperator; (void) SubstituteString(&fx_info->expression,"^=",(char *) fx_op); *fx_op=(unsigned char) ModuloAssignmentOperator; (void) SubstituteString(&fx_info->expression,"%=",(char *) fx_op); *fx_op=(unsigned char) PlusAssignmentOperator; (void) SubstituteString(&fx_info->expression,"+=",(char *) fx_op); *fx_op=(unsigned char) SubtractAssignmentOperator; (void) SubstituteString(&fx_info->expression,"-=",(char *) fx_op); *fx_op=(unsigned char) MultiplyAssignmentOperator; (void) SubstituteString(&fx_info->expression,"*=",(char *) fx_op); *fx_op=(unsigned char) DivideAssignmentOperator; (void) SubstituteString(&fx_info->expression,"/=",(char *) fx_op); *fx_op=(unsigned char) IncrementAssignmentOperator; (void) SubstituteString(&fx_info->expression,"++",(char *) fx_op); *fx_op=(unsigned char) DecrementAssignmentOperator; (void) SubstituteString(&fx_info->expression,"--",(char *) fx_op); *fx_op=(unsigned char) LeftShiftOperator; (void) SubstituteString(&fx_info->expression,"<<",(char *) fx_op); *fx_op=(unsigned char) RightShiftOperator; (void) SubstituteString(&fx_info->expression,">>",(char *) fx_op); *fx_op=(unsigned char) LessThanEqualOperator; (void) SubstituteString(&fx_info->expression,"<=",(char *) fx_op); *fx_op=(unsigned char) GreaterThanEqualOperator; (void) SubstituteString(&fx_info->expression,">=",(char *) fx_op); *fx_op=(unsigned char) EqualOperator; (void) SubstituteString(&fx_info->expression,"==",(char *) fx_op); *fx_op=(unsigned char) NotEqualOperator; (void) SubstituteString(&fx_info->expression,"!=",(char *) fx_op); *fx_op=(unsigned char) LogicalAndOperator; (void) SubstituteString(&fx_info->expression,"&&",(char *) fx_op); *fx_op=(unsigned char) LogicalOrOperator; (void) SubstituteString(&fx_info->expression,"||",(char *) fx_op); *fx_op=(unsigned char) ExponentialNotation; (void) SubstituteString(&fx_info->expression,"**",(char *) fx_op); /* 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-"); (void) SubstituteString(&fx_info->expression," ",""); /* compact string */ return(fx_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + 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. % */ MagickPrivate 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: % % double FxEvaluateChannelExpression(FxInfo *fx_info, % const PixelChannel channel,const ssize_t x,const ssize_t y, % double *alpha,Exceptioninfo *exception) % double 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 inline const double *GetFxSymbolValue(FxInfo *magick_restrict fx_info, const char *symbol) { return((const double *) GetValueFromSplayTree(fx_info->symbols,symbol)); } static inline MagickBooleanType SetFxSymbolValue( FxInfo *magick_restrict fx_info,const char *magick_restrict symbol, double const value) { double *object; object=(double *) GetValueFromSplayTree(fx_info->symbols,symbol); if (object != (double *) NULL) { *object=value; return(MagickTrue); } object=(double *) AcquireMagickMemory(sizeof(*object)); if (object == (double *) NULL) { (void) ThrowMagickException(fx_info->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", fx_info->images->filename); return(MagickFalse); } *object=value; return(AddValueToSplayTree(fx_info->symbols,ConstantString(symbol),object)); } static double FxChannelStatistics(FxInfo *fx_info,Image *image, PixelChannel channel,const char *symbol,ExceptionInfo *exception) { ChannelType channel_mask; char key[MagickPathExtent]; const double *value; double statistic; register const char *p; channel_mask=UndefinedChannel; for (p=symbol; (*p != '.') && (*p != '\0'); p++) ; if (*p == '.') { ssize_t option; option=ParseCommandOption(MagickPixelChannelOptions,MagickTrue,p+1); if (option >= 0) { channel=(PixelChannel) option; channel_mask=SetPixelChannelMask(image,(ChannelType) (1UL << channel)); } } (void) FormatLocaleString(key,MagickPathExtent,"%p.%.20g.%s",(void *) image, (double) channel,symbol); value=GetFxSymbolValue(fx_info,key); if (value != (const double *) NULL) { if (channel_mask != UndefinedChannel) (void) SetPixelChannelMask(image,channel_mask); return(QuantumScale*(*value)); } statistic=0.0; if (LocaleNCompare(symbol,"depth",5) == 0) { size_t depth; depth=GetImageDepth(image,exception); statistic=(double) depth; } if (LocaleNCompare(symbol,"kurtosis",8) == 0) { double kurtosis, skewness; (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); statistic=kurtosis; } if (LocaleNCompare(symbol,"maxima",6) == 0) { double maxima, minima; (void) GetImageRange(image,&minima,&maxima,exception); statistic=maxima; } if (LocaleNCompare(symbol,"mean",4) == 0) { double mean, standard_deviation; (void) GetImageMean(image,&mean,&standard_deviation,exception); statistic=mean; } if (LocaleNCompare(symbol,"median",6) == 0) { double median; (void) GetImageMedian(image,&median,exception); statistic=median; } if (LocaleNCompare(symbol,"minima",6) == 0) { double maxima, minima; (void) GetImageRange(image,&minima,&maxima,exception); statistic=minima; } if (LocaleNCompare(symbol,"skewness",8) == 0) { double kurtosis, skewness; (void) GetImageKurtosis(image,&kurtosis,&skewness,exception); statistic=skewness; } if (LocaleNCompare(symbol,"standard_deviation",18) == 0) { double mean, standard_deviation; (void) GetImageMean(image,&mean,&standard_deviation,exception); statistic=standard_deviation; } if (channel_mask != UndefinedChannel) (void) SetPixelChannelMask(image,channel_mask); if (SetFxSymbolValue(fx_info,key,statistic) == MagickFalse) return(0.0); return(QuantumScale*statistic); } static double FxEvaluateSubexpression(FxInfo *,const PixelChannel,const ssize_t, const ssize_t,const char *,const size_t,double *,ExceptionInfo *); static inline MagickBooleanType IsFxFunction(const char *expression, const char *name,const size_t length) { int c; register size_t i; for (i=0; i <= length; i++) if (expression[i] == '\0') return(MagickFalse); c=expression[length]; if ((LocaleNCompare(expression,name,length) == 0) && ((isspace(c) == 0) || (c == '('))) return(MagickTrue); return(MagickFalse); } static inline double FxGCD(const double alpha,const double beta) { if (alpha < beta) return(FxGCD(beta,alpha)); if (fabs(beta) < 0.001) return(alpha); return(FxGCD(beta,alpha-beta*floor(alpha/beta))); } 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 PixelChannel channel, const ssize_t x,const ssize_t y,const char *expression,const size_t depth, ExceptionInfo *exception) { char *q, symbol[MagickPathExtent]; const char *artifact, *p; const double *value; double alpha, beta; Image *image; MagickBooleanType status; PixelInfo 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); GetPixelInfo(image,&pixel); status=InterpolatePixelInfo(image,fx_info->view[i],image->interpolate, point.x,point.y,&pixel,exception); (void) status; if ((*p != '\0') && (*(p+1) != '\0') && (*(p+2) != '\0') && (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[MagickPathExtent]; size_t length; (void) CopyMagickString(name,p,MagickPathExtent); length=strlen(name); for (q=name+length-1; q > name; q--) { if (*q == ')') break; if (*q == '.') { *q='\0'; break; } } q=name; if ((*q != '\0') && (*(q+1) != '\0') && (*(q+2) != '\0') && (GetFxSymbolValue(fx_info,name) == (const double *) NULL)) { PixelInfo *color; color=(PixelInfo *) GetValueFromSplayTree(fx_info->colors,name); if (color != (PixelInfo *) NULL) { pixel=(*color); p+=length; } else { MagickBooleanType status; status=QueryColorCompliance(name,AllCompliance,&pixel, fx_info->exception); if (status != MagickFalse) { (void) AddValueToSplayTree(fx_info->colors, ConstantString(name),ClonePixelInfo(&pixel)); p+=length; } } } } (void) CopyMagickString(symbol,p,MagickPathExtent); StripString(symbol); if (*symbol == '\0') { switch (channel) { case RedPixelChannel: return(QuantumScale*pixel.red); case GreenPixelChannel: return(QuantumScale*pixel.green); case BluePixelChannel: return(QuantumScale*pixel.blue); case BlackPixelChannel: { if (image->colorspace != CMYKColorspace) { (void) ThrowMagickException(exception,GetMagickModule(), ImageError,"ColorSeparatedImageRequired","`%s'", image->filename); return(0.0); } return(QuantumScale*pixel.black); } case AlphaPixelChannel: { if (pixel.alpha_trait == UndefinedPixelTrait) return(1.0); alpha=(double) (QuantumScale*pixel.alpha); return(alpha); } case CompositePixelChannel: { Quantum quantum_pixel[MaxPixelChannels]; SetPixelViaPixelInfo(image,&pixel,quantum_pixel); return(QuantumScale*GetPixelIntensity(image,quantum_pixel)); } case IndexPixelChannel: return(0.0); 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((QuantumScale*pixel.alpha)); break; } case 'B': case 'b': { if (LocaleCompare(symbol,"b") == 0) return(QuantumScale*pixel.blue); break; } case 'C': case 'c': { if (IsFxFunction(symbol,"channel",7) != MagickFalse) { GeometryInfo channel_info; MagickStatusType flags; flags=ParseGeometry(symbol+7,&channel_info); if (image->colorspace == CMYKColorspace) switch (channel) { case CyanPixelChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case MagentaPixelChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case YellowPixelChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackPixelChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } case AlphaPixelChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } default: return(0.0); } switch (channel) { case RedPixelChannel: { if ((flags & RhoValue) == 0) return(0.0); return(channel_info.rho); } case GreenPixelChannel: { if ((flags & SigmaValue) == 0) return(0.0); return(channel_info.sigma); } case BluePixelChannel: { if ((flags & XiValue) == 0) return(0.0); return(channel_info.xi); } case BlackPixelChannel: { if ((flags & ChiValue) == 0) return(0.0); return(channel_info.chi); } case AlphaPixelChannel: { if ((flags & PsiValue) == 0) return(0.0); return(channel_info.psi); } 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.black); } break; } case 'H': case 'h': { if (LocaleCompare(symbol,"h") == 0) return((double) image->rows); if (LocaleCompare(symbol,"hue") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(pixel.red,pixel.green,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->resolution.x); if (LocaleCompare(symbol,"image.resolution.y") == 0) return(image->resolution.y); if (LocaleCompare(symbol,"intensity") == 0) { Quantum quantum_pixel[MaxPixelChannels]; SetPixelViaPixelInfo(image,&pixel,quantum_pixel); return(QuantumScale*GetPixelIntensity(image,quantum_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(pixel.red,pixel.green,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 luminence; luminence=0.212656*pixel.red+0.715158*pixel.green+0.072186*pixel.blue; return(QuantumScale*luminence); } 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,"median",6) == 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.alpha); 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->resolution.x)*image->columns); if (LocaleCompare(symbol,"printsize.y") == 0) return(PerceptibleReciprocal(image->resolution.y)*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->resolution.x); if (LocaleCompare(symbol,"resolution.y") == 0) return(image->resolution.y); if (LocaleCompare(symbol,"r") == 0) return(QuantumScale*pixel.red); break; } case 'S': case 's': { if (LocaleCompare(symbol,"saturation") == 0) { double hue, lightness, saturation; ConvertRGBToHSL(pixel.red,pixel.green,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) return((double) GetImageDepth(image,fx_info->exception)); break; } default: break; } value=GetFxSymbolValue(fx_info,symbol); if (value != (const double *) NULL) return(*value); artifact=GetImageArtifact(image,symbol); if (artifact != (const char *) NULL) return(StringToDouble(artifact,(char **) NULL)); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UndefinedVariable","`%s'",symbol); (void) SetFxSymbolValue(fx_info,symbol,0.0); 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 (IsFxFunction(expression,"acosh",5) != MagickFalse) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ASINH) if (IsFxFunction(expression,"asinh",5) != MagickFalse) { expression+=5; break; } #endif #if defined(MAGICKCORE_HAVE_ATANH) if (IsFxFunction(expression,"atanh",5) != MagickFalse) { expression+=5; break; } #endif if (IsFxFunction(expression,"atan2",5) != MagickFalse) { 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 ((IsFxFunction(expression,"j0",2) != MagickFalse) || (IsFxFunction(expression,"j1",2) != MagickFalse)) { 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 BitwiseAndAssignmentOperator: case BitwiseOrAssignmentOperator: case LeftShiftAssignmentOperator: case RightShiftAssignmentOperator: case PowerAssignmentOperator: case ModuloAssignmentOperator: case PlusAssignmentOperator: case SubtractAssignmentOperator: case MultiplyAssignmentOperator: case DivideAssignmentOperator: case IncrementAssignmentOperator: case DecrementAssignmentOperator: { precedence=AssignmentPrecedence; 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 PixelChannel 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); \ } #define FxParseConditional(subexpression,sentinal,p,q) \ { \ p=subexpression; \ for (q=(char *) p; (*q != (sentinal)) && (*q != '\0'); q++) \ if (*q == '(') \ { \ for (q++; (*q != ')') && (*q != '\0'); q++); \ if (*q == '\0') \ break; \ } \ if (*q == '\0') \ { \ (void) ThrowMagickException(exception,GetMagickModule(), \ OptionError,"UnableToParseExpression","`%s'",subexpression); \ FxReturn(0.0); \ } \ if (strlen(q) == 1) \ *(q+1)='\0'; \ *q='\0'; \ } char *q, *subexpression; double alpha, gamma, sans, value; register const char *p; *beta=0.0; sans=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); FxReturn(PerceptibleReciprocal(*beta)*alpha); } case '%': { *beta=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); FxReturn(fmod(alpha,*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 BitwiseAndAssignmentOperator: { 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); value=(double) ((size_t) (alpha+0.5) & (size_t) (*beta+0.5)); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case BitwiseOrAssignmentOperator: { 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); value=(double) ((size_t) (alpha+0.5) | (size_t) (*beta+0.5)); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case LeftShiftAssignmentOperator: { 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); if ((size_t) (*beta+0.5) >= (8*sizeof(size_t))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ShiftCountOverflow","`%s'",subexpression); FxReturn(0.0); } value=(double) ((size_t) (alpha+0.5) << (size_t) (*beta+0.5)); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case RightShiftAssignmentOperator: { 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); if ((size_t) (*beta+0.5) >= (8*sizeof(size_t))) { (void) ThrowMagickException(exception,GetMagickModule(), OptionError,"ShiftCountOverflow","`%s'",subexpression); FxReturn(0.0); } value=(double) ((size_t) (alpha+0.5) >> (size_t) (*beta+0.5)); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case PowerAssignmentOperator: { 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); value=pow(alpha,*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case ModuloAssignmentOperator: { 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); value=fmod(alpha,*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case PlusAssignmentOperator: { 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); value=alpha+(*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case SubtractAssignmentOperator: { 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); value=alpha-(*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case MultiplyAssignmentOperator: { 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); value=alpha*(*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case DivideAssignmentOperator: { 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); value=alpha*PerceptibleReciprocal(*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case IncrementAssignmentOperator: { if (*subexpression == '\0') alpha=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); value=alpha+1.0; if (*subexpression == '\0') { if (SetFxSymbolValue(fx_info,p,value) == MagickFalse) return(0.0); } else if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*beta); } case DecrementAssignmentOperator: { if (*subexpression == '\0') alpha=FxEvaluateSubexpression(fx_info,channel,x,y,++p,depth+1,beta, exception); value=alpha-1.0; if (*subexpression == '\0') { if (SetFxSymbolValue(fx_info,p,value) == MagickFalse) return(0.0); } else if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); FxReturn(*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 '?': { (void) CopyMagickString(subexpression,++p,MagickPathExtent-1); FxParseConditional(subexpression,':',p,q); 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+1,depth+1,beta, exception); FxReturn(gamma); } case '=': { 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); value=(*beta); if (SetFxSymbolValue(fx_info,subexpression,value) == MagickFalse) return(0.0); 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) { size_t length; if (depth >= FxMaxParenthesisDepth) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "ParenthesisNestedTooDeeply","`%s'",expression); length=CopyMagickString(subexpression,expression+1,MagickPathExtent); if (length != 0) subexpression[length-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 (IsFxFunction(expression,"abs",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(fabs(alpha)); } #if defined(MAGICKCORE_HAVE_ACOSH) if (IsFxFunction(expression,"acosh",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(acosh(alpha)); } #endif if (IsFxFunction(expression,"acos",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(acos(alpha)); } #if defined(MAGICKCORE_HAVE_J1) if (IsFxFunction(expression,"airy",4) != MagickFalse) { 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 (IsFxFunction(expression,"asinh",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(asinh(alpha)); } #endif if (IsFxFunction(expression,"asin",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(asin(alpha)); } if (IsFxFunction(expression,"alt",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(((ssize_t) alpha) & 0x01 ? -1.0 : 1.0); } if (IsFxFunction(expression,"atan2",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(atan2(alpha,*beta)); } #if defined(MAGICKCORE_HAVE_ATANH) if (IsFxFunction(expression,"atanh",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(atanh(alpha)); } #endif if (IsFxFunction(expression,"atan",4) != MagickFalse) { 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 (IsFxFunction(expression,"ceil",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(ceil(alpha)); } if (IsFxFunction(expression,"clamp",5) != MagickFalse) { 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 (IsFxFunction(expression,"cosh",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(cosh(alpha)); } if (IsFxFunction(expression,"cos",3) != MagickFalse) { 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 (IsFxFunction(expression,"debug",5) != MagickFalse) { const char *type; size_t length; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); switch (fx_info->images->colorspace) { case CMYKColorspace: { switch (channel) { case CyanPixelChannel: type="cyan"; break; case MagentaPixelChannel: type="magenta"; break; case YellowPixelChannel: type="yellow"; break; case AlphaPixelChannel: type="alpha"; break; case BlackPixelChannel: type="black"; break; default: type="unknown"; break; } break; } case GRAYColorspace: { switch (channel) { case RedPixelChannel: type="gray"; break; case AlphaPixelChannel: type="alpha"; break; default: type="unknown"; break; } break; } default: { switch (channel) { case RedPixelChannel: type="red"; break; case GreenPixelChannel: type="green"; break; case BluePixelChannel: type="blue"; break; case AlphaPixelChannel: type="alpha"; break; default: type="unknown"; break; } break; } } *subexpression='\0'; length=1; if (strlen(expression) > 6) length=CopyMagickString(subexpression,expression+6, MagickPathExtent); if (length != 0) subexpression[length-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(),alpha); FxReturn(alpha); } if (IsFxFunction(expression,"do",2) != MagickFalse) { size_t length; /* Parse do(expression,condition test). */ length=CopyMagickString(subexpression,expression+3, MagickPathExtent-1); if (length != 0) subexpression[length-1]='\0'; FxParseConditional(subexpression,',',p,q); for (alpha=0.0; ; ) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta, exception); gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans, exception); if (fabs(gamma) < MagickEpsilon) break; } FxReturn(alpha); } if (IsFxFunction(expression,"drc",3) != MagickFalse) { 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 (IsFxFunction(expression,"erf",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(erf(alpha)); } #endif if (IsFxFunction(expression,"exp",3) != MagickFalse) { 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 (IsFxFunction(expression,"floor",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(floor(alpha)); } if (IsFxFunction(expression,"for",3) != MagickFalse) { double sans = 0.0; size_t length; /* Parse for(initialization, condition test, expression). */ length=CopyMagickString(subexpression,expression+4, MagickPathExtent-1); if (length != 0) subexpression[length-1]='\0'; FxParseConditional(subexpression,',',p,q); alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans, exception); (void) CopyMagickString(subexpression,q+1,MagickPathExtent-1); FxParseConditional(subexpression,',',p,q); for (alpha=0.0; ; ) { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans, exception); if (fabs(gamma) < MagickEpsilon) break; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta, exception); } FxReturn(alpha); } break; } case 'G': case 'g': { if (IsFxFunction(expression,"gauss",5) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); FxReturn(exp((-alpha*alpha/2.0))/sqrt(2.0*MagickPI)); } if (IsFxFunction(expression,"gcd",3) != MagickFalse) { double gcd; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); gcd=FxGCD(alpha,*beta); FxReturn(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 (IsFxFunction(expression,"hypot",5) != MagickFalse) { 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 (IsFxFunction(expression,"if",2) != MagickFalse) { double sans = 0.0; size_t length; length=CopyMagickString(subexpression,expression+3, MagickPathExtent-1); if (length != 0) subexpression[length-1]='\0'; FxParseConditional(subexpression,',',p,q); alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans, exception); (void) CopyMagickString(subexpression,q+1,MagickPathExtent-1); FxParseConditional(subexpression,',',p,q); if (fabs(alpha) >= MagickEpsilon) alpha=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,beta, exception); else alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1,beta, exception); FxReturn(alpha); } if (LocaleCompare(expression,"intensity") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); if (IsFxFunction(expression,"int",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(floor(alpha)); } if (IsFxFunction(expression,"isnan",5) != MagickFalse) { 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 (IsFxFunction(expression,"j0",2) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(j0(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (IsFxFunction(expression,"j1",2) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(j1(alpha)); } #endif #if defined(MAGICKCORE_HAVE_J1) if (IsFxFunction(expression,"jinc",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); if (alpha == 0.0) FxReturn(1.0); FxReturn((2.0*j1((MagickPI*alpha))/(MagickPI*alpha))); } #endif break; } case 'L': case 'l': { if (IsFxFunction(expression,"ln",2) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+2, depth+1,beta,exception); FxReturn(log(alpha)); } if (IsFxFunction(expression,"logtwo",6) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+6, depth+1,beta,exception); FxReturn(log10(alpha)/log10(2.0)); } if (IsFxFunction(expression,"log",3) != MagickFalse) { 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(QuantumRange); if (LocaleNCompare(expression,"maxima",6) == 0) break; if (IsFxFunction(expression,"max",3) != MagickFalse) { 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 (IsFxFunction(expression,"min",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(alpha < *beta ? alpha : *beta); } if (IsFxFunction(expression,"mod",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(alpha-floor((alpha*PerceptibleReciprocal(*beta)))*(*beta)); } if (LocaleCompare(expression,"m") == 0) FxReturn(FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception)); break; } case 'N': case 'n': { if (IsFxFunction(expression,"not",3) != MagickFalse) { 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 (IsFxFunction(expression,"pow",3) != MagickFalse) { 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(QuantumRange); if (LocaleCompare(expression,"QuantumScale") == 0) FxReturn(QuantumScale); break; } case 'R': case 'r': { if (IsFxFunction(expression,"rand",4) != MagickFalse) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FxEvaluateSubexpression) #endif alpha=GetPseudoRandomValue(fx_info->random_info); FxReturn(alpha); } if (IsFxFunction(expression,"round",5) != MagickFalse) { /* Round the fraction to nearest integer. */ alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+5, depth+1,beta,exception); if ((alpha-floor(alpha)) < (ceil(alpha)-alpha)) FxReturn(floor(alpha)); FxReturn(ceil(alpha)); } 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 (IsFxFunction(expression,"sign",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(alpha < 0.0 ? -1.0 : 1.0); } if (IsFxFunction(expression,"sinc",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); if (alpha == 0) FxReturn(1.0); FxReturn(sin((MagickPI*alpha))/(MagickPI*alpha)); } if (IsFxFunction(expression,"sinh",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(sinh(alpha)); } if (IsFxFunction(expression,"sin",3) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+3, depth+1,beta,exception); FxReturn(sin(alpha)); } if (IsFxFunction(expression,"sqrt",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(sqrt(alpha)); } if (IsFxFunction(expression,"squish",6) != MagickFalse) { 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 (IsFxFunction(expression,"tanh",4) != MagickFalse) { alpha=FxEvaluateSubexpression(fx_info,channel,x,y,expression+4, depth+1,beta,exception); FxReturn(tanh(alpha)); } if (IsFxFunction(expression,"tan",3) != MagickFalse) { 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 (IsFxFunction(expression,"trunc",5) != MagickFalse) { 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 (IsFxFunction(expression,"while",5) != MagickFalse) { size_t length; /* Parse while(condition test, expression). */ length=CopyMagickString(subexpression,expression+6, MagickPathExtent-1); if (length != 0) subexpression[length-1]='\0'; FxParseConditional(subexpression,',',p,q); for (alpha=0.0; ; ) { gamma=FxEvaluateSubexpression(fx_info,channel,x,y,p,depth+1,&sans, exception); if (fabs(gamma) < MagickEpsilon) break; alpha=FxEvaluateSubexpression(fx_info,channel,x,y,q+1,depth+1, beta,exception); } FxReturn(alpha); } 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; } subexpression=DestroyString(subexpression); q=(char *) expression; alpha=InterpretSiPrefixValue(expression,&q); if (q == expression) alpha=FxGetSymbol(fx_info,channel,x,y,expression,depth+1,exception); FxReturn(alpha); } MagickPrivate MagickBooleanType FxEvaluateExpression(FxInfo *fx_info, double *alpha,ExceptionInfo *exception) { MagickBooleanType status; status=FxEvaluateChannelExpression(fx_info,GrayPixelChannel,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,GrayPixelChannel,0,0,alpha, exception); fx_info->file=file; return(status); } MagickPrivate MagickBooleanType FxEvaluateChannelExpression(FxInfo *fx_info, const PixelChannel 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) % % A description of each parameter follows: % % o image: the image. % % 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,exception); 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) { #define FxImageTag "Fx/Image" CacheView *fx_view, *image_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,exception) == MagickFalse) { fx_info=DestroyFxThreadSet(fx_info); fx_image=DestroyImage(fx_image); return((Image *) NULL); } /* Fx image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); fx_view=AcquireAuthenticCacheView(fx_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) 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(); 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=QueueCacheViewAuthenticPixels(fx_view,0,y,fx_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) fx_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double alpha; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait fx_traits=GetPixelChannelTraits(fx_image,channel); if ((traits == UndefinedPixelTrait) || (fx_traits == UndefinedPixelTrait)) continue; if ((fx_traits & CopyPixelTrait) != 0) { SetPixelChannel(fx_image,channel,p[i],q); continue; } alpha=0.0; (void) FxEvaluateChannelExpression(fx_info[id],channel,x,y,&alpha, exception); q[i]=ClampToQuantum(QuantumRange*alpha); } p+=GetPixelChannels(image); q+=GetPixelChannels(fx_image); } 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); image_view=DestroyCacheView(image_view); fx_info=DestroyFxThreadSet(fx_info); if (status == MagickFalse) fx_image=DestroyImage(fx_image); return(fx_image); }
activations.c
#include "activations.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <float.h> char *get_activation_string(ACTIVATION a) { switch(a){ case LOGISTIC: return "logistic"; case LOGGY: return "loggy"; case RELU: return "relu"; case ELU: return "elu"; case SELU: return "selu"; case GELU: return "gelu"; case RELIE: return "relie"; case RAMP: return "ramp"; case LINEAR: return "linear"; case TANH: return "tanh"; case PLSE: return "plse"; case LEAKY: return "leaky"; case STAIR: return "stair"; case HARDTAN: return "hardtan"; case LHTAN: return "lhtan"; default: break; } return "relu"; } ACTIVATION get_activation(char *s) { if (strcmp(s, "logistic")==0) return LOGISTIC; if (strcmp(s, "swish") == 0) return SWISH; if (strcmp(s, "mish") == 0) return MISH; if (strcmp(s, "normalize_channels") == 0) return NORM_CHAN; if (strcmp(s, "normalize_channels_softmax") == 0) return NORM_CHAN_SOFTMAX; if (strcmp(s, "normalize_channels_softmax_maxval") == 0) return NORM_CHAN_SOFTMAX_MAXVAL; if (strcmp(s, "loggy")==0) return LOGGY; if (strcmp(s, "relu")==0) return RELU; if (strcmp(s, "relu6") == 0) return RELU6; if (strcmp(s, "elu")==0) return ELU; if (strcmp(s, "selu") == 0) return SELU; if (strcmp(s, "gelu") == 0) return GELU; if (strcmp(s, "relie")==0) return RELIE; if (strcmp(s, "plse")==0) return PLSE; if (strcmp(s, "hardtan")==0) return HARDTAN; if (strcmp(s, "lhtan")==0) return LHTAN; if (strcmp(s, "linear")==0) return LINEAR; if (strcmp(s, "ramp")==0) return RAMP; if (strcmp(s, "leaky")==0) return LEAKY; if (strcmp(s, "tanh")==0) return TANH; if (strcmp(s, "stair")==0) return STAIR; fprintf(stderr, "Couldn't find activation function %s, going with ReLU\n", s); return RELU; } float activate(float x, ACTIVATION a) { switch(a){ case LINEAR: return linear_activate(x); case LOGISTIC: return logistic_activate(x); case LOGGY: return loggy_activate(x); case RELU: return relu_activate(x); case ELU: return elu_activate(x); case SELU: return selu_activate(x); case GELU: return gelu_activate(x); case RELIE: return relie_activate(x); case RAMP: return ramp_activate(x); case LEAKY: return leaky_activate(x); case TANH: return tanh_activate(x); case PLSE: return plse_activate(x); case STAIR: return stair_activate(x); case HARDTAN: return hardtan_activate(x); case LHTAN: return lhtan_activate(x); } return 0; } void activate_array(float *x, const int n, const ACTIVATION a) { int i; if (a == LINEAR) {} else if (a == LEAKY) { #pragma omp parallel for for (i = 0; i < n; ++i) { x[i] = leaky_activate(x[i]); } } else if (a == LOGISTIC) { #pragma omp parallel for for (i = 0; i < n; ++i) { x[i] = logistic_activate(x[i]); } } else { for (i = 0; i < n; ++i) { x[i] = activate(x[i], a); } } } void activate_array_swish(float *x, const int n, float * output_sigmoid, float * output) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float x_val = x[i]; float sigmoid = logistic_activate(x_val); output_sigmoid[i] = sigmoid; output[i] = x_val * sigmoid; } } // https://github.com/digantamisra98/Mish void activate_array_mish(float *x, const int n, float * activation_input, float * output) { const float MISH_THRESHOLD = 20; int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float x_val = x[i]; activation_input[i] = x_val; // store value before activation output[i] = x_val * tanh_activate( softplus_activate(x_val, MISH_THRESHOLD) ); } } void activate_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *output) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; const float eps = 0.0001; if (i < size) { float sum = eps; int k; for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > 0) sum += val; } for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > 0) val = val / sum; else val = 0; output[wh_i + k * wh_step + b*wh_step*channels] = val; } } } } void activate_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *output, int use_max_val) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; const float eps = 0.0001; if (i < size) { float sum = eps; float max_val = -FLT_MAX; int k; if (use_max_val) { for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; if (val > max_val || k == 0) max_val = val; } } else max_val = 0; for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; sum += expf(val - max_val); } for (k = 0; k < channels; ++k) { float val = x[wh_i + k * wh_step + b*wh_step*channels]; val = expf(val - max_val) / sum; output[wh_i + k * wh_step + b*wh_step*channels] = val; } } } } void gradient_array_normalize_channels_softmax(float *x, const int n, int batch, int channels, int wh_step, float *delta) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; if (i < size) { float grad = 0; int k; for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float out = x[index]; float d = delta[index]; grad += out*d; } for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float d = delta[index]; d = d * grad; delta[index] = d; } } } } void gradient_array_normalize_channels(float *x, const int n, int batch, int channels, int wh_step, float *delta) { int size = n / channels; int i; #pragma omp parallel for for (i = 0; i < size; ++i) { int wh_i = i % wh_step; int b = i / wh_step; if (i < size) { float grad = 0; int k; for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; float out = x[index]; float d = delta[index]; grad += out*d; } for (k = 0; k < channels; ++k) { const int index = wh_i + k * wh_step + b*wh_step*channels; if (x[index] > 0) { float d = delta[index]; d = d * grad; delta[index] = d; } } } } } float gradient(float x, ACTIVATION a) { switch(a){ case LINEAR: return linear_gradient(x); case LOGISTIC: return logistic_gradient(x); case LOGGY: return loggy_gradient(x); case RELU: return relu_gradient(x); case NORM_CHAN: //return relu_gradient(x); case NORM_CHAN_SOFTMAX_MAXVAL: //... case NORM_CHAN_SOFTMAX: printf(" Error: should be used custom NORM_CHAN or NORM_CHAN_SOFTMAX-function for gradient \n"); exit(0); return 0; case ELU: return elu_gradient(x); case SELU: return selu_gradient(x); case GELU: return gelu_gradient(x); case RELIE: return relie_gradient(x); case RAMP: return ramp_gradient(x); case LEAKY: return leaky_gradient(x); case TANH: return tanh_gradient(x); case PLSE: return plse_gradient(x); case STAIR: return stair_gradient(x); case HARDTAN: return hardtan_gradient(x); case LHTAN: return lhtan_gradient(x); } return 0; } void gradient_array(const float *x, const int n, const ACTIVATION a, float *delta) { int i; #pragma omp parallel for for(i = 0; i < n; ++i){ delta[i] *= gradient(x[i], a); } } // https://github.com/BVLC/caffe/blob/04ab089db018a292ae48d51732dd6c66766b36b6/src/caffe/layers/swish_layer.cpp#L54-L56 void gradient_array_swish(const float *x, const int n, const float * sigmoid, float * delta) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { float swish = x[i]; delta[i] *= swish + sigmoid[i]*(1 - swish); } } // https://github.com/digantamisra98/Mish void gradient_array_mish(const int n, const float * activation_input, float * delta) { int i; #pragma omp parallel for for (i = 0; i < n; ++i) { const float MISH_THRESHOLD = 20.0f; // implementation from TensorFlow: https://github.com/tensorflow/addons/commit/093cdfa85d334cbe19a37624c33198f3140109ed // implementation from Pytorch: https://github.com/thomasbrandon/mish-cuda/blob/master/csrc/mish.h#L26-L31 float inp = activation_input[i]; const float sp = softplus_activate(inp, MISH_THRESHOLD); const float grad_sp = 1 - exp(-sp); const float tsp = tanh(sp); const float grad_tsp = (1 - tsp*tsp) * grad_sp; const float grad = inp * grad_tsp + tsp; delta[i] *= grad; //float x = activation_input[i]; //float d = 2 * expf(x) + expf(2 * x) + 2; //float w = 4 * (x + 1) + 4 * expf(2 * x) + expf(3 * x) + expf(x)*(4 * x + 6); //float derivative = expf(x) * w / (d * d); //delta[i] *= derivative; } }
fibonacci.c
#include <stdio.h> #include <omp.h> #define NUM 10 int fibonacci(int n){ int x, y; printf("%d\n", omp_get_thread_num()); if (n<2) return n; #pragma omp task shared(x) x = fibonacci(n-1); #pragma omp task shared(y) y = fibonacci(n-2); #pragma omp taskwait return x + y; } int main(){ int res; #pragma omp parallel res = fibonacci(5); printf("Fibonacci = %d\n", res); return 0; }
partial.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) ******************************************************************************/ #include "_hypre_parcsr_ls.h" #include "aux_interp.h" /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtPIInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtPIInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] -= hypre_MPI_Wtime(); #endif /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; /*HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL;*/ HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ /*HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter, coarse_counter_offd; */ HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; /*HYPRE_Int strong_f_marker = -2;*/ /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i; /*HYPRE_Int i, ii, i1, i2, j, jj, kk, k1, jj1;*/ /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Int max_num_threads; HYPRE_Int *P_diag_array = NULL; HYPRE_Int *P_offd_array = NULL; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); max_num_threads = hypre_NumThreads(); my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); /*P_marker = hypre_CTAlloc(HYPRE_Int, n_fine); */ } if (full_off_procNodes) { /*P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes);*/ fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } /*hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd);*/ for (i = 0; i < full_off_procNodes; i++) { fine_to_coarse_offd[i] = -1; tmp_CF_marker_offd[i] = -1; } cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } P_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads + 1, HYPRE_MEMORY_HOST); P_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads + 1, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i, diagonal, distribute, sgn, sum) #endif { HYPRE_Int ii, jj_counter, jj_counter_offd, jj, kk, i1, i2, k1, jj1; HYPRE_BigInt big_k1; HYPRE_Int loc_col, jj_begin_row, jj_begin_row_offd; HYPRE_Int jj_end_row, jj_end_row_offd, strong_f_marker; HYPRE_Int size, rest, ne, ns; HYPRE_Int num_threads, my_thread_num; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; strong_f_marker = -2; num_threads = hypre_NumActiveThreads(); my_thread_num = hypre_GetThreadNum(); size = n_coarse_old / num_threads; rest = n_coarse_old - size * num_threads; if (my_thread_num < rest) { ns = my_thread_num * (size + 1); ne = (my_thread_num + 1) * (size + 1); } else { ns = my_thread_num * size + rest; ne = (my_thread_num + 1) * size + rest; } if (n_fine) { P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } for (ii = 0; ii < n_fine; ii++) { P_marker[ii] = -1; } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } for (ii = 0; ii < full_off_procNodes; ii++) { P_marker_offd[ii] = -1; } /*coarse_counter = 0; coarse_counter_offd = 0;*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; /*P_diag_i[ii] = jj_counter; if (num_procs > 1) P_offd_i[ii] = jj_counter_offd;*/ i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; /*coarse_counter++;*/ } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if (P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if (P_marker_offd[k1] < jj_begin_row_offd) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if (CF_marker_offd[i1] > 0) { if (P_marker_offd[i1] < jj_begin_row_offd) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; if (big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } P_diag_array[my_thread_num] = jj_counter; P_offd_array[my_thread_num] = jj_counter_offd; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num == 0) { if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } for (i = 0; i < max_num_threads; i++) { P_diag_array[i + 1] += P_diag_array[i]; P_offd_array[i + 1] += P_offd_array[i]; } P_diag_size = P_diag_array[max_num_threads]; P_offd_size = P_offd_array[max_num_threads]; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = P_diag_size; P_offd_i[n_coarse_old] = P_offd_size; /* Fine to coarse mapping */ if (num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif jj_counter = start_indexing; jj_counter_offd = start_indexing; if (my_thread_num) { jj_counter = P_diag_array[my_thread_num - 1]; jj_counter_offd = P_offd_array[my_thread_num - 1]; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = ns; ii < ne; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; P_diag_i[ii] = jj_counter; P_offd_i[ii] = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if (P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] >= 0) { if (P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] >= 0) { if (P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; /* Find local col number */ if (big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd] = loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i + 1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if (P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if (A_diag_data[A_diag_i[i1]] < 0) { sgn = -1; } /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for (jj1 = A_diag_i[i1] + 1; jj1 < A_diag_i[i1 + 1]; jj1++) { i2 = A_diag_j[jj1]; if ((P_marker[i2] >= jj_begin_row || i2 == i) && (sgn * A_diag_data[jj1]) < 0) { sum += A_diag_data[jj1]; } } if (num_procs > 1) { for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1 + 1]; jj1++) { i2 = A_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd && (sgn * A_offd_data[jj1]) < 0) { sum += A_offd_data[jj1]; } } } if (sum != 0) { distribute = A_diag_data[jj] / sum; /* Loop over row of A for point i1 and do the distribution */ for (jj1 = A_diag_i[i1] + 1; jj1 < A_diag_i[i1 + 1]; jj1++) { i2 = A_diag_j[jj1]; if (P_marker[i2] >= jj_begin_row && (sgn * A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute * A_diag_data[jj1]; if (i2 == i && (sgn * A_diag_data[jj1]) < 0) { diagonal += distribute * A_diag_data[jj1]; } } if (num_procs > 1) { for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1 + 1]; jj1++) { i2 = A_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd && (sgn * A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute * A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if (num_functions == 1 || dof_func[i] == dof_func[i1]) { diagonal += A_diag_data[jj]; } } } if (num_procs > 1) { for (jj = A_offd_i[i]; jj < A_offd_i[i + 1]; jj++) { i1 = A_offd_j[jj]; if (P_marker_offd[i1] >= jj_begin_row_offd) { P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; } else if (P_marker_offd[i1] == strong_f_marker) { sum = zero; for (jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1 + 1]; jj1++) { big_k1 = A_ext_j[jj1]; if (big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] >= jj_begin_row || loc_col == i) { sum += A_ext_data[jj1]; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] >= jj_begin_row_offd) { sum += A_ext_data[jj1]; } } } if (sum != 0) { distribute = A_offd_data[jj] / sum; for (jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1 + 1]; jj1++) { big_k1 = A_ext_j[jj1]; if (big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute * A_ext_data[jj1]; if (loc_col == i) { diagonal += distribute * A_ext_data[jj1]; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute * A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if (num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { diagonal += A_offd_data[jj]; } } } } if (diagonal) { for (jj = jj_begin_row; jj < jj_end_row; jj++) { P_diag_data[jj] /= -diagonal; } for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { P_offd_data[jj] /= -diagonal; } } } strong_f_marker--; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); } /* end parallel region */ if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if (P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i = 0; i < n_fine; i++) if (CF_marker[i] < -1) { CF_marker[i] = -1; } *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(P_offd_array, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if (num_functions > 1) { hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); } hypre_MatvecCommPkgDestroy(extend_comm_pkg); } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PARTIAL_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialStdInterp * Comment: The interpolatory weighting can be changed with the sep_weight * variable. This can enable not separating negative and positive * off diagonals in the weight formula. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialStdInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, HYPRE_Int sep_weight, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; HYPRE_Int *ihat = NULL; HYPRE_Int *ihat_offd = NULL; HYPRE_Int *ipnt = NULL; HYPRE_Int *ipnt_offd = NULL; HYPRE_Int strong_f_marker = -2; /* Interpolation weight variables */ HYPRE_Real *ahat = NULL; HYPRE_Real *ahat_offd = NULL; HYPRE_Real sum_pos, sum_pos_C, sum_neg, sum_neg_C, sum, sum_C; HYPRE_Real diagonal, distribute; HYPRE_Real alfa, beta; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, j1, jj, kk, k1; HYPRE_BigInt big_k1; HYPRE_Int cnt_c, cnt_f, cnt_c_offd, cnt_f_offd, indx; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; HYPRE_Real wall_1 = 0; HYPRE_Real wall_2 = 0; HYPRE_Real wall_3 = 0; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 0)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) { P_offd_i[ii] = jj_counter_offd; } i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if (P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if (P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if (CF_marker_offd[i1] > 0) { if (P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; if (big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (CF_marker[loc_col] >= 0) { if (P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (CF_marker_offd[loc_col] >= 0) { if (P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if (num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } /* Initialize ahat, which is a modification to a, used in the standard * interpolation routine. */ if (n_fine) { ahat = hypre_CTAlloc(HYPRE_Real, n_fine, HYPRE_MEMORY_HOST); ihat = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); ipnt = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { ahat_offd = hypre_CTAlloc(HYPRE_Real, full_off_procNodes, HYPRE_MEMORY_HOST); ihat_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); ipnt_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; ahat[i] = 0; ihat[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; ahat_offd[i] = 0; ihat_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] > 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = i1; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if (P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = k1; P_diag_data[jj_counter] = zero; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if (P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] > 0) { if (P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; if (big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1 - col_1); if (CF_marker[loc_col] > 0) { if (P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = loc_col; P_diag_data[jj_counter] = zero; jj_counter++; } } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (CF_marker_offd[loc_col] > 0) { if (P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd] = loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; wall_1 += wall_time; fflush(NULL); } if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } cnt_c = 0; cnt_f = jj_end_row - jj_begin_row; cnt_c_offd = 0; cnt_f_offd = jj_end_row_offd - jj_begin_row_offd; ihat[i] = cnt_f; ipnt[cnt_f] = i; ahat[cnt_f++] = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i + 1]; jj++) { /* i1 is direct neighbor */ i1 = A_diag_j[jj]; if (P_marker[i1] != strong_f_marker) { indx = ihat[i1]; if (indx > -1) { ahat[indx] += A_diag_data[jj]; } else if (P_marker[i1] >= jj_begin_row) { ihat[i1] = cnt_c; ipnt[cnt_c] = i1; ahat[cnt_c++] += A_diag_data[jj]; } else if (CF_marker[i1] != -3) { ihat[i1] = cnt_f; ipnt[cnt_f] = i1; ahat[cnt_f++] += A_diag_data[jj]; } } else { if (num_functions == 1 || dof_func[i] == dof_func[i1]) { distribute = A_diag_data[jj] / A_diag_data[A_diag_i[i1]]; for (kk = A_diag_i[i1] + 1; kk < A_diag_i[i1 + 1]; kk++) { k1 = A_diag_j[kk]; indx = ihat[k1]; if (indx > -1) { ahat[indx] -= A_diag_data[kk] * distribute; } else if (P_marker[k1] >= jj_begin_row) { ihat[k1] = cnt_c; ipnt[cnt_c] = k1; ahat[cnt_c++] -= A_diag_data[kk] * distribute; } else { ihat[k1] = cnt_f; ipnt[cnt_f] = k1; ahat[cnt_f++] -= A_diag_data[kk] * distribute; } } if (num_procs > 1) { for (kk = A_offd_i[i1]; kk < A_offd_i[i1 + 1]; kk++) { k1 = A_offd_j[kk]; indx = ihat_offd[k1]; if (num_functions == 1 || dof_func[i1] == dof_func_offd[k1]) { if (indx > -1) { ahat_offd[indx] -= A_offd_data[kk] * distribute; } else if (P_marker_offd[k1] >= jj_begin_row_offd) { ihat_offd[k1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = k1; ahat_offd[cnt_c_offd++] -= A_offd_data[kk] * distribute; } else { ihat_offd[k1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = k1; ahat_offd[cnt_f_offd++] -= A_offd_data[kk] * distribute; } } } } } } } if (num_procs > 1) { for (jj = A_offd_i[i]; jj < A_offd_i[i + 1]; jj++) { i1 = A_offd_j[jj]; if (P_marker_offd[i1] != strong_f_marker) { indx = ihat_offd[i1]; if (indx > -1) { ahat_offd[indx] += A_offd_data[jj]; } else if (P_marker_offd[i1] >= jj_begin_row_offd) { ihat_offd[i1] = cnt_c_offd; ipnt_offd[cnt_c_offd] = i1; ahat_offd[cnt_c_offd++] += A_offd_data[jj]; } else if (CF_marker_offd[i1] != -3) { ihat_offd[i1] = cnt_f_offd; ipnt_offd[cnt_f_offd] = i1; ahat_offd[cnt_f_offd++] += A_offd_data[jj]; } } else { if (num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { distribute = A_offd_data[jj] / A_ext_data[A_ext_i[i1]]; for (kk = A_ext_i[i1] + 1; kk < A_ext_i[i1 + 1]; kk++) { big_k1 = A_ext_j[kk]; if (big_k1 >= col_1 && big_k1 < col_n) { /*diag*/ loc_col = (HYPRE_Int)(big_k1 - col_1); indx = ihat[loc_col]; if (indx > -1) { ahat[indx] -= A_ext_data[kk] * distribute; } else if (P_marker[loc_col] >= jj_begin_row) { ihat[loc_col] = cnt_c; ipnt[cnt_c] = loc_col; ahat[cnt_c++] -= A_ext_data[kk] * distribute; } else { ihat[loc_col] = cnt_f; ipnt[cnt_f] = loc_col; ahat[cnt_f++] -= A_ext_data[kk] * distribute; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (num_functions == 1 || dof_func_offd[loc_col] == dof_func_offd[i1]) { indx = ihat_offd[loc_col]; if (indx > -1) { ahat_offd[indx] -= A_ext_data[kk] * distribute; } else if (P_marker_offd[loc_col] >= jj_begin_row_offd) { ihat_offd[loc_col] = cnt_c_offd; ipnt_offd[cnt_c_offd] = loc_col; ahat_offd[cnt_c_offd++] -= A_ext_data[kk] * distribute; } else { ihat_offd[loc_col] = cnt_f_offd; ipnt_offd[cnt_f_offd] = loc_col; ahat_offd[cnt_f_offd++] -= A_ext_data[kk] * distribute; } } } } } } } } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; wall_2 += wall_time; fflush(NULL); } if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } diagonal = ahat[cnt_c]; ahat[cnt_c] = 0; sum_pos = 0; sum_pos_C = 0; sum_neg = 0; sum_neg_C = 0; sum = 0; sum_C = 0; if (sep_weight == 1) { for (jj = 0; jj < cnt_c; jj++) { if (ahat[jj] > 0) { sum_pos_C += ahat[jj]; } else { sum_neg_C += ahat[jj]; } } if (num_procs > 1) { for (jj = 0; jj < cnt_c_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos_C += ahat_offd[jj]; } else { sum_neg_C += ahat_offd[jj]; } } } sum_pos = sum_pos_C; sum_neg = sum_neg_C; for (jj = cnt_c + 1; jj < cnt_f; jj++) { if (ahat[jj] > 0) { sum_pos += ahat[jj]; } else { sum_neg += ahat[jj]; } ahat[jj] = 0; } if (num_procs > 1) { for (jj = cnt_c_offd; jj < cnt_f_offd; jj++) { if (ahat_offd[jj] > 0) { sum_pos += ahat_offd[jj]; } else { sum_neg += ahat_offd[jj]; } ahat_offd[jj] = 0; } } if (sum_neg_C * diagonal != 0.0) { alfa = sum_neg / sum_neg_C / diagonal; } if (sum_pos_C * diagonal != 0.0) { beta = sum_pos / sum_pos_C / diagonal; } /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; if (ahat[j1] > 0) { P_diag_data[jj] = -beta * ahat[j1]; } else { P_diag_data[jj] = -alfa * ahat[j1]; } P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj = 0; jj < cnt_f; jj++) { ihat[ipnt[jj]] = -1; } if (num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; if (ahat_offd[j1] > 0) { P_offd_data[jj] = -beta * ahat_offd[j1]; } else { P_offd_data[jj] = -alfa * ahat_offd[j1]; } ahat_offd[j1] = 0; } for (jj = 0; jj < cnt_f_offd; jj++) { ihat_offd[ipnt_offd[jj]] = -1; } } } else { for (jj = 0; jj < cnt_c; jj++) { sum_C += ahat[jj]; } if (num_procs > 1) { for (jj = 0; jj < cnt_c_offd; jj++) { sum_C += ahat_offd[jj]; } } sum = sum_C; for (jj = cnt_c + 1; jj < cnt_f; jj++) { sum += ahat[jj]; ahat[jj] = 0; } if (num_procs > 1) { for (jj = cnt_c_offd; jj < cnt_f_offd; jj++) { sum += ahat_offd[jj]; ahat_offd[jj] = 0; } } if (sum_C * diagonal != 0.0) { alfa = sum / sum_C / diagonal; } /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ for (jj = jj_begin_row; jj < jj_end_row; jj++) { j1 = ihat[P_diag_j[jj]]; P_diag_data[jj] = -alfa * ahat[j1]; P_diag_j[jj] = fine_to_coarse[P_diag_j[jj]]; ahat[j1] = 0; } for (jj = 0; jj < cnt_f; jj++) { ihat[ipnt[jj]] = -1; } if (num_procs > 1) { for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { j1 = ihat_offd[P_offd_j[jj]]; P_offd_data[jj] = -alfa * ahat_offd[j1]; ahat_offd[j1] = 0; } for (jj = 0; jj < cnt_f_offd; jj++) { ihat_offd[ipnt_offd[jj]] = -1; } } } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; wall_3 += wall_time; fflush(NULL); } } } if (debug_flag == 4) { hypre_printf("Proc = %d fill part 1 %f part 2 %f part 3 %f\n", my_id, wall_1, wall_2, wall_3); fflush(NULL); } P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if (P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i = 0; i < n_fine; i++) if (CF_marker[i] < -1) { CF_marker[i] = -1; } *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); hypre_TFree(ahat, HYPRE_MEMORY_HOST); hypre_TFree(ihat, HYPRE_MEMORY_HOST); hypre_TFree(ipnt, HYPRE_MEMORY_HOST); if (full_off_procNodes) { hypre_TFree(ahat_offd, HYPRE_MEMORY_HOST); hypre_TFree(ihat_offd, HYPRE_MEMORY_HOST); hypre_TFree(ipnt_offd, HYPRE_MEMORY_HOST); } if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if (num_functions > 1) { hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); } hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildPartialExtInterp * Comment: *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildPartialExtInterp(hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_BigInt *num_old_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int max_elmts, hypre_ParCSRMatrix **P_ptr) { /* Communication Variables */ MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int my_id, num_procs; /* Variables to store input variables */ hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); /*HYPRE_Int num_cols_A_offd = hypre_CSRMatrixNumCols(A_offd); HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(A);*/ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(A); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_BigInt total_global_cpts, my_first_cpt; /* Variables to store strong connection matrix info */ hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); /* Interpolation matrix P */ hypre_ParCSRMatrix *P; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data = NULL; HYPRE_Int *P_diag_i, *P_diag_j = NULL; HYPRE_Real *P_offd_data = NULL; HYPRE_Int *P_offd_i, *P_offd_j = NULL; /*HYPRE_Int *col_map_offd_P = NULL;*/ HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker = NULL; HYPRE_Int *P_marker_offd = NULL; HYPRE_Int *CF_marker_offd = NULL; HYPRE_Int *tmp_CF_marker_offd = NULL; HYPRE_Int *dof_func_offd = NULL; /* Full row information for columns of A that are off diag*/ hypre_CSRMatrix *A_ext; HYPRE_Real *A_ext_data; HYPRE_Int *A_ext_i; HYPRE_BigInt *A_ext_j; HYPRE_Int *fine_to_coarse = NULL; HYPRE_BigInt *fine_to_coarse_offd = NULL; HYPRE_Int *old_coarse_to_fine = NULL; HYPRE_Int loc_col; HYPRE_Int full_off_procNodes; hypre_CSRMatrix *Sop; HYPRE_Int *Sop_i; HYPRE_BigInt *Sop_j; HYPRE_Int sgn; /* Variables to keep count of interpolatory points */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int jj_begin_row, jj_end_row; HYPRE_Int jj_begin_row_offd = 0; HYPRE_Int jj_end_row_offd = 0; HYPRE_Int coarse_counter; HYPRE_Int n_coarse_old; HYPRE_BigInt total_old_global_cpts; /* Interpolation weight variables */ HYPRE_Real sum, diagonal, distribute; HYPRE_Int strong_f_marker = -2; /* Loop variables */ /*HYPRE_Int index;*/ HYPRE_Int cnt, old_cnt; HYPRE_Int start_indexing = 0; HYPRE_Int i, ii, i1, i2, jj, kk, k1, jj1; HYPRE_BigInt big_k1; /* Definitions */ HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Real wall_time; hypre_ParCSRCommPkg *extend_comm_pkg = NULL; if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } /* BEGIN */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); my_first_cpt = num_cpts_global[0]; /*my_first_old_cpt = num_old_cpts_global[0];*/ n_coarse_old = (HYPRE_Int)(num_old_cpts_global[1] - num_old_cpts_global[0]); /*n_coarse = num_cpts_global[1] - num_cpts_global[0];*/ if (my_id == (num_procs - 1)) { total_global_cpts = num_cpts_global[1]; total_old_global_cpts = num_old_cpts_global[1]; } hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); hypre_MPI_Bcast(&total_old_global_cpts, 1, HYPRE_MPI_BIG_INT, num_procs - 1, comm); if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } /* Set up off processor information (specifically for neighbors of * neighbors */ full_off_procNodes = 0; if (num_procs > 1) { if (hypre_exchange_interp_data( &CF_marker_offd, &dof_func_offd, &A_ext, &full_off_procNodes, &Sop, &extend_comm_pkg, A, CF_marker, S, num_functions, dof_func, 1)) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_EXTENDED_I_INTERP] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } A_ext_i = hypre_CSRMatrixI(A_ext); A_ext_j = hypre_CSRMatrixBigJ(A_ext); A_ext_data = hypre_CSRMatrixData(A_ext); Sop_i = hypre_CSRMatrixI(Sop); Sop_j = hypre_CSRMatrixBigJ(Sop); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ P_diag_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); P_offd_i = hypre_CTAlloc(HYPRE_Int, n_coarse_old + 1, HYPRE_MEMORY_HOST); if (n_fine) { old_coarse_to_fine = hypre_CTAlloc(HYPRE_Int, n_coarse_old, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); } if (full_off_procNodes) { P_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, full_off_procNodes, HYPRE_MEMORY_HOST); tmp_CF_marker_offd = hypre_CTAlloc(HYPRE_Int, full_off_procNodes, HYPRE_MEMORY_HOST); } hypre_initialize_vecs(n_fine, full_off_procNodes, fine_to_coarse, fine_to_coarse_offd, P_marker, P_marker_offd, tmp_CF_marker_offd); jj_counter = start_indexing; jj_counter_offd = start_indexing; coarse_counter = 0; cnt = 0; old_cnt = 0; for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; if (CF_marker[i] == 1) { fine_to_coarse[i] = cnt++; old_coarse_to_fine[old_cnt++] = i; } else if (CF_marker[i] == -2) { old_coarse_to_fine[old_cnt++] = i; } } /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { P_diag_i[ii] = jj_counter; if (num_procs > 1) { P_offd_i[ii] = jj_counter_offd; } i = old_coarse_to_fine[ii]; if (CF_marker[i] > 0) { jj_counter++; coarse_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i, or C-points that stronly influence F-points * that strongly influence i. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] > 0) { /* i1 is a C point */ if (P_marker[i1] < P_diag_i[ii]) { P_marker[i1] = jj_counter; jj_counter++; } } else if (CF_marker[i1] != -3) { /* i1 is a F point, loop through it's strong neighbors */ for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] > 0) { if (P_marker[k1] < P_diag_i[ii]) { P_marker[k1] = jj_counter; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] > 0) { if (P_marker_offd[k1] < P_offd_i[ii]) { tmp_CF_marker_offd[k1] = 1; P_marker_offd[k1] = jj_counter_offd; jj_counter_offd++; } } } } } } /* Look at off diag strong connections of i */ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if (CF_marker_offd[i1] > 0) { if (P_marker_offd[i1] < P_offd_i[ii]) { tmp_CF_marker_offd[i1] = 1; P_marker_offd[i1] = jj_counter_offd; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { /* F point; look at neighbors of i1. Sop contains global col * numbers and entries that could be in S_diag or S_offd or * neither. */ for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; if (big_k1 >= col_1 && big_k1 < col_n) { /* In S_diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] < P_diag_i[ii]) { P_marker[loc_col] = jj_counter; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] < P_offd_i[ii]) { P_marker_offd[loc_col] = jj_counter_offd; tmp_CF_marker_offd[loc_col] = 1; jj_counter_offd++; } } } } } } } } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d determine structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } P_diag_size = jj_counter; P_offd_size = jj_counter_offd; if (P_diag_size) { P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); } if (P_offd_size) { P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); } P_diag_i[n_coarse_old] = jj_counter; P_offd_i[n_coarse_old] = jj_counter_offd; jj_counter = start_indexing; jj_counter_offd = start_indexing; /* Fine to coarse mapping */ if (num_procs > 1) { hypre_big_insert_new_nodes(comm_pkg, extend_comm_pkg, fine_to_coarse, full_off_procNodes, my_first_cpt, fine_to_coarse_offd); } for (i = 0; i < n_fine; i++) { P_marker[i] = -1; } for (i = 0; i < full_off_procNodes; i++) { P_marker_offd[i] = -1; } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ for (ii = 0; ii < n_coarse_old; ii++) { jj_begin_row = jj_counter; jj_begin_row_offd = jj_counter_offd; i = old_coarse_to_fine[ii]; /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] > 0) { P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else if (CF_marker[i] == -2) { strong_f_marker--; for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { if (P_marker[i1] < jj_begin_row) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } } else if (CF_marker[i1] != -3) { P_marker[i1] = strong_f_marker; for (kk = S_diag_i[i1]; kk < S_diag_i[i1 + 1]; kk++) { k1 = S_diag_j[kk]; if (CF_marker[k1] >= 0) { if (P_marker[k1] < jj_begin_row) { P_marker[k1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[k1]; P_diag_data[jj_counter] = zero; jj_counter++; } } } if (num_procs > 1) { for (kk = S_offd_i[i1]; kk < S_offd_i[i1 + 1]; kk++) { k1 = S_offd_j[kk]; if (CF_marker_offd[k1] >= 0) { if (P_marker_offd[k1] < jj_begin_row_offd) { P_marker_offd[k1] = jj_counter_offd; P_offd_j[jj_counter_offd] = k1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } if ( num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if ( CF_marker_offd[i1] >= 0) { if (P_marker_offd[i1] < jj_begin_row_offd) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } else if (CF_marker_offd[i1] != -3) { P_marker_offd[i1] = strong_f_marker; for (kk = Sop_i[i1]; kk < Sop_i[i1 + 1]; kk++) { big_k1 = Sop_j[kk]; /* Find local col number */ if (big_k1 >= col_1 && big_k1 < col_n) { loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] < jj_begin_row) { P_marker[loc_col] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[loc_col]; P_diag_data[jj_counter] = zero; jj_counter++; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] < jj_begin_row_offd) { P_marker_offd[loc_col] = jj_counter_offd; P_offd_j[jj_counter_offd] = loc_col; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } } } } } } jj_end_row = jj_counter; jj_end_row_offd = jj_counter_offd; diagonal = A_diag_data[A_diag_i[i]]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i + 1]; jj++) { /* i1 is a c-point and strongly influences i, accumulate * a_(i,i1) into interpolation weight */ i1 = A_diag_j[jj]; if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += A_diag_data[jj]; } else if (P_marker[i1] == strong_f_marker) { sum = zero; sgn = 1; if (A_diag_data[A_diag_i[i1]] < 0) { sgn = -1; } /* Loop over row of A for point i1 and calculate the sum * of the connections to c-points that strongly incluence i. */ for (jj1 = A_diag_i[i1] + 1; jj1 < A_diag_i[i1 + 1]; jj1++) { i2 = A_diag_j[jj1]; if ((P_marker[i2] >= jj_begin_row) && (sgn * A_diag_data[jj1]) < 0) { sum += A_diag_data[jj1]; } } if (num_procs > 1) { for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1 + 1]; jj1++) { i2 = A_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd && (sgn * A_offd_data[jj1]) < 0) { sum += A_offd_data[jj1]; } } } if (sum != 0) { distribute = A_diag_data[jj] / sum; /* Loop over row of A for point i1 and do the distribution */ for (jj1 = A_diag_i[i1] + 1; jj1 < A_diag_i[i1 + 1]; jj1++) { i2 = A_diag_j[jj1]; if (P_marker[i2] >= jj_begin_row && (sgn * A_diag_data[jj1]) < 0) P_diag_data[P_marker[i2]] += distribute * A_diag_data[jj1]; } if (num_procs > 1) { for (jj1 = A_offd_i[i1]; jj1 < A_offd_i[i1 + 1]; jj1++) { i2 = A_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd && (sgn * A_offd_data[jj1]) < 0) P_offd_data[P_marker_offd[i2]] += distribute * A_offd_data[jj1]; } } } else { diagonal += A_diag_data[jj]; } } /* neighbor i1 weakly influences i, accumulate a_(i,i1) into * diagonal */ else if (CF_marker[i1] != -3) { if (num_functions == 1 || dof_func[i] == dof_func[i1]) { diagonal += A_diag_data[jj]; } } } if (num_procs > 1) { for (jj = A_offd_i[i]; jj < A_offd_i[i + 1]; jj++) { i1 = A_offd_j[jj]; if (P_marker_offd[i1] >= jj_begin_row_offd) { P_offd_data[P_marker_offd[i1]] += A_offd_data[jj]; } else if (P_marker_offd[i1] == strong_f_marker) { sum = zero; sgn = 1; for (jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1 + 1]; jj1++) { big_k1 = A_ext_j[jj1]; if (big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] >= jj_begin_row ) { sum += A_ext_data[jj1]; } } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] >= jj_begin_row_offd && (sgn * A_ext_data[jj1]) < 0) { sum += A_ext_data[jj1]; } } } if (sum != 0) { distribute = A_offd_data[jj] / sum; for (jj1 = A_ext_i[i1]; jj1 < A_ext_i[i1 + 1]; jj1++) { big_k1 = A_ext_j[jj1]; if (big_k1 >= col_1 && big_k1 < col_n) { /* diag */ loc_col = (HYPRE_Int)(big_k1 - col_1); if (P_marker[loc_col] >= jj_begin_row) P_diag_data[P_marker[loc_col]] += distribute * A_ext_data[jj1]; } else { loc_col = -(HYPRE_Int)big_k1 - 1; if (P_marker_offd[loc_col] >= jj_begin_row_offd) P_offd_data[P_marker_offd[loc_col]] += distribute * A_ext_data[jj1]; } } } else { diagonal += A_offd_data[jj]; } } else if (CF_marker_offd[i1] != -3) { if (num_functions == 1 || dof_func[i] == dof_func_offd[i1]) { diagonal += A_offd_data[jj]; } } } } if (diagonal) { for (jj = jj_begin_row; jj < jj_end_row; jj++) { P_diag_data[jj] /= -diagonal; } for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { P_offd_data[jj] /= -diagonal; } } } strong_f_marker--; } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d fill structure %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ P = hypre_ParCSRMatrixCreate(comm, total_old_global_cpts, total_global_cpts, num_old_cpts_global, num_cpts_global, 0, P_diag_i[n_coarse_old], P_offd_i[n_coarse_old]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; hypre_CSRMatrixMemoryLocation(P_diag) = HYPRE_MEMORY_HOST; hypre_CSRMatrixMemoryLocation(P_offd) = HYPRE_MEMORY_HOST; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0 || max_elmts > 0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, max_elmts); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_coarse_old]; P_offd_size = P_offd_i[n_coarse_old]; } /* This builds col_map, col_map should be monotone increasing and contain * global numbers. */ if (P_offd_size) { hypre_build_interp_colmap(P, full_off_procNodes, tmp_CF_marker_offd, fine_to_coarse_offd); } hypre_MatvecCommPkgCreate(P); for (i = 0; i < n_fine; i++) if (CF_marker[i] < -1) { CF_marker[i] = -1; } *P_ptr = P; /* Deallocate memory */ hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(old_coarse_to_fine, HYPRE_MEMORY_HOST); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(Sop); hypre_CSRMatrixDestroy(A_ext); hypre_TFree(fine_to_coarse_offd, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_CF_marker_offd, HYPRE_MEMORY_HOST); if (num_functions > 1) { hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); } hypre_MatvecCommPkgDestroy(extend_comm_pkg); } return hypre_error_flag; }
work.c
/******************************************************************** * BenchIT - Performance Measurement for Scientific Applications * Contact: developer@benchit.org * * $Id: work.c 1 2009-09-11 12:26:19Z william $ * $URL: svn+ssh://william@rupert.zih.tu-dresden.de/svn-base/benchit-root/BenchITv6/kernel/numerical/gemv/C/OpenMP/0/float/work.c $ * For license details see COPYING in the package base directory *******************************************************************/ /* Kernel: C SGEMV kernel *******************************************************************/ #include "work.h" void ij_(int sizeVector,int sizeAusgabe,float alpha,float beta, float *x, float *A, float *y) { int i,j; float temp = 0.0; #pragma omp parallel for for (j=0;j<sizeAusgabe;j++) { y[j]=beta*y[j]; } // // now : x=x, A=A, y=beta*y // #pragma omp parallel for private(temp) for (i=0;i<sizeVector;i++) { temp=alpha*x[i]; for (j=0;j<sizeAusgabe;j++) { y[j]=y[j]+A[i*sizeAusgabe+j]*temp; } } } void ji_(int sizeVector,int sizeAusgabe,float alpha,float beta, float *x, float *A, float *y) { int i,j; float temp = 0.0; #pragma omp parallel for for (j=0;j<sizeAusgabe;j++) { y[j]=beta*y[j]; } // // now : x=x, A=A, y=beta*y // #pragma omp parallel for private(temp) for (j=0;j<sizeAusgabe;j++) { temp=0.0; for (i=0;i<sizeVector;i++) { temp=temp+A[i*sizeAusgabe+j]*x[i]; } temp=temp*alpha; y[j]=y[j]+temp; } }
GB_binop__times_int8.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__times_int8) // A.*B function (eWiseMult): GB (_AemultB_08__times_int8) // A.*B function (eWiseMult): GB (_AemultB_02__times_int8) // A.*B function (eWiseMult): GB (_AemultB_04__times_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__times_int8) // A*D function (colscale): GB (_AxD__times_int8) // D*A function (rowscale): GB (_DxB__times_int8) // C+=B function (dense accum): GB (_Cdense_accumB__times_int8) // C+=b function (dense accum): GB (_Cdense_accumb__times_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__times_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__times_int8) // C=scalar+B GB (_bind1st__times_int8) // C=scalar+B' GB (_bind1st_tran__times_int8) // C=A+scalar GB (_bind2nd__times_int8) // C=A'+scalar GB (_bind2nd_tran__times_int8) // C type: int8_t // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (aij * bij) #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) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // 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 = (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_TIMES || GxB_NO_INT8 || GxB_NO_TIMES_INT8) //------------------------------------------------------------------------------ // 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__times_int8) ( 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__times_int8) ( 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__times_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__times_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 //------------------------------------------------------------------------------ GrB_Info GB (_AxD__times_int8) ( 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 int8_t *restrict Cx = (int8_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__times_int8) ( 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 int8_t *restrict Cx = (int8_t *) 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__times_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 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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__times_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__times_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__times_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__times_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__times_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] = (x * bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__times_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] = (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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x * aij) ; \ } GrB_Info GB (_bind1st_tran__times_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] = (aij * y) ; \ } GrB_Info GB (_bind2nd_tran__times_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_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 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__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__gt_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__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,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint32_t bij = GBX (Bx, pB, B_iso) // 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_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_template.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_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, 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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__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_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__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_04__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_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__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 bnz, 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 < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint32_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__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 = 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) \ { \ uint32_t aij = GBX (Ax, pA, false) ; \ 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 = GBX (Ax, pA, false) ; \ 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
GB_unaryop__identity_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__identity_int16_int32 // op(A') function: GB_tran__identity_int16_int32 // C type: int16_t // A type: int32_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = 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 = 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_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_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__identity_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
FourierTransform.h
/* Copyright 2016 Kristofer Björnson * * 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. */ /** @package TBTKcalc * @file FourierTransform.h * @brief Fourier transform * * @author Kristofer Björnson */ #ifndef COM_DAFER45_TBTK_FOURIER_TRANSFORM #define COM_DAFER45_TBTK_FOURIER_TRANSFORM #include "TBTK/Index.h" #include <fftw3.h> #include <complex> namespace TBTK{ class FourierTransform{ public: /** Plan for executing the Fourier-transform. */ template<typename DataType> class Plan{ public: /** Constructor. */ Plan( DataType *in, DataType *out, int sizeX, int sign ); /** Constructor. */ Plan( DataType *in, DataType *out, int sizeX, int sizeY, int sign ); /** Constructor. */ Plan( DataType *in, DataType *out, int sizeX, int sizeY, int sizeZ, int sign ); /** Copy constructor. */ Plan(const Plan &plan) = delete; /** Move constructor. */ Plan(Plan &&plan); /** Destructor. */ ~Plan(); /** Assignment operator. */ Plan& operator=(const Plan &plan) = delete; /** Move assignment operator. */ Plan& operator=(Plan &&plan); /** Set normalization factor. */ void setNormalizationFactor(double normalizationFactor); /** Get normalizationFactor. */ double getNormalizationFactor() const; private: /** FFTW3 plan. */ fftw_plan *plan; /** Normalization factor. */ double normalizationFactor; /** Data size. */ unsigned int size; /** Input data. */ DataType *input; /** Output data. */ DataType *output; /** Get FFTW3 plan. */ fftw_plan& getFFTWPlan(); /** Get data size. */ unsigned int getSize() const; /** Get input data. */ DataType* getInput(); /** Get output data. */ DataType* getOutput(); /** Make FourierTransform a friend class. */ friend class FourierTransform; }; /** Plan for executing forward Fourier-transform. */ template<typename DataType> class ForwardPlan : public Plan<DataType>{ public: /** Constructor. */ ForwardPlan( DataType *in, DataType *out, int sizeX ) : Plan<DataType>( in, out, sizeX, -1 ){} /** Constructor. */ ForwardPlan( DataType *in, DataType *out, int sizeX, int sizeY ) : Plan<DataType>( in, out, sizeX, sizeY, -1 ){} /** Constructor. */ ForwardPlan( DataType *in, DataType *out, int sizeX, int sizeY, int sizeZ ) : Plan<DataType>( in, out, sizeX, sizeY, sizeZ, -1 ){} }; /** Plan for executing inverse Fourier-transform. */ template<typename DataType> class InversePlan : public Plan<DataType>{ public: /** Constructor. */ InversePlan( DataType *in, DataType *out, int sizeX ) : Plan<DataType>( in, out, sizeX, 1 ){} /** Constructor. */ InversePlan( DataType *in, DataType *out, int sizeX, int sizeY ) : Plan<DataType>( in, out, sizeX, sizeY, 1 ){} /** Constructor. */ InversePlan( DataType *in, DataType *out, int sizeX, int sizeY, int sizeZ ) : Plan<DataType>( in, out, sizeX, sizeY, sizeZ, 1 ){} }; /** One-dimensional complex Fourier transform. */ static void transform( std::complex<double> *in, std::complex<double> *out, int sizeX, int sign ); /** Two-dimensional complex Fourier transform. */ static void transform( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sign ); /** Three-dimensional complex Fourier transform. */ static void transform( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sizeZ, int sign ); /** One-dimensional complex Fourier transform. */ template<typename DataType> static void transform(Plan<DataType> &plan); /** One-dimensional complex forward Fourier transform. */ static void forward( std::complex<double> *in, std::complex<double> *out, int sizeX ); /** Two-dimensional complex forward Fourier transform. */ static void forward( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY ); /** Three-dimensional complex forward Fourier transform. */ static void forward( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sizeZ ); /** One-dimensional complex inverse Fourier transform. */ static void inverse( std::complex<double> *in, std::complex<double> *out, int sizeX ); /** Two-dimensional complex inverse Fourier transform. */ static void inverse( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY ); /** Three-dimensional complex inverse Fourier transform. */ static void inverse( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sizeZ ); private: }; template<typename DataType> inline void FourierTransform::transform(Plan<DataType> &plan){ fftw_execute(plan.getFFTWPlan()); double normalizationFactor = plan.getNormalizationFactor(); if(normalizationFactor != 1.){ Streams::out << "Normalizing\n"; DataType *output = plan.getOutput(); for(unsigned int n = 0; n < plan.getSize(); n++) output[n] /= normalizationFactor; } } inline void FourierTransform::forward( std::complex<double> *in, std::complex<double> *out, int sizeX ){ transform(in, out, sizeX, -1); } inline void FourierTransform::forward( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY ){ transform(in, out, sizeX, sizeY, -1); } inline void FourierTransform::forward( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sizeZ ){ transform(in, out, sizeX, sizeY, sizeZ, -1); } inline void FourierTransform::inverse( std::complex<double> *in, std::complex<double> *out, int sizeX ){ transform(in, out, sizeX, 1); } inline void FourierTransform::inverse( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY ){ transform(in, out, sizeX, sizeY, 1); } inline void FourierTransform::inverse( std::complex<double> *in, std::complex<double> *out, int sizeX, int sizeY, int sizeZ ){ transform(in, out, sizeX, sizeY, sizeZ, 1); } template<typename DataType> inline FourierTransform::Plan<DataType>::Plan(Plan &&plan){ this->plan = plan.plan; plan.plan = nullptr; normalizationFactor = plan.normalizationFactor; size = plan.size; input = plan.input; output = plan.output; } template<typename DataType> inline FourierTransform::Plan<DataType>::~Plan(){ if(plan != nullptr){ #pragma omp critical (TBTK_FOURIER_TRANSFORM) fftw_destroy_plan(*plan); delete plan; } } template<typename DataType> inline FourierTransform::Plan<DataType>& FourierTransform::Plan< DataType >::operator=(Plan &&rhs){ if(this != &rhs){ if(this->plan != nullptr){ #pragma omp critical (TBTK_FOURIER_TRANSFORM) fftw_destroy_plan(*this->plan); delete this->plan; this->plan = rhs.plan; normalizationFactor = rhs.normalizationFactor; size = rhs.size; input = rhs.input; output = rhs.output; } } return *this; } template<typename DataType> inline void FourierTransform::Plan<DataType>::setNormalizationFactor( double normalizationFactor ){ this->normalizationFactor = normalizationFactor; } template<typename DataType> inline double FourierTransform::Plan<DataType>::getNormalizationFactor() const{ return normalizationFactor; } template<typename DataType> inline fftw_plan& FourierTransform::Plan<DataType>::getFFTWPlan(){ return *plan; } template<typename DataType> inline unsigned int FourierTransform::Plan<DataType>::getSize() const{ return size; } template<typename DataType> inline DataType* FourierTransform::Plan<DataType>::getInput(){ return input; } template<typename DataType> inline DataType* FourierTransform::Plan<DataType>::getOutput(){ return output; } }; //End of namespace TBTK #endif
sample-2.c
#include <stdio.h> #include <omp.h> int main() { int id,x; omp_set_num_threads(100); #pragma omp parallel private(id,x) { // int id,x; id=omp_get_thread_num(); x=10*id; printf("\n"); printf("Hello from thread %d, x= %d", id,x); printf("\n"); } return 0; }
GB_unop__lnot_uint64_uint64.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 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__lnot_uint64_uint64) // op(A') function: GB (_unop_tran__lnot_uint64_uint64) // C type: uint64_t // A type: uint64_t // cast: uint64_t cij = aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ uint64_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CAST(z, aij) \ uint64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = aij ; \ Cx [pC] = !(z != 0) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_UINT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__lnot_uint64_uint64) ( uint64_t *Cx, // Cx and Ax may be aliased const uint64_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++) { uint64_t aij = Ax [p] ; uint64_t z = aij ; Cx [p] = !(z != 0) ; } } 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 ; uint64_t aij = Ax [p] ; uint64_t z = aij ; Cx [p] = !(z != 0) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__lnot_uint64_uint64) ( 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
GB_unop__minv_int16_int16.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__minv_int16_int16) // op(A') function: GB (_unop_tran__minv_int16_int16) // C type: int16_t // A type: int16_t // cast: int16_t cij = aij // unaryop: cij = GB_IMINV_SIGNED (aij, 16) #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 = GB_IMINV_SIGNED (x, 16) ; // 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] = GB_IMINV_SIGNED (z, 16) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MINV || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__minv_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 ; if (Ab == NULL) { #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] = GB_IMINV_SIGNED (z, 16) ; } } 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] = GB_IMINV_SIGNED (z, 16) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__minv_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
ike_fmt_plug.c
/* PSK cracker patch for JtR. Hacked together during March of 2012 by * Dhiru Kholia <dhiru.kholia at gmail.com> . * * This software is Copyright (c) 2012, Dhiru Kholia <dhiru.kholia at gmail.com> * and it is hereby released to the general public under GPL * * The IKE Scanner (ike-scan) is Copyright (C) 2003-2007 Roy Hills, * NTA Monitor Ltd. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library, and distribute linked combinations including the two. * * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. * * If this license is unacceptable to you, I may be willing to negotiate * alternative licenses (contact ike-scan@nta-monitor.com). * * You are encouraged to send comments, improvements or suggestions to * me at ike-scan@nta-monitor.com. * * psk-crack.c -- IKE Aggressive Mode Pre-Shared Key cracker for ike-scan * * Author: Roy Hills * Date: 8 July 2004 * * July, 2012, JimF small changes made, many more should be done. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_ike; #elif FMT_REGISTERS_H john_register_one(&fmt_ike); #else #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 "ike-crack.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 16 #endif static int omp_t = 1; #endif #include "memdbg.h" #define FORMAT_LABEL "IKE" #define FORMAT_NAME "PSK" #define FORMAT_TAG "$ike$*" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG)-1) #define ALGORITHM_NAME "HMAC MD5/SHA1 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 20 /* SHA1 */ #define BINARY_SIZE_SMALLER 16 /* MD5 */ #define SALT_SIZE sizeof(psk_entry) #define BINARY_ALIGN sizeof(uint32_t) #define SALT_ALIGN sizeof(size_t) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 16 static struct fmt_tests ike_tests[] = { {"$ike$*0*5c7916ddf8db4d233b3b36005bb3ccc115a73807e11a897be943fd4a2d0f942624cb00588d8b3a0a26502b73e639df217ef6c4cb90f96b0a3c3ef2f62ed025b4a705df9de65e33e380c1ba5fa23bf1f9911bbf388d0844256fa0131fc5cf8acb396936ba3295b4637b039d93f58db90a3a1cf1ef5051103bacf6e1a3334f9f89*fde8c68c5f324c7dbcbadde1d757af6962c63496c009f77cad647f2997fd4295e50821453a6dc2f6279fd7fef68768584d9cee0da6e68a534a097ce206bf77ecc798310206f3f82d92d02c885794e0a430ceb2d6b43c2aff45a6e14c6558382df0692ff65c2724eef750764ee456f31424a5ebd9e115d826bbb9722111aa4e01*b2a3c7aa4be95e85*756e3fa11c1b102c*00000001000000010000002c01010001000000240101000080010001800200018003000180040002800b0001000c000400007080*01000000ac100202*251d7ace920b17cb34f9d561bca46d037b337d19*e045819a64edbf022620bff3efdb935216584cc4*b9c594fa3fca6bb30a85c4208a8df348", "abc123"}, {"$ike$*0*9bdee7aa341cf1a6c19bc0191106b5056537ce6b837cd70678ea5a3ccb606b56dee4548feb67f24fd6f4d5f58967a9ff3c674d9d79e4195b7def5aac147c9fe9abdc2f8ba2eca58f4c863fedc7a8c8e1ad6e1551b1e44bf9a0e258561a5db1c2ca1e8b5dfda1b012012b6fdf24ecd07da6b10d76ab3b58d07b30b4f9da26aee4*c9b7ef0610a22b3e1c88b1a01ce4d4110edf6baa122ed1285eb2184cd75d30a11520a725c2d263de5a157f77f953880732f3b14521836d7f3585cb0ce3fcadf81c541dde2680bd81953cf88e8f8096c173470694ca7414fff9df0cdcdbb9d4f70ef1d6347293b507cfad965e2d2c1fa07326353e9a493d93284970040344fb11*3506592130312567*6c362583ce7a2a26*00000001000000010000002c01010001000000240101000080010001800200028003000180040002800b0001000c000400007080*01000000ac100202*84943233f42a0b5a9b33c327162fe0efee2545e4*76f451dce3fea6402b67f3fddae561ebdb4a6efe*f63f237b3c0f1fe57a5b852203cfd27cbf0c78d4", "abc123"}, {NULL} }; static psk_entry *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; 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(sizeof(*saved_key), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *ptr, *ctcopy, *keeptr; if (strncmp(ciphertext, FORMAT_TAG, FORMAT_TAG_LEN)) return 0; if (!(ctcopy = strdup(ciphertext))) return 0; keeptr = ctcopy; ctcopy += FORMAT_TAG_LEN; /* skip leading '$ike$*' */ if (*ctcopy != '0' && *ctcopy != '1') goto error; /* skip '*0' */ ctcopy += 1; if (*ctcopy != '*') goto error; ctcopy += 1; if (!(ptr = strtokm(ctcopy, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) > MAXLEN) goto error; if (!ishexlc(ptr)) goto error; if (!(ptr = strtokm(NULL, "*"))) goto error; if (strlen(ptr) != 32 && strlen(ptr) != 40) // md5 or sha1 length. goto error; if (!ishexlc(ptr)) goto error; MEM_FREE(keeptr); return 1; error: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { static psk_entry cs; cs.isnortel = atoi(&ciphertext[FORMAT_TAG_LEN]); load_psk_params(&ciphertext[FORMAT_TAG_LEN+2], NULL, &cs); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; p = strrchr(ciphertext, '*') + 1; for (i = 0; i < BINARY_SIZE_SMALLER; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static void set_salt(void *salt) { cur_salt = (psk_entry *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { compute_hash(cur_salt, saved_key[index], (unsigned char*)crypt_out[index]); } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (*((uint32_t*)binary) == crypt_out[index][0]) return 1; return 0; } static int cmp_one(void *binary, int index) { return (*((uint32_t*)binary) == crypt_out[index][0]); } static int cmp_exact(char *source, int index) { void *binary = get_binary(source); return !memcmp(binary, crypt_out[index], BINARY_SIZE_SMALLER); } static void ike_set_key(char *key, int index) { strnzcpy(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } /* * For ike, the hash algorithm used for hmac * is returned as the first "tunable cost": * 1: MD5 * 2: SHA1 * * However, the there is almost no difference in speed, * so if the different hash types for HMAC shouldn't be reported, * just define IKE_REPORT_TUNABLE_COSTS to be 0 instead of 1. */ #define IKE_REPORT_TUNABLE_COSTS 1 #if IKE_REPORT_TUNABLE_COSTS static unsigned int tunable_cost_hmac_hash_type(void *salt) { psk_entry *my_salt; my_salt = salt; return (unsigned int) my_salt->hash_type; } #endif struct fmt_main fmt_ike = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE_SMALLER, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_HUGE_INPUT, { #if IKE_REPORT_TUNABLE_COSTS "hash algorithm used for hmac [1:MD5 2:SHA1]", #else NULL #endif }, { FORMAT_TAG }, ike_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { #if IKE_REPORT_TUNABLE_COSTS tunable_cost_hmac_hash_type, #else NULL #endif }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, ike_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
CacheEfficientHogwildTrainer.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 _CACHE_EFFICIENT_HOGWILD_TRAINER_ #define _CACHE_EFFICIENT_HOGWILD_TRAINER_ #include <map> #include "Partitioner/DFSCachePartitioner.h" #include "Partitioner/GreedyCachePartitioner.h" #include "Trainer/Trainer.h" DEFINE_bool(dfs_cache_partitioner, false, "For cache efficient hogwild trainer, use the DFS method to cache partition data points."); DEFINE_bool( greedy_cache_partitioner, false, "For cache efficient hogwild trainer, use an n^2 greedy algorithm to generate cache friendyl data point ordering."); class CacheEfficientHogwildTrainer : public Trainer { protected: void PrintStatsAboutProblem(const std::vector<Datapoint *> &datapoints) { int n_total_coordinate_accesses = 0; int n_distinct_model_accesses = 0; double avg_num_coordinates_accessed_per_datapoint = 0; int max_coordinates_accessed_per_datapoint = 0; int min_coordinates_accessed_per_datapoint = INT_MAX; std::map<int, bool> coordinates_set; for (int i = 0; i < datapoints.size(); i++) { n_total_coordinate_accesses += datapoints[i]->GetCoordinates().size(); for (const auto &coordinate : datapoints[i]->GetCoordinates()) { coordinates_set[coordinate] = 1; } max_coordinates_accessed_per_datapoint = fmax(max_coordinates_accessed_per_datapoint, datapoints[i]->GetCoordinates().size()); min_coordinates_accessed_per_datapoint = fmin(max_coordinates_accessed_per_datapoint, datapoints[i]->GetCoordinates().size()); } n_distinct_model_accesses = coordinates_set.size(); avg_num_coordinates_accessed_per_datapoint = n_total_coordinate_accesses / (double)datapoints.size(); printf( "n_datapoints=%d\n" "n_total_coordinate_accesses=%d\n" "n_distinct_model_acceses=%d\n" "avg_num_coordinates_accessed_per_datapoint=%lf\n" "max_coordinates_accessed=%d\n" "min_coordinates_accessed=%d\n", (int)datapoints.size(), n_total_coordinate_accesses, n_distinct_model_accesses, avg_num_coordinates_accessed_per_datapoint, max_coordinates_accessed_per_datapoint, min_coordinates_accessed_per_datapoint); } public: CacheEfficientHogwildTrainer() {} ~CacheEfficientHogwildTrainer() {} TrainStatistics Train(Model *model, const std::vector<Datapoint *> &datapoints, Updater *updater) override { // Print some stats. PrintStatsAboutProblem(datapoints); // Partition. Timer partition_timer; DatapointPartitions partitions(FLAGS_n_threads); if (FLAGS_dfs_cache_partitioner) { DFSCachePartitioner partitioner; partitions = partitioner.Partition(datapoints, FLAGS_n_threads); } else if (FLAGS_greedy_cache_partitioner) { GreedyCachePartitioner partitioner; partitions = partitioner.Partition(datapoints, FLAGS_n_threads); } else { std::cout << "CacheEfficientHogwildTrainer.h: No partitioning method selected" << std::endl; exit(0); } if (FLAGS_print_partition_time) { this->PrintPartitionTime(partition_timer); } model->SetUpWithPartitions(partitions); updater->SetUpWithPartitions(partitions); TrainStatistics stats; // Train. Timer gradient_timer; for (int epoch = 0; epoch < FLAGS_n_epochs; epoch++) { this->EpochBegin(epoch, gradient_timer, model, datapoints, &stats); updater->EpochBegin(); #pragma omp parallel for schedule(static, 1) for (int thread = 0; thread < FLAGS_n_threads; thread++) { for (int batch = 0; batch < partitions.NumBatches(); batch++) { for (int index = 0; index < partitions.NumDatapointsInBatch(thread, batch); index++) { updater->Update(partitions.GetDatapoint(thread, batch, index)); } } } updater->EpochFinish(); } return stats; } }; #endif
risingexp.c
#include<Python.h> #include<numpy/arrayobject.h> #include<math.h> #include<omp.h> #define IND(a,i) *((double *)(a->data+i*a->strides[0])) static PyObject *risingexp(PyObject *self, PyObject *args, PyObject *keywds); static PyObject *risingexp(PyObject *self, PyObject *args, PyObject *keywds) { PyObject *etc; PyArrayObject *x,*y, *rampparams; double goal,m,x0; int i; npy_intp dims[1]; // etc = PyList_New(0); static char *kwlist[] = {"rampparams","x","etc",NULL}; if(!PyArg_ParseTupleAndKeywords(args,keywds,"OO|O",kwlist,&rampparams,&x,&etc)) { return NULL; } goal = IND(rampparams,0); m = IND(rampparams,1); x0 = IND(rampparams,2); dims[0] = x->dimensions[0]; y = (PyArrayObject *) PyArray_SimpleNew(1,dims,PyArray_DOUBLE); #pragma omp parallel for for(i=0;i<dims[0];i++) { IND(y,i) = goal*(1-exp(-1*m*(IND(x,i)-x0))); } return PyArray_Return(y); } static char module_docstring[]="\ This function creates a model that fits a ramp using a rising exponential.\n\ \n\ Parameters\n\ ----------\n\ goal: goal as x -> inf\n\ m: rise exp\n\ x0: time offset\n\ x: Array of time/phase points\n\ \n\ Returns\n\ -------\n\ This function returns an array of y values by combining an eclipse and a rising exponential\n\ \n\ Revisions\n\ ---------\n\ 2008-06-24 Kevin Stevenson, UCF \n\ kevin218@knights.ucf.edu\n\n\ Original version\n\ 2010-12-24 Nate Lust, UCF \n\ natelust at linux dot com\n\n\ 2018-11-22 Jonathan Fraine, SSI\n\ jfraine at spacescience.org\n\ Updated c extensions to python3, with support for python2.7\n\n\ "; static PyMethodDef module_methods[] = { {"risingexp",(PyCFunction)risingexp,METH_VARARGS|METH_KEYWORDS,module_docstring},{NULL}}; PyMODINIT_FUNC #if PY_MAJOR_VERSION >= 3 PyInit_risingexp(void) #else initrisingexp(void) #endif { #if PY_MAJOR_VERSION >= 3 PyObject *module; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "risingexp", /* m_name */ module_docstring, /* m_doc */ -1, /* m_size */ module_methods, /* m_methods */ NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL, /* m_free */ }; #endif #if PY_MAJOR_VERSION >= 3 module = PyModule_Create(&moduledef); if (!module) return NULL; /* Load `numpy` functionality. */ import_array(); return module; #else PyObject *m = Py_InitModule3("risingexp", module_methods, module_docstring); if (m == NULL) return; /* Load `numpy` functionality. */ import_array(); #endif }
x86_utils.h
/* Copyright (c) 2016 Anakin Authors All Rights Reserve. 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 X86_UTILS_H #define X86_UTILS_H #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "core/common.h" #include "saber/core/tensor.h" #include "mkl_cblas.h" namespace anakin { namespace saber { #define UNUSED(x) ((void)x) #define MAYBE_UNUSED(x) UNUSED(x) #ifdef _WIN32 #define __PRETTY_FUNCTION__ __FUNCSIG__ #endif namespace utils { /* a bunch of std:: analogues to be compliant with any msvs version * * Rationale: msvs c++ (and even some c) headers contain special pragma that * injects msvs-version check into object files in order to abi-mismatches * during the static linking. This makes sense if e.g. std:: objects are passed * through between application and library, which is not the case for mkl-dnn * (since there is no any c++-rt dependent stuff, ideally...). */ /* SFINAE helper -- analogue to std::enable_if */ class VectorPrint { public: template <typename Dtype> static void print_float(Dtype* target) { float* f = (float*)target; printf("size = %d\n", sizeof(Dtype)); for (int i = 0; i < sizeof(Dtype) / sizeof(float); i++) { printf(" %f ,", f[i]); } printf("\n"); } }; class AlignedUtils { public: template <typename Dtype> void aligned_last_dim(const Dtype* input, Dtype* output, int input_size, int ori_last_dim, int aligned_dim) { for (int i = 0; i < input_size; i++) { int row = i / ori_last_dim; int col = i % ori_last_dim; output[row * aligned_dim + col] = input[i]; } } template <typename Dtype> void unaligned_last_dim(const Dtype* input, Dtype* output, int output_size, int ori_last_dim, int aligned_dim) { for (int i = 0; i < output_size; i++) { int row = i / ori_last_dim; int col = i % ori_last_dim; output[i] = input[row * aligned_dim + col]; } } }; class SeqSortedseqTranseUtil { public: SeqSortedseqTranseUtil(bool is_reverse = false, bool is_bi = false) : _is_reverse(is_reverse), _is_bi(is_bi) {}; void print_vec(int* in, int size, const char* perfix) { for (int i = 0; i < size; i++) { printf("[%s] %d = %d\n", perfix, i, in[i]); } } template <typename Dtype> void seq_2_sorted_seq(const Dtype* input, Dtype* output, int word_size) { // _map_vec.resize(word_sum); int word_sum = _map_vec.size(); // std::cout << "word_sum = " << word_sum << std::endl; for (int ori_word_id = 0; ori_word_id < word_sum; ++ori_word_id) { //can param int word_start = ori_word_id * word_size; int maped_id = _map_vec[ori_word_id]; int maped_start = maped_id * word_size; for (int word_vec_offset = 0; word_vec_offset < word_size; ++word_vec_offset) { // std::cout<<maped_start + word_vec_offset<<" --> "<<word_start + word_vec_offset<<" , = "<<input[maped_start + word_vec_offset]<<std::endl; output[maped_start + word_vec_offset] = input[word_start + word_vec_offset]; } } } template <typename Dtype> void hidden_2_sorted_hidden(const Dtype* input, Dtype* output, int hidden_size) { // _map_vec.resize(word_sum); int batch_size = _length_index.size(); // std::cout << "word_sum = " << word_sum << std::endl; for (int ori_word_id = 0; ori_word_id < batch_size; ++ori_word_id) { //can param int word_start = ori_word_id * hidden_size; int maped_id = _length_index[ori_word_id]; int maped_start = maped_id * hidden_size; for (int word_vec_offset = 0; word_vec_offset < hidden_size; ++word_vec_offset) { // std::cout<<maped_start + word_vec_offset<<" --> "<<word_start + word_vec_offset<<" , = "<<input[maped_start + word_vec_offset]<<std::endl; output[word_start + word_vec_offset] = input[maped_start + word_vec_offset]; } } } template <typename Dtype> void sorted_seq_2_seq(const Dtype* input, Dtype* output, int hidden_size) { int word_sum = _map_vec.size(); for (int ori_word_id = 0; ori_word_id < word_sum; ori_word_id++) { //can param int word_start = ori_word_id * hidden_size; int maped_id = _map_vec[ori_word_id]; int maped_start = maped_id * hidden_size; for (int word_vec_offset = 0; word_vec_offset < hidden_size; word_vec_offset++) { // std::cout<<ori_word_id+word_vec_offset<<" -> "<<maped_start+word_vec_offset<<std::endl; output[word_start + word_vec_offset] = input[maped_start + word_vec_offset]; } } } template <typename Dtype> void sorted_seq_2_seq(const Dtype* input, Dtype* output, int hidden_size, int alligned_hidden_size) { int word_sum = _map_vec.size(); for (int ori_word_id = 0; ori_word_id < word_sum; ori_word_id++) { //can param int word_start = ori_word_id * hidden_size; int maped_id = _map_vec[ori_word_id]; int maped_start = maped_id * alligned_hidden_size; for (int word_vec_offset = 0; word_vec_offset < hidden_size; word_vec_offset++) { // std::cout<<ori_word_id+word_vec_offset<<" -> "<<maped_start+word_vec_offset<<std::endl; output[word_start + word_vec_offset] = input[maped_start + word_vec_offset]; } } } /** * return whether need to transform * @param offset_vec * @param emit_offset_vec * @param emit_length * @return */ bool get_sorted_map(std::vector<int>& offset_vec, std::vector<int>& emit_offset_vec, int& emit_length) { int batch_size = offset_vec.size() - 1; int word_sum = offset_vec[offset_vec.size() - 1]; std::vector<int>length_vec(batch_size); _length_index.resize(batch_size); if (batch_size == 1) { emit_length = offset_vec[1] - offset_vec[0]; emit_offset_vec.resize(emit_length + 1); for (int i = 0; i <= emit_length; i++) { emit_offset_vec[i] = i; } return false; } int max_len = 0; for (int i = 0; i < offset_vec.size() - 1; ++i) { int len = offset_vec[i + 1] - offset_vec[i]; max_len = max_len > len ? max_len : len; length_vec[i] = len; _length_index[i] = i; } emit_length = max_len; if (max_len == 1) { emit_offset_vec.push_back(0); emit_offset_vec.push_back(emit_length * batch_size); return false; } std::sort(_length_index.begin(), _length_index.end(), [&length_vec](int i1, int i2) { return length_vec[i1] > length_vec[i2]; }); emit_offset_vec.resize(max_len + 1); _map_vec.resize(word_sum); int target_word_id = 0; std::vector<int> length_vec_cnt = length_vec; for (int word_id_in_seq = 0; word_id_in_seq < max_len; word_id_in_seq++) { emit_offset_vec[word_id_in_seq] = target_word_id; for (int batch_id = 0; batch_id < batch_size; batch_id++) { int old_batch_id = _length_index[batch_id]; if (length_vec_cnt[old_batch_id] > 0) { int inner_word_id_in_seq = word_id_in_seq; if (_is_reverse) { inner_word_id_in_seq = length_vec[old_batch_id] - 1 - word_id_in_seq; } int old_word_id = offset_vec[old_batch_id] + inner_word_id_in_seq; _map_vec[old_word_id] = target_word_id; // printf("map %d -> %d\n",old_word_id,target_word_id); length_vec_cnt[old_batch_id]--; target_word_id++; } else { break; } } } // print_vec(_map_vec.data(),word_sum,"map"); emit_offset_vec[max_len] = word_sum; return true; } private: // std::vector<int> _length_vec; std::vector<int> _length_index; std::vector<int> _map_vec; bool _is_reverse; bool _is_bi; }; inline int round_up(int k, int c) { return ((k + c - 1) / c) * c; } inline int div_up(int k, int c) { return (k + c - 1) / c; } template<bool expr, class T = void> struct enable_if {}; template<class T> struct enable_if<true, T> { typedef T type; }; /* analogue std::conditional */ template <bool, typename, typename> struct conditional {}; template <typename T, typename F> struct conditional<true, T, F> { typedef T type; }; template <typename T, typename F> struct conditional<false, T, F> { typedef F type; }; template <bool, typename, bool, typename, typename> struct conditional3 {}; template <typename T, typename FT, typename FF> struct conditional3<true, T, false, FT, FF> { typedef T type; }; template <typename T, typename FT, typename FF> struct conditional3<false, T, true, FT, FF> { typedef FT type; }; template <typename T, typename FT, typename FF> struct conditional3<false, T, false, FT, FF> { typedef FF type; }; template <bool, typename U, U, U> struct conditional_v {}; template <typename U, U t, U f> struct conditional_v<true, U, t, f> { static constexpr U value = t; }; template <typename U, U t, U f> struct conditional_v<false, U, t, f> { static constexpr U value = f; }; template <typename T> struct remove_reference { typedef T type; }; template <typename T> struct remove_reference<T&> { typedef T type; }; template <typename T> struct remove_reference < T&& > { typedef T type; }; template<typename T> inline const T& min(const T& a, const T& b) { return a < b ? a : b; } template<typename T> inline const T& max(const T& a, const T& b) { return a > b ? a : b; } template <typename T> inline T&& forward(typename utils::remove_reference<T>::type& t) { return static_cast < T && >(t); } template <typename T> inline T&& forward(typename utils::remove_reference<T>::type&& t) { return static_cast < T && >(t); } template <typename T> inline typename remove_reference<T>::type zero() { auto zero = typename remove_reference<T>::type(); return zero; } template <typename T, typename P> inline bool everyone_is(T val, P item) { return val == item; } template <typename T, typename P, typename... Args> inline bool everyone_is(T val, P item, Args... item_others) { return val == item && everyone_is(val, item_others...); } template <typename T, typename P> inline bool one_of(T val, P item) { return val == item; } template <typename T, typename P, typename... Args> inline bool one_of(T val, P item, Args... item_others) { return val == item || one_of(val, item_others...); } template <typename... Args> inline bool any_null(Args... ptrs) { return one_of(nullptr, ptrs...); } inline bool implication(bool cause, bool effect) { return !cause || effect; } template<typename T> inline void array_copy(T* dst, const T* src, size_t size) { for (size_t i = 0; i < size; ++i) { dst[i] = src[i]; } } template<typename T> inline bool array_cmp(const T* a1, const T* a2, size_t size) { for (size_t i = 0; i < size; ++i) if (a1[i] != a2[i]) { return false; } return true; } template<typename T, typename U> inline void array_set(T* arr, const U& val, size_t size) { for (size_t i = 0; i < size; ++i) { arr[i] = static_cast<T>(val); } } namespace product_impl { template<size_t> struct int2type {}; template <typename T> constexpr int product_impl(const T* arr, int2type<0>) { return arr[0]; } template <typename T, size_t num> inline T product_impl(const T* arr, int2type<num>) { return arr[0] * product_impl(arr + 1, int2type < num - 1 > ()); } } template <size_t num, typename T> inline T array_product(const T* arr) { return product_impl::product_impl(arr, product_impl::int2type < num - 1 > ()); } template<typename T, typename R = T> inline R array_product(const T* arr, size_t size) { R prod = 1; for (size_t i = 0; i < size; ++i) { prod *= arr[i]; } return prod; } template <typename T, typename U> inline typename remove_reference<T>::type div_up(const T a, const U b) { assert(b); return (a + b - 1) / b; } template <typename T, typename U> inline typename remove_reference<T>::type rnd_up(const T a, const U b) { return div_up(a, b) * b; } template <typename T, typename U> inline typename remove_reference<T>::type rnd_dn(const T a, const U b) { return (a / b) * b; } template <typename T, typename U, typename V> inline U this_block_size(const T offset, const U max, const V block_size) { assert(offset < max); // TODO (Roma): can't use nstl::max() due to circular dependency... we // need to fix this const T block_boundary = offset + block_size; if (block_boundary > max) { return max - offset; } else { return block_size; } } template <typename T, typename U> inline void balance211(T n, U team, U tid, T& n_start, T& n_end) { T n_min = 1; T& n_my = n_end; if (team <= 1 || n == 0) { n_start = 0; n_my = n; } else if (n_min == 1) { // team = T1 + T2 // n = T1*n1 + T2*n2 (n1 - n2 = 1) T n1 = div_up(n, (T)team); T n2 = n1 - 1; T T1 = n - n2 * (T)team; n_my = (T)tid < T1 ? n1 : n2; n_start = (T)tid <= T1 ? tid * n1 : T1 * n1 + ((T)tid - T1) * n2; } n_end += n_start; } template<typename T> inline T nd_iterator_init(T start) { return start; } template<typename T, typename U, typename W, typename... Args> inline T nd_iterator_init(T start, U& x, const W& X, Args&& ... tuple) { start = nd_iterator_init(start, utils::forward<Args>(tuple)...); x = start % X; return start / X; } inline bool nd_iterator_step() { return true; } template<typename U, typename W, typename... Args> inline bool nd_iterator_step(U& x, const W& X, Args&& ... tuple) { if (nd_iterator_step(utils::forward<Args>(tuple)...)) { x = (x + 1) % X; return x == 0; } return false; } template<typename U, typename W, typename Y> inline bool nd_iterator_jump(U& cur, const U end, W& x, const Y& X) { U max_jump = end - cur; U dim_jump = X - x; if (dim_jump <= max_jump) { x = 0; cur += dim_jump; return true; } else { cur += max_jump; x += max_jump; return false; } } template<typename U, typename W, typename Y, typename... Args> inline bool nd_iterator_jump(U& cur, const U end, W& x, const Y& X, Args&& ... tuple) { if (nd_iterator_jump(cur, end, utils::forward<Args>(tuple)...)) { x = (x + 1) % X; return x == 0; } return false; } template <typename Telem, size_t Tdims> struct array_offset_calculator { template <typename... Targs> array_offset_calculator(Telem* base, Targs... Fargs) : _dims{ Fargs... } { _base_ptr = base; } template <typename... Targs> inline Telem& operator()(Targs... Fargs) { return *(_base_ptr + _offset(1, Fargs...)); } private: template <typename... Targs> inline size_t _offset(size_t const dimension, size_t element) { return element; } template <typename... Targs> inline size_t _offset(size_t const dimension, size_t theta, size_t element) { return element + (_dims[dimension] * theta); } template <typename... Targs> inline size_t _offset(size_t const dimension, size_t theta, size_t element, Targs... Fargs) { size_t t_prime = element + (_dims[dimension] * theta); return _offset(dimension + 1, t_prime, Fargs...); } Telem* _base_ptr; const int _dims[Tdims]; }; } // namespace utils inline void* zmalloc(size_t size, int alignment) { void* ptr = NULL; #ifdef _WIN32 ptr = _aligned_malloc(size, alignment); int rc = ptr ? 0 : -1; #else int rc = ::posix_memalign(&ptr, alignment, size); #endif return (rc == 0) ? ptr : NULL; } inline void zfree(void* p) { #ifdef _WIN32 _aligned_free(p); #else ::free(p); #endif } struct c_compatible { enum { default_alignment = 4096 }; static void* operator new (size_t sz) { return zmalloc(sz, default_alignment); } static void* operator new (size_t sz, void* p) { UNUSED(sz); return p; } static void* operator new[](size_t sz) { return zmalloc(sz, default_alignment); } static void operator delete (void* p) { zfree(p); } static void operator delete[](void* p) { zfree(p); } }; inline void yield_thread() { } // reorder weight layout from NCHW(oc, ic, kh, kw) to OIhw16i16o inline void weight_reorder_OIhw16i16o(Tensor<X86, AK_FLOAT, NCHW>& input, Tensor<X86, AK_FLOAT, NCHW>& output) { Shape shape = input.valid_shape(); int oc_value = shape[0], ic_value = shape[1], kh_value = shape[2], kw_value = shape[3]; #pragma omp parallel for collapse(6) schedule(static) for (int oc_idx = 0; oc_idx < oc_value / 16; ++oc_idx) { for (int ic_idx = 0; ic_idx < ic_value / 16; ++ic_idx) { for (int kh = 0; kh < kh_value; ++kh) { for (int kw = 0; kw < kw_value; ++kw) { for (int ic = 0; ic < 16; ++ic) { for (int oc = 0; oc < 16; ++oc) { int input_idx = (oc_idx * 16 + oc) * ic_value * kh_value * kw_value + (ic_idx * 16 + ic) * kh_value * kw_value + kh * kw_value + kw; int output_idx = oc_idx * ic_value / 16 * kh_value * kw_value * 16 * 16 + ic_idx * kh_value * kw_value * 16 * 16 + kh * kw_value * 16 * 16 + kw * 16 * 16 + ic * 16 + oc; *(output.mutable_data() + output_idx) = *(input.data() + input_idx); } } } } } } } // reorder weight layout from NCHW(oc, ic, kh, kw) to OIhwi16o inline void weight_reorder_OIhwi16o(Tensor<X86, AK_FLOAT, NCHW>& input, Tensor<X86, AK_FLOAT, NCHW>& output) { Shape shape = input.shape(); #pragma omp parallel for collapse(5) schedule(static) for (int oc_idx = 0; oc_idx < shape[0] / 16; ++oc_idx) { for (int kh = 0; kh < shape[2]; ++kh) { for (int kw = 0; kw < shape[3]; ++kw) { for (int ic = 0; ic < shape[1]; ++ic) { for (int oc = 0; oc < 16; ++oc) { int input_idx = (oc_idx * 16 + oc) * shape[1] * shape[2] * shape[3] + ic * shape[2] * shape[3] + kh * shape[3] + kw; int output_idx = oc_idx * shape[2] * shape[3] * shape[1] * 16 + kh * shape[3] * shape[1] * 16 + kw * shape[1] * 16 + ic * 16 + oc; *(output.mutable_data() + output_idx) = *(input.data() + input_idx); } } } } } } // reorder weight layout from NCHW(oc, ic, kh, kw) to OIhwi8o inline void weight_reorder_OIhwi8o(Tensor<X86, AK_FLOAT, NCHW>& input, Tensor<X86, AK_FLOAT, NCHW>& output) { Shape shape = input.shape(); #pragma omp parallel for collapse(5) schedule(static) for (int oc_idx = 0; oc_idx < shape[0] / 8; ++oc_idx) { for (int kh = 0; kh < shape[2]; ++kh) { for (int kw = 0; kw < shape[3]; ++kw) { for (int ic = 0; ic < shape[1]; ++ic) { for (int oc = 0; oc < 8; ++oc) { int input_idx = (oc_idx * 8 + oc) * shape[1] * shape[2] * shape[3] + ic * shape[2] * shape[3] + kh * shape[3] + kw; int output_idx = oc_idx * shape[2] * shape[3] * shape[1] * 8 + kh * shape[3] * shape[1] * 8 + kw * shape[1] * 8 + ic * 8 + oc; *(output.mutable_data() + output_idx) = *(input.data() + input_idx); } } } } } } // reorder weight layout from NCHW to Goihw16g static void weight_reorder_Goihw16g(Tensor<X86, AK_FLOAT, NCHW>& input, Tensor<X86, AK_FLOAT, NCHW>& output) { Shape shape = input.shape(); int g_value = shape[0], oc_value = shape[1], ic_value = shape[1], kh_value = shape[2], kw_value = shape[3]; #pragma omp parallel for collapse(6) schedule(static) for (int g_idx = 0; g_idx < g_value / 16; ++g_idx) { for (int oc_idx = 0; oc_idx < oc_value; ++oc_idx) { for (int ic_idx = 0; ic_idx < ic_value; ++ic_idx) { for (int kh = 0; kh < kh_value; ++kh) { for (int kw = 0; kw < kw_value; ++kw) { for (int g = 0; g < 16; ++g) { int input_idx = (g_idx * 16 + g) * oc_value * ic_value * kh_value * kw_value + oc_idx * ic_value * kh_value * kw_value + ic_idx * kh_value * kw_value + kh * kw_value + kw; int output_idx = g_idx * oc_value * ic_value * kh_value * kw_value * 16 + oc_idx * ic_value * kh_value * kw_value * 16 + ic_idx * kh_value * kw_value * 16 + kh * kw_value * 16 + kw * 16 + g; *(output.mutable_data() + output_idx) = *(input.data() + input_idx); } } } } } } } inline size_t datatype_size(DataType data_type) { switch (data_type) { case AK_FLOAT: return sizeof(float); case AK_INT32: return sizeof(int32_t); case AK_INT16: return sizeof(int16_t); case AK_INT8: return sizeof(int8_t); case AK_UINT8: return sizeof(uint8_t); case AK_INVALID: default: assert(!"unknown data_type"); } return 0; } template<typename DataTensor_in, typename DataTensor_out> inline void conv_basic_x86(DataTensor_in& tensor_out, DataTensor_out& tensor_in, const float* weights, const float* bias, int group, int kernel_w, int kernel_h, int stride_w, int stride_h, int dila_w, int dila_h, int pad_w, int pad_h, bool flag_bias, bool flag_relu) { auto src_data = reinterpret_cast<const float*>(tensor_in.data()); auto dst_data_ref = reinterpret_cast<float*>(tensor_out.mutable_data()); auto weights_data = weights; bool with_bias = flag_bias; auto bias_data = bias; int in_num = tensor_out.num(); int out_channels = tensor_out.channel(); int out_h = tensor_out.height(); int out_w = tensor_out.width(); int in_channel = tensor_in.channel(); int in_h = tensor_in.height(); int in_w = tensor_in.width(); int out_c_group = out_channels / group; int in_c_group = in_channel / group; for (int n = 0; n < in_num; ++n) { for (int g = 0; g < group; ++g) { for (int oc = 0; oc < out_c_group; ++oc) { for (int oh = 0; oh < out_h; ++oh) { for (int ow = 0; ow < out_w; ++ow) { int out_idx = n * group * out_c_group * out_h * out_w + g * out_c_group * out_h * out_w + oc * out_h * out_w + oh * out_w + ow; dst_data_ref[out_idx] = with_bias ? (float)(bias_data[g * out_c_group + oc]) : 0.f; for (int ic = 0; ic < in_c_group; ++ic) { for (int kh = 0; kh < kernel_h; ++kh) { for (int kw = 0; kw < kernel_w; ++kw) { int iw = ow * stride_w - pad_w + kw * (dila_w); int ih = oh * stride_h - pad_h + kh * (dila_h); if (iw < 0 || iw >= in_w) { continue; } if (ih < 0 || ih >= in_h) { continue; } int iidx = n * in_channel * in_h * in_w + g * in_c_group * in_h * in_w + ic * in_h * in_w + ih * in_w + iw; int widx = g * out_c_group * in_c_group * kernel_h * kernel_w + oc * in_c_group * kernel_h * kernel_w + ic * kernel_h * kernel_w + kh * kernel_w + kw; dst_data_ref[out_idx] += src_data[iidx] * weights_data[widx]; } } } if (flag_relu) { dst_data_ref[out_idx] = dst_data_ref[out_idx] > 0.f ? dst_data_ref[out_idx] : 0.f; } } } } } } } static inline bool is_a_ge_zero_and_a_lt_b(int a, int b) { return static_cast<unsigned>(a) < static_cast<unsigned>(b); } template <typename Dtype> static void im2col_cpu(const Dtype* data_im, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, Dtype* data_col) { const int output_h = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int output_w = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; const int channel_size = height * width; for (int channel = channels; channel--; data_im += channel_size) { for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) { for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) { int input_row = -pad_h + kernel_row * dilation_h; for (int output_rows = output_h; output_rows; output_rows--) { if (!is_a_ge_zero_and_a_lt_b(input_row, height)) { for (int output_cols = output_w; output_cols; output_cols--) { *(data_col++) = 0; } } else { int input_col = -pad_w + kernel_col * dilation_w; for (int output_col = output_w; output_col; output_col--) { if (is_a_ge_zero_and_a_lt_b(input_col, width)) { *(data_col++) = data_im[input_row * width + input_col]; } else { *(data_col++) = 0; } input_col += stride_w; } } input_row += stride_h; } } } } } inline void mkl_gemm(const bool TransA, const bool TransB, int m, int n, int k, const float alpha, const float* a, const float* b, const float beta, float* c) { // cout << "(" << m << "," << n << "," << k << ")" << endl; int lda = (!TransA/* == CblasNoTrans*/) ? k : m; int ldb = (!TransB/* == CblasNoTrans*/) ? n : k; CBLAS_TRANSPOSE cuTransA = (!TransA/* == CblasNoTrans*/) ? CblasNoTrans : CblasTrans; CBLAS_TRANSPOSE cuTransB = (!TransB/* == CblasNoTrans*/) ? CblasNoTrans : CblasTrans; cblas_sgemm(CblasRowMajor, cuTransA, cuTransB, m, n, k, alpha, a, k, b, n, beta, c, n); }; template<typename DataTensor_in, typename DataTensor_out,typename DataTensor_op> inline void im2col_conv_cpu(DataTensor_in& tensor_out, DataTensor_out& tensor_in,DataTensor_op& tensor_temp, const float* weights, const float* bias, int group, int kernel_w, int kernel_h, int stride_w, int stride_h, int dila_w, int dila_h, int pad_w, int pad_h, bool flag_bias, bool flag_relu ) { int in_c = tensor_in.channel(); int in_h = tensor_in.height(); int in_w = tensor_in.width(); int out_c = tensor_out.channel(); int out_h = tensor_out.height(); int out_w = tensor_out.width(); CHECK_EQ(group,1)<<"only support group == 1"; int slice_size=in_c*kernel_h*kernel_w * out_h*out_w; int batch_size=tensor_in.num(); tensor_temp.try_expand_size(slice_size); for(int i=0;i<batch_size;i++){ im2col_cpu(tensor_in.data()+i*(in_c*in_h*in_w),in_c,in_h,in_w,kernel_h,kernel_w,pad_h,pad_w,stride_h,stride_w,dila_h,dila_w,tensor_temp.mutable_data()); mkl_gemm(false,false,out_c,out_h*out_w,in_c*kernel_h*kernel_w,1.f,weights,tensor_temp.data(),0,tensor_out.mutable_data()+i*out_c*out_h*out_w); } if(flag_bias&& !flag_relu){ float *output=tensor_out.mutable_data(); int id=0; for(int i=0;i<batch_size;i++){ for(int oc=0;oc<out_c;++oc) { for (int inner_id = 0; inner_id < out_h*out_w; ++inner_id,++id) { output[id]+=bias[oc]; } } } }else if(!flag_bias&&flag_relu){ float *output=tensor_out.mutable_data(); int id=0; for(int i=0;i<batch_size;i++){ for(int oc=0;oc<out_c;++oc) { for (int inner_id = 0; inner_id < out_h*out_w; ++inner_id,++id) { if(output[id]<0){ output[id]=0; } } } } }else if(flag_bias&&flag_relu){ float *output=tensor_out.mutable_data(); int id=0; for(int i=0;i<batch_size;i++){ for(int oc=0;oc<out_c;++oc) { for (int inner_id = 0; inner_id < out_h*out_w; ++inner_id,++id) { float temp=output[id]; temp+=bias[oc]; if(temp<0){ temp=0; } output[id]=temp; } } } } } } // namespace saber } // namespace anakin #ifdef USE_OPENMP #include <omp.h> #else inline int omp_get_max_threads() { return 1; } inline int omp_get_num_threads() { return 1; } inline int omp_get_thread_num() { return 0; } inline int omp_in_parallel() { return 0; } #endif #endif // X86_UTILS_H // vim: et ts=4 sw=4 cindent cino^=l0,\:0,N-s
Example_task_dep.5.c
/* * @@name: task_dep.5c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ // Assume BS divides N perfectly void matmul_depend(int N, int BS, float A[N][N], float B[N][N], float C[N][N] ) { int i, j, k, ii, jj, kk; for (i = 0; i < N; i+=BS) { for (j = 0; j < N; j+=BS) { for (k = 0; k < N; k+=BS) { // Note 1: i, j, k, A, B, C are firstprivate by default // Note 2: A, B and C are just pointers #pragma omp task private(ii, jj, kk) \ depend ( in: A[i:BS][k:BS], B[k:BS][j:BS] ) \ depend ( inout: C[i:BS][j:BS] ) for (ii = i; ii < i+BS; ii++ ) for (jj = j; jj < j+BS; jj++ ) for (kk = k; kk < k+BS; kk++ ) C[ii][jj] = C[ii][jj] + A[ii][kk] * B[kk][jj]; } } } }
trmv_x_sky_u_lo.c
#include "alphasparse/kernel.h" #include "alphasparse/opt.h" #include "alphasparse/util.h" #include <string.h> #ifdef _OPENMP #include <omp.h> #endif static alphasparse_status_t ONAME_omp(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { const ALPHA_INT m = A->rows; const ALPHA_INT n = A->cols; if(m != n) return ALPHA_SPARSE_STATUS_INVALID_VALUE; const ALPHA_INT thread_num = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT i = 0; i < m; ++i) { alpha_mul(y[i], beta, y[i]); } #ifdef _OPENMP #pragma omp parallel for num_threads(thread_num) #endif for(ALPHA_INT r = 0; r < m; ++r) { const ALPHA_INT row_start = A->pointers[r]; const ALPHA_INT row_end = A->pointers[r + 1]; ALPHA_INT row_indx = 1; for(ALPHA_INT i = row_start; i < row_end; i++) { ALPHA_INT row_eles = row_end - row_start; const ALPHA_Number v = A->values[i]; ALPHA_INT c = r - row_eles + row_indx; if(i == row_end - 1) { alpha_madde(y[r], alpha, x[c]); } else { ALPHA_Number t; alpha_mul(t, alpha, A->values[i]); alpha_madde(y[r], t, x[c]); } row_indx ++; } } return ALPHA_SPARSE_STATUS_SUCCESS; } alphasparse_status_t ONAME(const ALPHA_Number alpha, const ALPHA_SPMAT_SKY *A, const ALPHA_Number *x, const ALPHA_Number beta, ALPHA_Number *y) { return ONAME_omp(alpha, A, x, beta, y); }
atomic-2.c
/* { dg-do run } */ /* { dg-options "-O2 -fopenmp" } */ /* { dg-options "-O2 -fopenmp -march=nocona" { target i?86-*-* x86_64-*-* } } */ /* { dg-options "-O2 -fopenmp" { target ilp32 } } */ double d = 1.5; long double ld = 3; extern void abort (void); void test (void) { #pragma omp atomic d *= 1.25; #pragma omp atomic ld /= 0.75; if (d != 1.875 || ld != 4.0L) abort (); } int main (void) { #ifdef __x86_64__ # define bit_SSE3 (1 << 0) # define bit_CX16 (1 << 13) unsigned int ax, bx, cx, dx; __asm__ ("cpuid" : "=a" (ax), "=b" (bx), "=c" (cx), "=d" (dx) : "0" (1) : "cc"); if ((cx & (bit_SSE3 | bit_CX16)) != (bit_SSE3 | bit_CX16)) return 0; #endif test (); return 0; }
tutorial_region_prof.c
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <stdlib.h> #include <stdio.h> #include <time.h> #include <math.h> #include <stdint.h> #include <mpi.h> #ifdef _OPENMP #include <omp.h> #endif #include <geopm.h> #include "tutorial_region.h" #ifdef _OPENMP static int stream_profiled_omp(uint64_t region_id, size_t num_stream, double scalar, double *a, double *b, double *c) { const size_t block = 256; const size_t num_block = num_stream / block; const size_t num_remain = num_stream % block; int err = 0; int num_thread = 1; #pragma omp parallel { num_thread = omp_get_num_threads(); } #pragma omp parallel { int thread_idx = omp_get_thread_num(); (void)geopm_tprof_init_loop(num_thread, thread_idx, num_block, 0); #pragma omp for for (size_t i = 0; i < num_block; ++i) { for (size_t j = 0; j < block; ++j) { a[i * block + j] = b[i * block + j] + scalar * c[i * block + j]; } (void)geopm_tprof_post(); } #pragma omp for for (size_t j = 0; j < num_remain; ++j) { a[num_block * block + j] = b[num_block * block + j] + scalar * c[num_block * block + j]; } } return err; } #endif static int stream_profiled_serial(uint64_t region_id, size_t num_stream, double scalar, double *a, double *b, double *c) { const size_t block = 256; const size_t num_block = num_stream / block; const size_t num_remain = num_stream % block; const double norm = 1.0 / num_block; for (size_t i = 0; i < num_block; ++i) { for (size_t j = 0; j < block; ++j) { a[i * block + j] = b[i * block + j] + scalar * c[i * block + j]; } geopm_prof_progress(region_id, i * norm); } for (size_t j = 0; j < num_remain; ++j) { a[num_block * block + j] = b[num_block * block + j] + scalar * c[num_block * block + j]; } return 0; } int tutorial_stream_profiled(double big_o, int do_report) { int err = 0; if (big_o != 0.0) { size_t cline_size = 64; size_t num_stream = (size_t)big_o * 500000000; size_t mem_size = sizeof(double) * num_stream; double *a = NULL; double *b = NULL; double *c = NULL; double scalar = 3.0; uint64_t stream_rid; if (!err) { err = geopm_prof_region("tutorial_stream", GEOPM_REGION_HINT_MEMORY, &stream_rid); } err = posix_memalign((void *)&a, cline_size, mem_size); if (!err) { err = posix_memalign((void *)&b, cline_size, mem_size); } if (!err) { err = posix_memalign((void *)&c, cline_size, mem_size); } if (!err) { #pragma omp parallel for for (int i = 0; i < num_stream; i++) { a[i] = 0.0; b[i] = 1.0; c[i] = 2.0; } if (do_report) { printf("Executing profiled STREAM triad on length %d vectors.\n", num_stream); fflush(stdout); } err = geopm_prof_enter(stream_rid); } if (!err) { #ifdef _OPENMP err = stream_profiled_omp(stream_rid, num_stream, scalar, a, b, c); #else err = stream_profiled_serial(stream_rid, num_stream, scalar, a, b, c); #endif } if (!err) { err = geopm_prof_exit(stream_rid); } if (!err) { free(c); free(b); free(a); } } }
time_omp_fib.c
#include <stdio.h> /* for printf() */ #include <assert.h> /* for assert() */ #include <omp.h> #include <qthread/qthread.h> #include <qthread/qtimer.h> #include "argparsing.h" static aligned_t validation[] = { 0, // 0 1, // 1 1, // 2 2, // 3 3, // 4 5, // 5 8, // 6 13, // 7 21, // 8 34, // 9 55, // 10 89, // 11 144, // 12 233, // 13 377, // 14 610, // 15 987, // 16 1597, // 17 2584, // 18 4181, // 19 6765, // 20 10946, // 21 17711, // 22 28657, // 23 46368, // 24 75025, // 25 121393, // 26 196418, // 27 317811, // 28 514229, // 29 832040, // 30 1346269, // 31 2178309, // 32 3524578, // 33 5702887, // 34 9227465, // 35 14930352, // 36 24157817, // 37 39088169 // 38 }; static aligned_t fib(void *arg_) { aligned_t *n = (aligned_t *)arg_; if (*n < 2) { return *n; } aligned_t ret1, ret2; aligned_t n1 = *n - 1; aligned_t n2 = *n - 2; #pragma omp task default(none) shared(ret1,n1) ret1 = fib(&n1); #pragma omp task default(none) shared(ret2,n2) ret2 = fib(&n2); #pragma omp taskwait return ret1 + ret2; } int main(int argc, char *argv[]) { qtimer_t timer = qtimer_create(); aligned_t n = 20; aligned_t ret = 0; int threads = 1; /* setup */ CHECK_VERBOSE(); NUMARG(n, "FIB_INPUT"); #pragma omp parallel #pragma omp single { threads = omp_get_num_threads(); qtimer_start(timer); #pragma omp task default(none) shared(ret,n) ret = fib(&n); #pragma omp taskwait qtimer_stop(timer); } if (validation[n] == ret) { fprintf(stdout, "%d %lu %lu %f\n", threads, (unsigned long)n, (unsigned long)ret, qtimer_secs(timer)); } else { iprintf("Fail %lu (== %lu) in %f sec\n", (unsigned long)ret, (unsigned long)validation[n], qtimer_secs(timer)); } qtimer_destroy(timer); return 0; } /* vim:set expandtab */
nco_var_rth.c
/* $Header$ */ /* Purpose: Variable arithmetic */ /* Copyright (C) 1995--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License with exceptions described in the LICENSE file */ #include "nco_var_rth.h" /* Variable arithmetic */ void nco_var_abs /* [fnc] Replace op1 values by their absolute values */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ ptr_unn op1) /* I/O [val] Values of first operand */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Replace op1 values by their absolute values */ /* Absolute value is currently defined as op1:=abs(op1) */ /* NB: Many compilers need to #include "nco_rth_flt.h" for fabsf() prototype */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.fp[idx]=fabsf(op1.fp[idx]); }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.fp[idx] != mss_val_flt) op1.fp[idx]=fabsf(op1.fp[idx]); } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.dp[idx]=fabs(op1.dp[idx]); }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.dp[idx] != mss_val_dbl) op1.dp[idx]=fabs(op1.dp[idx]); } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ip[idx]=labs(op1.ip[idx]); /* int abs(int), long labs(long) */ }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ip[idx] != mss_val_ntg) op1.ip[idx]=labs(op1.ip[idx]); /* int abs(int), long labs(long) */ } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op1.sp[idx] < 0) op1.sp[idx]=-op1.sp[idx] ; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.sp[idx] != mss_val_short && op1.sp[idx] < 0) op1.sp[idx]=-op1.sp[idx]; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op1.bp[idx] < 0) op1.bp[idx]=-op1.bp[idx] ; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.bp[idx] != mss_val_byte && op1.bp[idx] < 0) op1.bp[idx]=-op1.bp[idx]; } /* end for */ } /* end else */ case NC_UBYTE: break; /* Do nothing */ case NC_USHORT: break; /* Do nothing */ case NC_UINT: break; /* Do nothing */ case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.i64p[idx]=llabs(op1.i64p[idx]); }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.i64p[idx] != mss_val_int64) op1.i64p[idx]=llabs(op1.i64p[idx]); } /* end for */ } /* end else */ break; case NC_UINT64: break; /* Do nothing */ case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_abs() */ void nco_var_add /* [fnc] Add first operand to second operand */ (const nc_type type, /* I [enm] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of sum on output */ { /* Purpose: Add value of first operand to value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory nco_var_add() does _not_ increment tally counter nco_var_add_tll_ncra() does increment tally counter */ /* Addition is currently defined as op2:=op1+op2 where op1 != mss_val and op2 != mss_val */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]+=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)) op2.fp[idx]+=op1.fp[idx]; else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]+=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)) op2.dp[idx]+=op1.dp[idx]; else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ip[idx]+=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)) op2.ip[idx]+=op1.ip[idx]; else op2.ip[idx]=mss_val_ntg; } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.sp[idx]+=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)) op2.sp[idx]+=op1.sp[idx]; else op2.sp[idx]=mss_val_short; } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.usp[idx]+=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)) op2.usp[idx]+=op1.usp[idx]; else op2.usp[idx]=mss_val_ushort; } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.uip[idx]+=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)) op2.uip[idx]+=op1.uip[idx]; else op2.uip[idx]=mss_val_uint; } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.i64p[idx]+=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)) op2.i64p[idx]+=op1.i64p[idx]; else op2.i64p[idx]=mss_val_int64; } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ui64p[idx]+=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)) op2.ui64p[idx]+=op1.ui64p[idx]; else op2.ui64p[idx]=mss_val_uint64; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.bp[idx]+=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)) op2.bp[idx]+=op1.bp[idx]; else op2.bp[idx]=mss_val_byte; } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ubp[idx]+=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)) op2.ubp[idx]+=op1.ubp[idx]; else op2.ubp[idx]=mss_val_ubyte; } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_add() */ void nco_var_add_tll_ncflint /* [fnc] Add first operand to second operand, increment tally */ (const nc_type type, /* I [enm] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ long * restrict const tally, /* I/O [nbr] Counter space */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of sum on output */ { /* Purpose: Add value of first operand to value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory nco_var_add() does _not_ increment tally counter nco_var_add_tll_ncflint() does increment tally counter */ /* Addition is currently defined as op2:=op1+op2 where op1 != mss_val and op2 != mss_val */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); /* Return missing_value where either or both input values are missing Algorithm used since 20040603 NB: Tally is incremented but not used */ switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.fp[idx]+=op1.fp[idx]; tally[idx]++; } /* end for */ }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)){ op2.fp[idx]+=op1.fp[idx]; tally[idx]++; }else{ op2.fp[idx]=mss_val_flt; }/* end else */ } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.dp[idx]+=op1.dp[idx]; tally[idx]++; } /* end for */ }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)){ op2.dp[idx]+=op1.dp[idx]; tally[idx]++; }else{ op2.dp[idx]=mss_val_dbl; } /* end else */ } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ip[idx]+=op1.ip[idx]; tally[idx]++; } /* end for */ }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)){ op2.ip[idx]+=op1.ip[idx]; tally[idx]++; }else{ op2.ip[idx]=mss_val_ntg; } /* end else */ } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.sp[idx]+=op1.sp[idx]; tally[idx]++; } /* end for */ }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)){ op2.sp[idx]+=op1.sp[idx]; tally[idx]++; }else{ op2.sp[idx]=mss_val_short; } /* end else */ } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.usp[idx]+=op1.usp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)){ op2.usp[idx]+=op1.usp[idx]; tally[idx]++; }else{ op2.usp[idx]=mss_val_ushort; } /* end else */ } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.uip[idx]+=op1.uip[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)){ op2.uip[idx]+=op1.uip[idx]; tally[idx]++; }else{ op2.uip[idx]=mss_val_uint; } /* end else */ } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.i64p[idx]+=op1.i64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)){ op2.i64p[idx]+=op1.i64p[idx]; tally[idx]++; }else{ op2.i64p[idx]=mss_val_int64; } /* end else */ } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ui64p[idx]+=op1.ui64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)){ op2.ui64p[idx]+=op1.ui64p[idx]; tally[idx]++; }else{ op2.ui64p[idx]=mss_val_uint64; } /* end else */ } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.bp[idx]+=op1.bp[idx]; tally[idx]++; } /* end for */ }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)){ op2.bp[idx]+=op1.bp[idx]; tally[idx]++; }else{ op2.bp[idx]=mss_val_byte; } /* end else */ } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ubp[idx]+=op1.ubp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)){ op2.ubp[idx]+=op1.ubp[idx]; tally[idx]++; }else{ op2.ubp[idx]=mss_val_ubyte; } /* end else */ } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* Used this block of code until 20040603. It keeps track of tally but does not do anything with it later */ #if 0 switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.fp[idx]+=op1.fp[idx]; tally[idx]++; } /* end for */ }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)){ op2.fp[idx]+=op1.fp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.dp[idx]+=op1.dp[idx]; tally[idx]++; } /* end for */ }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)){ op2.dp[idx]+=op1.dp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ip[idx]+=op1.ip[idx]; tally[idx]++; } /* end for */ }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)){ op2.ip[idx]+=op1.ip[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.sp[idx]+=op1.sp[idx]; tally[idx]++; } /* end for */ }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)){ op2.sp[idx]+=op1.sp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.usp[idx]+=op1.usp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)){ op2.usp[idx]+=op1.usp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.uip[idx]+=op1.uip[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)){ op2.uip[idx]+=op1.uip[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.i64p[idx]+=op1.i64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)){ op2.i64p[idx]+=op1.i64p[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ui64p[idx]+=op1.ui64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)){ op2.ui64p[idx]+=op1.ui64p[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.bp[idx]+=op1.bp[idx]; tally[idx]++; } /* end for */ }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)){ op2.bp[idx]+=op1.bp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ubp[idx]+=op1.ubp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)){ op2.ubp[idx]+=op1.ubp[idx]; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ #endif /* endif 0 */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_add_tll_ncflint() */ void nco_var_add_tll_ncra /* [fnc] Add first operand to second operand, increment tally */ (const nc_type type, /* I [enm] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ long * restrict const tally, /* I/O [nbr] Counter space */ const double wgt_crr, /* I [frc] Weight of current record (ncra/ncea only) */ double * restrict const wgt_sum, /* I/O [frc] Running sum of per-file weights (ncra/ncea only) */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand (running sum) on input, values of new sum on output */ { /* Purpose: Add value of first operand to value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory nco_var_add() does _not_ increment tally counter. nco_var_add_tll_ncflint() adds if neither operand equals missing value nco_var_add_tll_ncflint() does increment tally counter (unlike nco_var_add()) nco_var_add_tll_ncra() adds if op1 does not equal missing value nco_var_add_tll_ncra() does increment tally counter (like nco_var_add_tll_ncflint()) nco_var_add_tll_ncra() is designed to: 1. Work for "running average" algorithms only 2. Assume running sum is valid and is stored in op2 3. Assume new record is stored in op1 4. Check only if new record (not running sum) equals missing_value Note that missing_value is associated with op1, i.e., new record, not running sum 5. Accumulate running sum only if new record is valid 6. Increment tally Difference between nco_var_add_tll_ncra() and nco_var_add_tll_ncflint() is that nco_var_add_tll_ncflint() checks both operands against the missing_value, whereas nco_var_add_tll_ncra() only checks first operand (new record) against missing_value nco_var_add_tll_ncflint() algorithm fails as running average algorithm when missing value is zero because running sum is bootstrapped to zero and this causes comparison to missing_value to always be true. nco_var_add_tll_ncflint() also fails as running average algorithm whenever running sum happens to equal missing_value (regardless if missing value is zero). NCO uses nco_var_add_tll_ncflint() only for ncflint NCO uses nco_var_add_tll_ncra() only for ncra/nces */ /* Addition is currently defined as op2:=op1+op2 where op1 != mss_val */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.fp[idx]+=op1.fp[idx]; tally[idx]++; } /* end for */ }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.fp[idx] != mss_val_flt){ op2.fp[idx]+=op1.fp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.dp[idx]+=op1.dp[idx]; tally[idx]++; } /* end for */ }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.dp[idx] != mss_val_dbl){ op2.dp[idx]+=op1.dp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ip[idx]+=op1.ip[idx]; tally[idx]++; } /* end for */ }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ip[idx] != mss_val_ntg){ op2.ip[idx]+=op1.ip[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.sp[idx]+=op1.sp[idx]; tally[idx]++; } /* end for */ }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.sp[idx] != mss_val_short){ op2.sp[idx]+=op1.sp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.usp[idx]+=op1.usp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.usp[idx] != mss_val_ushort){ op2.usp[idx]+=op1.usp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.uip[idx]+=op1.uip[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.uip[idx] != mss_val_uint){ op2.uip[idx]+=op1.uip[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.i64p[idx]+=op1.i64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.i64p[idx] != mss_val_int64){ op2.i64p[idx]+=op1.i64p[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ui64p[idx]+=op1.ui64p[idx]; tally[idx]++; } /* end for */ }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ui64p[idx] != mss_val_uint64){ op2.ui64p[idx]+=op1.ui64p[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.bp[idx]+=op1.bp[idx]; tally[idx]++; } /* end for */ }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.bp[idx] != mss_val_byte){ op2.bp[idx]+=op1.bp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ubp[idx]+=op1.ubp[idx]; tally[idx]++; } /* end for */ }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ubp[idx] != mss_val_ubyte){ op2.ubp[idx]+=op1.ubp[idx]; if(wgt_sum) wgt_sum[idx]+=wgt_crr; tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_add_tll_ncra() */ void nco_var_copy_tll /* [fnc] Copy hyperslab variables of type var_typ from op1 to op2, accounting for missing values in tally */ (const nc_type type, /* I [enm] netCDF type */ const long sz, /* I [nbr] Number of elements to copy */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ long * restrict const tally, /* O [nbr] Counter space */ const ptr_unn op1, /* I [sct] Values to copy */ ptr_unn op2) /* O [sct] Destination to copy values to */ { /* Purpose: Copy hyperslab variables of type var_typ from op1 to op2 Assumes memory area in op2 has already been malloc()'d Where the value copied is not equal to the missing value, set the tally to one nco_var_copy(): Does nothing with missing values and tallies nco_var_copy_tll(): Accounts for missing values in tally */ /* Algorithm is currently defined as: op2:=op1 */ long idx; /* Use fast nco_var_copy() method to copy variable */ (void)memcpy((void *)(op2.vp),(void *)(op1.vp),sz*nco_typ_lng(type)); if(has_mss_val){ /* Tally remains zero until verified (below) that datum is not missing value */ (void)nco_set_long(sz,0L,tally); }else{ /* !has_mss_val */ /* Tally is one if no missing value is defined */ (void)nco_set_long(sz,1L,tally); return; } /* !has_mss_val */ /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); /* Overwrite one's with zero's where value equals missing value */ switch(type){ case NC_FLOAT: { const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] == mss_val_flt) op2.fp[idx]=0.0f; else tally[idx]=1L; } break; case NC_DOUBLE: { const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] == mss_val_dbl) op2.dp[idx]=0.0; else tally[idx]=1L; } break; case NC_INT: { const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] == mss_val_ntg) op2.ip[idx]=0; else tally[idx]=1L; } break; case NC_SHORT: { const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] == mss_val_short) op2.sp[idx]=0; else tally[idx]=1L; } break; case NC_USHORT: { const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] == mss_val_ushort) op2.usp[idx]=0; else tally[idx]=1L; } break; case NC_UINT: { const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] == mss_val_uint) op2.uip[idx]=0; else tally[idx]=1L; } break; case NC_INT64: { const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] == mss_val_int64) op2.i64p[idx]=0; else tally[idx]=1L; } break; case NC_UINT64: { const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] == mss_val_uint64) op2.ui64p[idx]=0; else tally[idx]=1L; } break; case NC_BYTE: { const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] == mss_val_byte) op2.bp[idx]=0; else tally[idx]=1L; } break; case NC_UBYTE: { const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] == mss_val_ubyte) op2.ubp[idx]=0; else tally[idx]=1L; } break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_copy_tll() */ void nco_var_dvd /* [fnc] Divide second operand by first operand */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of denominator */ ptr_unn op2) /* I/O [val] Values of numerator on input, values of quotient on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Divide value of first operand by value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory */ /* Variable-variable division is currently defined as op2:=op2/op1 */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]/=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)) op2.fp[idx]/=op1.fp[idx]; else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; /* end NC_FLOAT */ case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]/=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)) op2.dp[idx]/=op1.dp[idx]; else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; /* end NC_DOUBLE */ case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ip[idx]/=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)) op2.ip[idx]/=op1.ip[idx]; else op2.ip[idx]=mss_val_ntg; } /* end for */ } /* end else */ break; /* end NC_INT */ case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.sp[idx]/=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)) op2.sp[idx]/=op1.sp[idx]; else op2.sp[idx]=mss_val_short; } /* end for */ } /* end else */ break; /* end NC_SHORT */ case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.usp[idx]/=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)) op2.usp[idx]/=op1.usp[idx]; else op2.usp[idx]=mss_val_ushort; } /* end for */ } /* end else */ break; /* end NC_USHORT */ case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.uip[idx]/=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)) op2.uip[idx]/=op1.uip[idx]; else op2.uip[idx]=mss_val_uint; } /* end for */ } /* end else */ break; /* end NC_UINT */ case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.i64p[idx]/=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)) op2.i64p[idx]/=op1.i64p[idx]; else op2.i64p[idx]=mss_val_int64; } /* end for */ } /* end else */ break; /* end NC_INT64 */ case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ui64p[idx]/=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)) op2.ui64p[idx]/=op1.ui64p[idx]; else op2.ui64p[idx]=mss_val_uint64; } /* end for */ } /* end else */ break; /* end NC_UINT64 */ case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.bp[idx]/=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)) op2.bp[idx]/=op1.bp[idx]; else op2.bp[idx]=mss_val_byte; } /* end for */ } /* end else */ break; /* end NC_BYTE */ case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ubp[idx]/=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)) op2.ubp[idx]/=op1.ubp[idx]; else op2.ubp[idx]=mss_val_ubyte; } /* end for */ } /* end else */ break; /* end NC_UBYTE */ case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_dvd() */ void nco_var_max_bnr /* [fnc] Maximize two operands */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of maximum on output */ { /* Purpose: Find maximum value(s) of two operands and store result in second operand Operands are assumed to conform, be of same specified type, and have values in memory */ long idx; /* Typecast pointer to values before access */ /* It is not necessary to untype-cast pointer types after using them as we have operated on local copies of them */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] < op1.fp[idx]) op2.fp[idx]=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.fp[idx] == mss_val_flt) op2.fp[idx]=op1.fp[idx]; else if((op1.fp[idx] != mss_val_flt) && (op2.fp[idx] < op1.fp[idx])) op2.fp[idx]=op1.fp[idx]; } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] < op1.dp[idx]) op2.dp[idx]=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.dp[idx] == mss_val_dbl) op2.dp[idx]=op1.dp[idx]; else if((op1.dp[idx] != mss_val_dbl) && (op2.dp[idx] < op1.dp[idx])) op2.dp[idx]=op1.dp[idx]; } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] < op1.ip[idx]) op2.ip[idx]=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ip[idx] == mss_val_ntg) op2.ip[idx]=op1.ip[idx]; else if((op1.ip[idx] != mss_val_ntg) && (op2.ip[idx] < op1.ip[idx])) op2.ip[idx]=op1.ip[idx]; } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] < op1.sp[idx]) op2.sp[idx]=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.sp[idx] == mss_val_short) op2.sp[idx]=op1.sp[idx]; else if((op1.sp[idx] != mss_val_short) && (op2.sp[idx] < op1.sp[idx])) op2.sp[idx]=op1.sp[idx]; } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] < op1.usp[idx]) op2.usp[idx]=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.usp[idx] == mss_val_ushort) op2.usp[idx]=op1.usp[idx]; else if((op1.usp[idx] != mss_val_ushort) && (op2.usp[idx] < op1.usp[idx])) op2.usp[idx]=op1.usp[idx]; } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] < op1.uip[idx]) op2.uip[idx]=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.uip[idx] == mss_val_uint) op2.uip[idx]=op1.uip[idx]; else if((op1.uip[idx] != mss_val_uint) && (op2.uip[idx] < op1.uip[idx])) op2.uip[idx]=op1.uip[idx]; } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] < op1.i64p[idx]) op2.i64p[idx]=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.i64p[idx] == mss_val_int64) op2.i64p[idx]=op1.i64p[idx]; else if((op1.i64p[idx] != mss_val_int64) && (op2.i64p[idx] < op1.i64p[idx])) op2.i64p[idx]=op1.i64p[idx]; } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] < op1.ui64p[idx]) op2.ui64p[idx]=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ui64p[idx] == mss_val_uint64) op2.ui64p[idx]=op1.ui64p[idx]; else if((op1.ui64p[idx] != mss_val_uint64) && (op2.ui64p[idx] < op1.ui64p[idx])) op2.ui64p[idx]=op1.ui64p[idx]; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] < op1.bp[idx]) op2.bp[idx]=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.bp[idx] == mss_val_byte) op2.bp[idx]=op1.bp[idx]; else if((op1.bp[idx] != mss_val_byte) && (op2.bp[idx] < op1.bp[idx])) op2.bp[idx]=op1.bp[idx]; } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] < op1.ubp[idx]) op2.ubp[idx]=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ubp[idx] == mss_val_ubyte) op2.ubp[idx]=op1.ubp[idx]; else if((op1.ubp[idx] != mss_val_ubyte) && (op2.ubp[idx] < op1.ubp[idx])) op2.ubp[idx]=op1.ubp[idx]; } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ } /* end nco_var_max_bnr() */ void nco_var_min_bnr /* [fnc] Minimize two operands */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of minimum on output */ { /* Purpose: Find minimum value(s) of two operands and store result in second operand Operands are assumed to conform, be of same specified type, and have values in memory */ long idx; /* Typecast pointer to values before access */ /* It is not necessary to uncast pointer types after using them as we have operated on local copies of them */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] > op1.fp[idx]) op2.fp[idx]=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.fp[idx] == mss_val_flt) op2.fp[idx]=op1.fp[idx]; else if((op1.fp[idx] != mss_val_flt) && (op2.fp[idx] > op1.fp[idx])) op2.fp[idx]=op1.fp[idx]; } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] > op1.dp[idx]) op2.dp[idx]=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.dp[idx] == mss_val_dbl) op2.dp[idx]=op1.dp[idx]; else if((op1.dp[idx] != mss_val_dbl) && (op2.dp[idx] > op1.dp[idx])) op2.dp[idx]=op1.dp[idx]; } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] > op1.ip[idx]) op2.ip[idx]=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ip[idx] == mss_val_ntg) op2.ip[idx]=op1.ip[idx]; else if((op1.ip[idx] != mss_val_ntg) && (op2.ip[idx] > op1.ip[idx])) op2.ip[idx]=op1.ip[idx]; } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] > op1.sp[idx]) op2.sp[idx]=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.sp[idx] == mss_val_short) op2.sp[idx]=op1.sp[idx]; else if((op1.sp[idx] != mss_val_short) && (op2.sp[idx] > op1.sp[idx])) op2.sp[idx]=op1.sp[idx]; } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] > op1.usp[idx]) op2.usp[idx]=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.usp[idx] == mss_val_ushort) op2.usp[idx]=op1.usp[idx]; else if((op1.usp[idx] != mss_val_ushort) && (op2.usp[idx] > op1.usp[idx])) op2.usp[idx]=op1.usp[idx]; } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] > op1.uip[idx]) op2.uip[idx]=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.uip[idx] == mss_val_uint) op2.uip[idx]=op1.uip[idx]; else if((op1.uip[idx] != mss_val_uint) && (op2.uip[idx] > op1.uip[idx])) op2.uip[idx]=op1.uip[idx]; } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] > op1.i64p[idx]) op2.i64p[idx]=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.i64p[idx] == mss_val_int64) op2.i64p[idx]=op1.i64p[idx]; else if((op1.i64p[idx] != mss_val_int64) && (op2.i64p[idx] > op1.i64p[idx])) op2.i64p[idx]=op1.i64p[idx]; } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] > op1.ui64p[idx]) op2.ui64p[idx]=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ui64p[idx] == mss_val_uint64) op2.ui64p[idx]=op1.ui64p[idx]; else if((op1.ui64p[idx] != mss_val_uint64) && (op2.ui64p[idx] > op1.ui64p[idx])) op2.ui64p[idx]=op1.ui64p[idx]; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] > op1.bp[idx]) op2.bp[idx]=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.bp[idx] == mss_val_byte) op2.bp[idx]=op1.bp[idx]; else if((op1.bp[idx] != mss_val_byte) && (op2.bp[idx] > op1.bp[idx])) op2.bp[idx]=op1.bp[idx]; } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] > op1.ubp[idx]) op2.ubp[idx]=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op2.ubp[idx] == mss_val_ubyte) op2.ubp[idx]=op1.ubp[idx]; else if((op1.ubp[idx] != mss_val_ubyte) && (op2.ubp[idx] > op1.ubp[idx])) op2.ubp[idx]=op1.ubp[idx]; } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ } /* end nco_var_min_bnr() */ void nco_var_mlt /* [fnc] Multiply first operand by second operand */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of product on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: multiply value of first operand by value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory */ /* Multiplication is currently defined as op2:=op1*op2 */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]*=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)) op2.fp[idx]*=op1.fp[idx]; else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]*=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)) op2.dp[idx]*=op1.dp[idx]; else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ip[idx]*=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)) op2.ip[idx]*=op1.ip[idx]; else op2.ip[idx]=mss_val_ntg; } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.sp[idx]*=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)) op2.sp[idx]*=op1.sp[idx]; else op2.sp[idx]=mss_val_short; } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.usp[idx]*=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)) op2.usp[idx]*=op1.usp[idx]; else op2.usp[idx]=mss_val_ushort; } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.uip[idx]*=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)) op2.uip[idx]*=op1.uip[idx]; else op2.uip[idx]=mss_val_uint; } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.i64p[idx]*=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)) op2.i64p[idx]*=op1.i64p[idx]; else op2.i64p[idx]=mss_val_int64; } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ui64p[idx]*=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)) op2.ui64p[idx]*=op1.ui64p[idx]; else op2.ui64p[idx]=mss_val_uint64; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.bp[idx]*=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)) op2.bp[idx]*=op1.bp[idx]; else op2.bp[idx]=mss_val_byte; } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ubp[idx]*=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)) op2.ubp[idx]*=op1.ubp[idx]; else op2.ubp[idx]=mss_val_ubyte; } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_mlt() */ void nco_var_mod /* [fnc] Remainder (modulo) operation of two variables */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of field */ ptr_unn op2) /* I/O [val] Values of divisor on input, values of remainder on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Divide value of first operand by value of second operand and store remainder in second operand. Assume operands conform, are same type, and are in memory */ /* Remainder (modulo) operation is currently defined as op2:=op1%op2 */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: /* Hand-code modulo operator for floating point arguments (intrinsic % requires integer arguments) */ if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]=op1.fp[idx]-op2.fp[idx]*(int)(op1.fp[idx]/op2.fp[idx]); }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)) op2.fp[idx]=op1.fp[idx]-op2.fp[idx]*(int)(op1.fp[idx]/op2.fp[idx]); else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; /* end NC_FLOAT */ case NC_DOUBLE: /* Hand-code modulo operator for floating point arguments (intrinsic % requires integer arguments) */ if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]=op1.dp[idx]-op2.dp[idx]*(int)(op1.dp[idx]/op2.dp[idx]); }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)) op2.dp[idx]=op1.dp[idx]-op2.dp[idx]*(int)(op1.dp[idx]/op2.dp[idx]); else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; /* end NC_DOUBLE */ case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ip[idx]=op1.ip[idx]%op2.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)) op2.ip[idx]=op1.ip[idx]%op2.ip[idx]; else op2.ip[idx]=mss_val_ntg; } /* end for */ } /* end else */ break; /* end NC_INT */ case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.sp[idx]=op1.sp[idx]%op2.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)) op2.sp[idx]=op1.sp[idx]%op2.sp[idx]; else op2.sp[idx]=mss_val_short; } /* end for */ } /* end else */ break; /* end NC_SHORT */ case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.usp[idx]=op1.usp[idx]%op2.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)) op2.usp[idx]=op1.usp[idx]%op2.usp[idx]; else op2.usp[idx]=mss_val_ushort; } /* end for */ } /* end else */ break; /* end NC_USHORT */ case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.uip[idx]=op1.uip[idx]%op2.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)) op2.uip[idx]=op1.uip[idx]%op2.uip[idx]; else op2.uip[idx]=mss_val_uint; } /* end for */ } /* end else */ break; /* end NC_UINT */ case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.i64p[idx]=op1.i64p[idx]%op2.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)) op2.i64p[idx]=op1.i64p[idx]%op2.i64p[idx]; else op2.i64p[idx]=mss_val_int64; } /* end for */ } /* end else */ break; /* end NC_INT64 */ case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ui64p[idx]=op1.ui64p[idx]%op2.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)) op2.ui64p[idx]=op1.ui64p[idx]%op2.ui64p[idx]; else op2.ui64p[idx]=mss_val_uint64; } /* end for */ } /* end else */ break; /* end NC_UINT64 */ case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.bp[idx]=op1.bp[idx]%op2.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)) op2.bp[idx]=op1.bp[idx]%op2.bp[idx]; else op2.bp[idx]=mss_val_byte; } /* end for */ } /* end else */ break; /* end NC_BYTE */ case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ubp[idx]=op1.ubp[idx]%op2.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)) op2.ubp[idx]=op1.ubp[idx]%op2.ubp[idx]; else op2.ubp[idx]=mss_val_ubyte; } /* end for */ } /* end else */ break; /* end NC_UBYTE */ case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_mod() */ void nco_var_msk /* [fnc] Mask third operand where first and second operands fail comparison */ (const nc_type type, /* I [enm] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operand op3 */ const int has_mss_val, /* I [flg] Flag for missing values (basically assumed to be true) */ ptr_unn mss_val, /* I [val] Value of missing value */ const double op1, /* I [val] Target value to compare against mask field (i.e., argument of -M) */ const int op_typ_rlt, /* I [enm] Comparison type test for op2 and op1 */ ptr_unn op2, /* I [val] Value of mask field */ ptr_unn op3) /* I/O [val] Values of second operand on input, masked values on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Mask third operand where first and second operands fail comparison Set third operand to missing value wherever second operand fails comparison with first operand */ /* Masking is currently defined as: if(op2 !op_typ_rlt op1) then op3:=mss_val */ long idx; double mss_val_dbl=double_CEWI; float mss_val_flt=float_CEWI; nco_int mss_val_ntg=nco_int_CEWI; nco_short mss_val_short=nco_short_CEWI; nco_ushort mss_val_ushort=nco_ushort_CEWI; nco_uint mss_val_uint=nco_uint_CEWI; nco_int64 mss_val_int64=nco_int64_CEWI; nco_uint64 mss_val_uint64=nco_uint64_CEWI; nco_byte mss_val_byte=nco_byte_CEWI; nco_ubyte mss_val_ubyte=nco_ubyte_CEWI; nco_char mss_val_char=nco_char_CEWI; /* nco_string mss_val_string=nco_string_CEWI;*/ /* 20120206: mss_val_string is not yet used so do not define */ /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op2); (void)cast_void_nctype(type,&op3); if(has_mss_val){ (void)cast_void_nctype(type,&mss_val); }else{ (void)fprintf(stdout,"%s: ERROR has_mss_val is inconsistent with purpose of var_ask(), i.e., has_mss_val is not True\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); } /* end else */ if(has_mss_val){ switch(type){ case NC_FLOAT: mss_val_flt=*mss_val.fp; break; case NC_DOUBLE: mss_val_dbl=*mss_val.dp; break; case NC_INT: mss_val_ntg=*mss_val.ip; break; case NC_SHORT: mss_val_short=*mss_val.sp; break; case NC_USHORT: mss_val_ushort=*mss_val.usp; break; case NC_UINT: mss_val_uint=*mss_val.uip; break; case NC_INT64: mss_val_int64=*mss_val.i64p; break; case NC_UINT64: mss_val_uint64=*mss_val.ui64p; break; case NC_BYTE: mss_val_byte=*mss_val.bp; break; case NC_UBYTE: mss_val_ubyte=*mss_val.ubp; break; case NC_CHAR: mss_val_char=*mss_val.cp; break; /* case NC_STRING: mss_val_string=*mss_val.sngp; break;*/ /* 20120206: mss_val_string is not yet used so do not define */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ } /* endif */ /* NB: Explicit coercion when comparing op2 to op1 is necessary */ switch(type){ case NC_FLOAT: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] != (float)op1) op3.fp[idx]=mss_val_flt; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] == (float)op1) op3.fp[idx]=mss_val_flt; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] >= (float)op1) op3.fp[idx]=mss_val_flt; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] <= (float)op1) op3.fp[idx]=mss_val_flt; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] > (float)op1) op3.fp[idx]=mss_val_flt; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.fp[idx] < (float)op1) op3.fp[idx]=mss_val_flt; break; } /* end switch */ break; case NC_DOUBLE: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] != (double)op1) op3.dp[idx]=mss_val_dbl; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] == (double)op1) op3.dp[idx]=mss_val_dbl; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] >= (double)op1) op3.dp[idx]=mss_val_dbl; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] <= (double)op1) op3.dp[idx]=mss_val_dbl; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] > (double)op1) op3.dp[idx]=mss_val_dbl; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.dp[idx] < (double)op1) op3.dp[idx]=mss_val_dbl; break; } /* end switch */ break; case NC_INT: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] != (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] == (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] >= (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] <= (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] > (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ip[idx] < (nco_int)op1) op3.ip[idx]=mss_val_ntg; break; } /* end switch */ break; case NC_SHORT: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] != (nco_short)op1) op3.sp[idx]=mss_val_short; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] == (nco_short)op1) op3.sp[idx]=mss_val_short; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] >= (nco_short)op1) op3.sp[idx]=mss_val_short; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] <= (nco_short)op1) op3.sp[idx]=mss_val_short; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] > (nco_short)op1) op3.sp[idx]=mss_val_short; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.sp[idx] < (nco_short)op1) op3.sp[idx]=mss_val_short; break; } /* end switch */ break; case NC_USHORT: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] != (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] == (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] >= (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] <= (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] > (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.usp[idx] < (nco_ushort)op1) op3.usp[idx]=mss_val_ushort; break; } /* end switch */ break; case NC_UINT: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] != (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] == (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] >= (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] <= (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] > (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.uip[idx] < (nco_uint)op1) op3.uip[idx]=mss_val_uint; break; } /* end switch */ break; case NC_INT64: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] != (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] == (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] >= (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] <= (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] > (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.i64p[idx] < (nco_int64)op1) op3.i64p[idx]=mss_val_int64; break; } /* end switch */ break; case NC_UINT64: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] != (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] == (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] >= (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] <= (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] > (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ui64p[idx] < (nco_uint64)op1) op3.ui64p[idx]=mss_val_uint64; break; } /* end switch */ break; case NC_BYTE: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] != (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] == (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] >= (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] <= (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] > (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.bp[idx] < (nco_byte)op1) op3.bp[idx]=mss_val_byte; break; } /* end switch */ break; case NC_UBYTE: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] != (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] == (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] >= (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] <= (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] > (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.ubp[idx] < (nco_ubyte)op1) op3.ubp[idx]=mss_val_ubyte; break; } /* end switch */ break; case NC_CHAR: switch(op_typ_rlt){ case nco_op_eq: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] != (nco_char)op1) op3.cp[idx]=mss_val_char; break; case nco_op_ne: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] == (nco_char)op1) op3.cp[idx]=mss_val_char; break; case nco_op_lt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] >= (nco_char)op1) op3.cp[idx]=mss_val_char; break; case nco_op_gt: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] <= (nco_char)op1) op3.cp[idx]=mss_val_char; break; case nco_op_le: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] > (nco_char)op1) op3.cp[idx]=mss_val_char; break; case nco_op_ge: #pragma omp simd for(idx=0;idx<sz;idx++) if(op2.cp[idx] < (nco_char)op1) op3.cp[idx]=mss_val_char; break; } /* end switch */ break; case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* It is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_msk() */ void nco_var_tll_zro_mss_val /* [fnc] Write missing value into elements with zero tally */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ const long * const tally, /* I [nbr] Counter to normalize by */ ptr_unn op1) /* I/O [val] Values of first operand on input, possibly missing values on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Write missing value into elements with zero tally Routine is necessary because initialization of accumulating sums (specified, e.g., with -y ttl or with -N) sets initial sum to zero (so augmenting works) regardless if first slice is missing. Such sums are usually normalized and set to missing if tally is zero. However, totals are integrals and thus are never normalized. Initialization value of zero will be output even if tally is zero, _unless field is processed with this routine after summing and prior to writing_ */ /* Filter currently works as op1:=mss_val where tally == 0 */ long idx; /* Routine changes nothing unless a missing value is defined */ if(!has_mss_val) return; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: { const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.fp[idx]=mss_val_flt; } break; case NC_DOUBLE: { const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.dp[idx]=mss_val_dbl; } break; case NC_INT: { const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.ip[idx]=mss_val_ntg; } break; case NC_SHORT: { const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.sp[idx]=mss_val_short; } break; case NC_USHORT: { const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.usp[idx]=mss_val_ushort; } break; case NC_UINT: { const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.uip[idx]=mss_val_uint; } break; case NC_INT64: { const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.i64p[idx]=mss_val_int64; } break; case NC_UINT64: { const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.ui64p[idx]=mss_val_uint64; } break; case NC_BYTE: { const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.bp[idx]=mss_val_byte; } break; case NC_UBYTE: { const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] == 0L) op1.ubp[idx]=mss_val_ubyte; } break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_tll_zro_mss_val() */ void nco_var_nrm /* [fnc] Normalize value of first operand by count in tally array */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ const long * const tally, /* I [nbr] Counter to normalize by */ ptr_unn op1) /* I/O [val] Values of first operand on input, normalized result on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Normalize value of first operand by count in tally array */ /* Normalization is currently defined as op1:=op1/tally */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ /* Operations: 1 fp divide, 2 pointer offset, 2 user memory fetch Repetitions: \dmnszavg^(\dmnnbr-\avgnbr) Total Counts: \flpnbr=\dmnszavg^(\dmnnbr-\avgnbr), \rthnbr=2\dmnszavg^(\dmnnbr-\avgnbr), \mmrusrnbr=2\dmnszavg^(\dmnnbr-\avgnbr) NB: Counted LHS+RHS+tally offsets and fetches */ #pragma omp simd for(idx=0;idx<sz;idx++) op1.fp[idx]/=tally[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.fp[idx]/=tally[idx]; else op1.fp[idx]=mss_val_flt; } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.dp[idx]/=tally[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.dp[idx]/=tally[idx]; else op1.dp[idx]=mss_val_dbl; } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ip[idx]/=tally[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ip[idx]/=tally[idx]; else op1.ip[idx]=mss_val_ntg; } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.sp[idx]/=tally[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.sp[idx]/=tally[idx]; else op1.sp[idx]=mss_val_short; } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.usp[idx]/=tally[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.usp[idx]/=tally[idx]; else op1.usp[idx]=mss_val_ushort; } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.uip[idx]/=tally[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.uip[idx]/=tally[idx]; else op1.uip[idx]=mss_val_uint; } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.i64p[idx]/=tally[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.i64p[idx]/=tally[idx]; else op1.i64p[idx]=mss_val_int64; } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ui64p[idx]/=tally[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ui64p[idx]/=tally[idx]; else op1.ui64p[idx]=mss_val_uint64; } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.bp[idx]/=tally[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.bp[idx]/=tally[idx]; else op1.bp[idx]=mss_val_byte; } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ubp[idx]/=tally[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ubp[idx]/=tally[idx]; else op1.ubp[idx]=mss_val_ubyte; } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_nrm() */ void nco_var_nrm_sdn /* [fnc] Normalize value of first operand by count-1 in tally array */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ const long * const tally, /* I [nbr] Counter to normalize by */ ptr_unn op1) /* I/O [val] Values of first operand on input, normalized result on output */ { /* Purpose: Normalize value of first operand by count-1 in tally array */ /* Normalization is currently defined as op1:=op1/(--tally) */ /* nco_var_nrm_sdn() is based on nco_var_nrm() and algorithms should be kept consistent with eachother */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.fp[idx]/=tally[idx]-1L; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.fp[idx]/=tally[idx]-1L; else op1.fp[idx]=mss_val_flt; } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.dp[idx]/=tally[idx]-1L; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.dp[idx]/=tally[idx]-1L; else op1.dp[idx]=mss_val_dbl; } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ip[idx]/=tally[idx]-1L; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.ip[idx]/=tally[idx]-1L; else op1.ip[idx]=mss_val_ntg; } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.sp[idx]/=tally[idx]-1L; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.sp[idx]/=tally[idx]-1L; else op1.sp[idx]=mss_val_short; } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.usp[idx]/=tally[idx]-1L; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.usp[idx]/=tally[idx]-1L; else op1.usp[idx]=mss_val_ushort; } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.uip[idx]/=tally[idx]-1L; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.uip[idx]/=tally[idx]-1L; else op1.uip[idx]=mss_val_uint; } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.i64p[idx]/=tally[idx]-1L; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.i64p[idx]/=tally[idx]-1L; else op1.i64p[idx]=mss_val_int64; } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ui64p[idx]/=tally[idx]-1L; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.ui64p[idx]/=tally[idx]-1L; else op1.ui64p[idx]=mss_val_uint64; } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.bp[idx]/=tally[idx]-1L; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.bp[idx]/=tally[idx]-1L; else op1.bp[idx]=mss_val_byte; } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op1.ubp[idx]/=tally[idx]-1L; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] > 1L) op1.ubp[idx]/=tally[idx]-1L; else op1.ubp[idx]=mss_val_ubyte; } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end of nco_var_nrm_sdn */ void nco_var_nrm_wgt /* [fnc] Normalize value of first operand by weight array */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ const long * const tally, /* I [nbr] Counter to normalize by */ const double * const wgt, /* I [nbr] Weight to normalize by */ ptr_unn op1) /* I/O [val] Values of first operand on input, normalized result on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Normalize value of first operand by value in weight array Routine is only called by ncra/ncea for variables that have missing values and weights */ /* Normalization is currently defined as op1:=op1/wgt */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: { const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.fp[idx]*=tally[idx]/wgt[idx]; else op1.fp[idx]=mss_val_flt; } break; case NC_DOUBLE: { const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.dp[idx]*=tally[idx]/wgt[idx]; else op1.dp[idx]=mss_val_dbl; } break; case NC_INT: { const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ip[idx]*=tally[idx]/wgt[idx]; else op1.ip[idx]=mss_val_ntg; } break; case NC_SHORT: { const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.sp[idx]*=tally[idx]/wgt[idx]; else op1.sp[idx]=mss_val_short; } break; case NC_USHORT: { const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.usp[idx]*=tally[idx]/wgt[idx]; else op1.usp[idx]=mss_val_ushort; } break; case NC_UINT: { const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.uip[idx]*=tally[idx]/wgt[idx]; else op1.uip[idx]=mss_val_uint; } break; case NC_INT64: { const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.i64p[idx]*=tally[idx]/wgt[idx]; else op1.i64p[idx]=mss_val_int64; } break; case NC_UINT64: { const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ui64p[idx]*=tally[idx]/wgt[idx]; else op1.ui64p[idx]=mss_val_uint64; } break; case NC_BYTE: { const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.bp[idx]*=tally[idx]/wgt[idx]; else op1.bp[idx]=mss_val_byte; } break; case NC_UBYTE: { const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++) if(tally[idx] != 0L) op1.ubp[idx]*=tally[idx]/wgt[idx]; else op1.ubp[idx]=mss_val_ubyte; } break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_nrm_wgt() */ void nco_var_pwr /* [fnc] Raise first operand to power of second operand */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of base */ ptr_unn op2) /* I/O [val] Values of exponent on input, values of power on output */ { /* Threads: Routine is thread safe and calls no unsafe routines */ /* Purpose: Raise value of first operand to power of second operand and store result in second operand. Assume operands conform, are same type, and are in memory */ /* Em-powering is currently defined as op2:=op1^op2 */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]=powf(op1.fp[idx],op2.fp[idx]); }else{ float mss_val_flt=*mss_val.fp; /* Temporary variable reduces de-referencing */ #pragma omp simd for(idx=0;idx<sz;idx++){ if((op1.fp[idx] != mss_val_flt) && (op2.fp[idx] != mss_val_flt)) op2.fp[idx]=powf(op1.fp[idx],op2.fp[idx]); else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; /* end NC_FLOAT */ case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]=pow(op1.dp[idx],op2.dp[idx]); }else{ double mss_val_dbl=*mss_val.dp; /* Temporary variable reduces de-referencing */ #pragma omp simd for(idx=0;idx<sz;idx++){ if((op1.dp[idx] != mss_val_dbl) && (op2.dp[idx] != mss_val_dbl)) op2.dp[idx]=pow(op1.dp[idx],op2.dp[idx]); else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; /* end NC_DOUBLE */ case NC_INT: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_SHORT: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_USHORT: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_UINT: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_INT64: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_UINT64: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_BYTE: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_UBYTE: (void)fprintf(stdout,"%s: ERROR Attempt to em-power integer type in nco_var_pwr(). See TODO #311.\n",nco_prg_nm_get()); break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_pwr */ void nco_var_sbt /* [fnc] Subtract first operand from second operand */ (const nc_type type, /* I [type] netCDF type of operands */ const long sz, /* I [nbr] Size (in elements) of operands */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [flg] Value of missing value */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* I/O [val] Values of second operand on input, values of difference on output */ { /* Purpose: Subtract value of first operand from value of second operand and store result in second operand. Assume operands conform, are same type, and are in memory */ /* Subtraction is currently defined as op2:=op2-op1 */ //static double total_time = 0; //clock_t tm_srt; //clock_t tm_end; //float tm_drn; //tm_srt = clock(); long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.fp[idx]-=op1.fp[idx]; }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.fp[idx] != mss_val_flt) && (op1.fp[idx] != mss_val_flt)) op2.fp[idx]-=op1.fp[idx]; else op2.fp[idx]=mss_val_flt; } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.dp[idx]-=op1.dp[idx]; }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.dp[idx] != mss_val_dbl) && (op1.dp[idx] != mss_val_dbl)) op2.dp[idx]-=op1.dp[idx]; else op2.dp[idx]=mss_val_dbl; } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ip[idx]-=op1.ip[idx]; }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ip[idx] != mss_val_ntg) && (op1.ip[idx] != mss_val_ntg)) op2.ip[idx]-=op1.ip[idx]; else op2.ip[idx]=mss_val_ntg; } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.sp[idx]-=op1.sp[idx]; }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.sp[idx] != mss_val_short) && (op1.sp[idx] != mss_val_short)) op2.sp[idx]-=op1.sp[idx]; else op2.sp[idx]=mss_val_short; } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.usp[idx]-=op1.usp[idx]; }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.usp[idx] != mss_val_ushort) && (op1.usp[idx] != mss_val_ushort)) op2.usp[idx]-=op1.usp[idx]; else op2.usp[idx]=mss_val_ushort; } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.uip[idx]-=op1.uip[idx]; }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.uip[idx] != mss_val_uint) && (op1.uip[idx] != mss_val_uint)) op2.uip[idx]-=op1.uip[idx]; else op2.uip[idx]=mss_val_uint; } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.i64p[idx]-=op1.i64p[idx]; }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.i64p[idx] != mss_val_int64) && (op1.i64p[idx] != mss_val_int64)) op2.i64p[idx]-=op1.i64p[idx]; else op2.i64p[idx]=mss_val_int64; } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ui64p[idx]-=op1.ui64p[idx]; }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ui64p[idx] != mss_val_uint64) && (op1.ui64p[idx] != mss_val_uint64)) op2.ui64p[idx]-=op1.ui64p[idx]; else op2.ui64p[idx]=mss_val_uint64; } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.bp[idx]-=op1.bp[idx]; }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.bp[idx] != mss_val_byte) && (op1.bp[idx] != mss_val_byte)) op2.bp[idx]-=op1.bp[idx]; else op2.bp[idx]=mss_val_byte; } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++) op2.ubp[idx]-=op1.ubp[idx]; }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if((op2.ubp[idx] != mss_val_ubyte) && (op1.ubp[idx] != mss_val_ubyte)) op2.ubp[idx]-=op1.ubp[idx]; else op2.ubp[idx]=mss_val_ubyte; } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ //tm_end = clock(); //tm_drn = (float)(tm_end - tm_srt)/CLOCKS_PER_SEC; //total_time += tm_drn; //fprintf(stdout, "Total subtraction took %gs seconds to run\n", total_time); } /* end nco_var_sbt() */ void nco_var_sqrt /* [fnc] Place squareroot of first operand in value of second operand */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ const int has_mss_val, /* I [flg] Flag for missing values */ ptr_unn mss_val, /* I [val] Value of missing value */ long * restrict const tally, /* I/O [nbr] Counter space */ ptr_unn op1, /* I [val] Values of first operand */ ptr_unn op2) /* O [val] Squareroot of first operand */ { /* Purpose: Place squareroot of first operand in value of second operand Assume operands conform, are same type, and are in memory */ /* Square root is currently defined as op2:=sqrt(op1) */ /* NB: Many compilers need to #include "nco_rth_flt.h" for sqrtf() prototype */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); (void)cast_void_nctype(type,&op2); if(has_mss_val) (void)cast_void_nctype(type,&mss_val); switch(type){ case NC_FLOAT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.fp[idx]=sqrtf(op1.fp[idx]); tally[idx]++; } /* end for */ }else{ const float mss_val_flt=*mss_val.fp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.fp[idx] != mss_val_flt){ op2.fp[idx]=sqrtf(op1.fp[idx]); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_DOUBLE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.dp[idx]=sqrt(op1.dp[idx]); tally[idx]++; } /* end for */ }else{ const double mss_val_dbl=*mss_val.dp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.dp[idx] != mss_val_dbl){ op2.dp[idx]=sqrt(op1.dp[idx]); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ip[idx]=(nco_int)sqrt((double)(op1.ip[idx])); tally[idx]++; } /* end for */ }else{ const nco_int mss_val_ntg=*mss_val.ip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ip[idx] != mss_val_ntg){ op2.ip[idx]=(nco_int)sqrt((double)(op1.ip[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_SHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.sp[idx]=(nco_short)sqrt((double)(op1.sp[idx])); tally[idx]++; } /* end for */ }else{ const nco_short mss_val_short=*mss_val.sp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.sp[idx] != mss_val_short){ op2.sp[idx]=(nco_short)sqrt((double)(op1.sp[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_USHORT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.usp[idx]=(nco_ushort)sqrt((double)(op1.usp[idx])); tally[idx]++; } /* end for */ }else{ const nco_ushort mss_val_ushort=*mss_val.usp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.usp[idx] != mss_val_ushort){ op2.usp[idx]=(nco_ushort)sqrt((double)(op1.usp[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.uip[idx]=(nco_uint)sqrt((double)(op1.uip[idx])); tally[idx]++; } /* end for */ }else{ const nco_uint mss_val_uint=*mss_val.uip; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.uip[idx] != mss_val_uint){ op2.uip[idx]=(nco_uint)sqrt((double)(op1.uip[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_INT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.i64p[idx]=(nco_int64)sqrt((double)(op1.i64p[idx])); tally[idx]++; } /* end for */ }else{ const nco_int64 mss_val_int64=*mss_val.i64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.i64p[idx] != mss_val_int64){ op2.i64p[idx]=(nco_int64)sqrt((double)(op1.i64p[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UINT64: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ui64p[idx]=(nco_uint64)sqrt((double)(op1.ui64p[idx])); tally[idx]++; } /* end for */ }else{ const nco_uint64 mss_val_uint64=*mss_val.ui64p; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ui64p[idx] != mss_val_uint64){ op2.ui64p[idx]=(nco_uint64)sqrt((double)(op1.ui64p[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_BYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.bp[idx]=(nco_byte)sqrt((double)(op1.bp[idx])); tally[idx]++; } /* end for */ }else{ const nco_byte mss_val_byte=*mss_val.bp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.bp[idx] != mss_val_byte){ op2.bp[idx]=(nco_byte)sqrt((double)(op1.bp[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_UBYTE: if(!has_mss_val){ #pragma omp simd for(idx=0;idx<sz;idx++){ op2.ubp[idx]=(nco_ubyte)sqrt((double)(op1.ubp[idx])); tally[idx]++; } /* end for */ }else{ const nco_ubyte mss_val_ubyte=*mss_val.ubp; #pragma omp simd for(idx=0;idx<sz;idx++){ if(op1.ubp[idx] != mss_val_ubyte){ op2.ubp[idx]=(nco_ubyte)sqrt((double)(op1.ubp[idx])); tally[idx]++; } /* end if */ } /* end for */ } /* end else */ break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_sqrt() */ void nco_var_zero /* [fnc] Zero value of first operand */ (const nc_type type, /* I [enm] netCDF type of operand */ const long sz, /* I [nbr] Size (in elements) of operand */ ptr_unn op1) /* O [val] Values of first operand zeroed on output */ { /* Purpose: Zero value of first operand */ /* NB: Floats and integers all use same bit pattern for zero Confirm this with ccc --tst=bnr --int_foo=0 ccc --dbg=0 --tst=gsl --gsl_a=0.0 Hence, it is faster to use memset() rather than explicit loop to zero memory calloc() would also work if interactions with NC_CHAR and NC_STRING were predictable Same approach is used in nco_zero_long() */ size_t sz_byt; /* [B] Number of bytes in variable buffer */ sz_byt=(size_t)sz*nco_typ_lng(type); switch(type){ case NC_FLOAT: case NC_DOUBLE: case NC_INT: case NC_SHORT: case NC_USHORT: case NC_UINT: case NC_INT64: case NC_UINT64: case NC_BYTE: case NC_UBYTE: (void)memset(op1.vp,0,sz_byt); break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ #if 0 /* Presumably this old method (used until 20050321) is slower because of pointer de-referencing */ long idx; /* Typecast pointer to values before access */ (void)cast_void_nctype(type,&op1); switch(type){ case NC_FLOAT: #pragma omp simd for(idx=0;idx<sz;idx++) op1.fp[idx]=0.0; break; case NC_DOUBLE: #pragma omp simd for(idx=0;idx<sz;idx++) op1.dp[idx]=0.0; break; case NC_INT: #pragma omp simd for(idx=0;idx<sz;idx++) op1.ip[idx]=0L; break; case NC_SHORT: #pragma omp simd for(idx=0;idx<sz;idx++) op1.sp[idx]=0; break; case NC_USHORT: #pragma omp simd for(idx=0;idx<sz;idx++) op1.usp[idx]=0; break; case NC_UINT: #pragma omp simd for(idx=0;idx<sz;idx++) op1.uip[idx]=0; break; case NC_INT64: #pragma omp simd for(idx=0;idx<sz;idx++) op1.i64p[idx]=0; break; case NC_UINT64: #pragma omp simd for(idx=0;idx<sz;idx++) op1.ui64p[idx]=0; break; case NC_BYTE: #pragma omp simd for(idx=0;idx<sz;idx++) op1.bp[idx]=0; break; case NC_UBYTE: #pragma omp simd for(idx=0;idx<sz;idx++) op1.ubp[idx]=0; break; case NC_CHAR: break; /* Do nothing */ case NC_STRING: break; /* Do nothing */ default: nco_dfl_case_nc_type_err(); break; } /* end switch */ #endif /* !0 */ /* NB: it is not neccessary to un-typecast pointers to values after access because we have only operated on local copies of them. */ } /* end nco_var_zero() */
GB_unop__cos_fc64_fc64.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__cos_fc64_fc64) // op(A') function: GB (_unop_tran__cos_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = ccos (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ccos (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = ccos (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_COS || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__cos_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_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 (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = ccos (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_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = ccos (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__cos_fc64_fc64) ( 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
geopm_sched.c
/* * Copyright (c) 2015, 2016, 2017, 2018, 2019, 2020, Intel Corporation * * 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 Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #include <stdlib.h> #include <string.h> #include <stdio.h> #include <stdint.h> #include <unistd.h> #include <pthread.h> #include <errno.h> #include <string.h> #include <signal.h> #include "geopm_sched.h" #include "geopm_error.h" #include "config.h" #ifdef _OPENMP #include <omp.h> #endif static volatile unsigned g_is_popen_complete = 0; static struct sigaction g_popen_complete_signal_action; static void geopm_sched_popen_complete(int signum) { if (signum == SIGCHLD) { g_is_popen_complete = 1; } } int geopm_sched_popen(const char *cmd, FILE **fid) { int err = 0; *fid = NULL; struct sigaction save_action; g_popen_complete_signal_action.sa_handler = geopm_sched_popen_complete; sigemptyset(&g_popen_complete_signal_action.sa_mask); g_popen_complete_signal_action.sa_flags = 0; err = sigaction(SIGCHLD, &g_popen_complete_signal_action, &save_action); if (!err) { *fid = popen(cmd, "r"); while (*fid && !g_is_popen_complete) { } g_is_popen_complete = 0; sigaction(SIGCHLD, &save_action, NULL); } if (!err && *fid == NULL) { err = errno ? errno : GEOPM_ERROR_RUNTIME; } return err; } int geopm_sched_num_cpu(void) { return sysconf(_SC_NPROCESSORS_CONF); } int geopm_sched_get_cpu(void) { return sched_getcpu(); } static pthread_once_t g_proc_cpuset_once = PTHREAD_ONCE_INIT; static cpu_set_t *g_proc_cpuset = NULL; static size_t g_proc_cpuset_size = 0; /* If /proc/self/status is usable and correct then parse this file to determine the process affinity. */ #ifdef GEOPM_PROCFS int geopm_sched_proc_cpuset_helper(int num_cpu, uint32_t *proc_cpuset, FILE *fid) { const char *key = "Cpus_allowed:"; const size_t key_len = strlen(key); const int num_read = num_cpu / 32 + (num_cpu % 32 ? 1 : 0); int err = 0; char *line = NULL; size_t line_len = 0; int read_idx = 0; while ((getline(&line, &line_len, fid)) != -1) { if (strncmp(line, key, key_len) == 0) { char *line_ptr = line + key_len; /* On some systems we have seen the mask padded with zeros beyond the number of online CPUs. Deal with this by skipping extra leading 32 bit masks */ int num_comma = 0; char *comma_ptr = line_ptr; while ((comma_ptr = strchr(comma_ptr, ','))) { ++comma_ptr; ++num_comma; } if (num_comma > num_read - 1) { num_comma -= num_read - 1; for (int i = 0; !err && i < num_comma; ++i) { line_ptr = strchr(line_ptr, ','); if (!line_ptr) { err = GEOPM_ERROR_LOGIC; } else { ++line_ptr; } } } for (read_idx = num_read - 1; !err && read_idx >= 0; --read_idx) { int num_match = sscanf(line_ptr, "%x", proc_cpuset + read_idx); if (num_match != 1) { err = GEOPM_ERROR_RUNTIME; } else { line_ptr = strchr(line_ptr, ','); if (read_idx != 0 && line_ptr == NULL) { err = GEOPM_ERROR_RUNTIME; } else { ++line_ptr; } } } } } if (line) { free(line); } if (read_idx != -1) { err = GEOPM_ERROR_RUNTIME; } return err; } static void geopm_proc_cpuset_once(void) { const char *status_path = "/proc/self/status"; const int num_cpu = geopm_sched_num_cpu(); const int num_read = num_cpu / 32 + (num_cpu % 32 ? 1 : 0); int err = 0; uint32_t *proc_cpuset = NULL; FILE *fid = NULL; g_proc_cpuset = CPU_ALLOC(num_cpu); if (g_proc_cpuset == NULL) { err = ENOMEM; } if (!err) { g_proc_cpuset_size = CPU_ALLOC_SIZE(num_cpu); proc_cpuset = calloc(num_read, sizeof(*proc_cpuset)); if (proc_cpuset == NULL) { err = ENOMEM; } } if (!err) { fid = fopen(status_path, "r"); if (!fid) { err = errno ? errno : GEOPM_ERROR_RUNTIME; } } if (!err) { err = geopm_sched_proc_cpuset_helper(num_cpu, proc_cpuset, fid); } if (fid) { fclose(fid); } if (!err) { /* cpu_set_t is managed in units of unsigned long, and may have extra * bits at the end with undefined values. If that happens, * g_proc_cpuset_size may be greater than the size of proc_cpuset, * resulting in reading past the end of proc_cpuset. Avoid this by * only copying the number of bytes needed to contain the mask. Zero * the destination first, since it may not be fully overwritten. * * See the CPU_SET(3) man page for more details about cpu_set_t. */ CPU_ZERO_S(g_proc_cpuset_size, g_proc_cpuset); memcpy(g_proc_cpuset, proc_cpuset, num_read * sizeof(*proc_cpuset)); } else if (g_proc_cpuset) { for (int i = 0; i < num_cpu; ++i) { CPU_SET_S(i, g_proc_cpuset_size, g_proc_cpuset); } } if (proc_cpuset) { free(proc_cpuset); } } /* If /proc/self/status is not available spawn a pthread requesting an open affinity mask and then have the thread query the affinity mask enforced by the OS using sched_getaffinity(). */ #else /* GEOPM_PROCFS */ static void *geopm_proc_cpuset_pthread(void *arg) { void *result = NULL; int err = sched_getaffinity(0, g_proc_cpuset_size, g_proc_cpuset); if (err) { result = (void *)(size_t)(errno ? errno : GEOPM_ERROR_RUNTIME); } return result; } static void geopm_proc_cpuset_once(void) { int err = 0; int num_cpu = geopm_sched_num_cpu(); pthread_t tid; pthread_attr_t attr; g_proc_cpuset = CPU_ALLOC(num_cpu); if (g_proc_cpuset == NULL) { err = ENOMEM; } if (!err) { g_proc_cpuset_size = CPU_ALLOC_SIZE(num_cpu); for (int i = 0; i < num_cpu; ++i) { CPU_SET_S(i, g_proc_cpuset_size, g_proc_cpuset); } err = pthread_attr_init(&attr); } if (!err) { err = pthread_attr_setaffinity_np(&attr, g_proc_cpuset_size, g_proc_cpuset); } if (!err) { err = pthread_create(&tid, &attr, geopm_proc_cpuset_pthread, NULL); } if (!err) { void *result = NULL; err = pthread_join(tid, &result); if (!err && result) { err = (int)(size_t)result; } } if (err && err != ENOMEM) { for (int i = 0; i < num_cpu; ++i) { CPU_SET_S(i, g_proc_cpuset_size, g_proc_cpuset); } } if (!err) { err = pthread_attr_destroy(&attr); } } #endif /* GEOPM_PROCFS */ int geopm_sched_proc_cpuset(int num_cpu, cpu_set_t *proc_cpuset) { int err = pthread_once(&g_proc_cpuset_once, geopm_proc_cpuset_once); int sched_num_cpu = geopm_sched_num_cpu(); size_t cpuset_size = CPU_ALLOC_SIZE(num_cpu); if (!err && cpuset_size < g_proc_cpuset_size) { err = GEOPM_ERROR_INVALID; } if (!err) { /* Copy up to the smaller of the sizes to avoid buffer overruns. Zero * the destination set first, since it may not be fully overwritten */ CPU_ZERO_S(cpuset_size, proc_cpuset); memcpy(proc_cpuset, g_proc_cpuset, g_proc_cpuset_size); for (int i = sched_num_cpu; i < num_cpu; ++i) { CPU_CLR_S(i, cpuset_size, proc_cpuset); } } return err; } int geopm_sched_woomp(int num_cpu, cpu_set_t *woomp) { /*! @brief Function that returns a cpuset that has bits set for all CPUs enabled for the process which are not used by OpenMP. Rather than returning an empty mask, if all CPUs allocated for the process are used by OpenMP, then the woomp mask will have all bits set. */ int err = pthread_once(&g_proc_cpuset_once, geopm_proc_cpuset_once); int sched_num_cpu = geopm_sched_num_cpu(); size_t req_alloc_size = CPU_ALLOC_SIZE(num_cpu); if (!err && !g_proc_cpuset) { err = ENOMEM; } if (!err && req_alloc_size < g_proc_cpuset_size) { err = EINVAL; } if (!err) { /* Copy the process CPU mask into the output. */ CPU_ZERO_S(req_alloc_size, woomp); memcpy(woomp, g_proc_cpuset, g_proc_cpuset_size); /* Start an OpenMP parallel region and have each thread clear its bit from the mask. */ #ifdef _OPENMP #pragma omp parallel default(shared) { #pragma omp critical { int cpu_index = sched_getcpu(); if (cpu_index != -1 && cpu_index < num_cpu) { /* Clear the bit for this OpenMP thread's CPU. */ CPU_CLR_S(cpu_index, g_proc_cpuset_size, woomp); } else { err = errno ? errno : GEOPM_ERROR_LOGIC; } } /* end pragma omp critical */ } /* end pragma omp parallel */ #endif /* _OPENMP */ } if (!err) { for (int i = sched_num_cpu; i < num_cpu; ++i) { CPU_CLR_S(i, req_alloc_size, woomp); } } if (err || CPU_COUNT_S(g_proc_cpuset_size, woomp) == 0) { /* If all CPUs are used by the OpenMP gang, then leave the mask open and allow the Linux scheduler to choose. */ for (int i = 0; i < num_cpu; ++i) { CPU_SET_S(i, g_proc_cpuset_size, woomp); } } return err; }
core_ztsmlq.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c d s * **/ #include "core_blas.h" #include "plasma_types.h" #include "plasma_internal.h" #include "core_lapack.h" #include <omp.h> /***************************************************************************//** * * @ingroup core_tsmlq * * Overwrites the general complex m1-by-n1 tile A1 and * m2-by-n2 tile A2 with * * side = PlasmaLeft side = PlasmaRight * trans = PlasmaNoTrans Q * | A1 | | A1 A2 | * Q * | A2 | * * trans = Plasma_ConjTrans Q^H * | A1 | | A1 A2 | * Q^H * | A2 | * * where Q is a complex unitary matrix defined as the product of k * elementary reflectors * * Q = H(k)^H . . . H(2)^H H(1)^H * * as returned by core_ztslqt. * ******************************************************************************* * * @param[in] side * - PlasmaLeft : apply Q or Q^H from the Left; * - PlasmaRight : apply Q or Q^H from the Right. * * @param[in] trans * - PlasmaNoTrans : Apply Q; * - Plasma_ConjTrans : Apply Q^H. * * @param[in] m1 * The number of rows of the tile A1. m1 >= 0. * * @param[in] n1 * The number of columns of the tile A1. n1 >= 0. * * @param[in] m2 * The number of rows of the tile A2. m2 >= 0. * m2 = m1 if side == PlasmaRight. * * @param[in] n2 * The number of columns of the tile A2. n2 >= 0. * n2 = n1 if side == PlasmaLeft. * * @param[in] k * The number of elementary reflectors whose product defines * the matrix Q. * * @param[in] ib * The inner-blocking size. ib >= 0. * * @param[in,out] A1 * On entry, the m1-by-n1 tile A1. * On exit, A1 is overwritten by the application of Q. * * @param[in] lda1 * The leading dimension of the array A1. lda1 >= max(1,m1). * * @param[in,out] A2 * On entry, the m2-by-n2 tile A2. * On exit, A2 is overwritten by the application of Q. * * @param[in] lda2 * The leading dimension of the tile A2. lda2 >= max(1,m2). * * @param[in] V * The i-th row must contain the vector which defines the * elementary reflector H(i), for i = 1,2,...,k, as returned by * core_ztslqt in the first k rows of its array argument V. * * @param[in] ldv * The leading dimension of the array V. ldv >= max(1,k). * * @param[in] T * The ib-by-k triangular factor T of the block reflector. * T is upper triangular by block (economic storage); * The rest of the array is not referenced. * * @param[in] ldt * The leading dimension of the array T. ldt >= ib. * * @param work * Auxiliary workspace array of length * ldwork-by-m1 if side == PlasmaLeft * ldwork-by-ib if side == PlasmaRight * * @param[in] ldwork * The leading dimension of the array work. * ldwork >= max(1,ib) if side == PlasmaLeft * ldwork >= max(1,n1) if side == PlasmaRight * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * ******************************************************************************/ int core_ztsmlq(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, const plasma_complex64_t *V, int ldv, const plasma_complex64_t *T, int ldt, plasma_complex64_t *work, int ldwork) { // Check input arguments. if (side != PlasmaLeft && side != PlasmaRight) { coreblas_error("illegal value of side"); return -1; } if (trans != PlasmaNoTrans && trans != Plasma_ConjTrans) { coreblas_error("illegal value of trans"); return -2; } if (m1 < 0) { coreblas_error("illegal value of m1"); return -3; } if (n1 < 0) { coreblas_error("illegal value of n1"); return -4; } if (m2 < 0 || (m2 != m1 && side == PlasmaRight)) { coreblas_error("illegal value of m2"); return -5; } if (n2 < 0 || (n2 != n1 && side == PlasmaLeft)) { coreblas_error("illegal value of n2"); return -6; } if (k < 0 || (side == PlasmaLeft && k > m1 ) || (side == PlasmaRight && k > n1)) { coreblas_error("illegal value of k"); return -7; } if (ib < 0) { coreblas_error("illegal value of ib"); return -8; } if (A1 == NULL) { coreblas_error("NULL A1"); return -9; } if (lda1 < imax(1, m1)) { coreblas_error("illegal value of lda1"); return -10; } if (A2 == NULL) { coreblas_error("NULL A2"); return -11; } if (lda2 < imax(1, m2)) { coreblas_error("illegal value of lda2"); return -12; } if (V == NULL) { coreblas_error("NULL V"); return -13; } if (ldv < imax(1, k)) { coreblas_error("illegal value of ldv"); return -14; } if (T == NULL) { coreblas_error("NULL T"); return -15; } if (ldt < imax(1, ib)) { coreblas_error("illegal value of ldt"); return -16; } if (work == NULL) { coreblas_error("NULL work"); return -17; } if (ldwork < imax(1, side == PlasmaLeft ? ib : n1)) { coreblas_error("illegal value of ldwork"); return -18; } // quick return if (m1 == 0 || n1 == 0 || m2 == 0 || n2 == 0 || k == 0 || ib == 0) return PlasmaSuccess; int i1, i3; if ((side == PlasmaLeft && trans == PlasmaNoTrans) || (side == PlasmaRight && trans != PlasmaNoTrans)) { i1 = 0; i3 = ib; } else { i1 = ((k-1)/ib)*ib; i3 = -ib; } if (trans == PlasmaNoTrans) trans = Plasma_ConjTrans; else trans = PlasmaNoTrans; for (int i = i1; i > -1 && i < k; i += i3) { int kb = imin(ib, k-i); int ic = 0; int jc = 0; int mi = m1; int ni = n1; if (side == PlasmaLeft) { // H or H^H is applied to C(i:m,1:n). mi = m1 - i; ic = i; } else { // H or H^H is applied to C(1:m,i:n). ni = n1 - i; jc = i; } // Apply H or H^H. core_zparfb(side, trans, PlasmaForward, PlasmaRowwise, mi, ni, m2, n2, kb, 0, &A1[lda1*jc+ic], lda1, A2, lda2, &V[i], ldv, &T[ldt*i], ldt, work, ldwork); } return PlasmaSuccess; } /******************************************************************************/ void core_omp_ztsmlq(plasma_enum_t side, plasma_enum_t trans, int m1, int n1, int m2, int n2, int k, int ib, plasma_complex64_t *A1, int lda1, plasma_complex64_t *A2, int lda2, const plasma_complex64_t *V, int ldv, const plasma_complex64_t *T, int ldt, plasma_workspace_t work, plasma_sequence_t *sequence, plasma_request_t *request) { #pragma omp task depend(inout:A1[0:lda1*n1]) \ depend(inout:A2[0:lda2*n2]) \ depend(in:V[0:ldv*n2]) \ depend(in:T[0:ib*k]) { if (sequence->status == PlasmaSuccess) { // Prepare workspaces. int tid = omp_get_thread_num(); plasma_complex64_t *W = (plasma_complex64_t*)work.spaces[tid]; int ldwork = side == PlasmaLeft ? ib : n1; // TODO: double check // Call the kernel. int info = core_ztsmlq(side, trans, m1, n1, m2, n2, k, ib, A1, lda1, A2, lda2, V, ldv, T, ldt, W, ldwork); if (info != PlasmaSuccess) { plasma_error("core_ztsmlq() failed"); plasma_request_fail(sequence, request, PlasmaErrorInternal); } } } }
dropout_op.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 <cstring> #include <random> #include <string> #include <algorithm> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/generator.h" #include "paddle/fluid/framework/op_registry.h" namespace paddle { namespace operators { using Tensor = framework::Tensor; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenVector = framework::EigenVector<T, MajorType, IndexType>; template <typename DeviceContext, typename T> class CPUDropoutKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* x = context.Input<Tensor>("X"); auto* seed = context.HasInput("Seed") ? context.Input<Tensor>("Seed") : nullptr; auto* y = context.Output<Tensor>("Out"); const auto* x_data = x->data<T>(); auto* y_data = y->mutable_data<T>(context.GetPlace()); float dropout_prob = context.Attr<float>("dropout_prob"); auto& dropout_implementation = context.Attr<std::string>("dropout_implementation"); bool upscale_in_train = (dropout_implementation == "upscale_in_train"); if (!context.Attr<bool>("is_test")) { auto* mask = context.Output<Tensor>("Mask"); auto* mask_data = mask->mutable_data<uint8_t>(context.GetPlace()); size_t size = pten::product(mask->dims()); // Special case when dropout_prob is 1.0 if (dropout_prob == 1.0f) { std::memset(y_data, 0, size * sizeof(*y_data)); // NOLINT std::memset(mask_data, 0, size * sizeof(*mask_data)); // NOLINT return; } // std::minstd_rand engine; // NOTE: fixed seed should only be used in unittest or for debug. // Guarantee to use random seed in training. int seed_data = 0; if (seed) { seed_data = *(seed->data<int>()); } else { seed_data = context.Attr<bool>("fix_seed") ? context.Attr<int>("seed") : 0; } auto engine = framework::GetCPURandomEngine(seed_data); std::uniform_real_distribution<float> dist(0, 1); for (size_t i = 0; i < size; ++i) { if (dist(*engine) < dropout_prob) { mask_data[i] = 0; y_data[i] = 0; } else { mask_data[i] = 1; if (upscale_in_train) { y_data[i] = x_data[i] / static_cast<T>(1.0f - dropout_prob); } else { y_data[i] = x_data[i]; } } } } else { if (upscale_in_train) { const auto* X_data = x->data<T>(); auto* Y_data = y->mutable_data<T>(context.GetPlace()); #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (int i = 0; i < x->numel(); i++) { Y_data[i] = X_data[i]; } } else { auto X = EigenMatrix<T>::Reshape(*x, 1); auto Y = EigenMatrix<T>::Reshape(*y, 1); auto& place = *context.template device_context<DeviceContext>().eigen_device(); Y.device(place) = X * static_cast<T>(1.0f - dropout_prob); } } } }; template <typename DeviceContext, typename T> class DropoutGradKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& context) const override { auto* grad_x = context.Output<Tensor>(framework::GradVarName("X")); auto* grad_y = context.Input<Tensor>(framework::GradVarName("Out")); auto* mask = context.Input<Tensor>("Mask"); grad_x->mutable_data<T>(context.GetPlace()); auto dX = EigenVector<T>::Flatten(*grad_x); auto dY = EigenVector<T>::Flatten(*grad_y); auto& place = *context.template device_context<DeviceContext>().eigen_device(); auto& dropout_implementation = context.Attr<std::string>("dropout_implementation"); if (context.Attr<bool>("is_test") == true) { if (dropout_implementation == "upscale_in_train") { dX.device(place) = static_cast<T>(1) * dY; } else { float dropout_prob = context.Attr<float>("dropout_prob"); dX.device(place) = dY * static_cast<T>(1.0f - dropout_prob); } } else { auto M = EigenVector<uint8_t>::Flatten(*mask); if (dropout_implementation == "upscale_in_train") { float dropout_prob = context.Attr<float>("dropout_prob"); if (dropout_prob == 1.0f) { dX.device(place) = static_cast<T>(0) * dY; } else { dX.device(place) = dY * M.cast<T>() / static_cast<T>(1.0f - dropout_prob); } } else { dX.device(place) = dY * M.cast<T>(); } } } }; } // namespace operators } // namespace paddle
main.c
#include <stdio.h> #if defined(_OPENMP) #include <omp.h> #endif int main() { #if defined(_OPENMP) omp_set_num_threads(4); #endif #pragma omp parallel { #if defined(_OPENMP) printf("Thread ID: %d\n", omp_get_thread_num()); #endif } printf("Done!\n"); return 0; }
opencl_iwork_fmt_plug.c
/* JtR format to crack iWork '09, and '13 / '14 files. * * This software is Copyright (c) 2015, Dhiru Kholia <kholia at kth.se> and * Maxime Hulliger <hulliger at kth.se>, 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. * * This code may be freely used and modified for any purpose. * * Big thanks to Sean Patrick O'Brien for making this format possible. */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_iwork; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_iwork); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #endif #include "aes.h" #include "hmac_sha.h" #include "arch.h" #include "formats.h" #include "common.h" #include "stdint.h" #include "iwork_common.h" #include "options.h" #include "jumbo.h" #include "sha2.h" #include "common-opencl.h" #include "misc.h" #define OUTLEN (16) #include "opencl_pbkdf2_hmac_sha1.h" #define FORMAT_LABEL "iwork-opencl" #define FORMAT_NAME "Apple iWork '09 / '13 / '14" #define OCL_ALGORITHM_NAME "PBKDF2-SHA1 OpenCL" #define CPU_ALGORITHM_NAME " AES" #define ALGORITHM_NAME OCL_ALGORITHM_NAME CPU_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 0 #define BINARY_ALIGN MEM_ALIGN_WORD #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(*fctx) #define SALT_ALIGN MEM_ALIGN_WORD /* This handles all widths */ #define GETPOS(i, index) (((index) % ocl_v_width) * 4 + ((i) & ~3U) * ocl_v_width + (((i) & 3) ^ 3) + ((index) / ocl_v_width) * 64 * ocl_v_width) static int *cracked; static int any_cracked; static iwork_common_custom_salt *fctx; static struct fmt_tests iwork_tests[] = { {"$iwork$1$2$1$100000$d77ce46a68697e08b76ac91de9117541$e7b72b2848dc27efed883963b00b1ac7$e794144cd2f04bd50e23957b30affb2898554a99a3accb7506c17132654e09c04bbeff45dc4f8a8a1db5fd1592f699eeff2f9a8c31b503e9631a25a344b517f7" ,"12345678"}, {FORMAT_TAG "1$2$1$100000$c773f06bcd580e4afa35618a7d0bee39$8b241504af92416f226d0eea4bf26443$18358e736a0401061f2dca103fceb29e88606d3ec80d09841360cbb8b9dc1d2908c270d3ff4c05cf7a46591e02ff3c9d75f4582f631721a3257dc087f98f523e", "password"}, // iWork '09 Keynote file {"$iwork$2$1$1$4000$736f6d6553616c74$a9d975f8b3e1bf0c388944b457127df4$09eb5d093584376001d4c94e9d0a41eb8a2993132849c5aed8e56e7bd0e8ed50ba38aced793e3480675990c828c01d25fe245cc6aa603c6cb1a0425988f1d3dc", "openwall"}, {NULL} }; static size_t key_buf_size; static unsigned int *inbuffer; static pbkdf2_out *output; static pbkdf2_salt currentsalt; static cl_mem mem_in, mem_out, mem_salt, mem_state; static size_t key_buf_size; static int new_keys; static struct fmt_main *self; static cl_kernel pbkdf2_init, pbkdf2_loop, pbkdf2_final; #define cracked_size (sizeof(*cracked) * global_work_size * ocl_v_width) /* * HASH_LOOPS is ideally made by factors of (iteration count - 1) and should * be chosen for a kernel duration of not more than 200 ms */ #define HASH_LOOPS (3 * 271) #define ITERATIONS 100000 /* Just for auto tune */ #define LOOP_COUNT (((currentsalt.iterations - 1 + HASH_LOOPS - 1)) / HASH_LOOPS) #define STEP 0 #define SEED 128 static const char * warn[] = { "P xfer: " , ", init: " , ", loop: " , ", final: ", ", res xfer: " }; static int split_events[] = { 2, -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, pbkdf2_init); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_loop)); s = MIN(s, autotune_get_task_max_work_group_size(FALSE, 0, pbkdf2_final)); return s; } #if 0 struct fmt_main *me; #endif static void create_clobj(size_t gws, struct fmt_main *self) { gws *= ocl_v_width; key_buf_size = 64 * gws; /// Allocate memory inbuffer = mem_calloc(1, key_buf_size); output = mem_alloc(sizeof(pbkdf2_out) * gws); cracked = mem_calloc(1, cracked_size); mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, key_buf_size, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem in"); mem_salt = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, sizeof(pbkdf2_salt), NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, sizeof(pbkdf2_out) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem out"); mem_state = clCreateBuffer(context[gpu_id], CL_MEM_READ_WRITE, sizeof(pbkdf2_state) * gws, NULL, &ret_code); HANDLE_CLERROR(ret_code, "Error allocating mem_state"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 1, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_init, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_loop, 0, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 0, sizeof(mem_salt), &mem_salt), "Error while setting mem_salt kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(pbkdf2_final, 2, sizeof(mem_state), &mem_state), "Error while setting mem_state kernel argument"); } static void release_clobj(void) { if (cracked) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_salt), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_state), "Release mem state"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(output); MEM_FREE(cracked); } } static void done(void) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(pbkdf2_init), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_loop), "Release kernel"); HANDLE_CLERROR(clReleaseKernel(pbkdf2_final), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { static char valgo[sizeof(ALGORITHM_NAME) + 8] = ""; self = _self; opencl_prepare_dev(gpu_id); /* VLIW5 does better with just 2x vectors due to GPR pressure */ if (!options.v_width && amd_vliw5(device_info[gpu_id])) ocl_v_width = 2; else ocl_v_width = opencl_get_vector_width(gpu_id, sizeof(cl_int)); if (ocl_v_width > 1) { /* Run vectorized kernel */ snprintf(valgo, sizeof(valgo), OCL_ALGORITHM_NAME " %ux" CPU_ALGORITHM_NAME, ocl_v_width); self->params.algorithm_name = valgo; } } static void reset(struct db_main *db) { if (!autotuned) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DHASH_LOOPS=%u -DOUTLEN=%u " "-DPLAINTEXT_LENGTH=%u -DV_WIDTH=%u", HASH_LOOPS, OUTLEN, PLAINTEXT_LENGTH, ocl_v_width); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_kernel.cl", gpu_id, build_opts); pbkdf2_init = clCreateKernel(program[gpu_id], "pbkdf2_init", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); crypt_kernel = pbkdf2_loop = clCreateKernel(program[gpu_id], "pbkdf2_loop", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); pbkdf2_final = clCreateKernel(program[gpu_id], "pbkdf2_final", &ret_code); HANDLE_CLERROR(ret_code, "Error creating kernel"); //Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 2*HASH_LOOPS, split_events, warn, 2, self, create_clobj, release_clobj, ocl_v_width * sizeof(pbkdf2_state), 0, db); //Auto tune execution from shared/included code. autotune_run(self, 2 * (ITERATIONS - 1) + 4, 0, (cpu(device_info[gpu_id]) ? 1000000000 : 10000000000ULL)); } } static void set_salt(void *salt) { fctx = (iwork_common_custom_salt*)salt; memcpy((char*)currentsalt.salt, fctx->salt, fctx->salt_length); currentsalt.length = fctx->salt_length; currentsalt.iterations = fctx->iterations; currentsalt.outlen = 16; // AES 128-bit key only HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_salt, CL_FALSE, 0, sizeof(pbkdf2_salt), &currentsalt, 0, NULL, NULL), "Copy salt to gpu"); } static void clear_keys(void) { memset(inbuffer, 0, key_buf_size); } static void iwork_set_key(char *key, int index) { int i; int length = strlen(key); for (i = 0; i < length; i++) ((char*)inbuffer)[GETPOS(i, index)] = key[i]; new_keys = 1; } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; int i = 0; while (i < PLAINTEXT_LENGTH && (ret[i] = ((char*)inbuffer)[GETPOS(i, index)])) i++; ret[i] = 0; return ret; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int i, j, index; size_t scalar_gws; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER_VW(count, local_work_size); scalar_gws = global_work_size * ocl_v_width; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu if (ocl_autotune_running || new_keys) { BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, key_buf_size, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); new_keys = 0; } /// Run kernels BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_init, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run initial kernel"); for (j = 0; j < (ocl_autotune_running ? 1 : (currentsalt.outlen + 19) / 20); j++) { for (i = 0; i < (ocl_autotune_running ? 1 : LOOP_COUNT); i++) { BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_loop, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[2]), "Run loop kernel"); BENCH_CLERROR(clFinish(queue[gpu_id]), "Error running loop kernel"); opencl_process_event(); } BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], pbkdf2_final, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[3]), "Run intermediate kernel"); } /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, sizeof(pbkdf2_out) * scalar_gws, output, 0, NULL, multi_profilingEvent[4]), "Copy result back"); if (!ocl_autotune_running) { #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) if (iwork_common_decrypt(fctx, (unsigned char*)output[index].dk, fctx->iv, fctx->blob)) { cracked[index] = 1; #ifdef _OPENMP #pragma omp atomic #endif any_cracked |= 1; } } return count; } static int cmp_all(void *binary, int count) { return any_cracked; } static int cmp_one(void *binary, int index) { return cracked[index]; } static int cmp_exact(char *source, int index) { return 1; } struct fmt_main fmt_opencl_iwork = { { 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, { "iteration count", }, { FORMAT_TAG }, iwork_tests }, { init, done, reset, fmt_default_prepare, iwork_common_valid, fmt_default_split, fmt_default_binary, iwork_common_get_salt, { iwork_common_iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, iwork_set_key, get_key, clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
dacemath.c
/****************************************************************************** * * * DIFFERENTIAL ALGEBRA CORE ENGINE * * * ******************************************************************************* * * * Copyright 2016 Politecnico di Milano (2014 Dinamica Srl) * * 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. * * * *******************************************************************************/ /* * dacemath.c * * Created on: November 18, 2016 * Author: Politecnico di Milano */ /** \addtogroup DACE Core * @{ */ // MS C library needs this to trigger it to define math constants #define _USE_MATH_DEFINES #include <math.h> #include <stdlib.h> #include "dace/config.h" #include "dace/dacebase.h" #include "dace/daceaux.h" #include "dacecontrib.h" // define various math constants in case they have not been defined by math.h // these are non-standard C, but most C libraries have them #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #ifndef M_PI_2 #define M_PI_2 (1.57079632679489661923) #endif /******************************************************************************** * Basic DACE arithmetic operations *********************************************************************************/ /*! Perform addition of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the first DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. */ void daceAdd(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { if(!daceIsSameObject(ina, inc) && !daceIsSameObject(inb, inc)) { daceWeightedSum(ina, 1.0, inb, 1.0, inc); } else { DACEDA idaadd; daceAllocateDA(&idaadd, 0); daceWeightedSum(ina, 1.0, inb, 1.0, &idaadd); daceCopy(&idaadd, inc); daceFreeDA(&idaadd); } } /*! Perform subtraction of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the first DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. */ void daceSubtract(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { if(!daceIsSameObject(ina, inc) && !daceIsSameObject(inb, inc)) { daceWeightedSum(ina, 1.0, inb, -1.0, inc); } else { DACEDA idasub; daceAllocateDA(&idasub, 0); daceWeightedSum(ina, 1.0, inb, -1.0, &idasub); daceCopy(&idasub, inc); daceFreeDA(&idasub); } } /*! Perform multiplication of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the first DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. */ void daceMultiply(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { // These should use thread local storage (TLS) for multithread safe implementations // see https://en.wikipedia.org/wiki/Thread-local_storage #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC static DACE_THREAD_LOCAL double cc[DACE_STATIC_NMMAX] = {0}; static DACE_THREAD_LOCAL extended_monomial emb[DACE_STATIC_NMMAX]; static DACE_THREAD_LOCAL extended_monomial *ipbeg[DACE_STATIC_NOMAX+1]; static DACE_THREAD_LOCAL extended_monomial *ipend[DACE_STATIC_NOMAX+1]; static DACE_THREAD_LOCAL unsigned int nomax = 0; static DACE_THREAD_LOCAL unsigned int nvmax = 0; // make sure static memory is correctly allocated if(UNLIKELY(nomax != DACECom.nomax || nvmax != DACECom.nvmax)) { nomax = DACECom.nomax; nvmax = DACECom.nvmax; ipbeg[0] = &emb[0]; for(unsigned int i = 1; i <= DACECom.nomax; i++) ipbeg[i] = emb + daceCountMonomials(i - 1, DACECom.nvmax); } #else static DACE_THREAD_LOCAL double *cc = NULL; static DACE_THREAD_LOCAL extended_monomial *emb = NULL; static DACE_THREAD_LOCAL extended_monomial **ipbeg = NULL; static DACE_THREAD_LOCAL extended_monomial **ipend = NULL; static DACE_THREAD_LOCAL unsigned int nomax = 0; static DACE_THREAD_LOCAL unsigned int nvmax = 0; // make sure static memory is correctly allocated if(UNLIKELY(nomax != DACECom.nomax || nvmax != DACECom.nvmax)) { nomax = DACECom.nomax; nvmax = DACECom.nvmax; dacefree(cc); dacefree(emb); dacefree(ipbeg); dacefree(ipend); cc = (double*) dacecalloc(DACECom.nmmax, sizeof(double)); emb = (extended_monomial*) dacecalloc(DACECom.nmmax, sizeof(extended_monomial)); ipbeg = (extended_monomial**) dacecalloc(DACECom.nomax+1, sizeof(extended_monomial*)); ipend = (extended_monomial**) dacecalloc(DACECom.nomax+1, sizeof(extended_monomial*)); ipbeg[0] = &emb[0]; for(unsigned int i = 1; i <= DACECom.nomax; i++) ipbeg[i] = emb + daceCountMonomials(i - 1, DACECom.nvmax); } #endif monomial *ipoa; unsigned int ilma, illa; monomial *ipob; unsigned int ilmb, illb; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inb, &ipob, &ilmb, &illb); // sort so that ina is the short DA vector if(illa>illb) { unsigned int t1; t1 = illb; illb = illa; illa = t1; t1 = ilmb; ilmb = ilma; ilma = t1; monomial* t2; t2 = ipoa; ipoa = ipob; ipob = t2; } for(unsigned int i = 0; i <= DACECom_t.nocut; i++) ipend[i] = ipbeg[i]; // sort vector b by order for(monomial *ib = ipob; ib < ipob+illb; ib++) { const unsigned int noib = DACECom.ieo[ib->ii]; if(noib > DACECom_t.nocut) continue; ipend[noib]->i1 = DACECom.ie1[ib->ii]; ipend[noib]->i2 = DACECom.ie2[ib->ii]; ipend[noib]->cc = ib->cc; ipend[noib]++; } // perform actual multiplication for(monomial *ia = ipoa; ia < ipoa+illa; ia++) { const unsigned int i1ia = DACECom.ie1[ia->ii]; const unsigned int i2ia = DACECom.ie2[ia->ii]; const double ccia = ia->cc; // Note: all of these inner loops can safely be run in parallel //#pragma omp parallel for for(int noib = DACECom_t.nocut-DACECom.ieo[ia->ii]; noib >= 0; noib--) { for(extended_monomial *ib = ipbeg[noib]; ib < ipend[noib]; ib++) { const unsigned int ic = DACECom.ia1[i1ia+ib->i1] + DACECom.ia2[i2ia+ib->i2]; cc[ic] += ccia*ib->cc; } } } dacePack(cc, inc); } /*! Multiply two DA vectors component-wise, i.e. each monomial of ina with the corresponding monomial of inb \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the first DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. \sa daceEvalMonomials */ void daceMultiplyMonomials(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { monomial *ipoa; unsigned int ilma, illa; monomial *ipob; unsigned int ilmb, illb; monomial *ipoc; unsigned int ilmc, illc; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inb, &ipob, &ilmb, &illb); daceVariableInformation(inc, &ipoc, &ilmc, &illc); monomial *ib = ipob, *ic = ipoc; monomial *const ibmax = ipob + ilmb, *const icmax = ipoc + ilmc; for (monomial *i = ipoa; i < ipoa + illa; i++) { while (ib->ii < i->ii && ib < ibmax) ib++; if (ib == ibmax) break; if (ib->ii == i->ii) { if (ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->cc = i->cc*ib->cc; ic->ii = i->ii; ic++; } } } /*! Perform division of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the first DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. */ void daceDivide(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { DACEDA idadiv; daceAllocateDA(&idadiv, 0); daceMultiplicativeInverse(inb, &idadiv); daceMultiply(ina, &idadiv, inc); daceFreeDA(&idadiv); } /*! Square a DA object. \param[in] ina Pointer to the DA object to square \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceSquare(const DACEDA *ina, DACEDA *inb) { daceMultiply(ina, ina, inb); } /*! Add constant to a DA object. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to add \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inb can be the same as ina. */ void daceAddDouble(const DACEDA *ina, const double ckon, DACEDA *inb) { if(!daceIsSameObject(ina, inb)) daceCopy(ina, inb); daceSetCoefficient0(inb, 0, daceGetConstant(inb)+ckon); } /*! Subtract DA object from constant. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to subtract from \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inb can be the same as ina. */ void daceDoubleSubtract(const DACEDA *ina, const double ckon, DACEDA *inb) { daceMultiplyDouble(ina, -1.0, inb); daceSetCoefficient0(inb, 0, daceGetConstant(inb)+ckon); } /*! Subtract constant from a DA object. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to subtract \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inb can be the same as ina. */ void daceSubtractDouble(const DACEDA *ina, const double ckon, DACEDA *inb) { daceAddDouble(ina, -ckon, inb); } /*! Multiply constant and DA object. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to multiply by \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inb can be the same as ina. */ void daceMultiplyDouble(const DACEDA *ina, const double ckon, DACEDA *inb) { monomial *ipoa; unsigned int ilma, illa; monomial *ipob; unsigned int ilmb, illb; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inb, &ipob, &ilmb, &illb); monomial *ib = ipob; if(illa <= ilmb) { for(monomial *ia = ipoa; ia < ipoa+illa; ia++) { if(DACECom.ieo[ia->ii] > DACECom_t.nocut) continue; const double c = ia->cc*ckon; if(fabs(c) < DACECom_t.eps) continue; ib->cc = c; ib->ii = ia->ii; ib++; } } else { monomial *const ibmax = ipob+ilmb; for(monomial *ia = ipoa; ia < ipoa+illa; ia++) { if(DACECom.ieo[ia->ii] > DACECom_t.nocut) continue; const double c = ia->cc*ckon; if(fabs(c) < DACECom_t.eps) continue; if(ib >= ibmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ib->cc = c; ib->ii = ia->ii; ib++; } } daceSetLength(inb, ib-ipob); } /*! Divide DA object by a constant. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to divide by \param[out] inb Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inb can be the same as ina. */ void daceDivideDouble(const DACEDA *ina, const double ckon, DACEDA *inb) { if(ckon == 0.0) { daceSetError(__func__, DACE_ERROR, 41); daceCreateConstant(inb, 0.0); return; } daceMultiplyDouble(ina, 1.0/ckon, inb); } /*! Divide constant by DA object. \param[in] ina Pointer to the first DA object to operate on \param[in] ckon Constant value to divide \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceDoubleDivide(const DACEDA *ina, const double ckon, DACEDA *inc) { daceMultiplicativeInverse(ina, inc); daceMultiplyDouble(inc, ckon, inc); } /*! Divide a DA vector by a single variable to some power, if possible. \param[in] ina Pointer to the DA object to operate on \param[in] var Number of the independent variable by which to divide \param[in] p Power of independent variable \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceDivideByVariable(const DACEDA *ina, const unsigned int var, const unsigned int p, DACEDA *inc) { monomial *ipoa; unsigned int ilma, illa; monomial *ipoc; unsigned int ilmc, illc; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inc, &ipoc, &ilmc, &illc); if(var < 1 || var > DACECom.nvmax) { daceSetError(__func__, DACE_ERROR, 24); daceCreateConstant(inc, 0.0); return; } // treat a few special cases if(p == 0) { // dividing by 1 daceCopy(ina, inc); return; } else if(illa == 0) { // dividing 0 by anything daceCreateConstant(inc, 0.0); return; } else if(p > DACECom.nomax) { // dividing non-zero DA by too high a power daceSetError(__func__, DACE_ERROR, 42); daceCreateConstant(inc, 0.0); return; } const unsigned int ibase = DACECom.nomax+1; unsigned int j = var-1; if(var > DACECom.nv1) j = j-DACECom.nv1; const unsigned int idiv = npown(ibase, j); monomial *ic = ipoc; monomial *const icmax = ipoc+ilmc; if(var > DACECom.nv1) { for(monomial *i = ipoa; i < ipoa+illa; i++) { const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic2/idiv)%ibase; if(ipow < p) { daceSetError(__func__, DACE_ERROR, 42); daceCreateConstant(inc, 0.0); return; } if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1] + DACECom.ia2[ic2-p*idiv]; ic->cc = i->cc; ic++; } } else { for(monomial *i = ipoa; i < ipoa+illa; i++) { const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic1/idiv)%ibase; if(ipow < p) { daceSetError(__func__, DACE_ERROR, 42); daceCreateConstant(inc, 0.0); return; } if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1-p*idiv] + DACECom.ia2[ic2]; ic->cc = i->cc; ic++; } } daceSetLength(inc, ic-ipoc); } /*! Derivative of DA object with respect to a given independent variable. \param[in] idif Number of the independent variable with respect to which the derivative is taken \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceDifferentiate(const unsigned int idif, const DACEDA *ina, DACEDA *inc) { monomial *ipoa; unsigned int ilma, illa; monomial *ipoc; unsigned int ilmc, illc; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inc, &ipoc, &ilmc, &illc); if(idif < 1 || idif > DACECom.nvmax) { daceSetError(__func__, DACE_ERROR, 24); daceCreateConstant(inc, 0.0); return; } const unsigned int ibase = DACECom.nomax+1; unsigned int j = idif-1; if(idif > DACECom.nv1) j = j-DACECom.nv1; const unsigned int idiv = npown(ibase, j); monomial *ic = ipoc; monomial *const icmax = ipoc+ilmc; if(idif > DACECom.nv1) { for(monomial *i = ipoa; i < ipoa+illa; i++) { const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic2/idiv)%ibase; if(ipow == 0 || DACECom.ieo[i->ii] > DACECom_t.nocut+1) continue; if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1] + DACECom.ia2[ic2-idiv]; ic->cc = i->cc*ipow; ic++; } } else { for(monomial *i = ipoa; i < ipoa+illa; i++) { const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic1/idiv)%ibase; if(ipow == 0 || DACECom.ieo[i->ii] > DACECom_t.nocut+1) continue; if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1-idiv] + DACECom.ia2[ic2]; ic->cc = i->cc*ipow; ic++; } } daceSetLength(inc, ic-ipoc); } /*! Integral of DA object with respect to a given independent variable. \param[in] iint Number of the independent variable with respect to which the integral is taken \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceIntegrate(const unsigned int iint, const DACEDA *ina, DACEDA *inc) { monomial *ipoa; unsigned int ilma, illa; monomial *ipoc; unsigned int ilmc, illc; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inc, &ipoc, &ilmc, &illc); if(iint < 1 || iint > DACECom.nvmax) { daceSetError(__func__, DACE_ERROR, 24); daceCreateConstant(inc, 0.0); return; } const unsigned int ibase = DACECom.nomax+1; unsigned int j = iint-1; if(iint > DACECom.nv1) j = j-DACECom.nv1; const unsigned int idiv = npown(ibase, j); monomial *ic = ipoc; monomial *const icmax = ipoc+ilmc; if(iint > DACECom.nv1) { for(monomial *i = ipoa; i < ipoa+illa; i++) { if(DACECom.ieo[i->ii] >= DACECom_t.nocut) continue; const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic2/idiv)%ibase; const double ccc = i->cc/(ipow+1); if(fabs(ccc) < DACECom_t.eps) continue; if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1] + DACECom.ia2[ic2+idiv]; ic->cc = ccc; ic = ic+1; } } else { for(monomial *i = ipoa; i < ipoa+illa; i++) { if(DACECom.ieo[i->ii] >= DACECom_t.nocut) continue; const unsigned int ic1 = DACECom.ie1[i->ii]; const unsigned int ic2 = DACECom.ie2[i->ii]; const unsigned int ipow = (ic1/idiv)%ibase; const double ccc = i->cc/(ipow+1); if(fabs(ccc) < DACECom_t.eps) continue; if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); break; } ic->ii = DACECom.ia1[ic1+idiv] + DACECom.ia2[ic2]; ic->cc = ccc; ic = ic+1; } } daceSetLength(inc, ic-ipoc); } /******************************************************************************** * DACE intrinsic function routines *********************************************************************************/ /*! Truncate the constant part of a DA object to an integer. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceTruncate(const DACEDA *ina, DACEDA *inc) { daceCopy(ina, inc); daceSetCoefficient0(inc, 0, rint(daceGetConstant(inc))); } /*! Round the constant part of a DA object to an integer. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceRound(const DACEDA *ina, DACEDA *inc) { daceCopy(ina, inc); daceSetCoefficient0(inc, 0, round(daceGetConstant(inc))); } /*! Modulo the constant part of a DA object by p. \param[in] ina Pointer to the DA object to operate on \param[in] p Value with respect to which to compute the modulo \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceModulo(const DACEDA *ina, const double p, DACEDA *inc) { daceCopy(ina, inc); daceSetCoefficient0(inc, 0, fmod(daceGetConstant(inc),p)); } /*! Raise a DA object to the p-th power. \param[in] ina Pointer to the DA object to operate on \param[in] p Power to which to raise the DA object \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void dacePowerDouble(const DACEDA *ina, const double p, DACEDA *inc) { // check simple cases if(p == 0.0) { daceCreateConstant(inc, 1.0); return; } else if(p == (int)p) { dacePower(ina, (int)p, inc); return; } const double a0 = daceGetConstant(ina); if(a0 <= 0.0) { daceSetError(__func__, DACE_ERROR, 43); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double *xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = pow(a0, p); for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) xf[i] = xf[i-1]/i*(p-(i-1)); daceDivideDouble(ina, a0, inc); // more accurate than including a0 in series (uses non-linear part in EvaluateSeries) daceEvaluateSeries(inc, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Raise a DA object to the p-th integer power. \param[in] ina Pointer to the DA object to operate on \param[in] np Power to which to raise the DA object \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void dacePower(const DACEDA *ina, const int np, DACEDA *inc) { DACEDA itemp; // handle some common simple cases directly switch(np) { case 0: daceCreateConstant(inc, 1.0); return; case 1: daceCopy(ina, inc); return; case -1: daceMultiplicativeInverse(ina, inc); return; } // handle all other cases, again with common special cases hard coded switch(abs(np)) { case 2: daceSquare(ina, inc); break; case 3: daceAllocateDA(&itemp, 0); daceSquare(ina, &itemp); daceMultiply(ina, &itemp, inc); daceFreeDA(&itemp); break; case 4: daceAllocateDA(&itemp, 0); daceSquare(ina, &itemp); daceSquare(&itemp, inc); daceFreeDA(&itemp); break; default: daceAllocateDA(&itemp, 0); daceCopy(ina, &itemp); daceCreateConstant(inc, 1.0); unsigned int inp = abs(np); while(inp) { if(inp & 1u) daceMultiply(inc, &itemp, inc); inp >>= 1; if(inp) daceSquare(&itemp, &itemp); } daceFreeDA(&itemp); } if(np < 0) daceMultiplicativeInverse(inc, inc); } /*! Take the np-th root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[in] np Root to take of the DA object \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceRoot(const DACEDA *ina, const int np, DACEDA *inc) { if(np == 0) { daceSetError(__func__, DACE_ERROR, 44); daceCreateConstant(inc, 0.0); return; } const double a0 = daceGetConstant(ina); const unsigned int iodd = abs(np) & 1u; if((iodd == 0) && (a0 <= 0.0)) { daceSetError(__func__, DACE_ERROR, 45); daceCreateConstant(inc, 0.0); return; } else if((iodd == 1) && (a0 == 0.0)) { daceSetError(__func__, DACE_ERROR, 46); daceCreateConstant(inc, 0.0); return; } double cr = 1.0/np; #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double *xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = copysign(pow(fabs(a0), cr), a0); for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) { xf[i] = xf[i-1]/i*cr; cr--; } daceDivideDouble(ina, a0, inc); // more accurate than including a0 in series (uses non-linear part in EvaluateSeries) daceEvaluateSeries(inc, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the multiplicative inverse of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceMultiplicativeInverse(const DACEDA *ina, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 == 0.0) { daceSetError(__func__, DACE_ERROR, 41); daceCreateConstant(inc, 0.0); return; } if(DACECom_t.nocut < 5) { // lower orders: compute series directly daceMultiplicativeInverse0(ina, inc, a0); } else { // higher orders: use iteration const unsigned int nocut = DACECom_t.nocut; DACECom_t.nocut = 2; daceMultiplicativeInverse0(ina, inc, a0); DACEDA temp; daceAllocateDA(&temp, 0); for(unsigned int ord = 3; ord <= nocut; ord *= 2) { DACECom_t.nocut = umin(nocut, 2*ord-1); daceMultiply(ina, inc, &temp); daceDoubleSubtract(&temp, 2.0, &temp); daceMultiply(inc, &temp, inc); } daceFreeDA(&temp); } } /*! Compute the multiplicative inverse of a DA object using series expansion. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \param[in] a0 Constant part of ina \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceMultiplicativeInverse0(const DACEDA *ina, DACEDA *inc, const double a0) { daceDivideDouble(ina, a0, inc); #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double *xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = 1.0/a0; for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) xf[i] = -xf[i-1]; daceEvaluateSeries(inc, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the square root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceSquareRoot(const DACEDA *ina, DACEDA *inc) { daceRoot(ina, 2, inc); } /*! Compute the inverse square root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceInverseSquareRoot(const DACEDA *ina, DACEDA *inc) { daceRoot(ina, -2, inc); } /*! Compute the cubic root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceCubicRoot(const DACEDA *ina, DACEDA *inc) { daceRoot(ina, 3, inc); } /*! Compute the inverse cubic root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceInverseCubicRoot(const DACEDA *ina, DACEDA *inc) { daceRoot(ina, -3, inc); } /*! Compute the hypothenuse of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the second DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina or inb. */ void daceHypotenuse(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { DACEDA itemp1, itemp2; daceAllocateDA(&itemp1, 0); daceAllocateDA(&itemp2, 0); daceSquare(ina, &itemp1); daceSquare(inb, &itemp2); daceAdd(&itemp1, &itemp2, inc); daceRoot(inc, 2, inc); daceFreeDA(&itemp2); daceFreeDA(&itemp1); } /*! Compute the exponential of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceExponential(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = exp(daceGetConstant(ina)); for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) xf[i] = xf[i-1]/i; daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the natural logarithm root of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceLogarithm(const DACEDA *ina, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0) { daceSetError(__func__, DACE_ERROR, 47); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif daceDivideDouble(ina, a0, inc); xf[0] = log(a0); xf[1] = 1.0; for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = -xf[i-1]/i*(i-1); } daceEvaluateSeries(inc, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the logarithm with respect to base b of a DA object. \param[in] ina Pointer to the DA object to operate on \param[in] b Base of the logarithm to use \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceLogarithmBase(const DACEDA *ina, const double b, DACEDA *inc) { if(b <= 0) { daceSetError(__func__, DACE_ERROR, 48); daceCreateConstant(inc, 0.0); return; } daceLogarithm(ina, inc); daceMultiplyDouble(inc, 1.0/log(b), inc); } /*! Compute the decadic logarithm of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceLogarithm10(const DACEDA *ina, DACEDA *inc) { daceLogarithmBase(ina, 10.0, inc); } /*! Compute the binary logarithm of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceLogarithm2(const DACEDA *ina, DACEDA *inc) { daceLogarithmBase(ina, 2.0, inc); } /*! Compute the sine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceSine(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); xf[0] = sin(a0); xf[1] = cos(a0); for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = -xf[i-2]/(i*(i-1)); } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the cosine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceCosine(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); xf[0] = cos(a0); xf[1] = -sin(a0); for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = -xf[i-2]/(i*(i-1)); } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the tangent of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceTangent(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; if(cos(daceGetConstant(ina)) == 0.0) { daceSetError(__func__, DACE_ERROR, 49); daceCreateConstant(inc, 0.0); return; } daceAllocateDA(&itemp, 0); daceSine(ina, &itemp); daceCosine(ina, inc); daceDivide(&itemp, inc, inc); daceFreeDA(&itemp); } /*! Compute the arcsine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceArcSine(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; if(fabs(daceGetConstant(ina)) >= 1.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceAllocateDA(&itemp, 0); daceSquare(ina, &itemp); daceDoubleSubtract(&itemp, 1.0, &itemp); daceSquareRoot(&itemp, &itemp); daceDivide(ina, &itemp, inc); daceArcTangent(inc, inc); daceFreeDA(&itemp); } /*! Compute the arccosine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceArcCosine(const DACEDA *ina, DACEDA *inc) { if(fabs(daceGetConstant(ina)) >= 1.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceArcSine(ina, inc); daceDoubleSubtract(inc, M_PI_2, inc); } /*! Compute the arctangent of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceArcTangent(const DACEDA *ina, DACEDA *inc) { DACEDA iarg; #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1] = {0}; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); daceAllocateDA(&iarg, 0); daceMultiplyDouble(ina, a0, &iarg); daceAddDouble(&iarg, 1.0, &iarg); daceSubtractDouble(ina, a0, inc); daceDivide(inc, &iarg, &iarg); double s = 1.0; xf[0] = atan(a0); for(unsigned int i = 1; i < DACECom_t.nocut+1; i+=2) { xf[i] = s/i; s = -s; } daceEvaluateSeries(&iarg, xf, inc); daceFreeDA(&iarg); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Arctangent of ina/inb with proper sign in [-pi, pi]. This function follows the C standard atan2(y,x) function syntax. \param[in] ina Pointer to the first DA object to operate on \param[in] inb Pointer to the second DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceArcTangent2(const DACEDA *ina, const DACEDA *inb, DACEDA *inc) { const double cx = daceGetConstant(inb); const double cy = daceGetConstant(ina); if(cx == 0.0 && cy == 0.0) { daceCreateConstant(inc, 0.0); } else { if(fabs(cy) > fabs(cx)) { daceDivide(inb, ina, inc); daceArcTangent(inc, inc); if(cy < 0.0) { daceDoubleSubtract(inc, -M_PI_2, inc); } else { daceDoubleSubtract(inc, M_PI_2, inc); } } else { daceDivide(ina, inb, inc); daceArcTangent(inc, inc); if(cx < 0.0) { if(cy > 0.0) { daceAddDouble(inc, M_PI, inc); } else { daceAddDouble(inc, -M_PI, inc); } } } } } /*! Compute the hyperbolic sine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicSine(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); xf[0] = sinh(a0); xf[1] = cosh(a0); for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = xf[i-2]/(i*(i-1)); } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the hyperbolic cosine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicCosine(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); xf[0] = cosh(a0); xf[1] = sinh(a0); for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = xf[i-2]/(i*(i-1)); } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the hyperbolic tangent of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicTangent(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; daceAllocateDA(&itemp, 0); daceHyperbolicSine(ina, &itemp); daceHyperbolicCosine(ina, inc); daceDivide(&itemp, inc, inc); daceFreeDA(&itemp); } /*! Compute the hyperbolic arcsince of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicArcSine(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; daceAllocateDA(&itemp, 0); daceSquare(ina, inc); daceAddDouble(inc, 1.0, &itemp); daceSquareRoot(&itemp, inc); daceAdd(ina, inc, &itemp); daceLogarithm(&itemp, inc); daceFreeDA(&itemp); } /*! Compute the hyperbolic arccosine of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicArcCosine(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; if(daceGetConstant(ina) <= 1.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceAllocateDA(&itemp, 0); daceSquare(ina, inc); daceSubtractDouble(inc, 1.0, &itemp); daceSquareRoot(&itemp, inc); daceAdd(ina, inc, &itemp); daceLogarithm(&itemp, inc); daceFreeDA(&itemp); } /*! Compute the hyperbolic arctangent of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceHyperbolicArcTangent(const DACEDA *ina, DACEDA *inc) { DACEDA itemp; if(fabs(daceGetConstant(ina)) >= 1.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceAllocateDA(&itemp, 0); daceAddDouble(ina, 1.0, &itemp); daceDoubleSubtract(ina, 1.0, inc); daceDivide(&itemp, inc, inc); daceLogarithm(inc, &itemp); daceMultiplyDouble(&itemp, 0.5, inc); daceFreeDA(&itemp); } /*! Compute the error function of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceErrorFunction(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); double factor = 2.0*exp(-a0*a0)/sqrt(M_PI); xf[0] = erf(a0); xf[1] = factor; double Hi2 = 1.0; // Hermite polynomial H_{i-2} = H_0 double Hi1 = 2.0*a0; // Hermite polynomial H_{i-1} = H_1 for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { factor /= -((double)i); xf[i] = factor*Hi1; const double temp = 2.0*a0*Hi1 - 2.0*(i-1)*Hi2; // recursion relation: H_i = 2*x*H_{i-1} - 2*(i-1)*H_{i-2} Hi2 = Hi1; Hi1 = temp; } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the complementary error function of a DA object. \param[in] ina Pointer to the DA object to operate on \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceComplementaryErrorFunction(const DACEDA *ina, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif const double a0 = daceGetConstant(ina); double factor = -2.0*exp(-a0*a0)/sqrt(M_PI); xf[0] = erfc(a0); xf[1] = factor; double Hi2 = 1.0; // Hermite polynomial H_{i-2} = H_0 double Hi1 = 2.0*a0; // Hermite polynomial H_{i-1} = H_1 for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { factor /= -((double)i); xf[i] = factor*Hi1; const double temp = 2.0*a0*Hi1 - 2.0*(i-1)*Hi2; // recursion relation: H_i = 2*x*H_{i-1} - 2*(i-1)*H_{i-2} Hi2 = Hi1; Hi1 = temp; } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /// @cond // Wrappers for contributed netlib Bessel functions (not for public use) /*! Compute value of Bessel functions J_n, Y_n for n in [n0, n1]. \param[in] x function argument (non-negative) \param[in] n0 Lowest order of the Bessel functions to calculate (n0 <= n1) \param[in] n1 Highest order of the Bessel functions to calculate (n0 <= n1) \param[in] type Type of function to evaluate: -1: Bessel J function 1: Bessel Y function \param[out] bz Array of size n1-n0+1 containing the values of B_{n0}, B_{n0+1}, ..., B_{n1} \return Returns 0 if all values are calculated accurately, -1 if x is too large to calculate the result or another error occured, or +1 if some of the results are of reduced accuracy. */ int BesselWrapper(const double x, const int n0, const int n1, const int type, double *bz) { long int nb = (abs(n0) > abs(n1) ? abs(n0) : abs(n1))+1, ncalc; double xx = x, alpha = 0.0; #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC #define DACE_STATIC_MAX_BESSEL_ORDER 100 if( DACE_STATIC_MAX_BESSEL_ORDER < nb ) return -1; double b[DACE_STATIC_MAX_BESSEL_ORDER]; #else double* b = (double*) dacecalloc(nb, sizeof(double)); #endif if(type < 0) rjbesl_(&xx, &alpha, &nb, b, &ncalc); else rybesl_(&xx, &alpha, &nb, b, &ncalc); // discombobulate results if(ncalc >= 0) { ncalc = (ncalc == nb ? 0 : 1); double s = (n0%2 == 0 ? 1.0 : -1.0); for(int i = n0; i <= n1; i++) { if(i >= 0) *(bz++) = b[i]; else { *(bz++) = s*b[-i]; // for integer orders considered here, (-1)^n J_n = J_{-n}, and (-1)^n Y_n = Y_{-n} s *= -1.0; } } } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(b); #endif return ncalc < 0 ? -1 : ncalc; } /*! Compute value of modified Bessel functions I_n, K_n for n in [n0, n1]. \param[in] x function argument (non-negative) \param[in] n0 Lowest order of the Bessel functions to calculate (n0 <= n1) \param[in] n1 Highest order of the Bessel functions to calculate (n0 <= n1) \param[in] type Type of function to evaluate: -2: Bessel I function, scaled (i.e. exp(-x)*I_n(x)) -1: Bessel I function 1: Bessel K function 2: Bessel K function, scaled (i.e. exp(x)*K_n(x)) \param[out] bz Array of size n1-n0+1 containing the values of B_{n0}, B_{n0+1}, ..., B_{n1} \return Returns 0 if all values are calculated accurately, -1 if x is too large to calculate the result or another error occured, or +1 if some of the results are of reduced accuracy. */ int ModifiedBesselWrapper(const double x, const int n0, const int n1, const int type, double *bz) { long int nb = (abs(n0) > abs(n1) ? abs(n0) : abs(n1))+1, ize = abs(type), ncalc; double xx = x, alpha = 0.0; #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC #define DACE_STATIC_MAX_BESSEL_ORDER 100 if( DACE_STATIC_MAX_BESSEL_ORDER < nb ) return -1; double b[DACE_STATIC_MAX_BESSEL_ORDER]; #else double* b = (double*) dacecalloc(nb, sizeof(double)); #endif if(type < 0) ribesl_(&xx, &alpha, &nb, &ize, b, &ncalc); else rkbesl_(&xx, &alpha, &nb, &ize, b, &ncalc); // discombobulate results if(ncalc >= 0) { ncalc = (ncalc == nb ? 0 : 1); for(int i = n0; i <= n1; i++) *(bz++) = b[abs(i)]; // for integer orders considered here, I_n = I_{-n}, and for all orders K_n = K_{-n} } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(b); #endif return ncalc < 0 ? -1 : ncalc; } /// @endcond /*! Compute the modified Bessel function I_n of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part >= 0) \param[in] n Order of the Bessel function \param[in] scaled If true, the scaled Bessel function is computed (i.e. exp(-x)*I_n(x)) \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceBesselIFunction(const DACEDA *ina, const int n, const bool scaled, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double bz[2*DACE_STATIC_NOMAX+1]; #else double* bz = (double*) dacecalloc(2*DACECom_t.nocut+1, sizeof(double)); #endif const int res = ModifiedBesselWrapper(a0, n-DACECom_t.nocut, n+DACECom_t.nocut, scaled ? -2 : -1, bz); if(res >= 0) { if(scaled) daceEvaluateScaledModifiedBesselFunction(ina, bz, 1.0, inc); else daceEvaluateBesselFunction(ina, bz, 1.0, 1.0, inc); } else { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(bz); #endif } /*! Compute the modified Bessel function K_n of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part >= 0) \param[in] n Order of the Bessel function \param[in] scaled If true, the scaled Bessel function is computed (i.e. exp(x)*K_n(x)) \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceBesselKFunction(const DACEDA *ina, const int n, const bool scaled, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double bz[2*DACE_STATIC_NOMAX+1]; #else double* bz = (double*) dacecalloc(2*DACECom_t.nocut+1, sizeof(double)); #endif const int res = ModifiedBesselWrapper(a0, n-DACECom_t.nocut, n+DACECom_t.nocut, scaled ? 2 : 1, bz); if(res >= 0) { if(scaled) daceEvaluateScaledModifiedBesselFunction(ina, bz, -1.0, inc); else daceEvaluateBesselFunction(ina, bz, 1.0, -1.0, inc); } else { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(bz); #endif } /*! Compute the Bessel function J_n of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part >= 0) \param[in] n Order of the Bessel function \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceBesselJFunction(const DACEDA *ina, const int n, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double bz[2*DACE_STATIC_NOMAX+1]; #else double* bz = (double*) dacecalloc(2*DACECom_t.nocut+1, sizeof(double)); #endif const int res = BesselWrapper(a0, n-DACECom_t.nocut, n+DACECom_t.nocut, -1, bz); if(res >= 0) daceEvaluateBesselFunction(ina, bz, -1.0, 1.0, inc); else { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(bz); #endif } /*! Compute the Bessel function Y_n of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part >= 0) \param[in] n Order of the Bessel function \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceBesselYFunction(const DACEDA *ina, const int n, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double bz[2*DACE_STATIC_NOMAX+1]; #else double* bz = (double*) dacecalloc(2*DACECom_t.nocut+1, sizeof(double)); #endif const int res = BesselWrapper(a0, n-DACECom_t.nocut, n+DACECom_t.nocut, 1, bz); if(res >= 0) daceEvaluateBesselFunction(ina, bz, -1.0, 1.0, inc); else { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); } #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(bz); #endif } /*! Evaluate a Bessel function with coefficients bz with the non-constant part of ina. \param[in] ina Pointer to the DA object to operate on \param[in] bz C array of 2*nocut+1 elements containing Bessel functions of orders n-nocut, ..., n+nocut \param[in] type Either -1.0 for normal Bessel functions, or +1.0 for modified Bessel functions. \param[in] ktype Either -1.0 for modified Bessel K function, or +1.0 for all other Bessel functions. \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceEvaluateBesselFunction(const DACEDA *ina, const double bz[], const double type, const double ktype, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; double binomial[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); double* binomial = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = bz[DACECom_t.nocut]; binomial[0] = 1.0; double factor = 1.0; for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) { factor *= ktype*0.5/i; // calculate binomial coefficients i choose j based on previously calculated i-1 choose j. binomial[i] = 1.0; for(unsigned int j = i-1; j > 0; j--) binomial[j] += binomial[j-1]; // Calculate n-th derivative of Bessel function C, see http://dlmf.nist.gov/10.6 // bz contains values of C_{n-o} to C_{n+o} of constant part of ina double sign = 1.0, c = 0.0; xf[i] = 0.0; for(unsigned int j = 0; j <= i; j++) { // use Kahan summation, since signs oscillate and magnitudes can also vary greatly const double y = binomial[j]*sign*bz[DACECom_t.nocut-i+2*j] - c; const double t = xf[i] + y; c = (t - xf[i]) - y; xf[i] = t; // in infinite precision the above is equivalent to: // xf[i] += binomial[j]*sign*bz[DACECom_t.nocut-i+2*j]; sign *= type; } xf[i] *= factor; } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(binomial); dacefree(xf); #endif } /*! Evaluate a scaled modified Bessel function with coefficients bz with the non-constant part of ina. \param[in] ina Pointer to the DA object to operate on \param[in] bz C array of 2*nocut+1 elements containing modified Bessel functions of orders n-nocut, ..., n+nocut \param[in] ktype Either -1.0 for scaled Bessel K function, or +1.0 for scaled Bessel I function \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceEvaluateScaledModifiedBesselFunction(const DACEDA *ina, const double bz[], const double ktype, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; double binomial[2*DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); double* binomial = (double*) dacecalloc(2*DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = bz[DACECom_t.nocut]; binomial[0] = 1.0; double factor = 1.0; for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) { factor *= ktype*0.5/i; // calculate binomial coefficients 2*i-1 choose j based on previously calculated 2*i-2 choose j. binomial[2*i-1] = 1.0; for(unsigned int j = 2*i-2; j > 0; j--) binomial[j] += binomial[j-1]; // calculate binomial coefficients 2*i choose j based on previously calculated 2*i-1 choose j. binomial[2*i] = 1.0; for(unsigned int j = 2*i-1; j > 0; j--) binomial[j] += binomial[j-1]; // Calculate n-th derivative of Bessel function C // bz contains values of C_{n-o} to C_{n+o} of constant part of ina double sign = 1.0, c = 0.0; xf[i] = 0.0; for(unsigned int j = 0; j <= 2*i; j++) { // use Kahan summation, since signs oscillate and magnitudes can also vary greatly const double y = binomial[j]*sign*bz[DACECom_t.nocut-i+j] - c; const double t = xf[i] + y; c = (t - xf[i]) - y; xf[i] = t; // in infinite precision the above is equivalent to: // xf[i] += binomial[j]*sign*bz[DACECom_t.nocut-i+j]; sign *= -1.0; } xf[i] *= factor; } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(binomial); dacefree(xf); #endif } /*! Compute the partial Logarithmic Gamma function of a DA object (without constant part). \param[in] ina Pointer to the DA object to operate on \param[in] a0 Constant part \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. \note No argument checking is performed to ensure values are within allowable range. */ void daceLogGammaFunction0(const DACEDA *ina, const double a0, DACEDA *inc) { #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif xf[0] = 0.0; xf[1] = psi_(&a0); double s = 1.0; for(unsigned int i = 2; i < DACECom_t.nocut+1; i++) { xf[i] = (s/i)*zeta_(i, a0, NULL); s *= -1.0; } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Compute the Logarithmic Gamma function of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part != 0, -1, -2, ...) \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceLogGammaFunction(const DACEDA *ina, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0 && trunc(a0) == a0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceLogGammaFunction0(ina, a0, inc); daceSetCoefficient0(inc, 0, log(dgamma_(&a0))); } /*! Compute the Gamma function of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part != 0, -1, -2, ...) \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceGammaFunction(const DACEDA *ina, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0 && trunc(a0) == a0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } daceLogGammaFunction0(ina, a0, inc); daceExponential(inc, inc); daceMultiplyDouble(inc, dgamma_(&a0), inc); } /*! Compute the n-th Psi function (i.e. the n+1 derivative of the logarithmic gamma function) of a DA object. \param[in] ina Pointer to the DA object to operate on (constant part != 0, -1, -2, ...) \param[in] n Order of the Psi function (n >= 0) \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void dacePsiFunction(const DACEDA *ina, const unsigned int n, DACEDA *inc) { const double a0 = daceGetConstant(ina); if(a0 <= 0.0 && trunc(a0) == a0) { daceSetError(__func__, DACE_ERROR, 50); daceCreateConstant(inc, 0.0); return; } #if DACE_MEMORY_MODEL == DACE_MEMORY_STATIC double xf[DACE_STATIC_NOMAX+1]; #else double* xf = (double*) dacecalloc(DACECom_t.nocut+1, sizeof(double)); #endif if(n == 0) { xf[0] = psi_(&a0); double s = 1.0; for(unsigned int i = 1; i < DACECom_t.nocut+1; i++) { xf[i] = s*zeta_(i+1, a0, NULL); s *= -1.0; } } else { double fac = (n%2 ? 1.0 : -1.0); for(unsigned int i = 2; i <= n; i++) fac *= i; for(unsigned int i = 0; i < DACECom_t.nocut+1; i++) { xf[i] = fac*zeta_(n+i+1, a0, NULL); fac = -(fac/(i+1))*(n+i+1); } } daceEvaluateSeries(ina, xf, inc); #if DACE_MEMORY_MODEL != DACE_MEMORY_STATIC dacefree(xf); #endif } /*! Evaluate a polynomial with coefficients xf with the non-constant part of ina. \param[in] ina Pointer to the DA object to operate on \param[in] xf C array of nocut+1 elements containing the coefficients of the polynomial \param[out] inc Pointer to the DA object to store the result in \note This routine is aliasing safe, i.e. inc can be the same as ina. */ void daceEvaluateSeries(const DACEDA *ina, const double xf[], DACEDA *inc) { DACEDA inon; const unsigned int nocut = DACECom_t.nocut; daceAllocateDA(&inon, 0); daceCopy(ina, &inon); daceSetCoefficient0(&inon, 0, 0.0); DACECom_t.nocut = 1; daceMultiplyDouble(&inon, xf[nocut], inc); daceAddDouble(inc, xf[nocut-1], inc); // evaluate series for(int i = nocut-2; i >= 0; i--) { DACECom_t.nocut = nocut-i; daceMultiply(&inon, inc, inc); daceAddDouble(inc, xf[i], inc); } DACECom_t.nocut = nocut; daceFreeDA(&inon); } /*! Compute the weighted sum of two DA objects. \param[in] ina Pointer to the first DA object to operate on \param[in] afac Weighting factor to multiply ina by \param[in] inb Pointer to the second DA object to operate on \param[in] bfac Weighting factor to multiply inb by \param[out] inc Pointer to the DA object to store the result in \note This routine is NOT aliasing safe! So inc MUST BE DIFFERENT from ina and inb. */ void daceWeightedSum(const DACEDA *ina, const double afac, const DACEDA *inb, const double bfac, DACEDA *inc) { monomial *ipoa; unsigned int ilma, illa; monomial *ipob; unsigned int ilmb, illb; monomial *ipoc; unsigned int ilmc, illc; daceVariableInformation(ina, &ipoa, &ilma, &illa); daceVariableInformation(inb, &ipob, &ilmb, &illb); daceVariableInformation(inc, &ipoc, &ilmc, &illc); monomial *ia = ipoa, *ib = ipob, *ic = ipoc; monomial *const iamax = ipoa+illa, *const ibmax = ipob+illb, *const icmax = ipoc+ilmc; if(illa > 0 && illb > 0) { // both polynomials have coefficients, merge until one runs out unsigned int ja = ia->ii; unsigned int jb = ib->ii; while(true) { if(ja == jb) { // add the two terms if(DACECom.ieo[ja] <= DACECom_t.nocut) { const double ccc = ia->cc*afac + ib->cc*bfac; if(fabs(ccc) >= DACECom_t.eps) { if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); daceSetLength(inc, ilmc); return; } ic->cc = ccc; ic->ii = ia->ii; ic++; } } ia++; ib++; if(ia >= iamax || ib >= ibmax) break; ja = ia->ii; jb = ib->ii; } else if(ja < jb) { // store term a if(DACECom.ieo[ja] <= DACECom_t.nocut) { const double ccc = ia->cc*afac; if(fabs(ccc) >= DACECom_t.eps) { if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); daceSetLength(inc, ilmc); return; } ic->cc = ccc; ic->ii = ia->ii; ic++; } } ia++; if(ia >= iamax) break; ja = ia->ii; } else { // store term b if(DACECom.ieo[jb] <= DACECom_t.nocut) { const double ccc = ib->cc*bfac; if(fabs(ccc) >= DACECom_t.eps) { if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); daceSetLength(inc, ilmc); return; } ic->cc = ccc; ic->ii = ib->ii; ic++; } } ib++; if(ib >= ibmax) break; jb = ib->ii; } } } // copy any remaining terms from either ina or inb monomial *ismin, *ismax; double fac; if(ia < iamax) { ismin = ia; ismax = iamax; fac = afac; } else { ismin = ib; ismax = ibmax; fac = bfac; } for(monomial *is = ismin; is < ismax; is++) { if(DACECom.ieo[is->ii] <= DACECom_t.nocut) { const double ccc = is->cc*fac; if(fabs(ccc) >= DACECom_t.eps) { if(ic >= icmax) { daceSetError(__func__, DACE_ERROR, 21); daceSetLength(inc, ilmc); return; } ic->cc = ccc; ic->ii = is->ii; ic++; } } } daceSetLength(inc, ic-ipoc); } /** @}*/
mergesort.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> long usecs (); void merge(int a[],int temp[], int low, int high, int mid); void mergesortrec(int a[],int temp[], int low, int high); /* Parallelization concerns this routine and the next one */ void mergesort(int a[],int temp[], int low, int high){ #pragma omp parallel { #pragma omp single { mergesortrec(a, temp, low, high); } } } void mergesortrec(int a[],int temp[], int low, int high) { /* Only the coefficients from low to high of the a and temp arrays are modified inside this routine */ int mid; /* CC: note that this is exactly the same as the tree traversal TP */ if(low<high) { mid=(low+high)/2; //find the midpoint #pragma omp task if(mid-low > 1000) { mergesortrec(a,temp,low,mid); //sort the first half } #pragma omp task if(high-mid > 1000) { mergesortrec(a,temp,mid+1,high); //sort the second half } #pragma omp taskwait merge(a,temp,low,high,mid); //merge them together into one sorted list } } /* This routine has to remain unchanged */ void merge(int a[],int temp[], int low, int high, int mid){ int i, j, k; i=low; j=mid+1; k=low; while((i<=mid)&&(j<=high)){ if(a[i]<a[j]){ temp[k]=a[i]; k++; i++; } else { temp[k]=a[j]; k++; j++; } } while(i<=mid){ temp[k]=a[i]; k++; i++; } while(j<=high){ temp[k]=a[j]; k++; j++; } for(i=low;i<k;i++) { a[i]=temp[i]; } } int main(int argc, char **argv) { int LEN; long t_start, t_end; int i, *x,*temp; // Command line argument: array length if ( argc == 2 ) { LEN = atoi(argv[1]); } else { printf("Usage:\n\n ./main n\n\nwhere n is the length of the array to be sorted.\n"); return 1; } x=(int *)malloc(sizeof(int)*LEN); temp=(int *)malloc(sizeof(int)*LEN); if(x==NULL || temp == NULL){ printf("Out of memory"); exit(0); } //Fill the array to be sorted with random numbers for (i = 0; i < LEN; i++) x[i] = rand() % LEN; #ifdef DEBUG printf("before sort:\n"); for (i = 0; i < LEN; i++) printf("%d ", x[i]); printf("\n"); #endif t_start = usecs(); mergesort(x,temp,0, (LEN-1)); t_end = usecs(); #ifdef DEBUG printf("after sort:\n"); for (i = 0; i < LEN; i++) printf("%d ", x[i]); printf("\n"); #endif /* Check the result */ for(i=1; i<LEN; i++) if(x[i] < x[i-1]){ printf("\nThe result is not correct\n"); return 1; } printf("\nThe result is correct\nTime : %8.2f msec.\n",((double)t_end-t_start)/1000.0); return 0; } long usecs (){ struct timeval t; gettimeofday(&t,NULL); return t.tv_sec*1000000+t.tv_usec; }
ompcompress.c
#ifdef _OPENMP /* compress 1d contiguous array in parallel */ static void _t2(compress_omp, Scalar, 1)(zfp_stream* stream, const zfp_field* field) { /* array metadata */ const Scalar* data = (const Scalar*)field->data; uint nx = field->nx; /* number of omp threads, blocks, and chunks */ uint threads = thread_count_omp(stream); uint blocks = (nx + 3) / 4; uint chunks = chunk_count_omp(stream, blocks, threads); /* allocate per-thread streams */ bitstream** bs = compress_init_par(stream, field, chunks, blocks); /* compress chunks of blocks in parallel */ int chunk; #pragma omp parallel for num_threads(threads) for (chunk = 0; chunk < (int)chunks; chunk++) { /* determine range of block indices assigned to this thread */ uint bmin = chunk_offset(blocks, chunks, chunk + 0); uint bmax = chunk_offset(blocks, chunks, chunk + 1); uint block; /* set up thread-local bit stream */ zfp_stream s = *stream; zfp_stream_set_bit_stream(&s, bs[chunk]); /* compress sequence of blocks */ for (block = bmin; block < bmax; block++) { /* determine block origin x within array */ const Scalar* p = data; uint x = 4 * block; p += x; /* compress partial or full block */ if (nx - x < 4) _t2(zfp_encode_partial_block_strided, Scalar, 1)(&s, p, MIN(nx - x, 4u), 1); else _t2(zfp_encode_block, Scalar, 1)(&s, p); } } /* concatenate per-thread streams */ compress_finish_par(stream, bs, chunks); } /* compress 1d strided array in parallel */ static void _t2(compress_strided_omp, Scalar, 1)(zfp_stream* stream, const zfp_field* field) { /* array metadata */ const Scalar* data = (const Scalar*)field->data; uint nx = field->nx; int sx = field->sx ? field->sx : 1; /* number of omp threads, blocks, and chunks */ uint threads = thread_count_omp(stream); uint blocks = (nx + 3) / 4; uint chunks = chunk_count_omp(stream, blocks, threads); /* allocate per-thread streams */ bitstream** bs = compress_init_par(stream, field, chunks, blocks); /* compress chunks of blocks in parallel */ int chunk; #pragma omp parallel for num_threads(threads) for (chunk = 0; chunk < (int)chunks; chunk++) { /* determine range of block indices assigned to this thread */ uint bmin = chunk_offset(blocks, chunks, chunk + 0); uint bmax = chunk_offset(blocks, chunks, chunk + 1); uint block; /* set up thread-local bit stream */ zfp_stream s = *stream; zfp_stream_set_bit_stream(&s, bs[chunk]); /* compress sequence of blocks */ for (block = bmin; block < bmax; block++) { /* determine block origin x within array */ const Scalar* p = data; uint x = 4 * block; p += sx * (ptrdiff_t)x; /* compress partial or full block */ if (nx - x < 4) _t2(zfp_encode_partial_block_strided, Scalar, 1)(&s, p, MIN(nx - x, 4u), sx); else _t2(zfp_encode_block_strided, Scalar, 1)(&s, p, sx); } } /* concatenate per-thread streams */ compress_finish_par(stream, bs, chunks); } /* compress 2d strided array in parallel */ static void _t2(compress_strided_omp, Scalar, 2)(zfp_stream* stream, const zfp_field* field) { /* array metadata */ const Scalar* data = (const Scalar*)field->data; uint nx = field->nx; uint ny = field->ny; int sx = field->sx ? field->sx : 1; int sy = field->sy ? field->sy : nx; /* number of omp threads, blocks, and chunks */ uint threads = thread_count_omp(stream); uint bx = (nx + 3) / 4; uint by = (ny + 3) / 4; uint blocks = bx * by; uint chunks = chunk_count_omp(stream, blocks, threads); /* allocate per-thread streams */ bitstream** bs = compress_init_par(stream, field, chunks, blocks); /* compress chunks of blocks in parallel */ int chunk; #pragma omp parallel for num_threads(threads) for (chunk = 0; chunk < (int)chunks; chunk++) { /* determine range of block indices assigned to this thread */ uint bmin = chunk_offset(blocks, chunks, chunk + 0); uint bmax = chunk_offset(blocks, chunks, chunk + 1); uint block; /* set up thread-local bit stream */ zfp_stream s = *stream; zfp_stream_set_bit_stream(&s, bs[chunk]); /* compress sequence of blocks */ for (block = bmin; block < bmax; block++) { /* determine block origin (x, y) within array */ const Scalar* p = data; uint b = block; uint x, y; x = 4 * (b % bx); b /= bx; y = 4 * b; p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y; /* compress partial or full block */ if (nx - x < 4 || ny - y < 4) _t2(zfp_encode_partial_block_strided, Scalar, 2)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), sx, sy); else _t2(zfp_encode_block_strided, Scalar, 2)(&s, p, sx, sy); } } /* concatenate per-thread streams */ compress_finish_par(stream, bs, chunks); } /* compress 3d strided array in parallel */ static void _t2(compress_strided_omp, Scalar, 3)(zfp_stream* stream, const zfp_field* field) { /* array metadata */ const Scalar* data = (const Scalar*)field->data; uint nx = field->nx; uint ny = field->ny; uint nz = field->nz; int sx = field->sx ? field->sx : 1; int sy = field->sy ? field->sy : nx; int sz = field->sz ? field->sz : (ptrdiff_t)nx * ny; /* number of omp threads, blocks, and chunks */ uint threads = thread_count_omp(stream); uint bx = (nx + 3) / 4; uint by = (ny + 3) / 4; uint bz = (nz + 3) / 4; uint blocks = bx * by * bz; uint chunks = chunk_count_omp(stream, blocks, threads); /* allocate per-thread streams */ bitstream** bs = compress_init_par(stream, field, chunks, blocks); /* compress chunks of blocks in parallel */ int chunk; #pragma omp parallel for num_threads(threads) for (chunk = 0; chunk < (int)chunks; chunk++) { /* determine range of block indices assigned to this thread */ uint bmin = chunk_offset(blocks, chunks, chunk + 0); uint bmax = chunk_offset(blocks, chunks, chunk + 1); uint block; /* set up thread-local bit stream */ zfp_stream s = *stream; zfp_stream_set_bit_stream(&s, bs[chunk]); /* compress sequence of blocks */ for (block = bmin; block < bmax; block++) { /* determine block origin (x, y, z) within array */ const Scalar* p = data; uint b = block; uint x, y, z; x = 4 * (b % bx); b /= bx; y = 4 * (b % by); b /= by; z = 4 * b; p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y + sz * (ptrdiff_t)z; /* compress partial or full block */ if (nx - x < 4 || ny - y < 4 || nz - z < 4) _t2(zfp_encode_partial_block_strided, Scalar, 3)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), sx, sy, sz); else _t2(zfp_encode_block_strided, Scalar, 3)(&s, p, sx, sy, sz); } } /* concatenate per-thread streams */ compress_finish_par(stream, bs, chunks); } /* compress 4d strided array in parallel */ static void _t2(compress_strided_omp, Scalar, 4)(zfp_stream* stream, const zfp_field* field) { /* array metadata */ const Scalar* data = field->data; uint nx = field->nx; uint ny = field->ny; uint nz = field->nz; uint nw = field->nw; int sx = field->sx ? field->sx : 1; int sy = field->sy ? field->sy : nx; int sz = field->sz ? field->sz : (ptrdiff_t)nx * ny; int sw = field->sw ? field->sw : (ptrdiff_t)nx * ny * nz; /* number of omp threads, blocks, and chunks */ uint threads = thread_count_omp(stream); uint bx = (nx + 3) / 4; uint by = (ny + 3) / 4; uint bz = (nz + 3) / 4; uint bw = (nw + 3) / 4; uint blocks = bx * by * bz * bw; uint chunks = chunk_count_omp(stream, blocks, threads); /* allocate per-thread streams */ bitstream** bs = compress_init_par(stream, field, chunks, blocks); /* compress chunks of blocks in parallel */ int chunk; #pragma omp parallel for num_threads(threads) for (chunk = 0; chunk < (int)chunks; chunk++) { /* determine range of block indices assigned to this thread */ uint bmin = chunk_offset(blocks, chunks, chunk + 0); uint bmax = chunk_offset(blocks, chunks, chunk + 1); uint block; /* set up thread-local bit stream */ zfp_stream s = *stream; zfp_stream_set_bit_stream(&s, bs[chunk]); /* compress sequence of blocks */ for (block = bmin; block < bmax; block++) { /* determine block origin (x, y, z, w) within array */ const Scalar* p = data; uint b = block; uint x, y, z, w; x = 4 * (b % bx); b /= bx; y = 4 * (b % by); b /= by; z = 4 * (b % bz); b /= bz; w = 4 * b; p += sx * (ptrdiff_t)x + sy * (ptrdiff_t)y + sz * (ptrdiff_t)z + sw * (ptrdiff_t)w; /* compress partial or full block */ if (nx - x < 4 || ny - y < 4 || nz - z < 4 || nw - w < 4) _t2(zfp_encode_partial_block_strided, Scalar, 4)(&s, p, MIN(nx - x, 4u), MIN(ny - y, 4u), MIN(nz - z, 4u), MIN(nw - w, 4u), sx, sy, sz, sw); else _t2(zfp_encode_block_strided, Scalar, 4)(&s, p, sx, sy, sz, sw); } } /* concatenate per-thread streams */ compress_finish_par(stream, bs, chunks); } #endif
NearestNeighbor.h
#pragma once #include <flann/flann.hpp> #include "Eigen.h" #define MAX_DISTANCE 0.005f struct Match { int idx; float weight; }; class NearestNeighborSearch { public: virtual ~NearestNeighborSearch() {} virtual void setMatchingMaxDistance(float maxDistance) { m_maxDistance = maxDistance; // Squared } float getMatchingMaxDistance(float maxDistance) { return m_maxDistance; // Squared } virtual void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints) = 0; virtual std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints) = 0; virtual void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints, const std::vector<Vector4uc>& targetColors) = 0; virtual std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints, const std::vector<Vector4uc>& transformedColors) = 0; virtual void setCameraParams(const Eigen::Matrix3f& depthIntrinsics, const unsigned width, const unsigned height) = 0; protected: float m_maxDistance; NearestNeighborSearch() : m_maxDistance{ MAX_DISTANCE } {} }; /** * Brute-force nearest neighbor search. */ class NearestNeighborSearchBruteForce : public NearestNeighborSearch { public: NearestNeighborSearchBruteForce() : NearestNeighborSearch() {} void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints) { m_points = targetPoints; } std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints) { const unsigned nMatches = transformedPoints.size(); std::vector<Match> matches(nMatches); const unsigned nTargetPoints = m_points.size(); std::cout << "nMatches: " << nMatches << std::endl; std::cout << "nTargetPoints: " << nTargetPoints << std::endl; #pragma omp parallel for for (int i = 0; i < nMatches; i++) { matches[i] = getClosestPoint(transformedPoints[i]); } return matches; } virtual void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints, const std::vector<Vector4uc>& targetColors){ return; } virtual std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints, const std::vector<Vector4uc>& transformedColors){ return {}; } void setCameraParams(const Eigen::Matrix3f& depthIntrinsics, const unsigned width, const unsigned height){ return; } private: std::vector<Eigen::Vector3f> m_points; Match getClosestPoint(const Vector3f& p) { int idx = -1; float minDist = std::numeric_limits<float>::max(); for (unsigned int i = 0; i < m_points.size(); ++i) { float dist = (p - m_points[i]).norm(); if (minDist > dist) { idx = i; minDist = dist; } } if (minDist <= m_maxDistance) return Match{ idx, 1.f }; else return Match{ -1, 0.f }; } }; /** * Nearest neighbor search using FLANN. */ class NearestNeighborSearchFlann : public NearestNeighborSearch { public: NearestNeighborSearchFlann() : NearestNeighborSearch(), m_nTrees{ 1 }, m_index{ nullptr }, m_flatPoints{ nullptr } { } ~NearestNeighborSearchFlann() { if (m_index) { delete m_flatPoints; delete m_index; m_flatPoints = nullptr; m_index = nullptr; } } void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints) { std::cout << "Initializing FLANN index with " << targetPoints.size() << " points." << std::endl; // FLANN requires that all the points be flat. Therefore we copy the points to a separate flat array. m_flatPoints = new float[targetPoints.size() * 3]; for (size_t pointIndex = 0; pointIndex < targetPoints.size(); pointIndex++) { for (size_t dim = 0; dim < 3; dim++) { m_flatPoints[pointIndex * 3 + dim] = targetPoints[pointIndex][dim]; } } flann::Matrix<float> dataset(m_flatPoints, targetPoints.size(), 3); // Building the index takes some time. m_index = new flann::Index<flann::L2<float>>(dataset, flann::KDTreeIndexParams(m_nTrees)); m_index->buildIndex(); std::cout << "FLANN index created." << std::endl; this->type = 0; // Only points } std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints) { if (!m_index) { std::cout << "FLANN index needs to be build before querying any matches." << std::endl; return {}; } if (this->type == 1) { std::cout << "Please call queryMatches with colors." << std::endl; return {}; } // FLANN requires that all the points be flat. Therefore we copy the points to a separate flat array. float* queryPoints = new float[transformedPoints.size() * 3]; for (size_t pointIndex = 0; pointIndex < transformedPoints.size(); pointIndex++) { for (size_t dim = 0; dim < 3; dim++) { queryPoints[pointIndex * 3 + dim] = transformedPoints[pointIndex][dim]; } } flann::Matrix<float> query(queryPoints, transformedPoints.size(), 3); flann::Matrix<int> indices(new int[query.rows * 1], query.rows, 1); flann::Matrix<float> distances(new float[query.rows * 1], query.rows, 1); //for (size_t i = 0; i < transformedPoints.size(); i++) //{ // std::cout << "Query: " << *query[i] << std::endl; //} // Do a knn search, searching for 1 nearest point and using 16 checks. flann::SearchParams searchParams{ 16 }; searchParams.cores = 0; m_index->knnSearch(query, indices, distances, 1, searchParams); // Filter the matches. const unsigned nMatches = transformedPoints.size(); std::vector<Match> matches; matches.reserve(nMatches); for (int i = 0; i < nMatches; ++i) { if (*distances[i] <= m_maxDistance) matches.push_back(Match{ *indices[i], 1.f }); else matches.push_back(Match{ -1, 0.f }); } //for (int i = 0; i < nMatches; i++) //{ // std::cout << "Query: " << *query[i] << std::endl; // std::cout << "Indices: " << *indices[i] << std::endl; // std::cout << "Distances: " << *distances[i] << std::endl; // std::cout << "Matches: " << matches[i].idx << std::endl; //} // Release the memory. delete[] query.ptr(); delete[] indices.ptr(); delete[] distances.ptr(); //for (int i = 0; i < nMatches; i++) //{ // std::cout << "Matches: " << matches[i].idx << std::endl; //} return matches; } virtual void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints, const std::vector<Vector4uc>& targetColors){ std::cout << "Initializing FLANN-Color index with " << targetPoints.size() << " points." << std::endl; float color_normalize = 1/float(255); float color_scale = 1;//this->m_maxDistance * 0.1; // FLANN requires that all the points be flat. Therefore we copy the points to a separate flat array. m_flatPoints = new float[targetPoints.size() * 6]; for (size_t pointIndex = 0; pointIndex < targetPoints.size(); pointIndex++) { for (size_t dim = 0; dim < 3; dim++) { m_flatPoints[pointIndex * 6 + dim] = targetPoints[pointIndex][dim]; m_flatPoints[pointIndex * 6 + (dim + 3)] = color_scale * color_normalize * targetColors[pointIndex][dim]; } } flann::Matrix<float> dataset(m_flatPoints, targetPoints.size(), 6); // Building the index takes some time. m_index = new flann::Index<flann::L2<float>>(dataset, flann::KDTreeIndexParams(m_nTrees)); m_index->buildIndex(); std::cout << "FLANN-Color index created." << std::endl; this->type = 1; } virtual std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints, const std::vector<Vector4uc>& transformedColors){ if (!m_index) { std::cout << "FLANN-Color index needs to be build before querying any matches." << std::endl; return {}; } if (this->type == 0) { std::cout << "Please call queryMatches without colors." << std::endl; return {}; } float color_normalize = 1/float(255); float color_scale = 1;//this->m_maxDistance * 0.1; // FLANN requires that all the points be flat. Therefore we copy the points to a separate flat array. float* queryPoints = new float[transformedPoints.size() * 6]; for (size_t pointIndex = 0; pointIndex < transformedPoints.size(); pointIndex++) { for (size_t dim = 0; dim < 3; dim++) { queryPoints[pointIndex * 6 + dim] = transformedPoints[pointIndex][dim]; queryPoints[pointIndex * 6 + (dim + 3)] = color_scale * color_normalize * transformedColors[pointIndex][dim]; } } flann::Matrix<float> query(queryPoints, transformedPoints.size(), 6); flann::Matrix<int> indices(new int[query.rows * 1], query.rows, 1); flann::Matrix<float> distances(new float[query.rows * 1], query.rows, 1); //for (size_t i = 0; i < transformedPoints.size(); i++) //{ // std::cout << "Query: " << *query[i] << std::endl; //} // Do a knn search, searching for 1 nearest point and using 16 checks. flann::SearchParams searchParams{ 16 }; searchParams.cores = 0; m_index->knnSearch(query, indices, distances, 1, searchParams); // Filter the matches. const unsigned nMatches = transformedPoints.size(); std::vector<Match> matches; matches.reserve(nMatches); for (int i = 0; i < nMatches; ++i) { if (*distances[i] <= m_maxDistance) matches.push_back(Match{ *indices[i], 1.f }); else matches.push_back(Match{ -1, 0.f }); } //for (int i = 0; i < nMatches; i++) //{ // std::cout << "Query: " << *query[i] << std::endl; // std::cout << "Indices: " << *indices[i] << std::endl; // std::cout << "Distances: " << *distances[i] << std::endl; // std::cout << "Matches: " << matches[i].idx << std::endl; //} // Release the memory. delete[] query.ptr(); delete[] indices.ptr(); delete[] distances.ptr(); //for (int i = 0; i < nMatches; i++) //{ // std::cout << "Matches: " << matches[i].idx << std::endl; //} return matches; } void setCameraParams(const Eigen::Matrix3f& depthIntrinsics, const unsigned width, const unsigned height){ return; } private: int m_nTrees; flann::Index<flann::L2<float>>* m_index; float* m_flatPoints; int type; // 0-> points. 1-> with colors }; // Project query source points to image target plane and find their closest neighbor by using a small search window // class NearestNeighborSearchProjective : public NearestNeighborSearch { public: NearestNeighborSearchProjective(): searchWindow(12), height(0) {} ~NearestNeighborSearchProjective() { } void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints) { std::cout << "Initializing Projective index with " << targetPoints.size() << " points." << std::endl; m_points = targetPoints; std::cout << "Projective index created." << std::endl; } std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints) { if (this->m_points.size() == 0) { std::cout << "Projective index needs to be build before querying any matches." << std::endl; return {}; } // No available camera params // if(this->height == 0){ std::cout << "Set camera params before querying any matches." << std::endl; return {}; } if(this->m_points.size() != (this->width * this->height)){ std::cout << "Invalid size of target points." << std::endl; return {}; } const unsigned nMatches = transformedPoints.size(); const unsigned nTargetPoints = m_points.size(); std::vector<Match> matches(nMatches); std::cout << "nTargetPoints: " << nTargetPoints << std::endl; std::cout << "nMatches: " << nMatches << std::endl; float fx, fy, mx, my; // Depth intrinsics int counterValid = 0; // Num of valid matches // Get depth intrinsics // fx = this->depthIntrinsics(0,0); fy = this->depthIntrinsics(1,1); mx = this->depthIntrinsics(0,2); my = this->depthIntrinsics(1,2); // For each source point find its closest neighbor // #pragma omp parallel for for (unsigned int i = 0; i < nMatches; i++) { // Invalid point // if(transformedPoints[i].x() == MINF) continue; unsigned int uPoint, vPoint; // Pixel coordinates // Tranfsorm camera coodinates to image coordinates of the current point // uPoint = std::round(((transformedPoints[i].x() * fx) / transformedPoints[i].z()) + mx); vPoint = std::round(((transformedPoints[i].y() * fy) / transformedPoints[i].z()) + my); float minDist = std::numeric_limits<float>::max(); unsigned int idx = -1; // Neighrest neighbor index // Scan neighbors and find the closest one // for(unsigned int v = vPoint - this->searchWindow; (v >= 0 && v < this->height && v <= vPoint + this->searchWindow); v++){ for(unsigned int u = uPoint - this->searchWindow; (u >= 0 && u < this->width && u <= uPoint + this->searchWindow); u++){ // Index of current neighbor // unsigned int neighborIndex = this->width * v + u; // Invalid neighbor point // if(this->m_points[neighborIndex].x() == MINF) continue; // Use squared distance // float dist = (transformedPoints[i] - this->m_points[neighborIndex]).squaredNorm(); // Closest neighbor found // if (minDist > dist) { idx = neighborIndex; minDist = dist; } } // End for u } // End for v // Add nearest neighbor for current (query) point // if (minDist <= m_maxDistance){ matches[i].idx = idx; matches[i].weight = 1.f; counterValid++; } else{ matches[i].idx = -1; matches[i].weight = 0.f; } } // End for i - Scan transformedPoints (query points) std::cout << "nValid matches: " << counterValid << std::endl; return matches; } virtual void buildIndex(const std::vector<Eigen::Vector3f>& targetPoints, const std::vector<Vector4uc>& targetColors){ return; } virtual std::vector<Match> queryMatches(const std::vector<Vector3f>& transformedPoints, const std::vector<Vector4uc>& transformedColors){ return {}; } // Parse camera parameters - required for querying points // void setCameraParams(const Eigen::Matrix3f& depthIntrinsics, const unsigned width, const unsigned height){ this->depthIntrinsics = depthIntrinsics; this->width = width; this->height = height; } private: std::vector<Eigen::Vector3f> m_points; // Target points unsigned searchWindow; // How many pixels to take into account during search unsigned width; // Img width unsigned height; Eigen::Matrix3f depthIntrinsics; };
GB_binop__lt_bool.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__lt_bool // A.*B function (eWiseMult): GB_AemultB__lt_bool // A*D function (colscale): GB_AxD__lt_bool // D*A function (rowscale): GB_DxB__lt_bool // C+=B function (dense accum): GB_Cdense_accumB__lt_bool // C+=b function (dense accum): GB_Cdense_accumb__lt_bool // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lt_bool // C=scalar+B GB_bind1st__lt_bool // C=scalar+B' GB_bind1st_tran__lt_bool // C=A+scalar GB_bind2nd__lt_bool // C=A'+scalar GB_bind2nd_tran__lt_bool // C type: bool // A type: bool // B,b type: bool // BinaryOp: cij = (aij < bij) #define GB_ATYPE \ bool #define GB_BTYPE \ bool #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 \ 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) \ bool aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ bool 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) \ z = (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_LT || GxB_NO_BOOL || GxB_NO_LT_BOOL) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (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__lt_bool ( 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__lt_bool ( 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__lt_bool ( 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 bool bool bwork = (*((bool *) 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__lt_bool ( 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 bool *GB_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__lt_bool ( 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 *GB_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__lt_bool ( 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__lt_bool ( 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__lt_bool ( 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 bool *Cx = (bool *) Cx_output ; bool x = (*((bool *) x_input)) ; bool *Bx = (bool *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool 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__lt_bool ( 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 ; bool *Cx = (bool *) Cx_output ; bool *Ax = (bool *) Ax_input ; bool y = (*((bool *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { bool 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 typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ bool aij = Ax [pA] ; \ Cx [pC] = (x < aij) ; \ } GrB_Info GB_bind1st_tran__lt_bool ( 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 \ bool #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool x = (*((const bool *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ bool } //------------------------------------------------------------------------------ // 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) \ { \ bool aij = Ax [pA] ; \ Cx [pC] = (aij < y) ; \ } GrB_Info GB_bind2nd_tran__lt_bool ( 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 bool y = (*((const bool *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fill_ints.c
/* Copyright 2014-2018 The PySCF Developers. 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. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <complex.h> #include <assert.h> #include "config.h" #include "cint.h" #include "vhf/fblas.h" #include "pbc/optimizer.h" #include "np_helper/np_helper.h" #define INTBUFMAX 1000 #define INTBUFMAX10 8000 #define IMGBLK 80 #define OF_CMPLX 2 int GTOmax_shell_dim(int *ao_loc, int *shls_slice, int ncenter); int GTOmax_cache_size(int (*intor)(), int *shls_slice, int ncenter, int *atm, int natm, int *bas, int nbas, double *env); static int shloc_partition(int *kshloc, int *ao_loc, int ksh0, int ksh1, int dkmax) { int ksh; int nloc = 0; int loclast = ao_loc[ksh0]; kshloc[0] = ksh0; for (ksh = ksh0+1; ksh < ksh1; ksh++) { assert(ao_loc[ksh+1] - ao_loc[ksh] < dkmax); if (ao_loc[ksh+1] - loclast > dkmax) { nloc += 1; kshloc[nloc] = ksh; loclast = ao_loc[ksh]; } } nloc += 1; kshloc[nloc] = ksh1; return nloc; } static void shift_bas(double *env_loc, double *env, double *Ls, int ptr, int iL) { env_loc[ptr+0] = env[ptr+0] + Ls[iL*3+0]; env_loc[ptr+1] = env[ptr+1] + Ls[iL*3+1]; env_loc[ptr+2] = env[ptr+2] + Ls[iL*3+2]; } static void sort3c_kks1(double complex *out, double *bufr, double *bufi, int *kptij_idx, int *shls_slice, int *ao_loc, int nkpts, int nkpts_ij, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t njk = naoj * naok; const size_t nijk = njk * naoi; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; const int dij = di * dj; const int dkmax = ao_loc[msh1] - ao_loc[msh0]; const size_t dijmc = dij * dkmax * comp; out += (ip * naoj + jp) * naok; int i, j, k, kk, ik, jk, ksh, ic, dk, dijk; size_t off; double *pbr, *pbi; double complex *pout; for (kk = 0; kk < nkpts_ij; kk++) { ik = kptij_idx[kk] / nkpts; jk = kptij_idx[kk] % nkpts; off = (ik*nkpts+jk) * dijmc; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; pbr = bufr + off + dijk*ic; pbi = bufi + off + dijk*ic; for (j = 0; j < dj; j++) { for (k = 0; k < dk; k++) { for (i = 0; i < di; i++) { pout[i*njk+k] = pbr[k*dij+i] + pbi[k*dij+i]*_Complex_I; } } pout += naok; pbr += di; pbi += di; } } off += dijk * comp; } out += nijk * comp; } } static void _nr3c_fill_kk(int (*intor)(), void (*fsort)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; const double ND1 = -1; jsh += jsh0; ish += ish0; int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS]; int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS]; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; int dkmax = INTBUFMAX / dij; int kshloc[ksh1-ksh0+1]; int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax); int i, m, msh0, msh1, dijm, dijmc, dijmk, empty; int ksh, dk, iL0, iL, jL, iLcount; int shls[3]; double *bufkk_r, *bufkk_i, *bufkL_r, *bufkL_i, *bufL, *pbuf, *cache; int (*fprescreen)(); if (pbcopt != NULL) { fprescreen = pbcopt->fprescreen; } else { fprescreen = PBCnoscreen; } shls[0] = ish; shls[1] = jsh; for (m = 0; m < nkshloc; m++) { msh0 = kshloc[m]; msh1 = kshloc[m+1]; dkmax = ao_loc[msh1] - ao_loc[msh0]; dijm = dij * dkmax; dijmc = dijm * comp; dijmk = dijmc * nkpts; bufkk_r = buf; bufkk_i = bufkk_r + (size_t)nkpts * dijmk; bufkL_r = bufkk_i + (size_t)nkpts * dijmk; bufkL_i = bufkL_r + (size_t)MIN(nimgs,IMGBLK) * dijmk; bufL = bufkL_i + (size_t)MIN(nimgs,IMGBLK) * dijmk; cache = bufL + (size_t)nimgs * dijmc; for (i = 0; i < nkpts*dijmk*OF_CMPLX; i++) { bufkk_r[i] = 0; } for (iL0 = 0; iL0 < nimgs; iL0+=IMGBLK) { iLcount = MIN(IMGBLK, nimgs - iL0); for (iL = iL0; iL < iL0+iLcount; iL++) { shift_bas(env_loc, env, Ls, iptrxyz, iL); pbuf = bufL; for (jL = 0; jL < nimgs; jL++) { shift_bas(env_loc, env, Ls, jptrxyz, jL); if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) { for (ksh = msh0; ksh < msh1; ksh++) { shls[2] = ksh; if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas, env_loc, cintopt, cache)) { empty = 0; } dk = ao_loc[ksh+1] - ao_loc[ksh]; pbuf += dij*dk * comp; } } else { for (i = 0; i < dijmc; i++) { pbuf[i] = 0; } pbuf += dijmc; } } dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &nimgs, &D1, bufL, &dijmc, expkL_r, &nimgs, &D0, bufkL_r+(iL-iL0)*(size_t)dijmk, &dijmc); dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &nimgs, &D1, bufL, &dijmc, expkL_i, &nimgs, &D0, bufkL_i+(iL-iL0)*(size_t)dijmk, &dijmc); } // iL in range(0, nimgs) // conj(exp(1j*dot(h,k))) dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount, &D1, bufkL_r, &dijmk, expkL_r+iL0, &nimgs, &D1, bufkk_r, &dijmk); dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount, &D1, bufkL_i, &dijmk, expkL_i+iL0, &nimgs, &D1, bufkk_r, &dijmk); dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount, &D1, bufkL_i, &dijmk, expkL_r+iL0, &nimgs, &D1, bufkk_i, &dijmk); dgemm_(&TRANS_N, &TRANS_N, &dijmk, &nkpts, &iLcount, &ND1, bufkL_r, &dijmk, expkL_i+iL0, &nimgs, &D1, bufkk_i, &dijmk); } (*fsort)(out, bufkk_r, bufkk_i, kptij_idx, shls_slice, ao_loc, nkpts, nkpts_ij, comp, ish, jsh, msh0, msh1); } } /* ('...LM,kL,lM->...kl', int3c, exp_kL, exp_kL) */ void PBCnr3c_fill_kks1(int (*intor)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { _nr3c_fill_kk(intor, &sort3c_kks1, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } static void sort3c_kks2_igtj(double complex *out, double *bufr, double *bufi, int *kptij_idx, int *shls_slice, int *ao_loc, int nkpts, int nkpts_ij, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; assert(naoi == naoj); const size_t njk = naoj * naok; const size_t nijk = njk * naoi; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; const int dij = di * dj; const int dkmax = ao_loc[msh1] - ao_loc[msh0]; const size_t dijmc = dij * dkmax * comp; double complex *outij = out + (ip * naoj + jp) * naok; double complex *outji = out + (jp * naoj + ip) * naok; int i, j, k, kk, ik, jk, ksh, ic, dk, dijk; size_t offij, offji; double *pbij_r, *pbij_i, *pbji_r, *pbji_i; double complex *poutij, *poutji; for (kk = 0; kk < nkpts_ij; kk++) { ik = kptij_idx[kk] / nkpts; jk = kptij_idx[kk] % nkpts; offij = (ik*nkpts+jk) * dijmc; offji = (jk*nkpts+ik) * dijmc; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { poutij = outij + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; poutji = outji + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; pbij_r = bufr + offij + dijk*ic; pbij_i = bufi + offij + dijk*ic; pbji_r = bufr + offji + dijk*ic; pbji_i = bufi + offji + dijk*ic; for (j = 0; j < dj; j++) { for (k = 0; k < dk; k++) { for (i = 0; i < di; i++) { poutij[i*njk +k] = pbij_r[k*dij+i] + pbij_i[k*dij+i]*_Complex_I; poutji[i*naok+k] = pbji_r[k*dij+i] - pbji_i[k*dij+i]*_Complex_I; } } poutij += naok; poutji += njk; pbij_r += di; pbij_i += di; pbji_r += di; pbji_i += di; } } offij += dijk * comp; offji += dijk * comp; } outij += nijk * comp; outji += nijk * comp; } } /* ('...LM,kL,lM->...kl', int3c, exp_kL, exp_kL) */ void PBCnr3c_fill_kks2(int (*intor)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { int ip = ish + shls_slice[0]; int jp = jsh + shls_slice[2] - nbas; if (ip > jp) { _nr3c_fill_kk(intor, &sort3c_kks2_igtj, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } else if (ip == jp) { _nr3c_fill_kk(intor, &sort3c_kks1, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } } static void sort3c_ks1(double complex *out, double *bufr, double *bufi, int *shls_slice, int *ao_loc, int nkpts, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t njk = naoj * naok; const size_t nijk = njk * naoi; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; const int dij = di * dj; const int dkmax = ao_loc[msh1] - ao_loc[msh0]; const size_t dijmc = dij * dkmax * comp; out += (ip * naoj + jp) * naok; int i, j, k, kk, ksh, ic, dk, dijk; size_t off; double *pbr, *pbi; double complex *pout; for (kk = 0; kk < nkpts; kk++) { off = kk * dijmc; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; pbr = bufr + off + dijk*ic; pbi = bufi + off + dijk*ic; for (j = 0; j < dj; j++) { for (k = 0; k < dk; k++) { for (i = 0; i < di; i++) { pout[i*njk+k] = pbr[k*dij+i] + pbi[k*dij+i]*_Complex_I; } } pout += naok; pbr += di; pbi += di; } } off += dijk * comp; } out += nijk * comp; } } /* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */ static void _nr3c_fill_k(int (*intor)(), void (*fsort)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const char TRANS_N = 'N'; const double D1 = 1; jsh += jsh0; ish += ish0; int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS]; int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS]; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; int dkmax = INTBUFMAX10 / dij; int kshloc[ksh1-ksh0+1]; int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax); int i, m, msh0, msh1, dijmc, empty; size_t dijmk; int ksh, dk, iL, jL, jLcount; int shls[3]; double *bufexp_r = buf; double *bufexp_i = bufexp_r + nimgs * nkpts; double *bufk_r = bufexp_i + nimgs * nkpts; double *bufk_i, *bufL, *pbuf, *cache; int (*fprescreen)(); if (pbcopt != NULL) { fprescreen = pbcopt->fprescreen; } else { fprescreen = PBCnoscreen; } shls[0] = ish; shls[1] = jsh; for (m = 0; m < nkshloc; m++) { msh0 = kshloc[m]; msh1 = kshloc[m+1]; dkmax = ao_loc[msh1] - ao_loc[msh0]; dijmc = dij * dkmax * comp; dijmk = dijmc * nkpts; bufk_i = bufk_r + dijmk; bufL = bufk_i + dijmk; cache = bufL + ((size_t)nimgs) * dijmc; for (i = 0; i < dijmk*OF_CMPLX; i++) { bufk_r[i] = 0; } for (iL = 0; iL < nimgs; iL++) { shift_bas(env_loc, env, Ls, iptrxyz, iL); pbuf = bufL; jLcount = 0; for (jL = 0; jL < nimgs; jL++) { shift_bas(env_loc, env, Ls, jptrxyz, jL); if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) { for (ksh = msh0; ksh < msh1; ksh++) { shls[2] = ksh; if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas, env_loc, cintopt, cache)) { empty = 0; } dk = ao_loc[ksh+1] - ao_loc[ksh]; pbuf += dij*dk * comp; } // ('k,kL->kL', conj(expkL[iL]), expkL) for (i = 0; i < nkpts; i++) { bufexp_r[i*nimgs+jLcount] = expkL_r[i*nimgs+jL] * expkL_r[i*nimgs+iL]; bufexp_r[i*nimgs+jLcount]+= expkL_i[i*nimgs+jL] * expkL_i[i*nimgs+iL]; bufexp_i[i*nimgs+jLcount] = expkL_i[i*nimgs+jL] * expkL_r[i*nimgs+iL]; bufexp_i[i*nimgs+jLcount]-= expkL_r[i*nimgs+jL] * expkL_i[i*nimgs+iL]; } jLcount++; } } dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &jLcount, &D1, bufL, &dijmc, bufexp_r, &nimgs, &D1, bufk_r, &dijmc); dgemm_(&TRANS_N, &TRANS_N, &dijmc, &nkpts, &jLcount, &D1, bufL, &dijmc, bufexp_i, &nimgs, &D1, bufk_i, &dijmc); } // iL in range(0, nimgs) (*fsort)(out, bufk_r, bufk_i, shls_slice, ao_loc, nkpts, comp, ish, jsh, msh0, msh1); } } /* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */ void PBCnr3c_fill_ks1(int (*intor)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { _nr3c_fill_k(intor, sort3c_ks1, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } static void sort3c_ks2_igtj(double complex *out, double *bufr, double *bufi, int *shls_slice, int *ao_loc, int nkpts, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off0 = ((size_t)ao_loc[ish0]) * (ao_loc[ish0] + 1) / 2; const size_t nij = ((size_t)ao_loc[ish1]) * (ao_loc[ish1] + 1) / 2 - off0; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; const int dkmax = ao_loc[msh1] - ao_loc[msh0]; const size_t dijmc = dij * dkmax * comp; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += (((size_t)ao_loc[ish])*(ao_loc[ish]+1)/2-off0 + jp) * naok; int i, j, k, ij, kk, ksh, ic, dk, dijk; size_t off; double *pbr, *pbi; double complex *pout; for (kk = 0; kk < nkpts; kk++) { off = kk * dijmc; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; pbr = bufr + off + dijk*ic; pbi = bufi + off + dijk*ic; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { ij = j * di + i; for (k = 0; k < dk; k++) { pout[j*naok+k] = pbr[k*dij+ij] + pbi[k*dij+ij]*_Complex_I; } } pout += (i+ao_loc[ish]+1) * naok; } } off += dijk * comp; } out += nijk * comp; } } static void sort3c_ks2_ieqj(double complex *out, double *bufr, double *bufi, int *shls_slice, int *ao_loc, int nkpts, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off0 = ((size_t)ao_loc[ish0]) * (ao_loc[ish0] + 1) / 2; const size_t nij = ((size_t)ao_loc[ish1]) * (ao_loc[ish1] + 1) / 2 - off0; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; const int dkmax = ao_loc[msh1] - ao_loc[msh0]; const size_t dijmc = dij * dkmax * comp; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += (((size_t)ao_loc[ish])*(ao_loc[ish]+1)/2-off0 + jp) * naok; int i, j, k, ij, kk, ksh, ic, dk, dijk; size_t off; double *pbr, *pbi; double complex *pout; for (kk = 0; kk < nkpts; kk++) { off = kk * dijmc; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk*ic + ao_loc[ksh]-ao_loc[ksh0]; pbr = bufr + off + dijk*ic; pbi = bufi + off + dijk*ic; for (i = 0; i < di; i++) { for (j = 0; j <= i; j++) { ij = j * di + i; for (k = 0; k < dk; k++) { pout[j*naok+k] = pbr[k*dij+ij] + pbi[k*dij+ij]*_Complex_I; } } pout += (i+ao_loc[ish]+1) * naok; } } off += dijk * comp; } out += nijk * comp; } } /* ('...LM,kL,kM->...k', int3c, exp_kL, exp_kL) */ void PBCnr3c_fill_ks2(int (*intor)(), double complex *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { int ip = ish + shls_slice[0]; int jp = jsh + shls_slice[2] - nbas; if (ip > jp) { _nr3c_fill_k(intor, &sort3c_ks2_igtj, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } else if (ip == jp) { _nr3c_fill_k(intor, &sort3c_ks2_ieqj, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } } static void sort3c_gs1(double *out, double *in, int *shls_slice, int *ao_loc, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t njk = naoj * naok; const size_t nijk = njk * naoi; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int ip = ao_loc[ish] - ao_loc[ish0]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; const int dij = di * dj; out += (ip * naoj + jp) * naok; int i, j, k, ksh, ic, dk, dijk; double *pin, *pout; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0]; pin = in + dijk * ic; for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { for (k = 0; k < dk; k++) { pout[i*njk+k] = pin[k*dij+i]; } } pout += naok; pin += di; } } in += dijk * comp; } } static void _nr3c_fill_g(int (*intor)(), void (*fsort)(), double *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; jsh += jsh0; ish += ish0; int iptrxyz = atm[PTR_COORD+bas[ATOM_OF+ish*BAS_SLOTS]*ATM_SLOTS]; int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS]; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; int dkmax = INTBUFMAX10 / dij / 2 * MIN(IMGBLK,nimgs); int kshloc[ksh1-ksh0+1]; int nkshloc = shloc_partition(kshloc, ao_loc, ksh0, ksh1, dkmax); int i, m, msh0, msh1, dijm; int ksh, dk, iL, jL, dijkc; int shls[3]; int dijmc = dij * dkmax * comp; double *bufL = buf + dijmc; double *cache = bufL + dijmc; double *pbuf; int (*fprescreen)(); if (pbcopt != NULL) { fprescreen = pbcopt->fprescreen; } else { fprescreen = PBCnoscreen; } shls[0] = ish; shls[1] = jsh; for (m = 0; m < nkshloc; m++) { msh0 = kshloc[m]; msh1 = kshloc[m+1]; dkmax = ao_loc[msh1] - ao_loc[msh0]; dijm = dij * dkmax; dijmc = dijm * comp; for (i = 0; i < dijmc; i++) { bufL[i] = 0; } for (iL = 0; iL < nimgs; iL++) { shift_bas(env_loc, env, Ls, iptrxyz, iL); for (jL = 0; jL < nimgs; jL++) { shift_bas(env_loc, env, Ls, jptrxyz, jL); if ((*fprescreen)(shls, pbcopt, atm, bas, env_loc)) { pbuf = bufL; for (ksh = msh0; ksh < msh1; ksh++) { shls[2] = ksh; dk = ao_loc[ksh+1] - ao_loc[ksh]; dijkc = dij*dk * comp; if ((*intor)(buf, NULL, shls, atm, natm, bas, nbas, env_loc, cintopt, cache)) { for (i = 0; i < dijkc; i++) { pbuf[i] += buf[i]; } } pbuf += dijkc; } } } } // iL in range(0, nimgs) (*fsort)(out, bufL, shls_slice, ao_loc, comp, ish, jsh, msh0, msh1); } } /* ('...LM->...', int3c) */ void PBCnr3c_fill_gs1(int (*intor)(), double *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { _nr3c_fill_g(intor, &sort3c_gs1, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } static void sort3c_gs2_igtj(double *out, double *in, int *shls_slice, int *ao_loc, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off0 = ((size_t)ao_loc[ish0]) * (ao_loc[ish0] + 1) / 2; const size_t nij = ((size_t)ao_loc[ish1]) * (ao_loc[ish1] + 1) / 2 - off0; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int dij = di * dj; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += (((size_t)ao_loc[ish])*(ao_loc[ish]+1)/2-off0 + jp) * naok; int i, j, k, ij, ksh, ic, dk, dijk; double *pin, *pout; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0]; pin = in + dijk * ic; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { ij = j * di + i; for (k = 0; k < dk; k++) { pout[j*naok+k] = pin[k*dij+ij]; } } pout += (i+ao_loc[ish]+1) * naok; } } in += dijk * comp; } } static void sort3c_gs2_ieqj(double *out, double *in, int *shls_slice, int *ao_loc, int comp, int ish, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int ksh0 = shls_slice[4]; const int ksh1 = shls_slice[5]; const size_t naok = ao_loc[ksh1] - ao_loc[ksh0]; const size_t off0 = ((size_t)ao_loc[ish0]) * (ao_loc[ish0] + 1) / 2; const size_t nij = ((size_t)ao_loc[ish1]) * (ao_loc[ish1] + 1) / 2 - off0; const size_t nijk = nij * naok; const int di = ao_loc[ish+1] - ao_loc[ish]; const int dij = di * di; const int jp = ao_loc[jsh] - ao_loc[jsh0]; out += (((size_t)ao_loc[ish])*(ao_loc[ish]+1)/2-off0 + jp) * naok; int i, j, k, ij, ksh, ic, dk, dijk; double *pin, *pout; for (ksh = msh0; ksh < msh1; ksh++) { dk = ao_loc[ksh+1] - ao_loc[ksh]; dijk = dij * dk; for (ic = 0; ic < comp; ic++) { pout = out + nijk * ic + ao_loc[ksh]-ao_loc[ksh0]; pin = in + dijk * ic; for (i = 0; i < di; i++) { for (j = 0; j <= i; j++) { ij = j * di + i; for (k = 0; k < dk; k++) { pout[j*naok+k] = pin[k*dij+ij]; } } pout += (i+ao_loc[ish]+1) * naok; } } in += dijk * comp; } } /* ('...LM->...', int3c) */ void PBCnr3c_fill_gs2(int (*intor)(), double *out, int nkpts_ij, int nkpts, int comp, int nimgs, int ish, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { int ip = ish + shls_slice[0]; int jp = jsh + shls_slice[2] - nbas; if (ip > jp) { _nr3c_fill_g(intor, &sort3c_gs2_igtj, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } else if (ip == jp) { _nr3c_fill_g(intor, &sort3c_gs2_ieqj, out, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } } int PBCsizeof_env(int *shls_slice, int *atm, int natm, int *bas, int nbas, double *env) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; int ish, ia, np, nc; int nenv = 0; for (ish = ish0; ish < ish1; ish++) { ia = bas[ATOM_OF +ish*BAS_SLOTS]; nenv = MAX(atm[PTR_COORD+ia*ATM_SLOTS]+3, nenv); np = bas[NPRIM_OF+ish*BAS_SLOTS]; nc = bas[NCTR_OF +ish*BAS_SLOTS]; nenv = MAX(bas[PTR_EXP +ish*BAS_SLOTS]+np, nenv); nenv = MAX(bas[PTR_COEFF+ish*BAS_SLOTS]+np*nc, nenv); } return nenv; } void PBCnr3c_drv(int (*intor)(), void (*fill)(), double complex *eri, int nkpts_ij, int nkpts, int comp, int nimgs, double *Ls, double complex *expkL, int *kptij_idx, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env, int nenv) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; double *expkL_r = malloc(sizeof(double) * nimgs*nkpts * OF_CMPLX); double *expkL_i = expkL_r + nimgs*nkpts; int i; for (i = 0; i < nimgs*nkpts; i++) { expkL_r[i] = creal(expkL[i]); expkL_i[i] = cimag(expkL[i]); } size_t count; if (fill == &PBCnr3c_fill_kks1 || fill == &PBCnr3c_fill_kks2) { int dijk =(GTOmax_shell_dim(ao_loc, shls_slice+0, 1) * GTOmax_shell_dim(ao_loc, shls_slice+2, 1) * GTOmax_shell_dim(ao_loc, shls_slice+4, 1)); count = nkpts*nkpts * OF_CMPLX + nkpts*MIN(nimgs,IMGBLK) * OF_CMPLX + nimgs; // MAX(INTBUFMAX, dijk) to ensure buffer is enough for at least one (i,j,k) shell count*= MAX(INTBUFMAX, dijk) * comp; } else { count = (nkpts * OF_CMPLX + nimgs) * INTBUFMAX10 * comp; count+= nimgs * nkpts * OF_CMPLX; } const int cache_size = GTOmax_cache_size(intor, shls_slice, 3, atm, natm, bas, nbas, env); #pragma omp parallel { int ish, jsh, ij; double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); double *buf = malloc(sizeof(double)*(count+cache_size)); #pragma omp for schedule(dynamic) for (ij = 0; ij < nish*njsh; ij++) { ish = ij / njsh; jsh = ij % njsh; (*fill)(intor, eri, nkpts_ij, nkpts, comp, nimgs, ish, jsh, buf, env_loc, Ls, expkL_r, expkL_i, kptij_idx, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } free(buf); free(env_loc); } free(expkL_r); } static void sort2c_ks1(double complex *out, double *bufr, double *bufi, int *shls_slice, int *ao_loc, int nkpts, int comp, int jsh, int msh0, int msh1) { const int ish0 = shls_slice[0]; const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const size_t nij = naoi * naoj; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; const int jp = ao_loc[jsh] - ao_loc[jsh0]; const int dimax = ao_loc[msh1] - ao_loc[msh0]; const size_t dmjc = dimax * dj * comp; out += jp; int i, j, kk, ish, ic, di, dij; size_t off; double *pbr, *pbi; double complex *pout; for (kk = 0; kk < nkpts; kk++) { off = kk * dmjc; for (ish = msh0; ish < msh1; ish++) { di = ao_loc[ish+1] - ao_loc[ish]; dij = di * dj; for (ic = 0; ic < comp; ic++) { pout = out + nij*ic + naoj*(ao_loc[ish]-ao_loc[ish0]); pbr = bufr + off + dij*ic; pbi = bufi + off + dij*ic; for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { pout[i*naoj+j] = pbr[j*di+i] + pbi[j*di+i]*_Complex_I; } } } off += dij * comp; } out += nij * comp; } } static void _nr2c_fill(int (*intor)(), double complex *out, int nkpts, int comp, int nimgs, int jsh, int ish0, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { const int ish1 = shls_slice[1]; const int jsh0 = shls_slice[2]; const char TRANS_N = 'N'; const double D1 = 1; const double D0 = 0; ish0 += shls_slice[0]; jsh += jsh0; int jptrxyz = atm[PTR_COORD+bas[ATOM_OF+jsh*BAS_SLOTS]*ATM_SLOTS]; const int dj = ao_loc[jsh+1] - ao_loc[jsh]; int dimax = INTBUFMAX10 / dj; int ishloc[ish1-ish0+1]; int nishloc = shloc_partition(ishloc, ao_loc, ish0, ish1, dimax); int m, msh0, msh1, dmjc, ish, di, empty; int jL; int shls[2]; double *bufk_r = buf; double *bufk_i, *bufL, *pbuf, *cache; shls[1] = jsh; for (m = 0; m < nishloc; m++) { msh0 = ishloc[m]; msh1 = ishloc[m+1]; dimax = ao_loc[msh1] - ao_loc[msh0]; dmjc = dj * dimax * comp; bufk_i = bufk_r + dmjc * nkpts; bufL = bufk_i + dmjc * nkpts; cache = bufL + dmjc * nimgs; pbuf = bufL; for (jL = 0; jL < nimgs; jL++) { shift_bas(env_loc, env, Ls, jptrxyz, jL); for (ish = msh0; ish < msh1; ish++) { shls[0] = ish; di = ao_loc[ish+1] - ao_loc[ish]; if ((*intor)(pbuf, NULL, shls, atm, natm, bas, nbas, env_loc, cintopt, cache)) { empty = 0; } pbuf += di * dj * comp; } } dgemm_(&TRANS_N, &TRANS_N, &dmjc, &nkpts, &nimgs, &D1, bufL, &dmjc, expkL_r, &nimgs, &D0, bufk_r, &dmjc); dgemm_(&TRANS_N, &TRANS_N, &dmjc, &nkpts, &nimgs, &D1, bufL, &dmjc, expkL_i, &nimgs, &D0, bufk_i, &dmjc); sort2c_ks1(out, bufk_r, bufk_i, shls_slice, ao_loc, nkpts, comp, jsh, msh0, msh1); } } /* ('...M,kL->...k', int3c, exp_kL, exp_kL) */ void PBCnr2c_fill_ks1(int (*intor)(), double complex *out, int nkpts, int comp, int nimgs, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { _nr2c_fill(intor, out, nkpts, comp, nimgs, jsh, 0, buf, env_loc, Ls, expkL_r, expkL_i, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } void PBCnr2c_fill_ks2(int (*intor)(), double complex *out, int nkpts, int comp, int nimgs, int jsh, double *buf, double *env_loc, double *Ls, double *expkL_r, double *expkL_i, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env) { _nr2c_fill(intor, out, nkpts, comp, nimgs, jsh, jsh, buf, env_loc, Ls, expkL_r, expkL_i, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } void PBCnr2c_drv(int (*intor)(), void (*fill)(), double complex *out, int nkpts, int comp, int nimgs, double *Ls, double complex *expkL, int *shls_slice, int *ao_loc, CINTOpt *cintopt, PBCOpt *pbcopt, int *atm, int natm, int *bas, int nbas, double *env, int nenv) { const int jsh0 = shls_slice[2]; const int jsh1 = shls_slice[3]; const int njsh = jsh1 - jsh0; double *expkL_r = malloc(sizeof(double) * nimgs*nkpts * OF_CMPLX); double *expkL_i = expkL_r + nimgs*nkpts; int i; for (i = 0; i < nimgs*nkpts; i++) { expkL_r[i] = creal(expkL[i]); expkL_i[i] = cimag(expkL[i]); } const int cache_size = GTOmax_cache_size(intor, shls_slice, 2, atm, natm, bas, nbas, env); #pragma omp parallel { int jsh; double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); size_t count = nkpts * OF_CMPLX + nimgs; double *buf = malloc(sizeof(double)*(count*INTBUFMAX10*comp+cache_size)); #pragma omp for schedule(dynamic) for (jsh = 0; jsh < njsh; jsh++) { (*fill)(intor, out, nkpts, comp, nimgs, jsh, buf, env_loc, Ls, expkL_r, expkL_i, shls_slice, ao_loc, cintopt, pbcopt, atm, natm, bas, nbas, env); } free(buf); free(env_loc); } free(expkL_r); }
deconvolution_4x4.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. // // 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 deconv4x4s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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 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++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch * 16 + q * 16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.row(i); float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j + 3 < w; j += 4) { float32x4_t _v = vld1q_f32(r0); // float32x4_t _out00 = vld1q_f32(outptr0 + 0); _out00 = vmlaq_lane_f32(_out00, _v, vget_low_f32(_k0), 0); vst1q_f32(outptr0 + 0, _out00); float32x4_t _out01 = vld1q_f32(outptr0 + 1); _out01 = vmlaq_lane_f32(_out01, _v, vget_low_f32(_k0), 1); vst1q_f32(outptr0 + 1, _out01); float32x4_t _out02 = vld1q_f32(outptr0 + 2); _out02 = vmlaq_lane_f32(_out02, _v, vget_high_f32(_k0), 0); vst1q_f32(outptr0 + 2, _out02); float32x4_t _out03 = vld1q_f32(outptr0 + 3); _out03 = vmlaq_lane_f32(_out03, _v, vget_high_f32(_k0), 1); vst1q_f32(outptr0 + 3, _out03); // float32x4_t _out10 = vld1q_f32(outptr1 + 0); _out10 = vmlaq_lane_f32(_out10, _v, vget_low_f32(_k1), 0); vst1q_f32(outptr1 + 0, _out10); float32x4_t _out11 = vld1q_f32(outptr1 + 1); _out11 = vmlaq_lane_f32(_out11, _v, vget_low_f32(_k1), 1); vst1q_f32(outptr1 + 1, _out11); float32x4_t _out12 = vld1q_f32(outptr1 + 2); _out12 = vmlaq_lane_f32(_out12, _v, vget_high_f32(_k1), 0); vst1q_f32(outptr1 + 2, _out12); float32x4_t _out13 = vld1q_f32(outptr1 + 3); _out13 = vmlaq_lane_f32(_out13, _v, vget_high_f32(_k1), 1); vst1q_f32(outptr1 + 3, _out13); // float32x4_t _out20 = vld1q_f32(outptr2 + 0); _out20 = vmlaq_lane_f32(_out20, _v, vget_low_f32(_k2), 0); vst1q_f32(outptr2 + 0, _out20); float32x4_t _out21 = vld1q_f32(outptr2 + 1); _out21 = vmlaq_lane_f32(_out21, _v, vget_low_f32(_k2), 1); vst1q_f32(outptr2 + 1, _out21); float32x4_t _out22 = vld1q_f32(outptr2 + 2); _out22 = vmlaq_lane_f32(_out22, _v, vget_high_f32(_k2), 0); vst1q_f32(outptr2 + 2, _out22); float32x4_t _out23 = vld1q_f32(outptr2 + 3); _out23 = vmlaq_lane_f32(_out23, _v, vget_high_f32(_k2), 1); vst1q_f32(outptr2 + 3, _out23); // float32x4_t _out30 = vld1q_f32(outptr3 + 0); _out30 = vmlaq_lane_f32(_out30, _v, vget_low_f32(_k3), 0); vst1q_f32(outptr3 + 0, _out30); float32x4_t _out31 = vld1q_f32(outptr3 + 1); _out31 = vmlaq_lane_f32(_out31, _v, vget_low_f32(_k3), 1); vst1q_f32(outptr3 + 1, _out31); float32x4_t _out32 = vld1q_f32(outptr3 + 2); _out32 = vmlaq_lane_f32(_out32, _v, vget_high_f32(_k3), 0); vst1q_f32(outptr3 + 2, _out32); float32x4_t _out33 = vld1q_f32(outptr3 + 3); _out33 = vmlaq_lane_f32(_out33, _v, vget_high_f32(_k3), 1); vst1q_f32(outptr3 + 3, _out33); r0 += 4; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0++; outptr1++; outptr2++; outptr3++; } } } } } static void deconv4x4s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, 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 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++) { const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p * inch * 16 + q * 16; const float* r0 = img0; const float* k0 = kernel0; const float* k1 = kernel0 + 4; const float* k2 = kernel0 + 8; const float* k3 = kernel0 + 12; #if __ARM_NEON float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); #endif // __ARM_NEON for (int i = 0; i < h; i++) { float* outptr = out.row(i * 2); float* outptr0 = outptr; float* outptr1 = outptr0 + outw; float* outptr2 = outptr1 + outw; float* outptr3 = outptr2 + outw; int j = 0; #if __ARM_NEON for (; j + 3 < w; j += 4) { float32x4_t _v = vld1q_f32(r0); // row 0 float32x4x2_t _out0 = vld2q_f32(outptr0); // 0,2,4,6 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_low_f32(_k0), 0); // 1,3,5,7 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_low_f32(_k0), 1); vst2q_f32(outptr0, _out0); _out0 = vld2q_f32(outptr0 + 2); // 2,4,6,8 _out0.val[0] = vmlaq_lane_f32(_out0.val[0], _v, vget_high_f32(_k0), 0); // 3,5,7,9 _out0.val[1] = vmlaq_lane_f32(_out0.val[1], _v, vget_high_f32(_k0), 1); vst2q_f32(outptr0 + 2, _out0); // row 1 float32x4x2_t _out1 = vld2q_f32(outptr1); // 0,2,4,6 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_low_f32(_k1), 0); // 1,3,5,7 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_low_f32(_k1), 1); vst2q_f32(outptr1, _out1); _out1 = vld2q_f32(outptr1 + 2); // 2,4,6,8 _out1.val[0] = vmlaq_lane_f32(_out1.val[0], _v, vget_high_f32(_k1), 0); // 3,5,7,9 _out1.val[1] = vmlaq_lane_f32(_out1.val[1], _v, vget_high_f32(_k1), 1); vst2q_f32(outptr1 + 2, _out1); // row 2 float32x4x2_t _out2 = vld2q_f32(outptr2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_low_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_low_f32(_k2), 1); vst2q_f32(outptr2, _out2); _out2 = vld2q_f32(outptr2 + 2); _out2.val[0] = vmlaq_lane_f32(_out2.val[0], _v, vget_high_f32(_k2), 0); _out2.val[1] = vmlaq_lane_f32(_out2.val[1], _v, vget_high_f32(_k2), 1); vst2q_f32(outptr2 + 2, _out2); // row 3 float32x4x2_t _out3 = vld2q_f32(outptr3); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_low_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_low_f32(_k3), 1); vst2q_f32(outptr3, _out3); _out3 = vld2q_f32(outptr3 + 2); _out3.val[0] = vmlaq_lane_f32(_out3.val[0], _v, vget_high_f32(_k3), 0); _out3.val[1] = vmlaq_lane_f32(_out3.val[1], _v, vget_high_f32(_k3), 1); vst2q_f32(outptr3 + 2, _out3); r0 += 4; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; } #endif // __ARM_NEON for (; j < w; j++) { float val = r0[0]; outptr0[0] += val * k0[0]; outptr0[1] += val * k0[1]; outptr0[2] += val * k0[2]; outptr0[3] += val * k0[3]; outptr1[0] += val * k1[0]; outptr1[1] += val * k1[1]; outptr1[2] += val * k1[2]; outptr1[3] += val * k1[3]; outptr2[0] += val * k2[0]; outptr2[1] += val * k2[1]; outptr2[2] += val * k2[2]; outptr2[3] += val * k2[3]; outptr3[0] += val * k3[0]; outptr3[1] += val * k3[1]; outptr3[2] += val * k3[2]; outptr3[3] += val * k3[3]; r0++; outptr0 += 2; outptr1 += 2; outptr2 += 2; outptr3 += 2; } } } } }
GB_binop__land_fp32.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__land_fp32 // A.*B function (eWiseMult): GB_AemultB__land_fp32 // A*D function (colscale): GB_AxD__land_fp32 // D*A function (rowscale): GB_DxB__land_fp32 // C+=B function (dense accum): GB_Cdense_accumB__land_fp32 // C+=b function (dense accum): GB_Cdense_accumb__land_fp32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__land_fp32 // C=scalar+B GB_bind1st__land_fp32 // C=scalar+B' GB_bind1st_tran__land_fp32 // C=A+scalar GB_bind2nd__land_fp32 // C=A'+scalar GB_bind2nd_tran__land_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = ((aij != 0) && (bij != 0)) #define GB_ATYPE \ float #define GB_BTYPE \ float #define GB_CTYPE \ float // 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) \ float aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ float bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ float 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 = ((x != 0) && (y != 0)) ; // 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_LAND || GxB_NO_FP32 || GxB_NO_LAND_FP32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void (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__land_fp32 ( 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__land_fp32 ( 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__land_fp32 ( 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 float float bwork = (*((float *) 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__land_fp32 ( 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 float *GB_RESTRICT Cx = (float *) 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__land_fp32 ( 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 float *GB_RESTRICT Cx = (float *) 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__land_fp32 ( 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__land_fp32 ( 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__land_fp32 ( 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 float *Cx = (float *) Cx_output ; float x = (*((float *) x_input)) ; float *Bx = (float *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float bij = Bx [p] ; Cx [p] = ((x != 0) && (bij != 0)) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__land_fp32 ( 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 ; float *Cx = (float *) Cx_output ; float *Ax = (float *) Ax_input ; float y = (*((float *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; Cx [p] = ((aij != 0) && (y != 0)) ; } 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = ((x != 0) && (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__land_fp32 ( 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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ float } //------------------------------------------------------------------------------ // 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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) && (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__land_fp32 ( 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 float y = (*((const float *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
quantize.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % QQQ U U AAA N N TTTTT IIIII ZZZZZ EEEEE % % Q Q U U A A NN N T I ZZ E % % Q Q U U AAAAA N N N T I ZZZ EEEEE % % Q QQ U U A A N NN T I ZZ E % % QQQQ UUU A A N N T IIIII ZZZZZ EEEEE % % % % % % MagickCore Methods to Reduce the Number of Unique Colors in an Image % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2020 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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Realism in computer graphics typically requires using 24 bits/pixel to % generate an image. Yet many graphic display devices do not contain the % amount of memory necessary to match the spatial and color resolution of % the human eye. The Quantize methods takes a 24 bit image and reduces % the number of colors so it can be displayed on raster device with less % bits per pixel. In most instances, the quantized image closely % resembles the original reference image. % % A reduction of colors in an image is also desirable for image % transmission and real-time animation. % % QuantizeImage() takes a standard RGB or monochrome images and quantizes % them down to some fixed number of colors. % % For purposes of color allocation, an image is a set of n pixels, where % each pixel is a point in RGB space. RGB space is a 3-dimensional % vector space, and each pixel, Pi, is defined by an ordered triple of % red, green, and blue coordinates, (Ri, Gi, Bi). % % Each primary color component (red, green, or blue) represents an % intensity which varies linearly from 0 to a maximum value, Cmax, which % corresponds to full saturation of that color. Color allocation is % defined over a domain consisting of the cube in RGB space with opposite % vertices at (0,0,0) and (Cmax, Cmax, Cmax). QUANTIZE requires Cmax = % 255. % % The algorithm maps this domain onto a tree in which each node % represents a cube within that domain. In the following discussion % these cubes are defined by the coordinate of two opposite vertices (vertex % nearest the origin in RGB space and the vertex farthest from the origin). % % The tree's root node represents the entire domain, (0,0,0) through % (Cmax,Cmax,Cmax). Each lower level in the tree is generated by % subdividing one node's cube into eight smaller cubes of equal size. % This corresponds to bisecting the parent cube with planes passing % through the midpoints of each edge. % % The basic algorithm operates in three phases: Classification, % Reduction, and Assignment. Classification builds a color description % tree for the image. Reduction collapses the tree until the number it % represents, at most, the number of colors desired in the output image. % Assignment defines the output image's color map and sets each pixel's % color by restorage_class in the reduced tree. Our goal is to minimize % the numerical discrepancies between the original colors and quantized % colors (quantization error). % % Classification begins by initializing a color description tree of % sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color description % tree in the storage_class phase for realistic values of Cmax. If % colors components in the input image are quantized to k-bit precision, % so that Cmax= 2k-1, the tree would need k levels below the root node to % allow representing each possible input color in a leaf. This becomes % prohibitive because the tree's total number of nodes is 1 + % sum(i=1, k, 8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing the pixel's color. It updates the following data for each % such node: % % n1: Number of pixels whose color is contained in the RGB cube which % this node represents; % % n2: Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb: Sums of the red, green, and blue component values for all % pixels not classified at a lower depth. The combination of these sums % and n2 will ultimately characterize the mean color of a set of pixels % represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the % quantization error for a node. % % Reduction repeatedly prunes the tree until the number of nodes with n2 % > 0 is less than or equal to the maximum number of colors allowed in % the output image. On any given iteration over the tree, it selects % those nodes whose E count is minimal for pruning and merges their color % statistics upward. It uses a pruning threshold, Ep, to govern node % selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors within % the cubic volume which the node represents. This includes n1 - n2 % pixels whose colors should be defined by nodes at a lower level in the % tree. % % Assignment generates the output image from the pruned tree. The output % image consists of two parts: (1) A color map, which is an array of % color descriptions (RGB triples) for each color present in the output % image; (2) A pixel array, which represents each pixel as an index % into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % This method is based on a similar algorithm written by Paul Raveling. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/cache-view.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/compare.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/histogram.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" /* Define declarations. */ #if !defined(__APPLE__) && !defined(TARGET_OS_IPHONE) #define CacheShift 2 #else #define CacheShift 3 #endif #define ErrorQueueLength 16 #define MaxNodes 266817 #define MaxTreeDepth 8 #define NodesInAList 1920 /* Typdef declarations. */ typedef struct _DoublePixelPacket { double red, green, blue, alpha; } DoublePixelPacket; typedef struct _NodeInfo { struct _NodeInfo *parent, *child[16]; MagickSizeType number_unique; DoublePixelPacket total_color; double quantize_error; size_t color_number, id, level; } NodeInfo; typedef struct _Nodes { NodeInfo *nodes; struct _Nodes *next; } Nodes; typedef struct _CubeInfo { NodeInfo *root; size_t colors, maximum_colors; ssize_t transparent_index; MagickSizeType transparent_pixels; DoublePixelPacket target; double distance, pruning_threshold, next_threshold; size_t nodes, free_nodes, color_number; NodeInfo *next_node; Nodes *node_queue; MemoryInfo *memory_info; ssize_t *cache; DoublePixelPacket error[ErrorQueueLength]; double weights[ErrorQueueLength]; QuantizeInfo *quantize_info; MagickBooleanType associate_alpha; ssize_t x, y; size_t depth; MagickOffsetType offset; MagickSizeType span; } CubeInfo; /* Method prototypes. */ static CubeInfo *GetCubeInfo(const QuantizeInfo *,const size_t,const size_t); static NodeInfo *GetNodeInfo(CubeInfo *,const size_t,const size_t,NodeInfo *); static MagickBooleanType AssignImageColors(Image *,CubeInfo *,ExceptionInfo *), ClassifyImageColors(CubeInfo *,const Image *,ExceptionInfo *), DitherImage(Image *,CubeInfo *,ExceptionInfo *), SetGrayscaleImage(Image *,ExceptionInfo *), SetImageColormap(Image *,CubeInfo *,ExceptionInfo *); static void ClosestColor(const Image *,CubeInfo *,const NodeInfo *), DefineImageColormap(Image *,CubeInfo *,NodeInfo *), DestroyCubeInfo(CubeInfo *), PruneLevel(CubeInfo *,const NodeInfo *), PruneToCubeDepth(CubeInfo *,const NodeInfo *), ReduceImageColors(const Image *,CubeInfo *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquireQuantizeInfo() allocates the QuantizeInfo structure. % % The format of the AcquireQuantizeInfo method is: % % QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) % % A description of each parameter follows: % % o image_info: the image info. % */ MagickExport QuantizeInfo *AcquireQuantizeInfo(const ImageInfo *image_info) { QuantizeInfo *quantize_info; quantize_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*quantize_info)); GetQuantizeInfo(quantize_info); if (image_info != (ImageInfo *) NULL) { const char *option; quantize_info->dither_method=image_info->dither == MagickFalse ? NoDitherMethod : RiemersmaDitherMethod; option=GetImageOption(image_info,"dither"); if (option != (const char *) NULL) quantize_info->dither_method=(DitherMethod) ParseCommandOption( MagickDitherOptions,MagickFalse,option); quantize_info->measure_error=image_info->verbose; } return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A s s i g n I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AssignImageColors() generates the output image from the pruned tree. The % output image consists of two parts: (1) A color map, which is an array % of color descriptions (RGB triples) for each color present in the % output image; (2) A pixel array, which represents each pixel as an % index into the color map array. % % First, the assignment phase makes one pass over the pruned color % description tree to establish the image's color map. For each node % with n2 > 0, it divides Sr, Sg, and Sb by n2 . This produces the mean % color of all pixels that classify no lower than this node. Each of % these colors becomes an entry in the color map. % % Finally, the assignment phase reclassifies each pixel in the pruned % tree to identify the deepest node containing the pixel's color. The % pixel's value in the pixel array becomes the index of this node's mean % color in the color map. % % The format of the AssignImageColors() method is: % % MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static inline void AssociateAlphaPixel(const Image *image, const CubeInfo *cube_info,const Quantum *pixel,DoublePixelPacket *alpha_pixel) { double alpha; if ((cube_info->associate_alpha == MagickFalse) || (GetPixelAlpha(image,pixel) == OpaqueAlpha)) { alpha_pixel->red=(double) GetPixelRed(image,pixel); alpha_pixel->green=(double) GetPixelGreen(image,pixel); alpha_pixel->blue=(double) GetPixelBlue(image,pixel); alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel); return; } alpha=(double) (QuantumScale*GetPixelAlpha(image,pixel)); alpha_pixel->red=alpha*GetPixelRed(image,pixel); alpha_pixel->green=alpha*GetPixelGreen(image,pixel); alpha_pixel->blue=alpha*GetPixelBlue(image,pixel); alpha_pixel->alpha=(double) GetPixelAlpha(image,pixel); } static inline void AssociateAlphaPixelInfo(const CubeInfo *cube_info, const PixelInfo *pixel,DoublePixelPacket *alpha_pixel) { double alpha; if ((cube_info->associate_alpha == MagickFalse) || (pixel->alpha == OpaqueAlpha)) { alpha_pixel->red=(double) pixel->red; alpha_pixel->green=(double) pixel->green; alpha_pixel->blue=(double) pixel->blue; alpha_pixel->alpha=(double) pixel->alpha; return; } alpha=(double) (QuantumScale*pixel->alpha); alpha_pixel->red=alpha*pixel->red; alpha_pixel->green=alpha*pixel->green; alpha_pixel->blue=alpha*pixel->blue; alpha_pixel->alpha=(double) pixel->alpha; } static inline size_t ColorToNodeId(const CubeInfo *cube_info, const DoublePixelPacket *pixel,size_t index) { size_t id; id=(size_t) (((ScaleQuantumToChar(ClampPixel(pixel->red)) >> index) & 0x01) | ((ScaleQuantumToChar(ClampPixel(pixel->green)) >> index) & 0x01) << 1 | ((ScaleQuantumToChar(ClampPixel(pixel->blue)) >> index) & 0x01) << 2); if (cube_info->associate_alpha != MagickFalse) id|=((ScaleQuantumToChar(ClampPixel(pixel->alpha)) >> index) & 0x1) << 3; return(id); } static MagickBooleanType AssignImageColors(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { #define AssignImageTag "Assign/Image" ColorspaceType colorspace; ssize_t y; /* Allocate image colormap. */ colorspace=image->colorspace; if (cube_info->quantize_info->colorspace != UndefinedColorspace) (void) TransformImageColorspace(image,cube_info->quantize_info->colorspace, exception); cube_info->transparent_pixels=0; cube_info->transparent_index=(-1); if (SetImageColormap(image,cube_info,exception) == MagickFalse) return(MagickFalse); /* Create a reduced color image. */ if (cube_info->quantize_info->dither_method != NoDitherMethod) (void) DitherImage(image,cube_info,exception); else { CacheView *image_view; MagickBooleanType status; 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++) { CubeInfo cube; register Quantum *magick_restrict q; register ssize_t x; ssize_t count; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } cube=(*cube_info); for (x=0; x < (ssize_t) image->columns; x+=count) { DoublePixelPacket pixel; register const NodeInfo *node_info; register ssize_t i; size_t id, index; /* Identify the deepest node containing the pixel's color. */ for (count=1; (x+count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,q+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,q,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,&cube,q,&pixel); node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+ 1.0); ClosestColor(image,&cube,node_info->parent); index=cube.color_number; for (i=0; i < (ssize_t) count; i++) { if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum( image->colormap[index].red),q); SetPixelGreen(image,ClampToQuantum( image->colormap[index].green),q); SetPixelBlue(image,ClampToQuantum( image->colormap[index].blue),q); if (cube.associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum( image->colormap[index].alpha),q); } q+=GetPixelChannels(image); } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } if (cube_info->quantize_info->measure_error != MagickFalse) (void) GetImageQuantizeError(image,exception); if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) { double intensity; /* Monochrome image. */ intensity=GetPixelInfoLuma(image->colormap+0) < QuantumRange/2.0 ? 0.0 : QuantumRange; if (image->colors > 1) { intensity=0.0; if (GetPixelInfoLuma(image->colormap+0) > GetPixelInfoLuma(image->colormap+1)) intensity=(double) QuantumRange; } image->colormap[0].red=intensity; image->colormap[0].green=intensity; image->colormap[0].blue=intensity; if (image->colors > 1) { image->colormap[1].red=(double) QuantumRange-intensity; image->colormap[1].green=(double) QuantumRange-intensity; image->colormap[1].blue=(double) QuantumRange-intensity; } } (void) SyncImage(image,exception); if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (IssRGBCompatibleColorspace(colorspace) == MagickFalse)) (void) TransformImageColorspace(image,colorspace,exception); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClassifyImageColors() begins by initializing a color description tree % of sufficient depth to represent each possible input color in a leaf. % However, it is impractical to generate a fully-formed color % description tree in the storage_class phase for realistic values of % Cmax. If colors components in the input image are quantized to k-bit % precision, so that Cmax= 2k-1, the tree would need k levels below the % root node to allow representing each possible input color in a leaf. % This becomes prohibitive because the tree's total number of nodes is % 1 + sum(i=1,k,8k). % % A complete tree would require 19,173,961 nodes for k = 8, Cmax = 255. % Therefore, to avoid building a fully populated tree, QUANTIZE: (1) % Initializes data structures for nodes only as they are needed; (2) % Chooses a maximum depth for the tree as a function of the desired % number of colors in the output image (currently log2(colormap size)). % % For each pixel in the input image, storage_class scans downward from % the root of the color description tree. At each level of the tree it % identifies the single node which represents a cube in RGB space % containing It updates the following data for each such node: % % n1 : Number of pixels whose color is contained in the RGB cube % which this node represents; % % n2 : Number of pixels whose color is not represented in a node at % lower depth in the tree; initially, n2 = 0 for all nodes except % leaves of the tree. % % Sr, Sg, Sb : Sums of the red, green, and blue component values for % all pixels not classified at a lower depth. The combination of % these sums and n2 will ultimately characterize the mean color of a % set of pixels represented by this node. % % E: the distance squared in RGB space between each pixel contained % within a node and the nodes' center. This represents the quantization % error for a node. % % The format of the ClassifyImageColors() method is: % % MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, % const Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o image: the image. % */ static inline void SetAssociatedAlpha(const Image *image,CubeInfo *cube_info) { MagickBooleanType associate_alpha; associate_alpha=image->alpha_trait == BlendPixelTrait ? MagickTrue : MagickFalse; if ((cube_info->quantize_info->number_colors == 2) && ((cube_info->quantize_info->colorspace == LinearGRAYColorspace) || (cube_info->quantize_info->colorspace == GRAYColorspace))) associate_alpha=MagickFalse; cube_info->associate_alpha=associate_alpha; } static MagickBooleanType ClassifyImageColors(CubeInfo *cube_info, const Image *image,ExceptionInfo *exception) { #define ClassifyImageTag "Classify/Image" CacheView *image_view; DoublePixelPacket error, mid, midpoint, pixel; MagickBooleanType proceed; double bisect; NodeInfo *node_info; size_t count, id, index, level; ssize_t y; /* Classify the first cube_info->maximum_colors colors to a tree depth of 8. */ SetAssociatedAlpha(image,cube_info); if (cube_info->quantize_info->colorspace != image->colorspace) { if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image, cube_info->quantize_info->colorspace,exception); else if (IssRGBCompatibleColorspace(image->colorspace) == MagickFalse) (void) TransformImageColorspace((Image *) image,sRGBColorspace, exception); } midpoint.red=(double) QuantumRange/2.0; midpoint.green=(double) QuantumRange/2.0; midpoint.blue=(double) QuantumRange/2.0; midpoint.alpha=(double) QuantumRange/2.0; error.alpha=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,p,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((double) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= MaxTreeDepth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.alpha+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); continue; } if (level == MaxTreeDepth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.alpha=QuantumScale*(pixel.alpha-mid.alpha); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.alpha*error.alpha); if (IsNaN(distance) != 0) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.alpha+=count*QuantumScale* ClampPixel(pixel.alpha); else node_info->total_color.alpha+=count*QuantumScale* ClampPixel((MagickRealType) OpaqueAlpha); p+=count*GetPixelChannels(image); } if (cube_info->colors > cube_info->maximum_colors) { PruneToCubeDepth(cube_info,cube_info->root); break; } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } for (y++; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (cube_info->nodes > MaxNodes) { /* Prune one level if the color tree is too large. */ PruneLevel(cube_info,cube_info->root); cube_info->depth--; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) count) { /* Start at the root and descend the color cube tree. */ for (count=1; (x+(ssize_t) count) < (ssize_t) image->columns; count++) { PixelInfo packet; GetPixelInfoPixel(image,p+count*GetPixelChannels(image),&packet); if (IsPixelEquivalent(image,p,&packet) == MagickFalse) break; } AssociateAlphaPixel(image,cube_info,p,&pixel); index=MaxTreeDepth-1; bisect=((double) QuantumRange+1.0)/2.0; mid=midpoint; node_info=cube_info->root; for (level=1; level <= cube_info->depth; level++) { double distance; bisect*=0.5; id=ColorToNodeId(cube_info,&pixel,index); mid.red+=(id & 1) != 0 ? bisect : -bisect; mid.green+=(id & 2) != 0 ? bisect : -bisect; mid.blue+=(id & 4) != 0 ? bisect : -bisect; mid.alpha+=(id & 8) != 0 ? bisect : -bisect; if (node_info->child[id] == (NodeInfo *) NULL) { /* Set colors of new node to contain pixel. */ node_info->child[id]=GetNodeInfo(cube_info,id,level,node_info); if (node_info->child[id] == (NodeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","%s", image->filename); continue; } if (level == cube_info->depth) cube_info->colors++; } /* Approximate the quantization error represented by this node. */ node_info=node_info->child[id]; error.red=QuantumScale*(pixel.red-mid.red); error.green=QuantumScale*(pixel.green-mid.green); error.blue=QuantumScale*(pixel.blue-mid.blue); if (cube_info->associate_alpha != MagickFalse) error.alpha=QuantumScale*(pixel.alpha-mid.alpha); distance=(double) (error.red*error.red+error.green*error.green+ error.blue*error.blue+error.alpha*error.alpha); if (IsNaN(distance) != 0) distance=0.0; node_info->quantize_error+=count*sqrt(distance); cube_info->root->quantize_error+=node_info->quantize_error; index--; } /* Sum RGB for this leaf for later derivation of the mean cube color. */ node_info->number_unique+=count; node_info->total_color.red+=count*QuantumScale*ClampPixel(pixel.red); node_info->total_color.green+=count*QuantumScale*ClampPixel(pixel.green); node_info->total_color.blue+=count*QuantumScale*ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) node_info->total_color.alpha+=count*QuantumScale* ClampPixel(pixel.alpha); else node_info->total_color.alpha+=count*QuantumScale* ClampPixel((MagickRealType) OpaqueAlpha); p+=count*GetPixelChannels(image); } proceed=SetImageProgress(image,ClassifyImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) break; } image_view=DestroyCacheView(image_view); if (cube_info->quantize_info->colorspace != image->colorspace) if ((cube_info->quantize_info->colorspace != UndefinedColorspace) && (cube_info->quantize_info->colorspace != CMYKColorspace)) (void) TransformImageColorspace((Image *) image,sRGBColorspace,exception); return(y < (ssize_t) image->rows ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CloneQuantizeInfo() makes a duplicate of the given quantize info structure, % or if quantize info is NULL, a new one. % % The format of the CloneQuantizeInfo method is: % % QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o clone_info: Method CloneQuantizeInfo returns a duplicate of the given % quantize info, or if image info is NULL a new one. % % o quantize_info: a structure of type info. % */ MagickExport QuantizeInfo *CloneQuantizeInfo(const QuantizeInfo *quantize_info) { QuantizeInfo *clone_info; clone_info=(QuantizeInfo *) AcquireCriticalMemory(sizeof(*clone_info)); GetQuantizeInfo(clone_info); if (quantize_info == (QuantizeInfo *) NULL) return(clone_info); clone_info->number_colors=quantize_info->number_colors; clone_info->tree_depth=quantize_info->tree_depth; clone_info->dither_method=quantize_info->dither_method; clone_info->colorspace=quantize_info->colorspace; clone_info->measure_error=quantize_info->measure_error; return(clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o s e s t C o l o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClosestColor() traverses the color cube tree at a particular node and % determines which colormap entry best represents the input color. % % The format of the ClosestColor method is: % % void ClosestColor(const Image *image,CubeInfo *cube_info, % const NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void ClosestColor(const Image *image,CubeInfo *cube_info, const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) ClosestColor(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { double pixel; register double alpha, beta, distance; register DoublePixelPacket *magick_restrict q; register PixelInfo *magick_restrict p; /* Determine if this color is "closest". */ p=image->colormap+node_info->color_number; q=(&cube_info->target); alpha=1.0; beta=1.0; if (cube_info->associate_alpha != MagickFalse) { alpha=(double) (QuantumScale*p->alpha); beta=(double) (QuantumScale*q->alpha); } pixel=alpha*p->red-beta*q->red; distance=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*p->green-beta*q->green; distance+=pixel*pixel; if (distance <= cube_info->distance) { pixel=alpha*p->blue-beta*q->blue; distance+=pixel*pixel; if (distance <= cube_info->distance) { if (cube_info->associate_alpha != MagickFalse) { pixel=p->alpha-q->alpha; distance+=pixel*pixel; } if (distance <= cube_info->distance) { cube_info->distance=distance; cube_info->color_number=node_info->color_number; } } } } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p r e s s I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompressImageColormap() compresses an image colormap by removing any % duplicate or unused color entries. % % The format of the CompressImageColormap method is: % % MagickBooleanType CompressImageColormap(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 CompressImageColormap(Image *image, ExceptionInfo *exception) { QuantizeInfo quantize_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (IsPaletteImage(image) == MagickFalse) return(MagickFalse); GetQuantizeInfo(&quantize_info); quantize_info.number_colors=image->colors; quantize_info.tree_depth=MaxTreeDepth; return(QuantizeImage(&quantize_info,image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineImageColormap() traverses the color cube tree and notes each colormap % entry. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. % % The format of the DefineImageColormap method is: % % void DefineImageColormap(Image *image,CubeInfo *cube_info, % NodeInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o node_info: the address of a structure of type NodeInfo which points to a % node in the color cube tree that is to be pruned. % */ static void DefineImageColormap(Image *image,CubeInfo *cube_info, NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) DefineImageColormap(image,cube_info,node_info->child[i]); if (node_info->number_unique != 0) { register double alpha; register PixelInfo *magick_restrict q; /* Colormap entry is defined by the mean color in this cube. */ q=image->colormap+image->colors; alpha=(double) ((MagickOffsetType) node_info->number_unique); alpha=PerceptibleReciprocal(alpha); if (cube_info->associate_alpha == MagickFalse) { q->red=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.blue); q->alpha=(double) OpaqueAlpha; } else { double opacity; opacity=(double) (alpha*QuantumRange*node_info->total_color.alpha); q->alpha=(double) ClampToQuantum(opacity); if (q->alpha == OpaqueAlpha) { q->red=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*QuantumRange* node_info->total_color.blue); } else { double gamma; gamma=(double) (QuantumScale*q->alpha); gamma=PerceptibleReciprocal(gamma); q->red=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.red); q->green=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.green); q->blue=(double) ClampToQuantum(alpha*gamma*QuantumRange* node_info->total_color.blue); if (node_info->number_unique > cube_info->transparent_pixels) { cube_info->transparent_pixels=node_info->number_unique; cube_info->transparent_index=(ssize_t) image->colors; } } } node_info->color_number=image->colors++; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyCubeInfo() deallocates memory associated with an image. % % The format of the DestroyCubeInfo method is: % % DestroyCubeInfo(CubeInfo *cube_info) % % A description of each parameter follows: % % o cube_info: the address of a structure of type CubeInfo. % */ static void DestroyCubeInfo(CubeInfo *cube_info) { register Nodes *nodes; /* Release color cube tree storage. */ do { nodes=cube_info->node_queue->next; cube_info->node_queue->nodes=(NodeInfo *) RelinquishMagickMemory( cube_info->node_queue->nodes); cube_info->node_queue=(Nodes *) RelinquishMagickMemory( cube_info->node_queue); cube_info->node_queue=nodes; } while (cube_info->node_queue != (Nodes *) NULL); if (cube_info->memory_info != (MemoryInfo *) NULL) cube_info->memory_info=RelinquishVirtualMemory(cube_info->memory_info); cube_info->quantize_info=DestroyQuantizeInfo(cube_info->quantize_info); cube_info=(CubeInfo *) RelinquishMagickMemory(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyQuantizeInfo() deallocates memory associated with an QuantizeInfo % structure. % % The format of the DestroyQuantizeInfo method is: % % QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % */ MagickExport QuantizeInfo *DestroyQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); quantize_info->signature=(~MagickCoreSignature); quantize_info=(QuantizeInfo *) RelinquishMagickMemory(quantize_info); return(quantize_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DitherImage() distributes the difference between an original image and % the corresponding color reduced algorithm to neighboring pixels using % serpentine-scan Floyd-Steinberg error diffusion. DitherImage returns % MagickTrue if the image is dithered otherwise MagickFalse. % % The format of the DitherImage method is: % % MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o exception: return any errors or warnings in this structure. % */ static DoublePixelPacket **DestroyPixelThreadSet(DoublePixelPacket **pixels) { register ssize_t i; assert(pixels != (DoublePixelPacket **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (DoublePixelPacket *) NULL) pixels[i]=(DoublePixelPacket *) RelinquishMagickMemory(pixels[i]); pixels=(DoublePixelPacket **) RelinquishMagickMemory(pixels); return(pixels); } static DoublePixelPacket **AcquirePixelThreadSet(const size_t count) { DoublePixelPacket **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(DoublePixelPacket **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (DoublePixelPacket **) NULL) return((DoublePixelPacket **) NULL); (void) memset(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { pixels[i]=(DoublePixelPacket *) AcquireQuantumMemory(count,2* sizeof(**pixels)); if (pixels[i] == (DoublePixelPacket *) NULL) return(DestroyPixelThreadSet(pixels)); } return(pixels); } static inline ssize_t CacheOffset(CubeInfo *cube_info, const DoublePixelPacket *pixel) { #define RedShift(pixel) (((pixel) >> CacheShift) << (0*(8-CacheShift))) #define GreenShift(pixel) (((pixel) >> CacheShift) << (1*(8-CacheShift))) #define BlueShift(pixel) (((pixel) >> CacheShift) << (2*(8-CacheShift))) #define AlphaShift(pixel) (((pixel) >> CacheShift) << (3*(8-CacheShift))) ssize_t offset; offset=(ssize_t) (RedShift(ScaleQuantumToChar(ClampPixel(pixel->red))) | GreenShift(ScaleQuantumToChar(ClampPixel(pixel->green))) | BlueShift(ScaleQuantumToChar(ClampPixel(pixel->blue)))); if (cube_info->associate_alpha != MagickFalse) offset|=AlphaShift(ScaleQuantumToChar(ClampPixel(pixel->alpha))); return(offset); } static MagickBooleanType FloydSteinbergDither(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; const char *artifact; double amount; DoublePixelPacket **pixels; MagickBooleanType status; ssize_t y; /* Distribute quantization error using Floyd-Steinberg. */ pixels=AcquirePixelThreadSet(image->columns); if (pixels == (DoublePixelPacket **) NULL) return(MagickFalse); status=MagickTrue; amount=1.0; artifact=GetImageArtifact(image,"dither:diffusion-amount"); if (artifact != (const char *) NULL) amount=StringToDoubleInterval(artifact,1.0); image_view=AcquireAuthenticCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); CubeInfo cube; DoublePixelPacket *current, *previous; register Quantum *magick_restrict q; register ssize_t x; size_t index; ssize_t v; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } cube=(*cube_info); current=pixels[id]+(y & 0x01)*image->columns; previous=pixels[id]+((y+1) & 0x01)*image->columns; v=(ssize_t) ((y & 0x01) != 0 ? -1 : 1); for (x=0; x < (ssize_t) image->columns; x++) { DoublePixelPacket color, pixel; register ssize_t i; ssize_t u; u=(y & 0x01) != 0 ? (ssize_t) image->columns-1-x : x; AssociateAlphaPixel(image,&cube,q+u*GetPixelChannels(image),&pixel); if (x > 0) { pixel.red+=7.0*amount*current[u-v].red/16; pixel.green+=7.0*amount*current[u-v].green/16; pixel.blue+=7.0*amount*current[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=7.0*amount*current[u-v].alpha/16; } if (y > 0) { if (x < (ssize_t) (image->columns-1)) { pixel.red+=previous[u+v].red/16; pixel.green+=previous[u+v].green/16; pixel.blue+=previous[u+v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=previous[u+v].alpha/16; } pixel.red+=5.0*amount*previous[u].red/16; pixel.green+=5.0*amount*previous[u].green/16; pixel.blue+=5.0*amount*previous[u].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=5.0*amount*previous[u].alpha/16; if (x > 0) { pixel.red+=3.0*amount*previous[u-v].red/16; pixel.green+=3.0*amount*previous[u-v].green/16; pixel.blue+=3.0*amount*previous[u-v].blue/16; if (cube.associate_alpha != MagickFalse) pixel.alpha+=3.0*amount*previous[u-v].alpha/16; } } pixel.red=(double) ClampPixel(pixel.red); pixel.green=(double) ClampPixel(pixel.green); pixel.blue=(double) ClampPixel(pixel.blue); if (cube.associate_alpha != MagickFalse) pixel.alpha=(double) ClampPixel(pixel.alpha); i=CacheOffset(&cube,&pixel); if (cube.cache[i] < 0) { register NodeInfo *node_info; register size_t node_id; /* Identify the deepest node containing the pixel's color. */ node_info=cube.root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { node_id=ColorToNodeId(&cube,&pixel,index); if (node_info->child[node_id] == (NodeInfo *) NULL) break; node_info=node_info->child[node_id]; } /* Find closest color among siblings and their children. */ cube.target=pixel; cube.distance=(double) (4.0*(QuantumRange+1.0)*(QuantumRange+1.0)+ 1.0); ClosestColor(image,&cube,node_info->parent); cube.cache[i]=(ssize_t) cube.color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) cube.cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q+u*GetPixelChannels(image)); if (cube.quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum(image->colormap[index].red), q+u*GetPixelChannels(image)); SetPixelGreen(image,ClampToQuantum(image->colormap[index].green), q+u*GetPixelChannels(image)); SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue), q+u*GetPixelChannels(image)); if (cube.associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha), q+u*GetPixelChannels(image)); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; /* Store the error. */ AssociateAlphaPixelInfo(&cube,image->colormap+index,&color); current[u].red=pixel.red-color.red; current[u].green=pixel.green-color.green; current[u].blue=pixel.blue-color.blue; if (cube.associate_alpha != MagickFalse) current[u].alpha=pixel.alpha-color.alpha; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,DitherImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } image_view=DestroyCacheView(image_view); pixels=DestroyPixelThreadSet(pixels); return(MagickTrue); } static MagickBooleanType RiemersmaDither(Image *,CacheView *,CubeInfo *,const unsigned int, ExceptionInfo *); static void Riemersma(Image *image,CacheView *image_view,CubeInfo *cube_info, const size_t level,const unsigned int direction,ExceptionInfo *exception) { if (level == 1) switch (direction) { case WestGravity: { (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); break; } case EastGravity: { (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); break; } case NorthGravity: { (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); break; } case SouthGravity: { (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); break; } default: break; } else switch (direction) { case WestGravity: { Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); break; } case EastGravity: { Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); break; } case NorthGravity: { Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,EastGravity, exception); Riemersma(image,image_view,cube_info,level-1,NorthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); break; } case SouthGravity: { Riemersma(image,image_view,cube_info,level-1,EastGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,NorthGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,WestGravity, exception); Riemersma(image,image_view,cube_info,level-1,SouthGravity, exception); (void) RiemersmaDither(image,image_view,cube_info,SouthGravity, exception); Riemersma(image,image_view,cube_info,level-1,WestGravity, exception); break; } default: break; } } static MagickBooleanType RiemersmaDither(Image *image,CacheView *image_view, CubeInfo *cube_info,const unsigned int direction,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" DoublePixelPacket color, pixel; MagickBooleanType proceed; register CubeInfo *p; size_t index; p=cube_info; if ((p->x >= 0) && (p->x < (ssize_t) image->columns) && (p->y >= 0) && (p->y < (ssize_t) image->rows)) { register Quantum *magick_restrict q; register ssize_t i; /* Distribute error. */ q=GetCacheViewAuthenticPixels(image_view,p->x,p->y,1,1,exception); if (q == (Quantum *) NULL) return(MagickFalse); AssociateAlphaPixel(image,cube_info,q,&pixel); for (i=0; i < ErrorQueueLength; i++) { pixel.red+=p->weights[i]*p->error[i].red; pixel.green+=p->weights[i]*p->error[i].green; pixel.blue+=p->weights[i]*p->error[i].blue; if (cube_info->associate_alpha != MagickFalse) pixel.alpha+=p->weights[i]*p->error[i].alpha; } pixel.red=(double) ClampPixel(pixel.red); pixel.green=(double) ClampPixel(pixel.green); pixel.blue=(double) ClampPixel(pixel.blue); if (cube_info->associate_alpha != MagickFalse) pixel.alpha=(double) ClampPixel(pixel.alpha); i=CacheOffset(cube_info,&pixel); if (p->cache[i] < 0) { register NodeInfo *node_info; register size_t id; /* Identify the deepest node containing the pixel's color. */ node_info=p->root; for (index=MaxTreeDepth-1; (ssize_t) index > 0; index--) { id=ColorToNodeId(cube_info,&pixel,index); if (node_info->child[id] == (NodeInfo *) NULL) break; node_info=node_info->child[id]; } /* Find closest color among siblings and their children. */ p->target=pixel; p->distance=(double) (4.0*(QuantumRange+1.0)*((double) QuantumRange+1.0)+1.0); ClosestColor(image,p,node_info->parent); p->cache[i]=(ssize_t) p->color_number; } /* Assign pixel to closest colormap entry. */ index=(size_t) p->cache[i]; if (image->storage_class == PseudoClass) SetPixelIndex(image,(Quantum) index,q); if (cube_info->quantize_info->measure_error == MagickFalse) { SetPixelRed(image,ClampToQuantum(image->colormap[index].red),q); SetPixelGreen(image,ClampToQuantum(image->colormap[index].green),q); SetPixelBlue(image,ClampToQuantum(image->colormap[index].blue),q); if (cube_info->associate_alpha != MagickFalse) SetPixelAlpha(image,ClampToQuantum(image->colormap[index].alpha),q); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) return(MagickFalse); /* Propagate the error as the last entry of the error queue. */ (void) memmove(p->error,p->error+1,(ErrorQueueLength-1)* sizeof(p->error[0])); AssociateAlphaPixelInfo(cube_info,image->colormap+index,&color); p->error[ErrorQueueLength-1].red=pixel.red-color.red; p->error[ErrorQueueLength-1].green=pixel.green-color.green; p->error[ErrorQueueLength-1].blue=pixel.blue-color.blue; if (cube_info->associate_alpha != MagickFalse) p->error[ErrorQueueLength-1].alpha=pixel.alpha-color.alpha; proceed=SetImageProgress(image,DitherImageTag,p->offset,p->span); if (proceed == MagickFalse) return(MagickFalse); p->offset++; } switch (direction) { case WestGravity: p->x--; break; case EastGravity: p->x++; break; case NorthGravity: p->y--; break; case SouthGravity: p->y++; break; } return(MagickTrue); } static MagickBooleanType DitherImage(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; register ssize_t i; size_t depth; if (cube_info->quantize_info->dither_method != RiemersmaDitherMethod) return(FloydSteinbergDither(image,cube_info,exception)); /* Distribute quantization error along a Hilbert curve. */ (void) memset(cube_info->error,0,ErrorQueueLength*sizeof(*cube_info->error)); cube_info->x=0; cube_info->y=0; i=MagickMax((ssize_t) image->columns,(ssize_t) image->rows); for (depth=1; i != 0; depth++) i>>=1; if ((ssize_t) (1L << depth) < MagickMax((ssize_t) image->columns,(ssize_t) image->rows)) depth++; cube_info->offset=0; cube_info->span=(MagickSizeType) image->columns*image->rows; image_view=AcquireAuthenticCacheView(image,exception); if (depth > 1) Riemersma(image,image_view,cube_info,depth-1,NorthGravity,exception); status=RiemersmaDither(image,image_view,cube_info,ForgetGravity,exception); image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t C u b e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetCubeInfo() initialize the Cube data structure. % % The format of the GetCubeInfo method is: % % CubeInfo GetCubeInfo(const QuantizeInfo *quantize_info, % const size_t depth,const size_t maximum_colors) % % A description of each parameter follows. % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o depth: Normally, this integer value is zero or one. A zero or % one tells Quantize to choose a optimal tree depth of Log4(number_colors). % A tree of this depth generally allows the best representation of the % reference image with the least amount of memory and the fastest % computational speed. In some cases, such as an image with low color % dispersion (a few number of colors), a value other than % Log4(number_colors) is required. To expand the color tree completely, % use a value of 8. % % o maximum_colors: maximum colors. % */ static CubeInfo *GetCubeInfo(const QuantizeInfo *quantize_info, const size_t depth,const size_t maximum_colors) { CubeInfo *cube_info; double sum, weight; register ssize_t i; size_t length; /* Initialize tree to describe color cube_info. */ cube_info=(CubeInfo *) AcquireQuantumMemory(1,sizeof(*cube_info)); if (cube_info == (CubeInfo *) NULL) return((CubeInfo *) NULL); (void) memset(cube_info,0,sizeof(*cube_info)); cube_info->depth=depth; if (cube_info->depth > MaxTreeDepth) cube_info->depth=MaxTreeDepth; if (cube_info->depth < 2) cube_info->depth=2; cube_info->maximum_colors=maximum_colors; /* Initialize root node. */ cube_info->root=GetNodeInfo(cube_info,0,0,(NodeInfo *) NULL); if (cube_info->root == (NodeInfo *) NULL) return((CubeInfo *) NULL); cube_info->root->parent=cube_info->root; cube_info->quantize_info=CloneQuantizeInfo(quantize_info); if (cube_info->quantize_info->dither_method == NoDitherMethod) return(cube_info); /* Initialize dither resources. */ length=(size_t) (1UL << (4*(8-CacheShift))); cube_info->memory_info=AcquireVirtualMemory(length,sizeof(*cube_info->cache)); if (cube_info->memory_info == (MemoryInfo *) NULL) return((CubeInfo *) NULL); cube_info->cache=(ssize_t *) GetVirtualMemoryBlob(cube_info->memory_info); /* Initialize color cache. */ (void) memset(cube_info->cache,(-1),sizeof(*cube_info->cache)*length); /* Distribute weights along a curve of exponential decay. */ weight=1.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[ErrorQueueLength-i-1]=PerceptibleReciprocal(weight); weight*=exp(log(((double) QuantumRange+1.0))/(ErrorQueueLength-1.0)); } /* Normalize the weighting factors. */ weight=0.0; for (i=0; i < ErrorQueueLength; i++) weight+=cube_info->weights[i]; sum=0.0; for (i=0; i < ErrorQueueLength; i++) { cube_info->weights[i]/=weight; sum+=cube_info->weights[i]; } cube_info->weights[0]+=1.0-sum; return(cube_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t N o d e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetNodeInfo() allocates memory for a new node in the color cube tree and % presets all fields to zero. % % The format of the GetNodeInfo method is: % % NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, % const size_t level,NodeInfo *parent) % % A description of each parameter follows. % % o node: The GetNodeInfo method returns a pointer to a queue of nodes. % % o id: Specifies the child number of the node. % % o level: Specifies the level in the storage_class the node resides. % */ static NodeInfo *GetNodeInfo(CubeInfo *cube_info,const size_t id, const size_t level,NodeInfo *parent) { NodeInfo *node_info; if (cube_info->free_nodes == 0) { Nodes *nodes; /* Allocate a new queue of nodes. */ nodes=(Nodes *) AcquireQuantumMemory(1,sizeof(*nodes)); if (nodes == (Nodes *) NULL) return((NodeInfo *) NULL); nodes->nodes=(NodeInfo *) AcquireQuantumMemory(NodesInAList, sizeof(*nodes->nodes)); if (nodes->nodes == (NodeInfo *) NULL) return((NodeInfo *) NULL); nodes->next=cube_info->node_queue; cube_info->node_queue=nodes; cube_info->next_node=nodes->nodes; cube_info->free_nodes=NodesInAList; } cube_info->nodes++; cube_info->free_nodes--; node_info=cube_info->next_node++; (void) memset(node_info,0,sizeof(*node_info)); node_info->parent=parent; node_info->id=id; node_info->level=level; return(node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e Q u a n t i z e E r r o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageQuantizeError() measures the difference between the original % and quantized images. This difference is the total quantization error. % The error is computed by summing over all pixels in an image the distance % squared in RGB space between each reference pixel value and its quantized % value. These values are computed: % % o mean_error_per_pixel: This value is the mean error for any single % pixel in the image. % % o normalized_mean_square_error: This value is the normalized mean % quantization error for any single pixel in the image. This distance % measure is normalized to a range between 0 and 1. It is independent % of the range of red, green, and blue values in the image. % % o normalized_maximum_square_error: Thsi value is the normalized % maximum quantization error for any single pixel in the image. This % distance measure is normalized to a range between 0 and 1. It is % independent of the range of red, green, and blue values in your image. % % The format of the GetImageQuantizeError method is: % % MagickBooleanType GetImageQuantizeError(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 GetImageQuantizeError(Image *image, ExceptionInfo *exception) { CacheView *image_view; double alpha, area, beta, distance, maximum_error, mean_error, mean_error_per_pixel; ssize_t index, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); image->total_colors=GetNumberColors(image,(FILE *) NULL,exception); (void) memset(&image->error,0,sizeof(image->error)); if (image->storage_class == DirectClass) return(MagickTrue); alpha=1.0; beta=1.0; area=3.0*image->columns*image->rows; maximum_error=0.0; mean_error_per_pixel=0.0; mean_error=0.0; image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { index=(ssize_t) GetPixelIndex(image,p); if (image->alpha_trait == BlendPixelTrait) { alpha=(double) (QuantumScale*GetPixelAlpha(image,p)); beta=(double) (QuantumScale*image->colormap[index].alpha); } distance=fabs((double) (alpha*GetPixelRed(image,p)-beta* image->colormap[index].red)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelGreen(image,p)-beta* image->colormap[index].green)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; distance=fabs((double) (alpha*GetPixelBlue(image,p)-beta* image->colormap[index].blue)); mean_error_per_pixel+=distance; mean_error+=distance*distance; if (distance > maximum_error) maximum_error=distance; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->error.mean_error_per_pixel=(double) mean_error_per_pixel/area; image->error.normalized_mean_error=(double) QuantumScale*QuantumScale* mean_error/area; image->error.normalized_maximum_error=(double) QuantumScale*maximum_error; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t Q u a n t i z e I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetQuantizeInfo() initializes the QuantizeInfo structure. % % The format of the GetQuantizeInfo method is: % % GetQuantizeInfo(QuantizeInfo *quantize_info) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to a QuantizeInfo structure. % */ MagickExport void GetQuantizeInfo(QuantizeInfo *quantize_info) { (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(quantize_info != (QuantizeInfo *) NULL); (void) memset(quantize_info,0,sizeof(*quantize_info)); quantize_info->number_colors=256; quantize_info->dither_method=RiemersmaDitherMethod; quantize_info->colorspace=UndefinedColorspace; quantize_info->measure_error=MagickFalse; quantize_info->signature=MagickCoreSignature; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % K m e a n s I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % KmeansImage() applies k-means color reduction to an image. This is a % colorspace clustering or segmentation technique. % % The format of the KmeansImage method is: % % MagickBooleanType KmeansImage(Image *image,const size_t number_colors, % const size_t max_iterations,const double tolerance, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_colors: number of colors to use as seeds. % % o max_iterations: maximum number of iterations while converging. % % o tolerance: the maximum tolerance. % % o exception: return any errors or warnings in this structure. % */ typedef struct _KmeansInfo { double red, green, blue, alpha, black, count, distortion; } KmeansInfo; static KmeansInfo **DestroyKmeansThreadSet(KmeansInfo **kmeans_info) { register ssize_t i; assert(kmeans_info != (KmeansInfo **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (kmeans_info[i] != (KmeansInfo *) NULL) kmeans_info[i]=(KmeansInfo *) RelinquishMagickMemory(kmeans_info[i]); kmeans_info=(KmeansInfo **) RelinquishMagickMemory(kmeans_info); return(kmeans_info); } static KmeansInfo **AcquireKmeansThreadSet(const size_t number_colors) { KmeansInfo **kmeans_info; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); kmeans_info=(KmeansInfo **) AcquireQuantumMemory(number_threads, sizeof(*kmeans_info)); if (kmeans_info == (KmeansInfo **) NULL) return((KmeansInfo **) NULL); (void) memset(kmeans_info,0,number_threads*sizeof(*kmeans_info)); for (i=0; i < (ssize_t) number_threads; i++) { kmeans_info[i]=(KmeansInfo *) AcquireQuantumMemory(number_colors, sizeof(**kmeans_info)); if (kmeans_info[i] == (KmeansInfo *) NULL) return(DestroyKmeansThreadSet(kmeans_info)); } return(kmeans_info); } static inline double KmeansMetric(const Image *magick_restrict image, const Quantum *magick_restrict p,const PixelInfo *magick_restrict q) { register double gamma, metric, pixel; gamma=1.0; metric=0.0; if ((image->alpha_trait != UndefinedPixelTrait) || (q->alpha_trait != UndefinedPixelTrait)) { pixel=GetPixelAlpha(image,p)-(q->alpha_trait != UndefinedPixelTrait ? q->alpha : OpaqueAlpha); metric+=pixel*pixel; if (image->alpha_trait != UndefinedPixelTrait) gamma*=QuantumScale*GetPixelAlpha(image,p); if (q->alpha_trait != UndefinedPixelTrait) gamma*=QuantumScale*q->alpha; } if (image->colorspace == CMYKColorspace) { pixel=QuantumScale*(GetPixelBlack(image,p)-q->black); metric+=gamma*pixel*pixel; gamma*=QuantumScale*(QuantumRange-GetPixelBlack(image,p)); gamma*=QuantumScale*(QuantumRange-q->black); } metric*=3.0; pixel=QuantumScale*(GetPixelRed(image,p)-q->red); if (IsHueCompatibleColorspace(image->colorspace) != MagickFalse) { if (fabs((double) pixel) > 0.5) pixel-=0.5; pixel*=2.0; } metric+=gamma*pixel*pixel; pixel=QuantumScale*(GetPixelGreen(image,p)-q->green); metric+=gamma*pixel*pixel; pixel=QuantumScale*(GetPixelBlue(image,p)-q->blue); metric+=gamma*pixel*pixel; return(metric); } MagickExport MagickBooleanType KmeansImage(Image *image, const size_t number_colors,const size_t max_iterations,const double tolerance, ExceptionInfo *exception) { #define KmeansImageTag "Kmeans/Image" #define RandomColorComponent(info) (QuantumRange*GetPseudoRandomValue(info)) CacheView *image_view; const char *colors; double previous_tolerance; KmeansInfo **kmeans_pixels; MagickBooleanType verbose, status; register ssize_t n; size_t number_threads; 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); colors=GetImageArtifact(image,"kmeans:seed-colors"); if (colors == (const char *) NULL) { CubeInfo *cube_info; QuantizeInfo *quantize_info; size_t colors, depth; /* Seed clusters from color quantization. */ quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->colorspace=image->colorspace; quantize_info->number_colors=number_colors; quantize_info->dither_method=NoDitherMethod; colors=number_colors; for (depth=1; colors != 0; depth++) colors>>=2; cube_info=GetCubeInfo(quantize_info,depth,number_colors); if (cube_info == (CubeInfo *) NULL) { quantize_info=DestroyQuantizeInfo(quantize_info); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } status=ClassifyImageColors(cube_info,image,exception); if (status != MagickFalse) { if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); status=SetImageColormap(image,cube_info,exception); } DestroyCubeInfo(cube_info); quantize_info=DestroyQuantizeInfo(quantize_info); if (status == MagickFalse) return(status); } else { char color[MagickPathExtent]; register const char *p; /* Seed clusters from color list (e.g. red;green;blue). */ status=AcquireImageColormap(image,number_colors,exception); if (status == MagickFalse) return(status); for (n=0, p=colors; n < (ssize_t) image->colors; n++) { register const char *q; for (q=p; *q != '\0'; q++) if (*q == ';') break; (void) CopyMagickString(color,p,(size_t) MagickMin(q-p+1, MagickPathExtent)); (void) QueryColorCompliance(color,AllCompliance,image->colormap+n, exception); if (*q == '\0') { n++; break; } p=q+1; } if (n < (ssize_t) image->colors) { RandomInfo *random_info; /* Seed clusters from random values. */ random_info=AcquireRandomInfo(); for ( ; n < (ssize_t) image->colors; n++) { (void) QueryColorCompliance("#000",AllCompliance,image->colormap+n, exception); image->colormap[n].red=RandomColorComponent(random_info); image->colormap[n].green=RandomColorComponent(random_info); image->colormap[n].blue=RandomColorComponent(random_info); if (image->alpha_trait != BlendPixelTrait) image->colormap[n].alpha=RandomColorComponent(random_info); if (image->colorspace == CMYKColorspace) image->colormap[n].black=RandomColorComponent(random_info); } random_info=DestroyRandomInfo(random_info); } } /* Iterative refinement. */ kmeans_pixels=AcquireKmeansThreadSet(number_colors); if (kmeans_pixels == (KmeansInfo **) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); previous_tolerance=0.0; verbose=IsStringTrue(GetImageArtifact(image,"debug")); number_threads=(size_t) GetMagickResourceLimit(ThreadResource); image_view=AcquireAuthenticCacheView(image,exception); for (n=0; n < (ssize_t) max_iterations; n++) { double distortion; register ssize_t i; ssize_t y; for (i=0; i < (ssize_t) number_threads; i++) (void) memset(kmeans_pixels[i],0,image->colors*sizeof(*kmeans_pixels[i])); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); 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++) { double min_distance; register ssize_t i; ssize_t j; /* Assign each pixel whose mean has the least squared color distance. */ j=0; min_distance=KmeansMetric(image,q,image->colormap+0); for (i=1; i < (ssize_t) image->colors; i++) { double distance; if (min_distance <= MagickEpsilon) break; distance=KmeansMetric(image,q,image->colormap+i); if (distance < min_distance) { min_distance=distance; j=i; } } kmeans_pixels[id][j].red+=QuantumScale*GetPixelRed(image,q); kmeans_pixels[id][j].green+=QuantumScale*GetPixelGreen(image,q); kmeans_pixels[id][j].blue+=QuantumScale*GetPixelBlue(image,q); if (image->alpha_trait != BlendPixelTrait) kmeans_pixels[id][j].alpha+=QuantumScale*GetPixelAlpha(image,q); if (image->colorspace == CMYKColorspace) kmeans_pixels[id][j].black+=QuantumScale*GetPixelBlack(image,q); kmeans_pixels[id][j].count++; kmeans_pixels[id][j].distortion+=min_distance; SetPixelIndex(image,(Quantum) j,q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } if (status == MagickFalse) break; /* Reduce sums to [0] entry. */ for (i=1; i < (ssize_t) number_threads; i++) { register ssize_t j; for (j=0; j < (ssize_t) image->colors; j++) { kmeans_pixels[0][j].red+=kmeans_pixels[i][j].red; kmeans_pixels[0][j].green+=kmeans_pixels[i][j].green; kmeans_pixels[0][j].blue+=kmeans_pixels[i][j].blue; if (image->alpha_trait != BlendPixelTrait) kmeans_pixels[0][j].alpha+=kmeans_pixels[i][j].alpha; if (image->colorspace == CMYKColorspace) kmeans_pixels[0][j].black+=kmeans_pixels[i][j].black; kmeans_pixels[0][j].count+=kmeans_pixels[i][j].count; kmeans_pixels[0][j].distortion+=kmeans_pixels[i][j].distortion; } } /* Calculate the new means (centroids) of the pixels in the new clusters. */ distortion=0.0; for (i=0; i < (ssize_t) image->colors; i++) { double gamma; gamma=PerceptibleReciprocal((double) kmeans_pixels[0][i].count); image->colormap[i].red=gamma*QuantumRange*kmeans_pixels[0][i].red; image->colormap[i].green=gamma*QuantumRange*kmeans_pixels[0][i].green; image->colormap[i].blue=gamma*QuantumRange*kmeans_pixels[0][i].blue; if (image->alpha_trait != BlendPixelTrait) image->colormap[i].alpha=gamma*QuantumRange*kmeans_pixels[0][i].alpha; if (image->colorspace == CMYKColorspace) image->colormap[i].black=gamma*QuantumRange*kmeans_pixels[0][i].black; distortion+=kmeans_pixels[0][i].distortion; } if (verbose != MagickFalse) (void) FormatLocaleFile(stderr,"distortion[%.20g]: %*g %*g\n",(double) n, GetMagickPrecision(),distortion,GetMagickPrecision(), fabs(distortion-previous_tolerance)); if (fabs(distortion-previous_tolerance) <= tolerance) break; previous_tolerance=distortion; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,KmeansImageTag,(MagickOffsetType) n, max_iterations); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); kmeans_pixels=DestroyKmeansThreadSet(kmeans_pixels); if (image->progress_monitor != (MagickProgressMonitor) NULL) (void) SetImageProgress(image,KmeansImageTag,(MagickOffsetType) max_iterations-1,max_iterations); if (status == MagickFalse) return(status); return(SyncImage(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PosterizeImage() reduces the image to a limited number of colors for a % "poster" effect. % % The format of the PosterizeImage method is: % % MagickBooleanType PosterizeImage(Image *image,const size_t levels, % const DitherMethod dither_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: Specifies a pointer to an Image structure. % % o levels: Number of color levels allowed in each channel. Very low values % (2, 3, or 4) have the most visible effect. % % o dither_method: choose from UndefinedDitherMethod, NoDitherMethod, % RiemersmaDitherMethod, FloydSteinbergDitherMethod. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport MagickBooleanType PosterizeImage(Image *image,const size_t levels, const DitherMethod dither_method,ExceptionInfo *exception) { #define PosterizeImageTag "Posterize/Image" #define PosterizePixel(pixel) ClampToQuantum((MagickRealType) QuantumRange*( \ MagickRound(QuantumScale*pixel*(levels-1)))/MagickMax((ssize_t) levels-1,1)) CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; QuantizeInfo *quantize_info; register ssize_t i; 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); if (image->storage_class == PseudoClass) #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->colors,1) #endif for (i=0; i < (ssize_t) image->colors; i++) { /* Posterize colormap. */ if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].red=(double) PosterizePixel(image->colormap[i].red); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].green=(double) PosterizePixel(image->colormap[i].green); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].blue=(double) PosterizePixel(image->colormap[i].blue); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->colormap[i].alpha=(double) PosterizePixel(image->colormap[i].alpha); } /* Posterize 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 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++) { if ((GetPixelRedTraits(image) & UpdatePixelTrait) != 0) SetPixelRed(image,PosterizePixel(GetPixelRed(image,q)),q); if ((GetPixelGreenTraits(image) & UpdatePixelTrait) != 0) SetPixelGreen(image,PosterizePixel(GetPixelGreen(image,q)),q); if ((GetPixelBlueTraits(image) & UpdatePixelTrait) != 0) SetPixelBlue(image,PosterizePixel(GetPixelBlue(image,q)),q); if (((GetPixelBlackTraits(image) & UpdatePixelTrait) != 0) && (image->colorspace == CMYKColorspace)) SetPixelBlack(image,PosterizePixel(GetPixelBlack(image,q)),q); if (((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) && (image->alpha_trait == BlendPixelTrait)) SetPixelAlpha(image,PosterizePixel(GetPixelAlpha(image,q)),q); q+=GetPixelChannels(image); } 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,PosterizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); quantize_info=AcquireQuantizeInfo((ImageInfo *) NULL); quantize_info->number_colors=(size_t) MagickMin((ssize_t) levels*levels* levels,MaxColormapSize+1); quantize_info->dither_method=dither_method; quantize_info->tree_depth=MaxTreeDepth; status=QuantizeImage(quantize_info,image,exception); quantize_info=DestroyQuantizeInfo(quantize_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e C h i l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneChild() deletes the given node and merges its statistics into its % parent. % % The format of the PruneSubtree method is: % % PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneChild(CubeInfo *cube_info,const NodeInfo *node_info) { NodeInfo *parent; register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneChild(cube_info,node_info->child[i]); /* Merge color statistics into parent. */ parent=node_info->parent; parent->number_unique+=node_info->number_unique; parent->total_color.red+=node_info->total_color.red; parent->total_color.green+=node_info->total_color.green; parent->total_color.blue+=node_info->total_color.blue; parent->total_color.alpha+=node_info->total_color.alpha; parent->child[node_info->id]=(NodeInfo *) NULL; cube_info->nodes--; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e L e v e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneLevel() deletes all nodes at the bottom level of the color tree merging % their color statistics into their parent node. % % The format of the PruneLevel method is: % % PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneLevel(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneLevel(cube_info,node_info->child[i]); if (node_info->level == cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P r u n e T o C u b e D e p t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PruneToCubeDepth() deletes any nodes at a depth greater than % cube_info->depth while merging their color statistics into their parent % node. % % The format of the PruneToCubeDepth method is: % % PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void PruneToCubeDepth(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) PruneToCubeDepth(cube_info,node_info->child[i]); if (node_info->level > cube_info->depth) PruneChild(cube_info,node_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImage() analyzes the colors within a reference image and chooses a % fixed number of colors to represent the image. The goal of the algorithm % is to minimize the color difference between the input and output image while % minimizing the processing time. % % The format of the QuantizeImage method is: % % MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType QuantizeImage(const QuantizeInfo *quantize_info, Image *image,ExceptionInfo *exception) { CubeInfo *cube_info; MagickBooleanType status; size_t depth, maximum_colors; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); 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); maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; if (image->alpha_trait != BlendPixelTrait) { if (SetImageGray(image,exception) != MagickFalse) (void) SetGrayscaleImage(image,exception); } depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if ((quantize_info->dither_method != NoDitherMethod) && (depth > 2)) depth--; if ((image->alpha_trait == BlendPixelTrait) && (depth > 5)) depth--; if (SetImageGray(image,exception) != MagickFalse) depth=MaxTreeDepth; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,image,exception); if (status != MagickFalse) { /* Reduce the number of colors in the image. */ if (cube_info->colors > cube_info->maximum_colors) ReduceImageColors(image,cube_info); status=AssignImageColors(image,cube_info,exception); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u a n t i z e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeImages() analyzes the colors within a set of reference images and % chooses a fixed number of colors to represent the set. The goal of the % algorithm is to minimize the color difference between the input and output % images while minimizing the processing time. % % The format of the QuantizeImages method is: % % MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, % Image *images,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: Specifies a pointer to a list of Image structures. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType QuantizeImages(const QuantizeInfo *quantize_info, Image *images,ExceptionInfo *exception) { CubeInfo *cube_info; Image *image; MagickBooleanType proceed, status; MagickProgressMonitor progress_monitor; register ssize_t i; size_t depth, maximum_colors, number_images; assert(quantize_info != (const QuantizeInfo *) NULL); assert(quantize_info->signature == MagickCoreSignature); 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); if (GetNextImageInList(images) == (Image *) NULL) { /* Handle a single image with QuantizeImage. */ status=QuantizeImage(quantize_info,images,exception); return(status); } status=MagickFalse; maximum_colors=quantize_info->number_colors; if (maximum_colors == 0) maximum_colors=MaxColormapSize; if (maximum_colors > MaxColormapSize) maximum_colors=MaxColormapSize; depth=quantize_info->tree_depth; if (depth == 0) { size_t colors; /* Depth of color tree is: Log4(colormap size)+2. */ colors=maximum_colors; for (depth=1; colors != 0; depth++) colors>>=2; if (quantize_info->dither_method != NoDitherMethod) depth--; } /* Initialize color cube. */ cube_info=GetCubeInfo(quantize_info,depth,maximum_colors); if (cube_info == (CubeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return(MagickFalse); } number_images=GetImageListLength(images); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL, image->client_data); status=ClassifyImageColors(cube_info,image,exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor,image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } if (status != MagickFalse) { /* Reduce the number of colors in an image sequence. */ ReduceImageColors(images,cube_info); image=images; for (i=0; image != (Image *) NULL; i++) { progress_monitor=SetImageProgressMonitor(image,(MagickProgressMonitor) NULL,image->client_data); status=AssignImageColors(image,cube_info,exception); if (status == MagickFalse) break; (void) SetImageProgressMonitor(image,progress_monitor, image->client_data); proceed=SetImageProgress(image,AssignImageTag,(MagickOffsetType) i, number_images); if (proceed == MagickFalse) break; image=GetNextImageInList(image); } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u a n t i z e E r r o r F l a t t e n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QuantizeErrorFlatten() traverses the color cube and flattens the quantization % error into a sorted 1D array. This accelerates the color reduction process. % % Contributed by Yoya. % % The format of the QuantizeErrorFlatten method is: % % size_t QuantizeErrorFlatten(const CubeInfo *cube_info, % const NodeInfo *node_info,const ssize_t offset, % double *quantize_error) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is current pointer. % % o offset: quantize error offset. % % o quantize_error: the quantization error vector. % */ static size_t QuantizeErrorFlatten(const CubeInfo *cube_info, const NodeInfo *node_info,const ssize_t offset,double *quantize_error) { register ssize_t i; size_t n, number_children; if (offset >= (ssize_t) cube_info->nodes) return(0); quantize_error[offset]=node_info->quantize_error; n=1; number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children ; i++) if (node_info->child[i] != (NodeInfo *) NULL) n+=QuantizeErrorFlatten(cube_info,node_info->child[i],offset+n, quantize_error); return(n); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Reduce() traverses the color cube tree and prunes any node whose % quantization error falls below a particular threshold. % % The format of the Reduce method is: % % Reduce(CubeInfo *cube_info,const NodeInfo *node_info) % % A description of each parameter follows. % % o cube_info: A pointer to the Cube structure. % % o node_info: pointer to node in color cube tree that is to be pruned. % */ static void Reduce(CubeInfo *cube_info,const NodeInfo *node_info) { register ssize_t i; size_t number_children; /* Traverse any children. */ number_children=cube_info->associate_alpha == MagickFalse ? 8UL : 16UL; for (i=0; i < (ssize_t) number_children; i++) if (node_info->child[i] != (NodeInfo *) NULL) Reduce(cube_info,node_info->child[i]); if (node_info->quantize_error <= cube_info->pruning_threshold) PruneChild(cube_info,node_info); else { /* Find minimum pruning threshold. */ if (node_info->number_unique > 0) cube_info->colors++; if (node_info->quantize_error < cube_info->next_threshold) cube_info->next_threshold=node_info->quantize_error; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e d u c e I m a g e C o l o r s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReduceImageColors() repeatedly prunes the tree until the number of nodes % with n2 > 0 is less than or equal to the maximum number of colors allowed % in the output image. On any given iteration over the tree, it selects % those nodes whose E value is minimal for pruning and merges their % color statistics upward. It uses a pruning threshold, Ep, to govern % node selection as follows: % % Ep = 0 % while number of nodes with (n2 > 0) > required maximum number of colors % prune all nodes such that E <= Ep % Set Ep to minimum E in remaining nodes % % This has the effect of minimizing any quantization error when merging % two nodes together. % % When a node to be pruned has offspring, the pruning procedure invokes % itself recursively in order to prune the tree from the leaves upward. % n2, Sr, Sg, and Sb in a node being pruned are always added to the % corresponding data in that node's parent. This retains the pruned % node's color characteristics for later averaging. % % For each node, n2 pixels exist for which that node represents the % smallest volume in RGB space containing those pixel's colors. When n2 % > 0 the node will uniquely define a color in the output image. At the % beginning of reduction, n2 = 0 for all nodes except a the leaves of % the tree which represent colors present in the input image. % % The other pixel count, n1, indicates the total number of colors % within the cubic volume which the node represents. This includes n1 - % n2 pixels whose colors should be defined by nodes at a lower level in % the tree. % % The format of the ReduceImageColors method is: % % ReduceImageColors(const Image *image,CubeInfo *cube_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % */ static int QuantizeErrorCompare(const void *error_p,const void *error_q) { double *p, *q; p=(double *) error_p; q=(double *) error_q; if (*p > *q) return(1); if (fabs(*q-*p) <= MagickEpsilon) return(0); return(-1); } static void ReduceImageColors(const Image *image,CubeInfo *cube_info) { #define ReduceImageTag "Reduce/Image" MagickBooleanType proceed; MagickOffsetType offset; size_t span; cube_info->next_threshold=0.0; if (cube_info->colors > cube_info->maximum_colors) { double *quantize_error; /* Enable rapid reduction of the number of unique colors. */ quantize_error=(double *) AcquireQuantumMemory(cube_info->nodes, sizeof(*quantize_error)); if (quantize_error != (double *) NULL) { (void) QuantizeErrorFlatten(cube_info,cube_info->root,0, quantize_error); qsort(quantize_error,cube_info->nodes,sizeof(double), QuantizeErrorCompare); if (cube_info->nodes > (110*(cube_info->maximum_colors+1)/100)) cube_info->next_threshold=quantize_error[cube_info->nodes-110* (cube_info->maximum_colors+1)/100]; quantize_error=(double *) RelinquishMagickMemory(quantize_error); } } for (span=cube_info->colors; cube_info->colors > cube_info->maximum_colors; ) { cube_info->pruning_threshold=cube_info->next_threshold; cube_info->next_threshold=cube_info->root->quantize_error-1; cube_info->colors=0; Reduce(cube_info,cube_info->root); offset=(MagickOffsetType) span-cube_info->colors; proceed=SetImageProgress(image,ReduceImageTag,offset,span- cube_info->maximum_colors+1); if (proceed == MagickFalse) break; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImage() replaces the colors of an image with the closest of the colors % from the reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, % Image *image,const Image *remap_image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o image: the image. % % o remap_image: the reference image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RemapImage(const QuantizeInfo *quantize_info, Image *image,const Image *remap_image,ExceptionInfo *exception) { CubeInfo *cube_info; MagickBooleanType status; /* Initialize color cube. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(remap_image != (Image *) NULL); assert(remap_image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; status=AssignImageColors(image,cube_info,exception); } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e m a p I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RemapImages() replaces the colors of a sequence of images with the % closest color from a reference image. % % The format of the RemapImage method is: % % MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, % Image *images,Image *remap_image,ExceptionInfo *exception) % % A description of each parameter follows: % % o quantize_info: Specifies a pointer to an QuantizeInfo structure. % % o images: the image sequence. % % o remap_image: the reference image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RemapImages(const QuantizeInfo *quantize_info, Image *images,const Image *remap_image,ExceptionInfo *exception) { CubeInfo *cube_info; Image *image; MagickBooleanType status; 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; if (remap_image == (Image *) NULL) { /* Create a global colormap for an image sequence. */ status=QuantizeImages(quantize_info,images,exception); return(status); } /* Classify image colors from the reference image. */ cube_info=GetCubeInfo(quantize_info,MaxTreeDepth, quantize_info->number_colors); if (cube_info == (CubeInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); status=ClassifyImageColors(cube_info,remap_image,exception); if (status != MagickFalse) { /* Classify image colors from the reference image. */ cube_info->quantize_info->number_colors=cube_info->colors; image=images; for ( ; image != (Image *) NULL; image=GetNextImageInList(image)) { status=AssignImageColors(image,cube_info,exception); if (status == MagickFalse) break; } } DestroyCubeInfo(cube_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t G r a y s c a l e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetGrayscaleImage() converts an image to a PseudoClass grayscale image. % % The format of the SetGrayscaleImage method is: % % MagickBooleanType SetGrayscaleImage(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { double intensity; PixelInfo *color_1, *color_2; color_1=(PixelInfo *) x; color_2=(PixelInfo *) y; intensity=GetPixelInfoIntensity((const Image *) NULL,color_1)- GetPixelInfoIntensity((const Image *) NULL,color_2); if (intensity < (double) INT_MIN) intensity=(double) INT_MIN; if (intensity > (double) INT_MAX) intensity=(double) INT_MAX; return((int) intensity); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static MagickBooleanType SetGrayscaleImage(Image *image, ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; PixelInfo *colormap; register ssize_t i; size_t extent; ssize_t *colormap_index, j, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->type != GrayscaleType) (void) TransformImageColorspace(image,GRAYColorspace,exception); extent=MagickMax(image->colors+1,MagickMax(MaxColormapSize,MaxMap+1)); colormap_index=(ssize_t *) AcquireQuantumMemory(extent, sizeof(*colormap_index)); if (colormap_index == (ssize_t *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); if (image->storage_class != PseudoClass) { (void) memset(colormap_index,(-1),extent*sizeof(*colormap_index)); if (AcquireImageColormap(image,MaxColormapSize,exception) == MagickFalse) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } image->colors=0; 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++) { register size_t intensity; intensity=ScaleQuantumToMap(GetPixelRed(image,q)); if (colormap_index[intensity] < 0) { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_SetGrayscaleImage) #endif if (colormap_index[intensity] < 0) { colormap_index[intensity]=(ssize_t) image->colors; image->colormap[image->colors].red=(double) GetPixelRed(image,q); image->colormap[image->colors].green=(double) GetPixelGreen(image,q); image->colormap[image->colors].blue=(double) GetPixelBlue(image,q); image->colors++; } } SetPixelIndex(image,(Quantum) colormap_index[intensity],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); } (void) memset(colormap_index,0,extent*sizeof(*colormap_index)); for (i=0; i < (ssize_t) image->colors; i++) image->colormap[i].alpha=(double) i; qsort((void *) image->colormap,image->colors,sizeof(PixelInfo), IntensityCompare); colormap=(PixelInfo *) AcquireQuantumMemory(image->colors,sizeof(*colormap)); if (colormap == (PixelInfo *) NULL) { colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } j=0; colormap[j]=image->colormap[0]; for (i=0; i < (ssize_t) image->colors; i++) { if (IsPixelInfoEquivalent(&colormap[j],&image->colormap[i]) == MagickFalse) { j++; colormap[j]=image->colormap[i]; } colormap_index[(ssize_t) image->colormap[i].alpha]=j; } image->colors=(size_t) (j+1); image->colormap=(PixelInfo *) RelinquishMagickMemory(image->colormap); image->colormap=colormap; 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++) { SetPixelIndex(image,(Quantum) colormap_index[ScaleQuantumToMap( GetPixelIndex(image,q))],q); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } image_view=DestroyCacheView(image_view); colormap_index=(ssize_t *) RelinquishMagickMemory(colormap_index); image->type=GrayscaleType; if (SetImageMonochrome(image,exception) != MagickFalse) image->type=BilevelType; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t I m a g e C o l o r m a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetImageColormap() traverses the color cube tree and sets the colormap of % the image. A colormap entry is any node in the color cube tree where the % of unique colors is not zero. % % The format of the SetImageColormap method is: % % MagickBooleanType SetImageColormap(Image *image,CubeInfo *cube_info, % ExceptionInfo *node_info) % % A description of each parameter follows. % % o image: the image. % % o cube_info: A pointer to the Cube structure. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType SetImageColormap(Image *image,CubeInfo *cube_info, ExceptionInfo *exception) { size_t number_colors; number_colors=MagickMax(cube_info->maximum_colors,cube_info->colors); if (AcquireImageColormap(image,number_colors,exception) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); image->colors=0; DefineImageColormap(image,cube_info,cube_info->root); if (image->colors != number_colors) { image->colormap=(PixelInfo *) ResizeQuantumMemory(image->colormap, image->colors+1,sizeof(*image->colormap)); if (image->colormap == (PixelInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); } return(MagickTrue); }
GB_unop__conj_fc32_fc32.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__conj_fc32_fc32) // op(A') function: GB (_unop_tran__conj_fc32_fc32) // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = conjf (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 = conjf (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] = conjf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CONJ || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__conj_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] = conjf (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] = conjf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__conj_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
spmm_x_csr.c
#include "alphasparse/kernel.h" #include "alphasparse/util.h" #include "alphasparse/opt.h" #include <memory.h> #ifdef _OPENMP #include <omp.h> #endif alphasparse_status_t ONAME(const ALPHA_SPMAT_CSR *A, const ALPHA_SPMAT_CSR *B, ALPHA_SPMAT_CSR **matC) { check_return(B->cols != A->rows, ALPHA_SPARSE_STATUS_INVALID_VALUE); ALPHA_SPMAT_CSR *mat = alpha_malloc(sizeof(ALPHA_SPMAT_CSR)); *matC = mat; mat->rows = A->rows; mat->cols = B->cols; ALPHA_INT m = A->rows; ALPHA_INT n = B->cols; ALPHA_INT64 flop[m]; memset(flop,'\0',m*sizeof(ALPHA_INT64)); ALPHA_INT *row_offset = alpha_memalign(sizeof(ALPHA_INT) * (m + 1), DEFAULT_ALIGNMENT); mat->rows_start = row_offset; mat->rows_end = row_offset + 1; memset(row_offset,'\0',sizeof(ALPHA_INT)*(m+1)); ALPHA_INT num_thread = alpha_get_thread_num(); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT ar = 0; ar < m; ar++) { bool flag[n]; memset(flag, '\0', sizeof(bool) * n); for (ALPHA_INT ai = A->rows_start[ar]; ai < A->rows_end[ar]; ai++) { ALPHA_INT br = A->col_indx[ai]; flop[ar] += B->rows_end[br] - B->rows_start[br]; for (ALPHA_INT bi = B->rows_start[br]; bi < B->rows_end[br]; bi++) { if (!flag[B->col_indx[bi]]) { mat->rows_end[ar] += 1; flag[B->col_indx[bi]] = true; } } } } for(ALPHA_INT i = 1;i < m;++i) { flop[i] += flop[i - 1]; mat->rows_end[i] += mat->rows_end[i-1]; } ALPHA_INT nnz = mat->rows_end[m-1]; mat->col_indx = alpha_memalign(nnz * sizeof(ALPHA_INT), DEFAULT_ALIGNMENT); mat->values = alpha_memalign(nnz * sizeof(ALPHA_Number), DEFAULT_ALIGNMENT); #ifdef _OPENMP #pragma omp parallel for num_threads(num_thread) #endif for (ALPHA_INT ar = 0; ar < m; ar++) { ALPHA_Number values[n]; memset(values, '\0', sizeof(ALPHA_Number) * n); bool write_back[n]; memset(write_back, '\0', sizeof(bool) * n); for (ALPHA_INT ai = A->rows_start[ar]; ai < A->rows_end[ar]; ai++) { ALPHA_INT br = A->col_indx[ai]; ALPHA_Number av = A->values[ai]; ALPHA_INT bis = B->rows_start[br]; ALPHA_INT bie = B->rows_end[br]; ALPHA_INT bil = bie-bis; const ALPHA_INT* B_col = &B->col_indx[bis]; const ALPHA_Number* B_val = &B->values[bis]; ALPHA_INT bi = 0; for (; bi < bil-3; bi+=4) { ALPHA_INT bc0 = B_col[bi]; ALPHA_INT bc1 = B_col[bi+1]; ALPHA_INT bc2 = B_col[bi+2]; ALPHA_INT bc3 = B_col[bi+3]; ALPHA_Number bv0 = B_val[bi]; ALPHA_Number bv1 = B_val[bi+1]; ALPHA_Number bv2 = B_val[bi+2]; ALPHA_Number bv3 = B_val[bi+3]; alpha_madde(values[bc0], av, bv0); alpha_madde(values[bc1], av, bv1); alpha_madde(values[bc2], av, bv2); alpha_madde(values[bc3], av, bv3); write_back[bc0] = true; write_back[bc1] = true; write_back[bc2] = true; write_back[bc3] = true; } for (; bi < bil; bi++) { ALPHA_INT bc = B_col[bi]; ALPHA_Number bv = B_val[bi]; alpha_madde(values[bc], av, bv); write_back[bc] = true; } } ALPHA_INT index = mat->rows_start[ar]; for (ALPHA_INT c = 0; c < n; c++) { if (write_back[c]) { mat->col_indx[index] = c; mat->values[index] = values[c]; index += 1; } } } return ALPHA_SPARSE_STATUS_SUCCESS; }
GB_unop__atanh_fp32_fp32.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__atanh_fp32_fp32 // op(A') function: GB_unop_tran__atanh_fp32_fp32 // C type: float // A type: float // cast: float cij = aij // unaryop: cij = atanhf (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 = atanhf (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] = atanhf (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_ATANH || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__atanh_fp32_fp32 ( float *Cx, // Cx and Ax may be aliased const float *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 (float), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = atanhf (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 ; float aij = Ax [p] ; float z = aij ; Cx [p] = atanhf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__atanh_fp32_fp32 ( 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
builder.h
// Copyright (c) 2015, The Regents of the University of California (Regents) // See LICENSE.txt for license details #ifndef BUILDER_H_ #define BUILDER_H_ #include <algorithm> #include <cinttypes> #include <fstream> #include <functional> #include <type_traits> #include <utility> #include "command_line.h" #include "generator.h" #include "graph.h" #include "platform_atomics.h" #include "pvector.h" #include "reader.h" #include "timer.h" #include "util.h" /* GAP Benchmark Suite Class: BuilderBase Author: Scott Beamer Given arguements from the command line (cli), returns a built graph - MakeGraph() will parse cli and obtain edgelist and call MakeGraphFromEL(edgelist) to perform actual graph construction - edgelist can be from file (reader) or synthetically generated (generator) - Common case: BuilderBase typedef'd (w/ params) to be Builder (benchmark.h) */ template <typename NodeID_, typename DestID_ = NodeID_, typename WeightT_ = NodeID_, bool invert = true> class BuilderBase { typedef EdgePair<NodeID_, DestID_> Edge; typedef pvector<Edge> EdgeList; const CLBase &cli_; bool symmetrize_; bool needs_weights_; bool in_place_ = false; int64_t num_nodes_ = -1; public: explicit BuilderBase(const CLBase &cli) : cli_(cli) { symmetrize_ = cli_.symmetrize(); needs_weights_ = !std::is_same<NodeID_, DestID_>::value; in_place_ = cli_.in_place(); if (in_place_ && needs_weights_) { std::cout << "In-place building (-m) does not support weighted graphs" << std::endl; exit(-30); } } DestID_ GetSource(EdgePair<NodeID_, NodeID_> e) { return e.u; } DestID_ GetSource(EdgePair<NodeID_, NodeWeight<NodeID_, WeightT_>> e) { return NodeWeight<NodeID_, WeightT_>(e.u, e.v.w); } NodeID_ FindMaxNodeID(const EdgeList &el) { NodeID_ max_seen = 0; #pragma omp parallel for reduction(max : max_seen) for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; max_seen = std::max(max_seen, e.u); max_seen = std::max(max_seen, (NodeID_) e.v); } return max_seen; } pvector<NodeID_> CountDegrees(const EdgeList &el, bool transpose) { pvector<NodeID_> degrees(num_nodes_, 0); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) fetch_and_add(degrees[e.u], 1); if ((symmetrize_ && !in_place_) || (!symmetrize_ && transpose)) fetch_and_add(degrees[(NodeID_) e.v], 1); } return degrees; } static pvector<SGOffset> PrefixSum(const pvector<NodeID_> &degrees) { pvector<SGOffset> sums(degrees.size() + 1); SGOffset total = 0; for (size_t n=0; n < degrees.size(); n++) { sums[n] = total; total += degrees[n]; } sums[degrees.size()] = total; return sums; } static pvector<SGOffset> ParallelPrefixSum(const pvector<NodeID_> &degrees) { const size_t block_size = 1<<20; const size_t num_blocks = (degrees.size() + block_size - 1) / block_size; pvector<SGOffset> local_sums(num_blocks); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset lsum = 0; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) lsum += degrees[i]; local_sums[block] = lsum; } pvector<SGOffset> bulk_prefix(num_blocks+1); SGOffset total = 0; for (size_t block=0; block < num_blocks; block++) { bulk_prefix[block] = total; total += local_sums[block]; } bulk_prefix[num_blocks] = total; pvector<SGOffset> prefix(degrees.size() + 1); #pragma omp parallel for for (size_t block=0; block < num_blocks; block++) { SGOffset local_total = bulk_prefix[block]; size_t block_end = std::min((block + 1) * block_size, degrees.size()); for (size_t i=block * block_size; i < block_end; i++) { prefix[i] = local_total; local_total += degrees[i]; } } prefix[degrees.size()] = bulk_prefix[num_blocks]; return prefix; } // Removes self-loops and redundant edges // Side effect: neighbor IDs will be sorted void SquishCSR(const CSRGraph<NodeID_, DestID_, invert> &g, bool transpose, DestID_*** sq_index, DestID_** sq_neighs) { pvector<NodeID_> diffs(g.num_nodes()); DestID_ *n_start, *n_end; #pragma omp parallel for private(n_start, n_end) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) { n_start = g.in_neigh(n).begin(); n_end = g.in_neigh(n).end(); } else { n_start = g.out_neigh(n).begin(); n_end = g.out_neigh(n).end(); } std::sort(n_start, n_end); DestID_ *new_end = std::unique(n_start, n_end); new_end = std::remove(n_start, new_end, n); diffs[n] = new_end - n_start; } pvector<SGOffset> sq_offsets = ParallelPrefixSum(diffs); *sq_neighs = new DestID_[sq_offsets[g.num_nodes()]]; *sq_index = CSRGraph<NodeID_, DestID_>::GenIndex(sq_offsets, *sq_neighs); #pragma omp parallel for private(n_start) for (NodeID_ n=0; n < g.num_nodes(); n++) { if (transpose) n_start = g.in_neigh(n).begin(); else n_start = g.out_neigh(n).begin(); std::copy(n_start, n_start+diffs[n], (*sq_index)[n]); } } CSRGraph<NodeID_, DestID_, invert> SquishGraph( const CSRGraph<NodeID_, DestID_, invert> &g) { DestID_ **out_index, *out_neighs, **in_index, *in_neighs; SquishCSR(g, false, &out_index, &out_neighs); if (g.directed()) { if (invert) SquishCSR(g, true, &in_index, &in_neighs); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs, in_index, in_neighs); } else { return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), out_index, out_neighs); } } /* In-Place Graph Building Steps - sort edges and squish (remove self loops and redundant edges) - overwrite EdgeList's memory with outgoing neighbors - if graph not being symmetrized - finalize structures and make incoming structures if requested - if being symmetrized - search for needed inverses, make room for them, add them in place */ void MakeCSRInPlace(EdgeList &el, DestID_*** index, DestID_** neighs, DestID_*** inv_index, DestID_** inv_neighs) { // preprocess EdgeList - sort & squish in place std::sort(el.begin(), el.end()); auto new_end = std::unique(el.begin(), el.end()); el.resize(new_end - el.begin()); auto self_loop = [](Edge e){ return e.u == e.v; }; new_end = std::remove_if(el.begin(), el.end(), self_loop); el.resize(new_end - el.begin()); // analyze EdgeList and repurpose it for outgoing edges pvector<NodeID_> degrees = CountDegrees(el, false); pvector<SGOffset> offsets = ParallelPrefixSum(degrees); pvector<NodeID_> indegrees = CountDegrees(el, true); *neighs = reinterpret_cast<DestID_*>(el.data()); for (Edge e : el) (*neighs)[offsets[e.u]++] = e.v; size_t num_edges = el.size(); el.leak(); // revert offsets by shifting them down for (NodeID_ n = num_nodes_; n >= 0; n--) offsets[n] = n != 0 ? offsets[n-1] : 0; if (!symmetrize_) { // not going to symmetrize so no need to add edges size_t new_size = num_edges * sizeof(DestID_); *neighs = static_cast<DestID_*>(std::realloc(*neighs, new_size)); *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); if (invert) { // create inv_neighs & inv_index for incoming edges pvector<SGOffset> inoffsets = ParallelPrefixSum(indegrees); *inv_neighs = new DestID_[inoffsets[num_nodes_]]; *inv_index = CSRGraph<NodeID_, DestID_>::GenIndex(inoffsets, *inv_neighs); for (NodeID_ u = 0; u < num_nodes_; u++) { for (DestID_* it = (*index)[u]; it < (*index)[u+1]; it++) { NodeID_ v = static_cast<NodeID_>(*it); (*inv_neighs)[inoffsets[v]] = u; inoffsets[v]++; } } } } else { // symmetrize graph by adding missing inverse edges // Step 1 - count number of needed inverses pvector<NodeID_> invs_needed(num_nodes_, 0); for (NodeID_ u = 0; u < num_nodes_; u++) { for (SGOffset i = offsets[u]; i < offsets[u+1]; i++) { DestID_ v = (*neighs)[i]; bool inv_found = std::binary_search(*neighs + offsets[v], *neighs + offsets[v+1], static_cast<DestID_>(u)); if (!inv_found) invs_needed[v]++; } } // increase offsets to account for missing inverses, realloc neighs SGOffset total_missing_inv = 0; for (NodeID_ n = 0; n <= num_nodes_; n++) { offsets[n] += total_missing_inv; total_missing_inv += invs_needed[n]; } size_t newsize = (offsets[num_nodes_] * sizeof(DestID_)); *neighs = static_cast<DestID_*>(std::realloc(*neighs, newsize)); if (*neighs == nullptr) { std::cout << "Call to realloc() failed" << std::endl; exit(-33); } // Step 2 - spread out existing neighs to make room for inverses // copies backwards (overwrites) and inserts free space at starts SGOffset tail_index = offsets[num_nodes_] - 1; for (NodeID_ n = num_nodes_ - 1; n >= 0; n--) { SGOffset new_start = offsets[n] + invs_needed[n]; for (SGOffset i = offsets[n+1]-1; i >= new_start; i--) { (*neighs)[tail_index] = (*neighs)[i - total_missing_inv]; tail_index--; } total_missing_inv -= invs_needed[n]; tail_index -= invs_needed[n]; } // Step 3 - add missing inverse edges into free spaces from Step 2 for (NodeID_ u = 0; u < num_nodes_; u++) { for (SGOffset i = offsets[u] + invs_needed[u]; i < offsets[u+1]; i++) { DestID_ v = (*neighs)[i]; bool inv_found = std::binary_search( *neighs + offsets[v] + invs_needed[v], *neighs + offsets[v+1], static_cast<DestID_>(u)); if (!inv_found) { (*neighs)[offsets[v] + invs_needed[v] -1] = static_cast<DestID_>(u); invs_needed[v]--; } } } for (NodeID_ n = 0; n < num_nodes_; n++) std::sort(*neighs + offsets[n], *neighs + offsets[n+1]); *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); } } /* Graph Bulding Steps (for CSR): - Read edgelist once to determine vertex degrees (CountDegrees) - Determine vertex offsets by a prefix sum (ParallelPrefixSum) - Allocate storage and set points according to offsets (GenIndex) - Copy edges into storage */ void MakeCSR(const EdgeList &el, bool transpose, DestID_*** index, DestID_** neighs) { pvector<NodeID_> degrees = CountDegrees(el, transpose); pvector<SGOffset> offsets = ParallelPrefixSum(degrees); *neighs = new DestID_[offsets[num_nodes_]]; *index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, *neighs); #pragma omp parallel for for (auto it = el.begin(); it < el.end(); it++) { Edge e = *it; if (symmetrize_ || (!symmetrize_ && !transpose)) (*neighs)[fetch_and_add(offsets[e.u], 1)] = e.v; if (symmetrize_ || (!symmetrize_ && transpose)) (*neighs)[fetch_and_add(offsets[static_cast<NodeID_>(e.v)], 1)] = GetSource(e); } } CSRGraph<NodeID_, DestID_, invert> MakeGraphFromEL(EdgeList &el) { DestID_ **index = nullptr, **inv_index = nullptr; DestID_ *neighs = nullptr, *inv_neighs = nullptr; Timer t; t.Start(); if (num_nodes_ == -1) num_nodes_ = FindMaxNodeID(el)+1; if (needs_weights_) Generator<NodeID_, DestID_, WeightT_>::InsertWeights(el); if (in_place_) { MakeCSRInPlace(el, &index, &neighs, &inv_index, &inv_neighs); } else { MakeCSR(el, false, &index, &neighs); if (!symmetrize_ && invert) { MakeCSR(el, true, &inv_index, &inv_neighs); } } t.Stop(); PrintTime("Build Time", t.Seconds()); if (symmetrize_) return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs); else return CSRGraph<NodeID_, DestID_, invert>(num_nodes_, index, neighs, inv_index, inv_neighs); } CSRGraph<NodeID_, DestID_, invert> MakeGraph() { CSRGraph<NodeID_, DestID_, invert> g; { // extra scope to trigger earlier deletion of el (save memory) EdgeList el; if (cli_.filename() != "") { Reader<NodeID_, DestID_, WeightT_, invert> r(cli_.filename()); if ((r.GetSuffix() == ".sg") || (r.GetSuffix() == ".wsg")) { return r.ReadSerializedGraph(); } else { el = r.ReadFile(needs_weights_); } } else if (cli_.scale() != -1) { Generator<NodeID_, DestID_> gen(cli_.scale(), cli_.degree()); el = gen.GenerateEL(cli_.uniform()); } g = MakeGraphFromEL(el); } if (in_place_) return g; else return SquishGraph(g); } // Relabels (and rebuilds) graph by order of decreasing degree static CSRGraph<NodeID_, DestID_, invert> RelabelByDegree( const CSRGraph<NodeID_, DestID_, invert> &g) { if (g.directed()) { std::cout << "Cannot relabel directed graph" << std::endl; std::exit(-11); } Timer t; t.Start(); typedef std::pair<int64_t, NodeID_> degree_node_p; pvector<degree_node_p> degree_id_pairs(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) degree_id_pairs[n] = std::make_pair(g.out_degree(n), n); std::sort(degree_id_pairs.begin(), degree_id_pairs.end(), std::greater<degree_node_p>()); pvector<NodeID_> degrees(g.num_nodes()); pvector<NodeID_> new_ids(g.num_nodes()); #pragma omp parallel for for (NodeID_ n=0; n < g.num_nodes(); n++) { degrees[n] = degree_id_pairs[n].first; new_ids[degree_id_pairs[n].second] = n; } pvector<SGOffset> offsets = ParallelPrefixSum(degrees); DestID_* neighs = new DestID_[offsets[g.num_nodes()]]; DestID_** index = CSRGraph<NodeID_, DestID_>::GenIndex(offsets, neighs); #pragma omp parallel for for (NodeID_ u=0; u < g.num_nodes(); u++) { for (NodeID_ v : g.out_neigh(u)) neighs[offsets[new_ids[u]]++] = new_ids[v]; std::sort(index[new_ids[u]], index[new_ids[u]+1]); } t.Stop(); PrintTime("Relabel", t.Seconds()); return CSRGraph<NodeID_, DestID_, invert>(g.num_nodes(), index, neighs); } }; #endif // BUILDER_H_
GB_binop__ne_int8.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__ne_int8) // A.*B function (eWiseMult): GB (_AemultB_08__ne_int8) // A.*B function (eWiseMult): GB (_AemultB_02__ne_int8) // A.*B function (eWiseMult): GB (_AemultB_04__ne_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ne_int8) // A*D function (colscale): GB (_AxD__ne_int8) // D*A function (rowscale): GB (_DxB__ne_int8) // C+=B function (dense accum): GB (_Cdense_accumB__ne_int8) // C+=b function (dense accum): GB (_Cdense_accumb__ne_int8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ne_int8) // C=scalar+B GB (_bind1st__ne_int8) // C=scalar+B' GB (_bind1st_tran__ne_int8) // C=A+scalar GB (_bind2nd__ne_int8) // C=A'+scalar GB (_bind2nd_tran__ne_int8) // C type: bool // A type: int8_t // B,b type: int8_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_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) \ int8_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // 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_NE || GxB_NO_INT8 || GxB_NO_NE_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 //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__ne_int8) ( 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__ne_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 #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__ne_int8) ( 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 int8_t int8_t bwork = (*((int8_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__ne_int8) ( 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_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ne_int8) ( 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_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ne_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 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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__ne_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__ne_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__ne_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__ne_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__ne_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 bool *Cx = (bool *) 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] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__ne_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 ; bool *Cx = (bool *) 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] = (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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB (_bind1st_tran__ne_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] = (aij != y) ; \ } GrB_Info GB (_bind2nd_tran__ne_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
omp.c
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <sys/time.h> #include <omp.h> double get_walltime() { struct timeval tp; gettimeofday(&tp, NULL); return (double) (tp.tv_sec + tp.tv_usec*1e-6); } void force_repulsionStatic(int np, const double *pos, double L, double krepulsion, double *forcesStatic, int cs) { int i, j; double posi [4]; double rvec [4]; double s2, s, f; // initialize forces to zero for (i=0; i<3*np; i++) forcesStatic[i] = 0.; // loop over all pairs for (i=0; i<np; i++) { posi[0] = pos[3*i ]; posi[1] = pos[3*i+1]; posi[2] = pos[3*i+2]; for (j=i+1; j<np; j++) { // compute minimum image difference rvec[0] = remainder(posi[0] - pos[3*j ], L); rvec[1] = remainder(posi[1] - pos[3*j+1], L); rvec[2] = remainder(posi[2] - pos[3*j+2], L); s2 = rvec [0]* rvec [0] + rvec [1]* rvec [1] + rvec [2]* rvec [2]; if (s2 < 4) { s = sqrt(s2); rvec[0] /= s; rvec[1] /= s; rvec[2] /= s; f = krepulsion*(2.-s); printf("%d - %f \n", 3*i,f*rvec[0]); printf("%d - %f \n", 3*i+1, f*rvec[1]); printf("%d - %f \n", 3*i+2, f*rvec[2]); printf("%d - %f \n", 3*j,-f*rvec[0]); printf("%d - %f \n", 3*j+1, -f*rvec[1]); printf("%d - %f \n", 3*j+2, -f*rvec[2]); forcesStatic[3*i ] += f*rvec[0]; forcesStatic[3*i+1] += f*rvec[1]; forcesStatic[3*i+2] += f*rvec[2]; forcesStatic[3*j ] += -f*rvec[0]; forcesStatic[3*j+1] += -f*rvec[1]; forcesStatic[3*j+2] += -f*rvec[2]; printf("\n-----------------\n"); printf("%f\n", forcesStatic[3*i ]); printf("%f\n", forcesStatic[3*i+1]); printf("%f\n", forcesStatic[3*i+2]); printf("%f\n", forcesStatic[3*j ]) ; printf("%f\n", forcesStatic[3*j+1]); printf("%f\n", forcesStatic[3*j+2]); printf("\n-----------------\n"); } } } } void force_repulsion(int np, const double *pos, double L, double krepulsion, double *forces, int cs) { #pragma omp parallel { int i, j, xi; double posi[4]; double rvec[4]; double s2, s, f; ; // initialize forces to zero for (i = 0; i < 3 * np; i++) forces[i] = 0.; #pragma omp for for (i=0; i<np; i++) { posi[0] = pos[3*i]; posi[1] = pos[3*i+1]; posi[2] = pos[3*i+2]; for (j=i+1; j<np; j++) { // compute minimum image difference rvec[0] = remainder(posi[0] - pos[3*j ], L); rvec[1] = remainder(posi[1] - pos[3*j+1], L); rvec[2] = remainder(posi[2] - pos[3*j+2], L); s2 = rvec[0]* rvec[0] + rvec[1]* rvec[1] + rvec[2]* rvec[2]; if (s2 < 4) { s = sqrt(s2); rvec[0] /= s; rvec[1] /= s; rvec[2] /= s; f = krepulsion*(2.-s); printf("%d - %f \n", 3*i,f*rvec[0]); printf("%d - %f \n", 3*i+1, f*rvec[1]); printf("%d - %f \n", 3*i+2, f*rvec[2]); printf("%d - %f \n", 3*j,-f*rvec[0]); printf("%d - %f \n", 3*j+1, -f*rvec[1]); printf("%d - %f \n", 3*j+2, -f*rvec[2]); forces[3*i ] += f*rvec[0]; forces[3*i+1] += f*rvec[1]; forces[3*i+2] += f*rvec[2]; forces[3*j ] += -f*rvec[0]; forces[3*j+1] += -f*rvec[1]; forces[3*j+2] += -f*rvec[2]; printf("\n-----------------\n"); printf("%f\n", forces[3*i ]); printf("%f\n", forces[3*i+1]); printf("%f\n", forces[3*i+2]); printf("%f\n", forces[3*j ]) ; printf("%f\n", forces[3*j+1]); printf("%f\n", forces[3*j+2]); printf("\n-----------------\n"); } } } } } int main(int argc, char *argv[]) { int i; int np = 100; // default number of particles double phi = 0.3; // volume fraction double krepulsion = 125.; // force constant double *pos, *posStatic; double *forces, *forcesStatic; double L, time0 , time1, time2, time3; if (argc > 1) np = atoi(argv[1]); L = pow(4./3.*3.1415926536*np/phi, 1./3.); // generate random particle positions inside simulation box forces = (double *) malloc(3*np*sizeof(double)); forcesStatic = (double *) malloc(3*np*sizeof(double)); posStatic = (double *) malloc(3*np*sizeof(double)); pos = (double *) malloc(3*np*sizeof(double)); for (i=0; i<3*np; i++) pos[i] = posStatic[i] = rand()/(double)RAND_MAX*L; // measure execution time of this function time0 = get_walltime (); force_repulsion(np, pos, L, krepulsion, forces, 1); time1 = get_walltime (); printf(">>>>>>>>>>>>>>>>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<<<<<\n"); time2 = get_walltime (); force_repulsionStatic(np, posStatic, L, krepulsion, forcesStatic, 1); time3 = get_walltime (); for(int x=0; x<=np; x++) { printf("%d %f \t\t %f \n", x, forcesStatic[x], forces[x]); } printf("number of particles: %d\n", np); printf("elapsed time ST: %f\n", time3-time2); printf("elapsed time MT static: %f\n", time1-time0); free(forces); free(forcesStatic); free(pos); free(posStatic); return 0; }
dyn_mc.h
#ifndef DYN_MC_H_ #define DYN_MC_H_ #include <algorithm> #include "traversal.h" #include "../common/timer.h" #include "sliding_queue_dynamic.h" #include "../common/pvector.h" /* Algorithm: Incremental Max computation and Max Computation starting from scratch */ #include <fstream> extern std::ofstream algF; template<typename T> void MCIter0(T* ds, SlidingQueue<NodeID>& queue){ pvector<bool> visited(ds->num_nodes, false); #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for schedule(dynamic, 64) for(NodeID n=0; n < ds->num_nodes; n++){ if(ds->affected[n]){ float old_val = ds->property[n]; float new_val = old_val; // calculate new value for(auto v: in_neigh(n, ds)){ new_val = std::max(new_val, ds->property[v]); } assert(new_val >= old_val); ds->property[n] = new_val; bool trigger = ( (ds->property[n] > old_val) || (old_val == n) ); if(trigger){ //put the out-neighbors into active list for(auto v: out_neigh(n, ds)){ bool curr_val = visited[v]; if(!curr_val){ if(compare_and_swap(visited[v], curr_val, true)) lqueue.push_back(v); } } } } } lqueue.flush(); } } template<typename T> void dynMCAlg(T* ds){ //std::cout << "Number of nodes: "<< ds->num_nodes << std::endl; std::cout << "Running dynamic MC" << std::endl; Timer t; t.Start(); SlidingQueue<NodeID> queue(ds->num_nodes); // Assign value of newly added vertices #pragma omp parallel for schedule(dynamic, 64) for(NodeID n = 0; n < ds->num_nodes; n++){ if(ds->property[n] == -1){ ds->property[n] = n; } } MCIter0(ds, queue); queue.slide_window(); while(!queue.empty()){ //std::cout << "Queue not empty, Queue size: " << queue.size() << std::endl; pvector<bool> visited(ds->num_nodes, false); #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for schedule(dynamic, 64) for (auto q_iter = queue.begin(); q_iter < queue.end(); q_iter++){ NodeID n = *q_iter; float old_val = ds->property[n]; float new_val = old_val; // calculate new value for(auto v: in_neigh(n, ds)){ new_val = std::max(new_val, ds->property[v]); } assert(new_val >= old_val); ds->property[n] = new_val; bool trigger = (ds->property[n] > old_val); if(trigger){ for(auto v: out_neigh(n, ds)){ bool curr_val = visited[v]; if(!curr_val){ if(compare_and_swap(visited[v], curr_val, true)) lqueue.push_back(v); } } } } lqueue.flush(); } queue.slide_window(); } // clear affected array to get ready for the next update round #pragma omp parallel for schedule(dynamic, 64) for(NodeID i = 0; i < ds->num_nodes; i++){ ds->affected[i] = false; } t.Stop(); algF << t.Seconds() << std::endl; } template<typename T> void MCStartFromScratch(T* ds){ std::cout << "Running MC from scratch" << std::endl; Timer t; t.Start(); #pragma omp parallel for for (NodeID n=0; n < ds->num_nodes; n++) ds->property[n] = n; SlidingQueue<NodeID> queue(ds->num_nodes); pvector<bool> visited(ds->num_nodes, false); // first iteration: all active vertices #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for for(NodeID n = 0; n < ds->num_nodes; n++){ float old_val = ds->property[n]; float new_val = old_val; for(auto v: in_neigh(n, ds)){ new_val = std::max(new_val, ds->property[v]); } assert(new_val >= old_val); ds->property[n] = new_val; if(ds->property[n] != old_val){ for(auto w: out_neigh(n, ds)){ bool curr_val = visited[w]; if(!curr_val){ if(compare_and_swap(visited[w], curr_val, true)) lqueue.push_back(w); } } } } lqueue.flush(); } queue.slide_window(); // Next iterations: According to active vertices in queue while(!queue.empty()){ //std::cout << "Queue not empty, Queue size: " << queue.size() << std::endl; visited.fill(0); #pragma omp parallel { QueueBuffer<NodeID> lqueue(queue); #pragma omp for for (auto q_iter = queue.begin(); q_iter < queue.end(); q_iter++){ NodeID n = *q_iter; float old_val = ds->property[n]; float new_val = old_val; for(auto v: in_neigh(n, ds)){ new_val = std::max(new_val, ds->property[v]); } assert(new_val >= old_val); ds->property[n] = new_val; if(ds->property[n] != old_val){ for(auto w: out_neigh(n, ds)){ bool curr_val = visited[w]; if(!curr_val){ if(compare_and_swap(visited[w], curr_val, true)) lqueue.push_back(w); } } } } lqueue.flush(); } queue.slide_window(); } t.Stop(); algF << t.Seconds() << std::endl; } /*template<typename T> void MCStartFromScratch(const string& datatype, T* partition, bool directed){ std::cout << "Running MC from scratch" << std::endl; #pragma omp parallel for for (NodeID n=0; n < partition->num_nodes; n++) partition->property[n] = n; int num_iter = 0; bool change = true; while(change){ change = false; num_iter++; #pragma omp parallel for for(NodeID n = 0; n < partition->num_nodes; n++){ float old_val = partition->property[n]; float new_val = old_val; for(auto v: in_neigh(n, datatype, partition, partition->directed)){ new_val = std::max(new_val, partition->property[v]); } assert(new_val >= old_val); partition->property[n] = new_val; if(partition->property[n] != old_val) change = true; } } std::cout << "MCFromScratch took " << num_iter << " iterations" << std::endl; }*/ #endif // DYN_MC_H_
Example_affinity.2.c
/* * @@name: affinity.2c * @@type: C * @@compilable: yes * @@linkable: no * @@expect: success * @@version: omp_4.0 */ void work(); void foo() { #pragma omp parallel num_threads(16) proc_bind(spread) { work(); } }
temporal_max_method.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Suneth Warnakulasuriya (https://github.com/sunethwarna) // #if !defined(KRATOS_TEMPORAL_MAX_METHOD_H_INCLUDED) #define KRATOS_TEMPORAL_MAX_METHOD_H_INCLUDED // System includes #include <limits> #include <string> // External includes // Project includes #include "includes/define.h" #include "includes/model_part.h" // Application includes #include "custom_methods/temporal_method.h" #include "custom_utilities/method_utilities.h" #include "custom_utilities/temporal_method_utilities.h" namespace Kratos { ///@addtogroup StatisticsApplication ///@{ ///@name Kratos Globals ///@{ namespace TemporalMethods { template <class TContainerType, class TContainerItemType, template <class T> class TDataRetrievalFunctor, template <class T> class TDataStorageFunctor> class TemporalMaxMethod { public: template <class TDataType> class NormMethod : public TemporalMethod { public: KRATOS_CLASS_POINTER_DEFINITION(NormMethod); NormMethod( ModelPart& rModelPart, const std::string& rNormType, const Variable<TDataType>& rInputVariable, const int EchoLevel, const Variable<double>& rOutputVariable, const Variable<double>& rMaxTimeValueVariable) : TemporalMethod(rModelPart, EchoLevel), mNormType(rNormType), mrInputVariable(rInputVariable), mrOutputVariable(rOutputVariable), mrMaxTimeValueVariable(rMaxTimeValueVariable) { KRATOS_TRY KRATOS_ERROR_IF(rOutputVariable == rMaxTimeValueVariable) << "Same variable is given for maximum and its time value " "variable in norm min method for input variable " << rInputVariable.Name() << ". Please provide two different " "variables. [ variable = " << rOutputVariable.Name() << " ].\n"; KRATOS_CATCH(""); } void CalculateStatistics() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); const auto& norm_method = MethodUtilities::GetNormMethod(mrInputVariable, mNormType); const double total_time = this->GetTotalTime(); const int number_of_items = r_container.size(); #pragma omp parallel for for (int i = 0; i < number_of_items; ++i) { TContainerItemType& r_item = *(r_container.begin() + i); const TDataType& r_input_value = TDataRetrievalFunctor<TContainerItemType>()(r_item, mrInputVariable); const double input_norm_value = norm_method(r_input_value); double& r_output_value = TDataStorageFunctor<TContainerItemType>()(r_item, mrOutputVariable); double& r_max_time_value = TDataStorageFunctor<TContainerItemType>()( r_item, mrMaxTimeValueVariable); if (input_norm_value > r_output_value) { r_output_value = input_norm_value; r_max_time_value = total_time; } } KRATOS_INFO_IF("TemporalNormMaxMethod", this->GetEchoLevel() > 1) << "Calculated temporal norm max for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " max variable and " << mrMaxTimeValueVariable.Name() << " time value variable in " << this->GetModelPart().Name() << ".\n"; } void InitializeStatisticsVariables() override { TContainerType& r_container = MethodUtilities::GetDataContainer<TContainerType>(this->GetModelPart()); auto& initializer_method = TemporalMethodUtilities::InitializeVariables<TContainerType, TContainerItemType, TDataStorageFunctor>; initializer_method( r_container, mrOutputVariable, std::numeric_limits<double>::lowest()); initializer_method(r_container, mrMaxTimeValueVariable, 0.0); KRATOS_INFO_IF("TemporalNormMaxMethod", this->GetEchoLevel() > 0) << "Initialized temporal norm max method for " << mrInputVariable.Name() << " input variable with " << mrOutputVariable.Name() << " max variable and " << mrMaxTimeValueVariable.Name() << " time value variable in " << this->GetModelPart().Name() << ".\n"; } private: const std::string mNormType; const Variable<TDataType>& mrInputVariable; const Variable<double>& mrOutputVariable; const Variable<double>& mrMaxTimeValueVariable; }; std::vector<TemporalMethod::Pointer> static CreateTemporalMethodObject( ModelPart& rModelPart, const std::string& rNormType, const int EchoLevel, Parameters Params) { KRATOS_TRY Parameters default_parameters = Parameters(R"( { "input_variables" : [], "output_variables" : [], "output_time_step_variables" : [] })"); Params.RecursivelyValidateAndAssignDefaults(default_parameters); const std::vector<std::string>& input_variable_names_list = Params["input_variables"].GetStringArray(); const std::vector<std::string>& output_variable_1_names_list = Params["output_variables"].GetStringArray(); const std::vector<std::string>& output_variable_2_names_list = Params["output_time_step_variables"].GetStringArray(); std::vector<TemporalMethod::Pointer> method_list; if (rNormType == "none") // for non norm types { KRATOS_ERROR << "none norm type is not defined for Min method.\n"; } else // for values with norms { MethodUtilities::CheckVariableType<double>(output_variable_1_names_list); MethodUtilities::CheckVariableType<double>(output_variable_2_names_list); const int number_of_variables = input_variable_names_list.size(); for (int i = 0; i < number_of_variables; ++i) { const std::string& r_variable_input_name = input_variable_names_list[i]; const std::string& r_variable_1_output_name = output_variable_1_names_list[i]; const std::string& r_variable_2_output_name = output_variable_2_names_list[i]; ADD_TEMPORAL_NORM_METHOD_TWO_OUTPUT_VARIABLE_OBJECT( rModelPart, rNormType, r_variable_input_name, EchoLevel, r_variable_1_output_name, r_variable_2_output_name, method_list, NormMethod) } } return method_list; KRATOS_CATCH(""); } }; } // namespace TemporalMethods } // namespace Kratos #endif // KRATOS_TEMPORAL_MAX_METHOD_H_INCLUDED
doitgen.c
/** * This version is stamped on May 10, 2016 * * Contact: * Louis-Noel Pouchet <pouchet.ohio-state.edu> * Tomofumi Yuki <tomofumi.yuki.fr> * * Web address: http://polybench.sourceforge.net */ /* doitgen.c: this file is part of PolyBench/C */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ #include "doitgen.h" /* Array initialization. */ static void init_array(int nr, int nq, int np, DATA_TYPE POLYBENCH_3D(A, NR, NQ, NP, nr, nq, np), DATA_TYPE POLYBENCH_2D(C4, NP, NP, np, np)) { int i, j, k; for (i = 0; i < nr; i++) for (j = 0; j < nq; j++) for (k = 0; k < np; k++) A[i][j][k] = (DATA_TYPE) ((i * j + k) % np) / np; for (i = 0; i < np; i++) for (j = 0; j < np; j++) C4[i][j] = (DATA_TYPE) (i * j % np) / np; } /* 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 nr, int nq, int np, DATA_TYPE POLYBENCH_3D(A, NR, NQ, NP, nr, nq, np)) { int i, j, k; POLYBENCH_DUMP_START; POLYBENCH_DUMP_BEGIN("A"); for (i = 0; i < nr; i++) for (j = 0; j < nq; j++) for (k = 0; k < np; k++) { if ((i * nq * np + j * np + k) % 20 == 0) fprintf (POLYBENCH_DUMP_TARGET, "\n"); fprintf (POLYBENCH_DUMP_TARGET, DATA_PRINTF_MODIFIER, A[i][j][k]); } POLYBENCH_DUMP_END("A"); POLYBENCH_DUMP_FINISH; } /* Main computational kernel. The whole function will be timed, including the call and return. */ void kernel_doitgen(int nr, int nq, int np, DATA_TYPE POLYBENCH_3D(A, NR, NQ, NP, nr, nq, np), DATA_TYPE POLYBENCH_2D(C4, NP, NP, np, np), DATA_TYPE POLYBENCH_1D(sum, NP, np)) { int r, q, p, s; printf("_PB_NR = %d \t _PB_NQ = %d \t _PB_NP = %d \n", _PB_NR, _PB_NQ, _PB_NP); #pragma omp parallel for default(shared) private(r, q, p, s) firstprivate(nr, nq, np, C4) reduction(+ : sum[:160]) for (r = 0; r < _PB_NR; r++) { for (q = 0; q < _PB_NQ; q++) { for (p = 0; p < _PB_NP; p++) { sum[p] = SCALAR_VAL(0.0); for (s = 0; s < _PB_NP; s++) sum[p] += A[r][q][s] * C4[s][p]; } for (p = 0; p < _PB_NP; p++) A[r][q][p] = sum[p]; } } } int main(int argc, char** argv) { /* Retrieve problem size. */ int nr = NR; int nq = NQ; int np = NP; /* Variable declaration/allocation. */ POLYBENCH_3D_ARRAY_DECL(A, DATA_TYPE, NR, NQ, NP, nr, nq, np); POLYBENCH_1D_ARRAY_DECL(sum, DATA_TYPE, NP, np); POLYBENCH_2D_ARRAY_DECL(C4, DATA_TYPE, NP, NP, np, np); /* Initialize array(s). */ init_array (nr, nq, np, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C4)); /* Start timer. */ polybench_start_instruments; /* Run kernel. */ kernel_doitgen (nr, nq, np, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(C4), POLYBENCH_ARRAY(sum)); /* 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(nr, nq, np, POLYBENCH_ARRAY(A))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(sum); POLYBENCH_FREE_ARRAY(C4); return 0; }
Cycle.c
/* * The MIT License * * Copyright 2020 The OpenNARS authors. * * 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 "Cycle.h" //doing inference within the matched concept, returning whether decisionMaking should continue static Decision Cycle_ActivateConcept(Concept *c, Event *e, long currentTime) { Decision decision = {0}; Event eMatch = *e; if(eMatch.truth.confidence > MIN_CONFIDENCE) { c->usage = Usage_use(c->usage, currentTime); //add event as spike to the concept: if(eMatch.type == EVENT_TYPE_BELIEF) { c->belief_spike = eMatch; } else { //pass spike if the concept doesn't have a satisfying motor command decision = Decision_Suggest(&eMatch, currentTime); if(!decision.execute) { c->incoming_goal_spike = eMatch; } else { e->propagated = true; } } } return decision; } //Process an event, by creating a concept, or activating an existing static Decision Cycle_ProcessEvent(Event *e, long currentTime) { Decision best_decision = {0}; //add a new concept for e if not yet existing Memory_Conceptualize(&e->term, currentTime); e->processed = true; Event_SetTerm(e, e->term); // TODO make sure that hash needs to be calculated once instead already IN_DEBUG( puts("Event was selected:"); Event_Print(e); ) //determine the concept it is related to Event ecp = *e; for(int concept_i=0; concept_i<concepts.itemsAmount; concept_i++) { Concept *c = concepts.items[concept_i].address; if(!Variable_hasVariable(&e->term, true, true, true)) //concept matched to the event which doesn't have variables { Substitution subs = Variable_Unify(&c->term, &e->term); //concept with variables, if(subs.success) { ecp.term = e->term; Concept *c = concepts.items[concept_i].address; Decision decision = Cycle_ActivateConcept(c, &ecp, currentTime); if(decision.execute && decision.desire >= best_decision.desire) { best_decision = decision; } } } else { Substitution subs = Variable_Unify(&e->term, &c->term); //event with variable matched to concept if(subs.success) { ecp.term = Variable_ApplySubstitute(e->term, subs); Concept *c = concepts.items[concept_i].address; Decision decision = Cycle_ActivateConcept(c, &ecp, currentTime); if(decision.execute && decision.desire >= best_decision.desire) { best_decision = decision; } } } } return best_decision; } //Propagate spikes for subgoal processing, generating anticipations and decisions static Decision Cycle_PropagateSpikes(long currentTime) { Decision decision = {0}; //pass goal spikes on to the next for(int i=0; i<concepts.itemsAmount; i++) { Concept *postc = concepts.items[i].address; if(postc->goal_spike.type != EVENT_TYPE_DELETED && !postc->goal_spike.propagated && Truth_Expectation(postc->goal_spike.truth) > PROPAGATION_THRESHOLD) { for(int opi=0; opi<OPERATIONS_MAX; opi++) { for(int j=0; j<postc->precondition_beliefs[opi].itemsAmount; j++) { Implication *imp = &postc->precondition_beliefs[opi].array[j]; if(!Memory_ImplicationValid(imp)) { Table_Remove(&postc->precondition_beliefs[opi], j); j--; continue; } //no var, just send to source concept if(!Variable_hasVariable(&imp->term, true, true, true)) { Concept *pre = imp->sourceConcept; if(pre->incoming_goal_spike.type == EVENT_TYPE_DELETED || pre->incoming_goal_spike.processed) { pre->incoming_goal_spike = Inference_GoalDeduction(&postc->goal_spike, imp); } } //find proper source to send to! else { assert(Narsese_copulaEquals(imp->term.atoms[0], '$'), "Not an implication!"); Term right_side = Term_ExtractSubterm(&imp->term, 2); Substitution subs = Variable_Unify(&right_side, &postc->goal_spike.term); assert(subs.success, "Implication and spike needs to be compatible!"); Term left_side_with_op = Term_ExtractSubterm(&imp->term, 1); Term left_side = Narsese_GetPreconditionWithoutOp(&left_side_with_op); Term left_side_substituted = Variable_ApplySubstitute(left_side, subs); for(int concept_i=0; concept_i<concepts.itemsAmount; concept_i++) { Concept *pre = concepts.items[concept_i].address; if(Variable_Unify(&pre->term, &left_side_substituted).success) //could be <a --> M>! matching to some <... =/> <$1 --> M>>. { if(pre->incoming_goal_spike.type == EVENT_TYPE_DELETED || pre->incoming_goal_spike.processed) { pre->incoming_goal_spike = Inference_GoalDeduction(&postc->goal_spike, imp); pre->incoming_goal_spike.term = left_side_substituted; //set term as well, it's a specific goal now as it got specialized! } } } } } } } postc->goal_spike.propagated = true; } //process incoming goal spikes, invoking potential operations for(int i=0; i<concepts.itemsAmount; i++) { Concept *c = concepts.items[i].address; if(c->incoming_goal_spike.type != EVENT_TYPE_DELETED) { c->goal_spike = Inference_IncreasedActionPotential(&c->goal_spike, &c->incoming_goal_spike, currentTime, NULL); Memory_printAddedEvent(&c->goal_spike, 1, false, true, false); if(c->goal_spike.type != EVENT_TYPE_DELETED && !c->goal_spike.processed && Truth_Expectation(c->goal_spike.truth) > PROPAGATION_THRESHOLD) { Decision decision = Cycle_ProcessEvent(&c->goal_spike, currentTime); if(decision.execute) { return decision; } } } c->incoming_goal_spike = (Event) {0}; } return decision; } //Reinforce link between concept a and b (creating it if non-existent) static void Cycle_ReinforceLink(Event *a, Event *b) { if(a->type != EVENT_TYPE_BELIEF || b->type != EVENT_TYPE_BELIEF) { return; } Term a_term_nop = Narsese_GetPreconditionWithoutOp(&a->term); Concept *A = Memory_FindConceptByTerm(&a_term_nop); Concept *B = Memory_FindConceptByTerm(&b->term); if(A != NULL && B != NULL && A != B) { //temporal induction if(!Stamp_checkOverlap(&a->stamp, &b->stamp)) { Implication precondition_implication = Inference_BeliefInduction(a, b); precondition_implication.sourceConcept = A; precondition_implication.sourceConceptId = A->id; if(precondition_implication.truth.confidence >= MIN_CONFIDENCE) { Term general_implication_term = IntroduceImplicationVariables(precondition_implication.term); if(Variable_hasVariable(&general_implication_term, true, true, false)) { NAL_DerivedEvent(general_implication_term, OCCURRENCE_ETERNAL, precondition_implication.truth, precondition_implication.stamp, currentTime, 1, 1, NULL, 0); } int operationID = Narsese_getOperationID(&a->term); IN_DEBUG ( if(operationID != 0) { Narsese_PrintTerm(&precondition_implication.term); Truth_Print(&precondition_implication.truth); puts("\n"); getchar(); } ) IN_DEBUG( fputs("Formed implication: ", stdout); Implication_Print(&precondition_implication); ) Implication *revised_precon = Table_AddAndRevise(&B->precondition_beliefs[operationID], &precondition_implication); if(revised_precon != NULL) { revised_precon->creationTime = currentTime; //for evaluation revised_precon->sourceConcept = A; revised_precon->sourceConceptId = A->id; /*IN_DEBUG( if(true && revised_precon->term_hash != 0) { fputs("REVISED pre-condition implication: ", stdout); Implication_Print(revised_precon); } ) */ Memory_printAddedImplication(&revised_precon->term, &revised_precon->truth, false, revised_precon->truth.confidence > precondition_implication.truth.confidence); } } } } } void popEvents() { for(int i=0; i<EVENT_SELECTIONS; i++) { Event *e; double priority = 0; if(!PriorityQueue_PopMax(&cycling_events, (void**) &e, &priority)) { assert(cycling_events.itemsAmount == 0, "No item was popped, only acceptable reason is when it's empty"); IN_DEBUG( puts("Selecting event failed, maybe there is no event left."); ) break; } selectedEventsPriority[eventsSelected] = priority; selectedEvents[eventsSelected] = *e; //needs to be copied because will be added in a batch eventsSelected++; //that while processing, would make recycled pointers invalid to use } } void pushEvents(long currentTime) { for(int i=0; i<eventsSelected; i++) { Memory_addEvent(&selectedEvents[i], currentTime, selectedEventsPriority[i], false, false, true, false); } } void Cycle_Perform(long currentTime) { eventsSelected = 0; popEvents(); //1. process newest event if(belief_events.itemsAmount > 0) { //form concepts for the sequences of different length for(int len=0; len<MAX_SEQUENCE_LEN; len++) { Event *toProcess = FIFO_GetNewestSequence(&belief_events, len); if(toProcess != NULL && !toProcess->processed && toProcess->type != EVENT_TYPE_DELETED) { assert(toProcess->type == EVENT_TYPE_BELIEF, "A different event type made it into belief events!"); Cycle_ProcessEvent(toProcess, currentTime); Event postcondition = *toProcess; //Mine for <(&/,precondition,operation) =/> postcondition> patterns in the FIFO: if(len == 0) //postcondition always len1 { int op_id = Narsese_getOperationID(&postcondition.term); Decision_AssumptionOfFailure(op_id, currentTime); //collection of negative evidence, new way //build link between internal derivations and external event to explain it: for(int k=0; k<eventsSelected; k++) { if(selectedEvents[k].occurrenceTime < postcondition.occurrenceTime) { Cycle_ReinforceLink(&selectedEvents[k], &postcondition); } } for(int k=1; k<belief_events.itemsAmount; k++) { for(int len2=0; len2<MAX_SEQUENCE_LEN; len2++) { Event *precondition = FIFO_GetKthNewestSequence(&belief_events, k, len2); if(precondition != NULL && precondition->type != EVENT_TYPE_DELETED) { Term precond = Narsese_GetPreconditionWithoutOp(&precondition->term); //a or (&/,a,op) for(int i=0; i<COMPOUND_TERM_SIZE_MAX; i++) { if(Narsese_isOperator(precond.atoms[i])) { goto NoReinforce; //if there is an op in a, then a longer sequ has also, try different k } } Cycle_ReinforceLink(precondition, &postcondition); NoReinforce:; } } } } } } } //process goals Decision decision[PROPAGATION_ITERATIONS + 1] = {0}; if(goal_events.itemsAmount > 0) { Event *goal = FIFO_GetNewestSequence(&goal_events, 0); if(!goal->processed && goal->type!=EVENT_TYPE_DELETED) { assert(goal->type == EVENT_TYPE_GOAL, "A different event type made it into goal events!"); decision[0] = Cycle_ProcessEvent(goal, currentTime); //allow reasoning into the future by propagating spikes from goals back to potential current events for(int i=0; i<PROPAGATION_ITERATIONS; i++) { decision[i+1] = Cycle_PropagateSpikes(currentTime); } } } //inject the best action if there was one Decision best_decision = {0}; for(int i=0; i<PROPAGATION_ITERATIONS+1; i++) { if(decision[i].execute && decision[i].desire >= best_decision.desire) { best_decision = decision[i]; } } if(best_decision.execute && best_decision.operationID > 0) { Decision_Execute(&best_decision); } //end of iterations, remove spikes for(int i=0; i<concepts.itemsAmount; i++) { Concept *c = concepts.items[i].address; c->incoming_goal_spike = (Event) {0}; c->goal_spike = (Event) {0}; } //Inferences #if STAGE==2 long countConceptsMatched = 0; for(int i=0; i<eventsSelected; i++) { Event *e = &selectedEvents[i]; Term subterms_of_e[6] = {0}; //subterms up to level 2 for(int j=0; j<5; j++) { subterms_of_e[j] = Term_ExtractSubterm(&e->term, j+1); } double priority = selectedEventsPriority[i]; Term dummy_term = {0}; Truth dummy_truth = {0}; RuleTable_Apply(e->term, dummy_term, e->truth, dummy_truth, e->occurrenceTime, e->stamp, currentTime, priority, 1, false, NULL, 0); IN_DEBUG( puts("Event was selected:"); Event_Print(e); ) //Adjust dynamic firing threshold: (proportional "self"-control) double conceptPriorityThresholdCurrent = conceptPriorityThreshold; long countConceptsMatchedAverage = Stats_countConceptsMatchedTotal / currentTime; double set_point = BELIEF_CONCEPT_MATCH_TARGET; double process_value = countConceptsMatchedAverage; double error = process_value - set_point; double increment = error*CONCEPT_THRESHOLD_ADAPTATION; conceptPriorityThreshold = MIN(1.0, MAX(0.0, conceptPriorityThreshold + increment)); //printf("conceptPriorityThreshold=%f\n", conceptPriorityThreshold); //Main inference loop: #pragma omp parallel for for(int j=0; j<concepts.itemsAmount; j++) { Concept *c = concepts.items[j].address; long validation_cid = c->id; //allows for lockfree rule table application (only adding to memory is locked) if(c->priority < conceptPriorityThresholdCurrent) { continue; } //first filter based on common term (semantic relationship) bool has_common_term = false; for(int k=0; k<5; k++) { Term current = Term_ExtractSubterm(&c->term, k+1); for(int h=0; h<5; h++) { if(current.atoms[0] != 0 && subterms_of_e[h].atoms[0] != 0) { if(Term_Equal(&current, &subterms_of_e[h])) { has_common_term = true; goto PROCEED; } } } } PROCEED:; //second filter based on precondition implication (temporal relationship) bool is_temporally_related = false; for(int k=0; k<c->precondition_beliefs[0].itemsAmount; k++) { Implication imp = c->precondition_beliefs[0].array[k]; Term subject = Term_ExtractSubterm(&imp.term, 1); if(Variable_Unify(&subject, &e->term).success) { is_temporally_related = true; break; } } if(has_common_term) { #pragma omp critical { countConceptsMatched++; Stats_countConceptsMatchedTotal++; } } if(has_common_term && c->belief.type != EVENT_TYPE_DELETED) { //use eternal belief as belief Event* belief = &c->belief; Event future_belief = c->predicted_belief; //but if there is a predicted one in the event's window, use this one if(e->occurrenceTime != OCCURRENCE_ETERNAL && future_belief.type != EVENT_TYPE_DELETED && abs(e->occurrenceTime - future_belief.occurrenceTime) < EVENT_BELIEF_DISTANCE) //take event as belief if it's stronger { future_belief.truth = Truth_Projection(future_belief.truth, future_belief.occurrenceTime, e->occurrenceTime); future_belief.occurrenceTime = e->occurrenceTime; belief = &future_belief; } //unless there is an actual belief which falls into the event's window Event project_belief = c->belief_spike; if(e->occurrenceTime != OCCURRENCE_ETERNAL && project_belief.type != EVENT_TYPE_DELETED && abs(e->occurrenceTime - project_belief.occurrenceTime) < EVENT_BELIEF_DISTANCE) //take event as belief if it's stronger { project_belief.truth = Truth_Projection(project_belief.truth, project_belief.occurrenceTime, e->occurrenceTime); project_belief.occurrenceTime = e->occurrenceTime; belief = &project_belief; } //Check for overlap and apply inference rules if(!Stamp_checkOverlap(&e->stamp, &belief->stamp)) { Stamp stamp = Stamp_make(&e->stamp, &belief->stamp); if(PRINT_CONTROL_INFO) { fputs("Apply rule table on ", stdout); Narsese_PrintTerm(&e->term); printf(" Priority=%f\n", priority); fputs(" and ", stdout); Narsese_PrintTerm(&c->term); puts(""); } RuleTable_Apply(e->term, c->term, e->truth, belief->truth, e->occurrenceTime, stamp, currentTime, priority, c->priority, true, c, validation_cid); } } if(is_temporally_related) { for(int i=0; i<c->precondition_beliefs[0].itemsAmount; i++) { Implication *imp = &c->precondition_beliefs[0].array[i]; assert(Narsese_copulaEquals(imp->term.atoms[0],'$'), "Not a valid implication term!"); Term precondition_with_op = Term_ExtractSubterm(&imp->term, 1); Term precondition = Narsese_GetPreconditionWithoutOp(&precondition_with_op); Substitution subs = Variable_Unify(&precondition, &e->term); if(subs.success) { Implication updated_imp = *imp; updated_imp.term = Variable_ApplySubstitute(updated_imp.term, subs); Event predicted = Inference_BeliefDeduction(e, &updated_imp); NAL_DerivedEvent(predicted.term, predicted.occurrenceTime, predicted.truth, predicted.stamp, currentTime, priority, Truth_Expectation(imp->truth), c, validation_cid); } } } } if(countConceptsMatched > Stats_countConceptsMatchedMax) { Stats_countConceptsMatchedMax = countConceptsMatched; } } #endif //Apply event forgetting: for(int i=0; i<cycling_events.itemsAmount; i++) { cycling_events.items[i].priority *= EVENT_DURABILITY; } //Apply concept forgetting: for(int i=0; i<concepts.itemsAmount; i++) { Concept *c = concepts.items[i].address; c->priority *= CONCEPT_DURABILITY; concepts.items[i].priority = Usage_usefulness(c->usage, currentTime); //how concept memory is sorted by, by concept usefulness } //Re-sort queues PriorityQueue_Rebuild(&concepts); PriorityQueue_Rebuild(&cycling_events); //push selected events back to the queue as well pushEvents(currentTime); }
GB_unaryop__lnot_uint8_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__lnot_uint8_bool // op(A') function: GB_tran__lnot_uint8_bool // C type: uint8_t // A type: bool // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ bool #define GB_CTYPE \ uint8_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 != 0) ; // casting #define GB_CASTING(z, x) \ uint8_t z = (uint8_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_LNOT || GxB_NO_UINT8 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_uint8_bool ( uint8_t *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__lnot_uint8_bool ( 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
ex2_reduction.c
/* * This code calculates pi using the formula to calculate * the atan(z) which is the integral from 0 to z of 1/(1+x*x) * times dx. atan(1) is 45 degrees or pi/4 */ #include <stdio.h> #include <omp.h> static long num_steps = 10000000; /* number of intervals */ double step; /* the size of the interval - dx */ int main () { int i; /* Loop control variable */ double x; /* The current x position for function evaluation */ double pi; /* final results */ double sum = 0.0; /* maintains the sum of the partial results */ step = 1.0 / (double) num_steps; /* * Calculate the integral */ double t1,t2; t1 = omp_get_wtime(); #pragma omp parallel for reduction(+:sum) private(x) for (i = 1; i <= num_steps; i++) { x = (i - 0.5) * step; sum = sum + 4.0 / (1.0 + x * x); } t2 = omp_get_wtime(); printf("Execution time %g\n", t2 - t1); /* * Multiply by dx */ pi = step * sum; printf( "The computed value of pi is %f\n", pi); return 0; }
sections.c
/* --- File sections.c --- */ #include <omp.h> #include <stdio.h> #include <stdlib.h> #define N 5000 int main(int argc, char *argv[]) { int i, th; float a[N], b[N], c[N], d[N]; /* Initialize arrays */ for (i = 0; i < N; i++) { a[i] = i * 2.3; b[i] = i + 10.35; } #pragma omp parallel private(i, th) { th = omp_get_thread_num(); printf("Thread %d starting...\n", th); #pragma omp sections nowait { #pragma omp section { printf("Thread %d doing section 1\n", th); for (i = 0; i < N; i++) c[i] = a[i] + b[i]; printf("Thread %d done\n", th); } #pragma omp section { printf("Thread %d doing section 2\n", th); for (i = 0; i < N; i++) d[i] = a[i] * b[i]; printf("Thread %d done\n", th); } } /* end of sections */ } /* end of parallel section */ }
eavlDestinationTopologyPackedMapOp.h
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information. #ifndef EAVL_DESTINATION_TOPOLOGY_PACKED_MAP_OP_H #define EAVL_DESTINATION_TOPOLOGY_PACKED_MAP_OP_H #include "eavlCUDA.h" #include "eavlCellSet.h" #include "eavlCellSetExplicit.h" #include "eavlCellSetAllStructured.h" #include "eavlDataSet.h" #include "eavlArray.h" #include "eavlOpDispatch.h" #include "eavlOperation.h" #include "eavlTopology.h" #include "eavlException.h" #include <time.h> #ifdef HAVE_OPENMP #include <omp.h> #endif #ifndef DOXYGEN template <class CONN> struct eavlDestinationTopologyPackedMapOp_CPU { static inline eavlArray::Location location() { return eavlArray::HOST; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int *sparseindices = get<0>(indices).array; int ids[MAX_LOCAL_TOPOLOGY_IDS]; #pragma omp parallel for private(ids) for (int denseindex = 0; denseindex < nitems; ++denseindex) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int nids; int shapeType = conn.GetElementComponents(sparseindex, nids, ids); collect(denseindex, outputs) = functor(shapeType, nids, ids, collect(denseindex, inputs)); } } }; #if defined __CUDACC__ template <class CONN, class F, class IN, class OUT, class INDEX> __global__ void eavlDestinationTopologyPackedMapOp_kernel(int nitems, CONN conn, const IN inputs, OUT outputs, INDEX indices, F functor) { int *sparseindices = get<0>(indices).array; const int numThreads = blockDim.x * gridDim.x; const int threadID = blockIdx.x * blockDim.x + threadIdx.x; int ids[MAX_LOCAL_TOPOLOGY_IDS]; for (int denseindex = threadID; denseindex < nitems; denseindex += numThreads) { int sparseindex = sparseindices[get<0>(indices).indexer.index(denseindex)]; int nids; int shapeType = conn.GetElementComponents(sparseindex, nids, ids); collect(denseindex, outputs) = functor(shapeType, nids, ids, collect(denseindex, inputs)); } } template <class CONN> struct eavlDestinationTopologyPackedMapOp_GPU { static inline eavlArray::Location location() { return eavlArray::DEVICE; } template <class F, class IN, class OUT, class INDEX> static void call(int nitems, CONN &conn, const IN inputs, OUT outputs, INDEX indices, F &functor) { int numThreads = 256; dim3 threads(numThreads, 1, 1); dim3 blocks (32, 1, 1); eavlDestinationTopologyPackedMapOp_kernel<<< blocks, threads >>>(nitems, conn, inputs, outputs, indices, functor); CUDA_CHECK_ERROR(); } }; #endif #endif // **************************************************************************** // Class: eavlDestinationTopologyPackedMapOp // // Purpose: /// Map from one element in a mesh to the same element, with /// topological information passed along to the functor. /// In this packed version of the operation, the inputs (on the destination) /// topology are sparsely indexed and the outputs are compacted, i.e. /// the outputs are densely indexed 0 to n-1. // // Programmer: Jeremy Meredith // Creation: August 1, 2013 // // Modifications: // **************************************************************************** template <class I, class O, class INDEX, class F> class eavlDestinationTopologyPackedMapOp : public eavlOperation { protected: eavlCellSet *cells; eavlTopology topology; I inputs; O outputs; INDEX indices; F functor; public: eavlDestinationTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX ind, F f) : cells(c), topology(t), inputs(i), outputs(o), indices(ind), functor(f) { } virtual void GoCPU() { eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_CPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_CPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } } virtual void GoGPU() { #ifdef HAVE_CUDA eavlCellSetExplicit *elExp = dynamic_cast<eavlCellSetExplicit*>(cells); eavlCellSetAllStructured *elStr = dynamic_cast<eavlCellSetAllStructured*>(cells); int n = outputs.first.length(); if (elExp) { eavlExplicitConnectivity &conn = elExp->GetConnectivity(topology); conn.shapetype.NeedOnDevice(); conn.connectivity.NeedOnDevice(); conn.mapCellToIndex.NeedOnDevice(); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_GPU<eavlExplicitConnectivity> >(n, conn, inputs, outputs, indices, functor); conn.shapetype.NeedOnHost(); conn.connectivity.NeedOnHost(); conn.mapCellToIndex.NeedOnHost(); } else if (elStr) { eavlRegularConnectivity conn = eavlRegularConnectivity(elStr->GetRegularStructure(),topology); eavlOpDispatch<eavlDestinationTopologyPackedMapOp_GPU<eavlRegularConnectivity> >(n, conn, inputs, outputs, indices, functor); } #else THROW(eavlException,"Executing GPU code without compiling under CUDA compiler."); #endif } }; // helper function for type deduction template <class I, class O, class INDEX, class F> eavlDestinationTopologyPackedMapOp<I,O,INDEX,F> *new_eavlDestinationTopologyPackedMapOp(eavlCellSet *c, eavlTopology t, I i, O o, INDEX indices, F f) { return new eavlDestinationTopologyPackedMapOp<I,O,INDEX,F>(c,t,i,o,indices,f); } #endif
GB_unaryop__minv_int64_int8.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__minv_int64_int8 // op(A') function: GB_tran__minv_int64_int8 // C type: int64_t // A type: int8_t // cast: int64_t cij = (int64_t) aij // unaryop: cij = GB_IMINV_SIGNED (aij, 64) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int64_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, 64) ; // casting #define GB_CASTING(z, aij) \ int64_t z = (int64_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_MINV || GxB_NO_INT64 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__minv_int64_int8 ( int64_t *Cx, // Cx and Ax may be aliased 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++) { 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_int64_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_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__gt_uint8.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 GBCUDA_DEV #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_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__gt_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__gt_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__gt_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__gt_uint8) // A*D function (colscale): GB (_AxD__gt_uint8) // D*A function (rowscale): GB (_DxB__gt_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__gt_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__gt_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__gt_uint8) // C=scalar+B GB (_bind1st__gt_uint8) // C=scalar+B' GB (_bind1st_tran__gt_uint8) // C=A+scalar GB (_bind2nd__gt_uint8) // C=A'+scalar GB (_bind2nd_tran__gt_uint8) // C type: bool // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = (aij > bij) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_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) \ uint8_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) \ uint8_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_GT || GxB_NO_UINT8 || GxB_NO_GT_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__gt_uint8) ( 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__gt_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 #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_uint8) ( 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 uint8_t uint8_t bwork = (*((uint8_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_uint8) ( 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__gt_uint8) ( 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__gt_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 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) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_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__gt_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_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__gt_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_04__gt_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_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__gt_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__gt_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 bool *Cx = (bool *) 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__gt_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 ; bool *Cx = (bool *) 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__gt_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__gt_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
GB_unop__abs_fp64_fc64.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__abs_fp64_fc64 // op(A') function: GB_unop_tran__abs_fp64_fc64 // C type: double // A type: GxB_FC64_t // cast: GxB_FC64_t cij = (aij) // unaryop: cij = cabs (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ double // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = cabs (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = (aij) ; \ Cx [pC] = cabs (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_ABS || GxB_NO_FP64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__abs_fp64_fc64 ( double *Cx, // Cx and Ax may be aliased const GxB_FC64_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_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = cabs (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_FC64_t aij = Ax [p] ; GxB_FC64_t z = (aij) ; Cx [p] = cabs (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__abs_fp64_fc64 ( 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
softmax_layer.c
#include "softmax_layer.h" #include "blas.h" #include "dark_cuda.h" #include "utils.h" #include "blas.h" #include <float.h> #include <math.h> #include <stdlib.h> #include <stdio.h> #include <assert.h> #define SECRET_NUM -1234 void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output) { int b; for (b = 0; b < batch; ++b) { int i; int count = 0; for (i = 0; i < hierarchy->groups; ++i) { int group_size = hierarchy->group_size[i]; softmax(input + b*inputs + count, group_size, temp, output + b*inputs + count, 1); count += group_size; } } } softmax_layer make_softmax_layer(int batch, int inputs, int groups) { assert(inputs%groups == 0); fprintf(stderr, "softmax %4d\n", inputs); softmax_layer l = { (LAYER_TYPE)0 }; l.type = SOFTMAX; l.batch = batch; l.groups = groups; l.inputs = inputs; l.outputs = inputs; l.loss = (float*)xcalloc(inputs * batch, sizeof(float)); l.output = (float*)xcalloc(inputs * batch, sizeof(float)); l.delta = (float*)xcalloc(inputs * batch, sizeof(float)); l.cost = (float*)xcalloc(1, sizeof(float)); l.forward = forward_softmax_layer; l.backward = backward_softmax_layer; #ifdef GPU l.forward_gpu = forward_softmax_layer_gpu; l.backward_gpu = backward_softmax_layer_gpu; l.output_gpu = cuda_make_array(l.output, inputs*batch); l.loss_gpu = cuda_make_array(l.loss, inputs*batch); l.delta_gpu = cuda_make_array(l.delta, inputs*batch); #endif return l; } void forward_softmax_layer(const softmax_layer l, network_state net) { if(l.softmax_tree){ int i; int count = 0; for (i = 0; i < l.softmax_tree->groups; ++i) { int group_size = l.softmax_tree->group_size[i]; softmax_cpu(net.input + count, group_size, l.batch, l.inputs, 1, 0, 1, l.temperature, l.output + count); count += group_size; } } else { softmax_cpu(net.input, l.inputs/l.groups, l.batch, l.inputs, l.groups, l.inputs/l.groups, 1, l.temperature, l.output); } if(net.truth && !l.noloss){ softmax_x_ent_cpu(l.batch*l.inputs, l.output, net.truth, l.delta, l.loss); l.cost[0] = sum_array(l.loss, l.batch*l.inputs); } } void backward_softmax_layer(const softmax_layer l, network_state net) { axpy_cpu(l.inputs*l.batch, 1, l.delta, 1, net.delta, 1); } #ifdef GPU void pull_softmax_layer_output(const softmax_layer layer) { cuda_pull_array(layer.output_gpu, layer.output, layer.inputs*layer.batch); } void forward_softmax_layer_gpu(const softmax_layer l, network_state net) { if(l.softmax_tree){ softmax_tree_gpu(net.input, 1, l.batch, l.inputs, l.temperature, l.output_gpu, *l.softmax_tree); /* int i; int count = 0; for (i = 0; i < l.softmax_tree->groups; ++i) { int group_size = l.softmax_tree->group_size[i]; softmax_gpu(net.input_gpu + count, group_size, l.batch, l.inputs, 1, 0, 1, l.temperature, l.output_gpu + count); count += group_size; } */ } else { if(l.spatial){ softmax_gpu_new_api(net.input, l.c, l.batch*l.c, l.inputs/l.c, l.w*l.h, 1, l.w*l.h, 1, l.output_gpu); }else{ softmax_gpu_new_api(net.input, l.inputs/l.groups, l.batch, l.inputs, l.groups, l.inputs/l.groups, 1, l.temperature, l.output_gpu); } } if(net.truth && !l.noloss){ softmax_x_ent_gpu(l.batch*l.inputs, l.output_gpu, net.truth, l.delta_gpu, l.loss_gpu); if(l.softmax_tree){ mask_gpu_new_api(l.batch*l.inputs, l.delta_gpu, SECRET_NUM, net.truth, 0); mask_gpu_new_api(l.batch*l.inputs, l.loss_gpu, SECRET_NUM, net.truth, 0); } cuda_pull_array(l.loss_gpu, l.loss, l.batch*l.inputs); l.cost[0] = sum_array(l.loss, l.batch*l.inputs); } } void backward_softmax_layer_gpu(const softmax_layer layer, network_state state) { axpy_ongpu(layer.batch*layer.inputs, state.net.loss_scale, layer.delta_gpu, 1, state.delta, 1); } #endif // ------------------------------------- // Supervised Contrastive Learning: https://arxiv.org/pdf/2004.11362.pdf contrastive_layer make_contrastive_layer(int batch, int w, int h, int c, int classes, int inputs, layer *yolo_layer) { contrastive_layer l = { (LAYER_TYPE)0 }; l.type = CONTRASTIVE; l.batch = batch; l.inputs = inputs; l.w = w; l.h = h; l.c = c; l.temperature = 1; l.max_boxes = 0; if (yolo_layer) { l.detection = 1; l.max_boxes = yolo_layer->max_boxes; l.labels = yolo_layer->labels; // track id l.class_ids = yolo_layer->class_ids; // class_ids l.n = yolo_layer->n; // num of embeddings per cell = num of anchors l.classes = yolo_layer->classes;// num of classes classes = l.classes; l.embedding_size = l.inputs / (l.n*l.h*l.w); l.truths = yolo_layer->truths; if (l.embedding_size != yolo_layer->embedding_size) { printf(" Error: [contrastive] embedding_size=%d isn't equal to [yolo] embedding_size=%d. They should use the same [convolutional] layer \n", l.embedding_size, yolo_layer->embedding_size); getchar(); exit(0); } if (l.inputs % (l.n*l.h*l.w) != 0) { printf(" Warning: filters= number in the previous (embedding) layer isn't divisable by number of anchors %d \n", l.n); getchar(); } } else { l.detection = 0; l.labels = (int*)xcalloc(l.batch, sizeof(int)); // labels l.n = 1; // num of embeddings per cell l.classes = classes; // num of classes l.embedding_size = l.c; } l.outputs = inputs; l.loss = (float*)xcalloc(1, sizeof(float)); l.output = (float*)xcalloc(inputs * batch, sizeof(float)); l.delta = (float*)xcalloc(inputs * batch, sizeof(float)); l.cost = (float*)xcalloc(1, sizeof(float)); const size_t step = l.batch*l.n*l.h*l.w; l.cos_sim = NULL; l.exp_cos_sim = NULL; l.p_constrastive = NULL; if (!l.detection) { l.cos_sim = (float*)xcalloc(step*step, sizeof(float)); l.exp_cos_sim = (float*)xcalloc(step*step, sizeof(float)); l.p_constrastive = (float*)xcalloc(step*step, sizeof(float)); } //l.p_constrastive = (float*)xcalloc(step*step, sizeof(float)); //l.contrast_p_size = (int*)xcalloc(1, sizeof(int)); //*l.contrast_p_size = step; //l.contrast_p = (contrastive_params*)xcalloc(*l.contrast_p_size, sizeof(contrastive_params)); l.forward = forward_contrastive_layer; l.backward = backward_contrastive_layer; #ifdef GPU l.forward_gpu = forward_contrastive_layer_gpu; l.backward_gpu = backward_contrastive_layer_gpu; l.output_gpu = cuda_make_array(l.output, inputs*batch); l.delta_gpu = cuda_make_array(l.delta, inputs*batch); const int max_contr_size = (l.max_boxes*l.batch)*(l.max_boxes*l.batch) * sizeof(contrastive_params)/4; printf(" max_contr_size = %d MB \n", max_contr_size / (1024*1024)); l.contrast_p_gpu = (contrastive_params *)cuda_make_array(NULL, max_contr_size); #endif fprintf(stderr, "contrastive %4d x%4d x%4d x emb_size %4d x batch: %4d classes = %4d, step = %4d \n", w, h, l.n, l.embedding_size, batch, l.classes, step); if(l.detection) fprintf(stderr, "detection \n"); return l; } static inline float clip_value(float val, const float max_val) { if (val > max_val) { //printf("\n val = %f > max_val = %f \n", val, max_val); val = max_val; } else if (val < -max_val) { //printf("\n val = %f < -max_val = %f \n", val, -max_val); val = -max_val; } return val; } void forward_contrastive_layer(contrastive_layer l, network_state state) { if (!state.train) return; const float truth_thresh = state.net.label_smooth_eps; const int mini_batch = l.batch / l.steps; int b, n, w, h; fill_cpu(l.batch*l.inputs, 0, l.delta, 1); if (!l.detection) { for (b = 0; b < l.batch; ++b) { if (state.net.adversarial) l.labels[b] = b % 2; else l.labels[b] = b / 2; } // set labels for (b = 0; b < l.batch; ++b) { for (h = 0; h < l.h; ++h) { for (w = 0; w < l.w; ++w) { // find truth with max prob (only 1 label even if mosaic is used) float max_truth = 0; int n; for (n = 0; n < l.classes; ++n) { const float truth_prob = state.truth[b*l.classes + n]; //printf(" truth_prob = %f, ", truth_prob); //if (truth_prob > max_truth) if (truth_prob > truth_thresh) { //printf(" truth_prob = %f, max_truth = %f, n = %d; ", truth_prob, max_truth, n); max_truth = truth_prob; l.labels[b] = n; } } //printf(", l.labels[b] = %d ", l.labels[b]); } } } } //printf("\n\n"); // set pointers to features float **z = (float**)xcalloc(l.batch*l.n*l.h*l.w, sizeof(float*)); for (b = 0; b < l.batch; ++b) { for (n = 0; n < l.n; ++n) { for (h = 0; h < l.h; ++h) { for (w = 0; w < l.w; ++w) { const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w; if (l.labels[z_index] < 0) continue; //const int input_index = b*l.inputs + n*l.embedding_size*l.h*l.w + h*l.w + w; //float *ptr = state.input + input_index; //z[z_index] = ptr; z[z_index] = (float*)xcalloc(l.embedding_size, sizeof(float)); get_embedding(state.input, l.w, l.h, l.c, l.embedding_size, w, h, n, b, z[z_index]); } } } } int b2, n2, h2, w2; int contrast_p_index = 0; const size_t step = l.batch*l.n*l.h*l.w; size_t contrast_p_size = step; if (!l.detection) contrast_p_size = l.batch*l.batch; contrastive_params *contrast_p = (contrastive_params*)xcalloc(contrast_p_size, sizeof(contrastive_params)); float *max_sim_same = (float *)xcalloc(l.batch*l.inputs, sizeof(float)); float *max_sim_diff = (float *)xcalloc(l.batch*l.inputs, sizeof(float)); fill_cpu(l.batch*l.inputs, -10, max_sim_same, 1); fill_cpu(l.batch*l.inputs, -10, max_sim_diff, 1); // precalculate cosine similiraty for (b = 0; b < l.batch; ++b) { for (n = 0; n < l.n; ++n) { for (h = 0; h < l.h; ++h) { for (w = 0; w < l.w; ++w) { const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w; if (l.labels[z_index] < 0) continue; for (b2 = 0; b2 < l.batch; ++b2) { for (n2 = 0; n2 < l.n; ++n2) { for (h2 = 0; h2 < l.h; ++h2) { for (w2 = 0; w2 < l.w; ++w2) { const int z_index2 = b2*l.n*l.h*l.w + n2*l.h*l.w + h2*l.w + w2; if (l.labels[z_index2] < 0) continue; if (z_index == z_index2) continue; if (l.detection) if (l.class_ids[z_index] != l.class_ids[z_index2]) continue; const int time_step_i = b / mini_batch; const int time_step_j = b2 / mini_batch; if (time_step_i != time_step_j) continue; const size_t step = l.batch*l.n*l.h*l.w; const float sim = cosine_similarity(z[z_index], z[z_index2], l.embedding_size); const float exp_sim = expf(sim / l.temperature); if (!l.detection) { l.cos_sim[z_index*step + z_index2] = sim; l.exp_cos_sim[z_index*step + z_index2] = exp_sim; } // calc good sim if (l.labels[z_index] == l.labels[z_index2] && max_sim_same[z_index] < sim) max_sim_same[z_index] = sim; if (l.labels[z_index] != l.labels[z_index2] && max_sim_diff[z_index] < sim) max_sim_diff[z_index] = sim; //printf(" z_i = %d, z_i2 = %d, l = %d, l2 = %d, sim = %f \n", z_index, z_index2, l.labels[z_index], l.labels[z_index2], sim); contrast_p[contrast_p_index].sim = sim; contrast_p[contrast_p_index].exp_sim = exp_sim; contrast_p[contrast_p_index].i = z_index; contrast_p[contrast_p_index].j = z_index2; contrast_p[contrast_p_index].time_step_i = time_step_i; contrast_p[contrast_p_index].time_step_j = time_step_j; contrast_p_index++; //printf(" contrast_p_index = %d, contrast_p_size = %d \n", contrast_p_index, contrast_p_size); if ((contrast_p_index+1) >= contrast_p_size) { contrast_p_size = contrast_p_index + 1; //printf(" contrast_p_size = %d, z_index = %d, z_index2 = %d \n", contrast_p_size, z_index, z_index2); contrast_p = (contrastive_params*)xrealloc(contrast_p, contrast_p_size * sizeof(contrastive_params)); } if (sim > 1.001 || sim < -1.001) { printf(" sim = %f, ", sim); getchar(); } } } } } } } } } // calc contrastive accuracy int i; int good_sims = 0, all_sims = 0, same_sim = 0, diff_sim = 0; for (i = 0; i < l.batch*l.inputs; ++i) { if (max_sim_same[i] >= -1 && max_sim_diff[i] >= -1) { if (max_sim_same[i] >= -1) same_sim++; if (max_sim_diff[i] >= -1) diff_sim++; ++all_sims; //printf(" max_sim_diff[i] = %f, max_sim_same[i] = %f \n", max_sim_diff[i], max_sim_same[i]); if (max_sim_diff[i] < max_sim_same[i]) good_sims++; } } if (all_sims > 0) { *l.loss = 100 * good_sims / all_sims; } else *l.loss = -1; printf(" Contrast accuracy = %f %%, all = %d, good = %d, same = %d, diff = %d \n", *l.loss, all_sims, good_sims, same_sim, diff_sim); free(max_sim_same); free(max_sim_diff); /* // show near sim float good_contrast = 0; for (b = 0; b < l.batch; b += 2) { float same = l.cos_sim[b*l.batch + b]; float aug = l.cos_sim[b*l.batch + b + 1]; float diff = l.cos_sim[b*l.batch + b + 2]; good_contrast += (aug > diff); //printf(" l.labels[b] = %d, l.labels[b+1] = %d, l.labels[b+2] = %d, b = %d \n", l.labels[b], l.labels[b + 1], l.labels[b + 2], b); //printf(" same = %f, aug = %f, diff = %f, (aug > diff) = %d \n", same, aug, diff, (aug > diff)); } *l.loss = 100 * good_contrast / (l.batch / 2); printf(" Contrast accuracy = %f %% \n", *l.loss); */ /* // precalculate P_contrastive for (b = 0; b < l.batch; ++b) { int b2; for (b2 = 0; b2 < l.batch; ++b2) { if (b != b2) { const float P = P_constrastive(b, b2, l.labels, l.batch, z, l.embedding_size, l.temperature, l.cos_sim); l.p_constrastive[b*l.batch + b2] = P; if (P > 1 || P < -1) { printf(" p = %f, ", P); getchar(); } } } } */ const size_t contr_size = contrast_p_index; if (l.detection) { #ifdef GPU const int max_contr_size = (l.max_boxes*l.batch)*(l.max_boxes*l.batch); if (max_contr_size < contr_size) { printf(" Error: too large number of bboxes: contr_size = %d > max_contr_size = %d \n", contr_size, max_contr_size); exit(0); } int *labels = NULL; if (contr_size > 2) { cuda_push_array((float *)l.contrast_p_gpu, (float *)contrast_p, contr_size * sizeof(contrastive_params) / 4); P_constrastive_f_det_gpu(labels, l.embedding_size, l.temperature, l.contrast_p_gpu, contr_size); cuda_pull_array((float *)l.contrast_p_gpu, (float *)contrast_p, contr_size * sizeof(contrastive_params) / 4); } #else // GPU int k; //#pragma omp parallel for for (k = 0; k < contr_size; ++k) { contrast_p[k].P = P_constrastive_f_det(k, l.labels, z, l.embedding_size, l.temperature, contrast_p, contr_size); } #endif // GPU } else { // precalculate P-contrastive for (b = 0; b < l.batch; ++b) { for (n = 0; n < l.n; ++n) { for (h = 0; h < l.h; ++h) { for (w = 0; w < l.w; ++w) { const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w; if (l.labels[z_index] < 0) continue; for (b2 = 0; b2 < l.batch; ++b2) { for (n2 = 0; n2 < l.n; ++n2) { for (h2 = 0; h2 < l.h; ++h2) { for (w2 = 0; w2 < l.w; ++w2) { const int z_index2 = b2*l.n*l.h*l.w + n2*l.h*l.w + h2*l.w + w2; if (l.labels[z_index2] < 0) continue; if (z_index == z_index2) continue; if (l.detection) if (l.class_ids[z_index] != l.class_ids[z_index2]) continue; const int time_step_i = b / mini_batch; const int time_step_j = b2 / mini_batch; if (time_step_i != time_step_j) continue; const size_t step = l.batch*l.n*l.h*l.w; float P = -10; if (l.detection) { P = P_constrastive_f(z_index, z_index2, l.labels, z, l.embedding_size, l.temperature, contrast_p, contr_size); } else { P = P_constrastive(z_index, z_index2, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.exp_cos_sim); l.p_constrastive[z_index*step + z_index2] = P; } int q; for (q = 0; q < contr_size; ++q) if (contrast_p[q].i == z_index && contrast_p[q].j == z_index2) { contrast_p[q].P = P; break; } //if (q == contr_size) getchar(); //if (P > 1 || P < -1) { // printf(" p = %f, z_index = %d, z_index2 = %d ", P, z_index, z_index2); getchar(); //} } } } } } } } } } // calc deltas int bd = 0; #pragma omp parallel for for (bd = 0; bd < l.batch; ++bd) { for (int nd = 0; nd < l.n; ++nd) { for (int hd = 0; hd < l.h; ++hd) { for (int wd = 0; wd < l.w; ++wd) { const int z_index = bd*l.n*l.h*l.w + nd*l.h*l.w + hd*l.w + wd; const size_t step = l.batch*l.n*l.h*l.w; if (l.labels[z_index] < 0) continue; const int delta_index = bd*l.embedding_size*l.n*l.h*l.w + nd*l.embedding_size*l.h*l.w + hd*l.w + wd; const int wh = l.w*l.h; if (l.detection) { // detector // positive grad_contrastive_loss_positive_f(z_index, l.class_ids, l.labels, step, z, l.embedding_size, l.temperature, l.delta + delta_index, wh, contrast_p, contr_size); // negative grad_contrastive_loss_negative_f(z_index, l.class_ids, l.labels, step, z, l.embedding_size, l.temperature, l.delta + delta_index, wh, contrast_p, contr_size, l.contrastive_neg_max); } else { // classifier // positive grad_contrastive_loss_positive(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.p_constrastive, l.delta + delta_index, wh); // negative grad_contrastive_loss_negative(z_index, l.labels, step, z, l.embedding_size, l.temperature, l.cos_sim, l.p_constrastive, l.delta + delta_index, wh); } } } } } scal_cpu(l.inputs * l.batch, l.cls_normalizer, l.delta, 1); for (i = 0; i < l.inputs * l.batch; ++i) { l.delta[i] = clip_value(l.delta[i], l.max_delta); } *(l.cost) = pow(mag_array(l.delta, l.inputs * l.batch), 2); if (state.net.adversarial) { printf(" adversarial contrastive loss = %f \n\n", *(l.cost)); } else { printf(" contrastive loss = %f \n\n", *(l.cost)); } for (b = 0; b < l.batch; ++b) { for (n = 0; n < l.n; ++n) { for (h = 0; h < l.h; ++h) { for (w = 0; w < l.w; ++w) { const int z_index = b*l.n*l.h*l.w + n*l.h*l.w + h*l.w + w; //if (l.labels[z_index] < 0) continue; if (z[z_index]) free(z[z_index]); } } } } free(contrast_p); free(z); } void backward_contrastive_layer(contrastive_layer l, network_state state) { axpy_cpu(l.inputs*l.batch, 1, l.delta, 1, state.delta, 1); } #ifdef GPU void pull_contrastive_layer_output(const contrastive_layer l) { cuda_pull_array(l.output_gpu, l.output, l.inputs*l.batch); } void push_contrastive_layer_output(const contrastive_layer l) { cuda_push_array(l.delta_gpu, l.delta, l.inputs*l.batch); } void forward_contrastive_layer_gpu(contrastive_layer l, network_state state) { simple_copy_ongpu(l.batch*l.inputs, state.input, l.output_gpu); if (!state.train) return; float *in_cpu = (float *)xcalloc(l.batch*l.inputs, sizeof(float)); cuda_pull_array(l.output_gpu, l.output, l.batch*l.outputs); memcpy(in_cpu, l.output, l.batch*l.outputs * sizeof(float)); float *truth_cpu = 0; if (state.truth) { int num_truth = l.batch*l.classes; if (l.detection) num_truth = l.batch*l.truths; truth_cpu = (float *)xcalloc(num_truth, sizeof(float)); cuda_pull_array(state.truth, truth_cpu, num_truth); } network_state cpu_state = state; cpu_state.net = state.net; cpu_state.index = state.index; cpu_state.train = state.train; cpu_state.truth = truth_cpu; cpu_state.input = in_cpu; forward_contrastive_layer(l, cpu_state); cuda_push_array(l.delta_gpu, l.delta, l.batch*l.outputs); free(in_cpu); if (cpu_state.truth) free(cpu_state.truth); } void backward_contrastive_layer_gpu(contrastive_layer layer, network_state state) { axpy_ongpu(layer.batch*layer.inputs, state.net.loss_scale, layer.delta_gpu, 1, state.delta, 1); } #endif
depth-metrics.h
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2017 Intel Corporation. All Rights Reserved. // // Plane Fit implementation follows http://www.ilikebigbits.com/blog/2015/3/2/plane-from-points algorithm #pragma once #include <vector> #include <mutex> #include <array> #include <imgui.h> #include <librealsense2/rsutil.h> #include <librealsense2/rs.hpp> #include "rendering.h" namespace rs2 { namespace depth_quality { struct snapshot_metrics { int width; int height; rs2::region_of_interest roi; float distance; float angle; float angle_x; float angle_y; plane p; std::array<float3, 4> plane_corners; }; struct single_metric_data { single_metric_data(std::string name, float val) : val(val), name(name) {} float val; std::string name; }; using callback_type = std::function<void( const std::vector<rs2::float3>& points, const plane p, const rs2::region_of_interest roi, const float baseline_mm, const float focal_length_pixels, const int ground_thruth_mm, const bool plane_fit, const float plane_fit_to_ground_truth_mm, bool record, std::vector<single_metric_data>& samples)>; inline plane plane_from_point_and_normal(const rs2::float3& point, const rs2::float3& normal) { return{ normal.x, normal.y, normal.z, -(normal.x*point.x + normal.y*point.y + normal.z*point.z) }; } inline plane plane_from_points(const std::vector<rs2::float3> points) { if (points.size() < 3) throw std::runtime_error("Not enough points to calculate plane"); rs2::float3 sum = { 0,0,0 }; for (auto point : points) sum = sum + point; rs2::float3 centroid = sum / float(points.size()); double xx = 0, xy = 0, xz = 0, yy = 0, yz = 0, zz = 0; for (auto point : points) { rs2::float3 temp = point - centroid; xx += temp.x * temp.x; xy += temp.x * temp.y; xz += temp.x * temp.z; yy += temp.y * temp.y; yz += temp.y * temp.z; zz += temp.z * temp.z; } double det_x = yy*zz - yz*yz; double det_y = xx*zz - xz*xz; double det_z = xx*yy - xy*xy; double det_max = std::max({ det_x, det_y, det_z }); if (det_max <= 0) return{ 0, 0, 0, 0 }; rs2::float3 dir{}; if (det_max == det_x) { float a = static_cast<float>((xz*yz - xy*zz) / det_x); float b = static_cast<float>((xy*yz - xz*yy) / det_x); dir = { 1, a, b }; } else if (det_max == det_y) { float a = static_cast<float>((yz*xz - xy*zz) / det_y); float b = static_cast<float>((xy*xz - yz*xx) / det_y); dir = { a, 1, b }; } else { float a = static_cast<float>((yz*xy - xz*yy) / det_z); float b = static_cast<float>((xz*xy - yz*xx) / det_z); dir = { a, b, 1 }; } return plane_from_point_and_normal(centroid, dir.normalize()); } inline double evaluate_pixel(const plane& p, const rs2_intrinsics* intrin, float x, float y, float distance, float3& output) { float pixel[2] = { x, y }; rs2_deproject_pixel_to_point(&output.x, intrin, pixel, distance); return evaluate_plane(p, output); } inline float3 approximate_intersection(const plane& p, const rs2_intrinsics* intrin, float x, float y, float min, float max) { float3 point; auto far = evaluate_pixel(p, intrin, x, y, max, point); if (fabs(max - min) < 1e-3) return point; auto near = evaluate_pixel(p, intrin, x, y, min, point); if (far*near > 0) return{ 0, 0, 0 }; auto avg = (max + min) / 2; auto mid = evaluate_pixel(p, intrin, x, y, avg, point); if (mid*near < 0) return approximate_intersection(p, intrin, x, y, min, avg); return approximate_intersection(p, intrin, x, y, avg, max); } inline float3 approximate_intersection(const plane& p, const rs2_intrinsics* intrin, float x, float y) { return approximate_intersection(p, intrin, x, y, 0.f, 1000.f); } inline snapshot_metrics analyze_depth_image( const rs2::video_frame& frame, float units, float baseline_mm, const rs2_intrinsics * intrin, rs2::region_of_interest roi, const int ground_truth_mm, bool plane_fit_present, std::vector<single_metric_data>& samples, bool record, callback_type callback) { auto pixels = (const uint16_t*)frame.get_data(); const auto w = frame.get_width(); const auto h = frame.get_height(); snapshot_metrics result{ w, h, roi, {} }; std::mutex m; std::vector<rs2::float3> roi_pixels; //#pragma omp parallel for - TODO optimization envisaged for (int y = roi.min_y; y < roi.max_y; ++y) for (int x = roi.min_x; x < roi.max_x; ++x) { auto depth_raw = pixels[y*w + x]; if (depth_raw) { // units is float float pixel[2] = { float(x), float(y) }; float point[3]; auto distance = depth_raw * units; rs2_deproject_pixel_to_point(point, intrin, pixel, distance); std::lock_guard<std::mutex> lock(m); roi_pixels.push_back({ point[0], point[1], point[2] }); } } if (roi_pixels.size() < 3) { // Not enough pixels in RoI to fit a plane return result; } plane p = plane_from_points(roi_pixels); if (p == plane{ 0, 0, 0, 0 }) { // The points in RoI don't span a valid plane return result; } // Calculate intersection of the plane fit with a ray along the center of ROI // that by design coincides with the center of the frame float3 plane_fit_pivot = approximate_intersection(p, intrin, intrin->width / 2.f, intrin->height / 2.f); float plane_fit_to_gt_offset_mm = (ground_truth_mm > 0.f) ? (plane_fit_pivot.z * 1000 - ground_truth_mm) : 0; result.p = p; result.plane_corners[0] = approximate_intersection(p, intrin, float(roi.min_x), float(roi.min_y)); result.plane_corners[1] = approximate_intersection(p, intrin, float(roi.max_x), float(roi.min_y)); result.plane_corners[2] = approximate_intersection(p, intrin, float(roi.max_x), float(roi.max_y)); result.plane_corners[3] = approximate_intersection(p, intrin, float(roi.min_x), float(roi.max_y)); // Distance of origin (the camera) from the plane is encoded in parameter D of the plane // The parameter represents the euclidian distance (along plane normal) from camera to the plane result.distance = static_cast<float>(-p.d * 1000); // Angle can be calculated from param C result.angle = static_cast<float>(std::acos(std::abs(p.c)) / M_PI * 180.); callback(roi_pixels, p, roi, baseline_mm, intrin->fx, ground_truth_mm, plane_fit_present, plane_fit_to_gt_offset_mm, record, samples); // Calculate normal auto n = float3{ p.a, p.b, p.c }; auto cam = float3{ 0.f, 0.f, -1.f }; auto dot = n * cam; auto u = cam - n * dot; result.angle_x = u.x; result.angle_y = u.y; return result; } } }
ordering_op-inl.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. */ /*! * Copyright (c) 2016 by Contributors * \file ordering_op-inl.h * \brief Function definition of ordering operators */ #ifndef MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #define MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_ #include <mxnet/operator_util.h> #include <dmlc/optional.h> #include <mshadow/tensor.h> #include <algorithm> #include <vector> #include <type_traits> #include "../mshadow_op.h" #include "../elemwise_op_common.h" #include "./sort_op.h" #include "./indexing_op.h" namespace mshadow { template<typename xpu, int src_dim, typename DType, int dst_dim> inline Tensor<xpu, dst_dim, DType> inplace_reshape(Tensor<xpu, src_dim, DType> src, Shape<dst_dim> target_shape) { CHECK_EQ(src.CheckContiguous(), true); return Tensor<xpu, dst_dim, DType>(src.dptr_, target_shape, src.stream_); } }; namespace mxnet { namespace op { // These enums are only visible within this header namespace topk_enum { enum TopKReturnType {kReturnValue, kReturnIndices, kReturnMask, kReturnBoth}; } // topk_enum struct TopKParam : public dmlc::Parameter<TopKParam> { dmlc::optional<int> axis; int k; int ret_typ; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(TopKParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose the top k indices." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(k).set_default(1) .describe("Number of top elements to select," " should be always smaller than or equal to the element number in the given axis." " A global sort is performed if set k < 1."); DMLC_DECLARE_FIELD(ret_typ).set_default(topk_enum::kReturnIndices) .add_enum("value", topk_enum::kReturnValue) .add_enum("indices", topk_enum::kReturnIndices) .add_enum("mask", topk_enum::kReturnMask) .add_enum("both", topk_enum::kReturnBoth) .describe("The return type.\n" " \"value\" means to return the top k values," " \"indices\" means to return the indices of the top k values," " \"mask\" means to return a mask array containing 0 and 1. 1 means the top k values." " \"both\" means to return a list of both values and indices of top k elements."); DMLC_DECLARE_FIELD(is_ascend).set_default(false) .describe("Whether to choose k largest or k smallest elements." " Top K largest elements will be chosen if set to false."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices when ret_typ is \"indices\" or \"both\". " "An error will be raised if the selected data type cannot precisely represent the " "indices."); } }; struct SortParam : public dmlc::Parameter<SortParam> { dmlc::optional<int> axis; bool is_ascend; DMLC_DECLARE_PARAMETER(SortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to choose sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); } }; struct ArgSortParam : public dmlc::Parameter<ArgSortParam> { dmlc::optional<int> axis; bool is_ascend; int dtype; DMLC_DECLARE_PARAMETER(ArgSortParam) { DMLC_DECLARE_FIELD(axis).set_default(dmlc::optional<int>(-1)) .describe("Axis along which to sort the input tensor." " If not given, the flattened array is used. Default is -1."); DMLC_DECLARE_FIELD(is_ascend).set_default(true) .describe("Whether to sort in ascending or descending order."); DMLC_DECLARE_FIELD(dtype) // TODO(srivrohi): remove support for real data type in mxnet-2.0 .add_enum("uint8", mshadow::kUint8) .add_enum("int32", mshadow::kInt32) .add_enum("int64", mshadow::kInt64) .add_enum("float16", mshadow::kFloat16) .add_enum("float32", mshadow::kFloat32) .add_enum("float64", mshadow::kFloat64) .set_default(mshadow::kFloat32) .describe("DType of the output indices. It is only valid when ret_typ is \"indices\" or" " \"both\". An error will be raised if the selected data type cannot precisely " "represent the indices."); } }; inline void ParseTopKParam(const TShape& src_shape, const TopKParam& param, TShape *target_shape, size_t *batch_size, index_t *element_num, int *axis, index_t *k, bool *do_transpose, bool *is_ascend) { *do_transpose = false; *k = param.k; *is_ascend = param.is_ascend; // get batch_size, axis and element_num if (!static_cast<bool>(param.axis)) { // No axis given *axis = 0; *batch_size = 1; *element_num = src_shape.Size(); } else { *axis = param.axis.value(); if (*axis < 0) { *axis += src_shape.ndim(); } CHECK(*axis >= 0 && *axis < static_cast<int>(src_shape.ndim())) << "Invalid axis! axis should be between 0 and " << src_shape.ndim() << ", found axis=" << *axis; if (src_shape[*axis] != 0) { *batch_size = src_shape.Size() / src_shape[*axis]; } *element_num = src_shape[*axis]; if (*axis != src_shape.ndim() - 1) { *do_transpose = true; } } // get k if (param.k <= 0) { *k = *element_num; } // get target_shape if (!static_cast<bool>(param.axis)) { if (param.ret_typ != topk_enum::kReturnMask) { *target_shape = mshadow::Shape1(*k); } else { *target_shape = src_shape; } } else { *target_shape = src_shape; if (param.ret_typ != topk_enum::kReturnMask) { (*target_shape)[*axis] = *k; } } CHECK(*k >= 0 && *k <= *element_num) << "k must be smaller than " << *element_num << ", get k = " << *k; } using namespace mshadow; struct fill_ind_to_one { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, DType* out) { out[indices[i]] = static_cast<DType>(1); } }; struct fill_ind { template<typename DType> MSHADOW_XINLINE static void Map(int i, const index_t* indices, const DType* val, int req, DType* out) { KERNEL_ASSIGN(out[indices[i]], req, val[i]); } }; template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<cpu, 1, DType>& dat, const Tensor<cpu, 1, index_t>& ind, const Tensor<cpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<cpu> *s) { // Use full sort when K is relatively large. const bool full_sort(K*8 > N); // Batch size. const index_t M(work.size(0)/(sizeof(DType)*N)); const int omp_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()); #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < M; ++i) { // Tensor `work` stores the flattened source data, while `dat` stores the sorted result. DType *vals = reinterpret_cast<DType*>(work.dptr_); DType *sorted_vals = dat.dptr_+i*N; index_t *indices = ind.dptr_+i*N; if (is_ascend) { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] < vals[i2]; }); } } else { if (full_sort) { std::sort(indices, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } else { std::partial_sort(indices, indices+K, indices+N, [&](const index_t& i1, const index_t& i2){ return vals[i1] > vals[i2]; }); } } for (index_t j = 0; j < K; ++j) { sorted_vals[j] = vals[indices[j]]; } } } #ifdef __CUDACC__ template<typename DType> MSHADOW_XINLINE bool TopKCompare(DType val1, index_t ind1, DType val2, index_t ind2, bool is_ascend) { // Negative indices denote undefined values which are considered arbitrary small resp. large. return (ind2 < 0) || (ind1 >= 0 && ((is_ascend && val1 < val2) || (!is_ascend && val1 > val2))); } template<typename DType> MSHADOW_XINLINE void MergeTopK(index_t K, DType *val1, index_t *ind1, DType *val2, index_t *ind2, bool is_ascend) { // In-place merge of two sorted top-K lists into val1/ind1. First determine the intervals // [0,..,i1], [0,..i2] of the two lists that will be part of the merged list. index_t i1(K-1), i2(K-1); for (index_t i = 0; i < K; ++i) { if (TopKCompare(val1[i1], ind1[i1], val2[i2], ind2[i2], is_ascend)) { --i2; } else { --i1; } } // Now merge the lists from back to front. for (index_t i = K; i--;) { if (i2 < 0 || i1 >= 0 && TopKCompare(val2[i2], ind2[i2], val1[i1], ind1[i1], is_ascend)) { val1[i] = val1[i1]; ind1[i] = ind1[i1]; --i1; } else { val1[i] = val2[i2]; ind1[i] = ind2[i2]; --i2; } } } template<typename DType> __global__ void PartialSortSmallK(index_t K, index_t N, DType *val, index_t *ind, bool is_ascend) { // Buffer for pairwise reduction. extern __shared__ index_t buff[]; // Start of buffer sections associated with this thread. const index_t offset(threadIdx.x*K); index_t *ind_buff = &buff[offset]; DType *val_buff = reinterpret_cast<DType*>(&buff[blockDim.x*K])+offset; // Initialize top-K values for this thread. for (index_t i = 0; i < K; ++i) { ind_buff[i] = -1; } // Range of values this thread cares about. Each thread block processes // a different batch item (i.e. a different set of ind/val where we // have to select the top-K elements). All threads within the same // block work on the same batch item. const index_t first(blockIdx.x*N+threadIdx.x), last((blockIdx.x+1)*N); // Select top-K from this range and store it sorted in the buffer. // We assume a small K, so linear insertion is o.k. for (index_t i = first; i < last; i += blockDim.x) { DType cur_val(val[i]); index_t cur_ind(ind[i]); for (index_t j = K; j-- && TopKCompare(cur_val, cur_ind, val_buff[j], ind_buff[j], is_ascend); ) { if (j+1 < K) { val_buff[j+1] = val_buff[j]; ind_buff[j+1] = ind_buff[j]; } val_buff[j] = cur_val; ind_buff[j] = cur_ind; } } // Recursive merge of sorted lists for this thread block. Note that blockDim.x is not // necessary a power of two, therefore the additional checks for last_s. for (index_t s = (blockDim.x+1)/2, last_s = blockDim.x; last_s > 1; last_s = s, s = (s+1)/2) { __syncthreads(); if (threadIdx.x < s && threadIdx.x+s < last_s) { MergeTopK(K, val_buff, ind_buff, val_buff+s*K, ind_buff+s*K, is_ascend); } } // Final updates on master thread. if (threadIdx.x == 0) { for (index_t i = 0; i < K; ++i) { ind[blockIdx.x*N+i] = ind_buff[i]; val[blockIdx.x*N+i] = val_buff[i]; } } } template<typename DType> MSHADOW_FORCE_INLINE void TopKSort(const Tensor<gpu, 1, DType>& dat, const Tensor<gpu, 1, index_t>& ind, const Tensor<gpu, 1, char>& work, index_t K, index_t N, bool is_ascend, Stream<gpu> *s) { // Use full sort for all but very small K for which we // can do a partial sort entirely within shared memory. const bool full_sort(K > 5); // Batch size. const index_t M(dat.size(0)/N); if (full_sort) { // Divide workspace into two parts. The first one is needed to store batch ids. size_t alignment = std::max(sizeof(DType), sizeof(index_t)); size_t id_size = PadBytes(sizeof(index_t) * ind.size(0), alignment); Tensor<gpu, 1, index_t> batch_id(reinterpret_cast<index_t*>(work.dptr_), Shape1(ind.size(0)), s); Tensor<gpu, 1, char> sort_work(work.dptr_+id_size, Shape1(work.size(0)-id_size), s); mxnet::op::SortByKey(dat, ind, is_ascend, &sort_work); if (M > 1) { // Back to back sorting. Note that mxnet::op::SortByKey is a stable sort. batch_id = ind / N; mxnet::op::SortByKey(batch_id, dat, true, &sort_work); batch_id = ind / N; mxnet::op::SortByKey(batch_id, ind, true, &sort_work); } } else { const int nthreads(mshadow::cuda::kBaseThreadNum); PartialSortSmallK<<<M, nthreads, nthreads*K*(sizeof(int)+sizeof(DType)), mshadow::Stream<gpu>::GetStream(s)>>> (K, N, dat.dptr_, ind.dptr_, is_ascend); } } #endif /*! * \brief Implementation of the TopK operation * * * \param ctx the running context * \param resource temporary resource handler * \param src the Source blob * \param ret the destination blobs * \param param the topk parameters * \tparam xpu the device type. * \tparam DType type of the output value/mask. * \tparam IDType type of the output indices. */ template<typename xpu, typename DType, typename IDType> void TopKImpl(const RunContext &ctx, const Resource &resource, const std::vector<OpReqType>& req, const TBlob& src, const std::vector<TBlob>& ret, const TopKParam& param) { using namespace mshadow; using namespace mshadow::expr; // 0. If input shape is 0-shape, directly return if (src.Size() == 0) return; // 1. Parse and initialize information Stream<xpu> *s = ctx.get_stream<xpu>(); Tensor<xpu, 1, char> workspace; Tensor<xpu, 1, char> temp_workspace; Tensor<xpu, 1, DType> sorted_dat; Tensor<xpu, 1, index_t> indices, sel_indices; size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; size_t alignment = std::max(sizeof(DType), sizeof(index_t)); mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<index_t>()) << "'index_t' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<index_t>() << " elements"; Tensor<xpu, 3, DType> dat = src.FlatTo3D<xpu, DType>(axis, axis, s); // Temp space needed by the full sorts. size_t temp_size = std::max( mxnet::op::SortByKeyWorkspaceSize<index_t, DType, xpu>(src.Size()), mxnet::op::SortByKeyWorkspaceSize<DType, index_t, xpu>(src.Size())); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<index_t, index_t, xpu>(src.Size())); // Additional temp space for gpu full sorts for batch ids. temp_size += PadBytes(sizeof(index_t) * src.Size(), alignment); // Temp space for cpu sorts. temp_size = std::max(temp_size, sizeof(DType) * src.Size()); size_t workspace_size = temp_size + PadBytes(sizeof(DType) * src.Size(), alignment) + PadBytes(sizeof(index_t) * src.Size(), alignment); if (param.ret_typ == topk_enum::kReturnMask) { workspace_size += PadBytes(sizeof(index_t) * batch_size * k, alignment); } workspace = resource.get_space_typed<xpu, 1, char>(Shape1(workspace_size), s); char* workspace_curr_ptr = workspace.dptr_; sorted_dat = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(src.Size()), s); // contain sorted dat workspace_curr_ptr += PadBytes(sizeof(DType) * src.Size(), alignment); indices = Tensor<xpu, 1, index_t>(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(src.Size()), s); // indices in the original matrix workspace_curr_ptr += PadBytes(sizeof(index_t) * src.Size(), alignment); if (param.ret_typ == topk_enum::kReturnMask) { sel_indices = Tensor<xpu, 1, index_t>(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(batch_size * k), s); workspace_curr_ptr += PadBytes(sizeof(index_t) * batch_size * k, alignment); CHECK_EQ(sel_indices.CheckContiguous(), true); } if (std::is_same<xpu, cpu>::value) { Tensor<xpu, 1, DType> flattened_data; if (do_transpose) { flattened_data = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(src.Size()), s); workspace_curr_ptr += sizeof(DType) * src.Size(); flattened_data = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); CHECK_EQ(flattened_data.CheckContiguous(), true); } else { flattened_data = src.FlatTo1D<xpu, DType>(s); } // `temp_workspace` stores the flattened data temp_workspace = Tensor<xpu, 1, char>(reinterpret_cast<char*>(flattened_data.dptr_), Shape1(sizeof(DType)*src.Size()), s); CHECK_EQ(temp_workspace.CheckContiguous(), true); } else { if (do_transpose) { sorted_dat = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); } else { sorted_dat = reshape(dat, Shape1(src.Size())); } CHECK_EQ(sorted_dat.CheckContiguous(), true); temp_workspace = Tensor<xpu, 1, char>(workspace_curr_ptr, Shape1(temp_size), s); // temp space workspace_curr_ptr += temp_size; } mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size * element_num, 1, index_t{0}, index_t{1}, kWriteTo, indices.dptr_); CHECK_EQ(indices.CheckContiguous(), true); // 2. Perform inplace batch sort. // After sorting, each batch in `sorted_dat` will be sorted in the corresponding order // up to the k-th element and the `indices` will contain the corresponding index in `sorted_dat` // `temp_workspace` is used to store the flattend source data for CPU device, and it's used as // a temporal buffer for GPU device. TopKSort(sorted_dat, indices, temp_workspace, k, element_num, is_ascend, s); // 3. Assign results to the ret blob // When returning indices, only update(modulo) required elements instead of full elements // to avoid redundant calculation. // Cast `ret_indices` from int to real_t could introduce conversion error when the element_num // is large enough. if (param.ret_typ == topk_enum::kReturnMask) { Tensor<xpu, 1, DType> ret_mask = ret[0].FlatTo1D<xpu, DType>(s); ret_mask = scalar<DType>(0); sel_indices = reshape(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), Shape1(batch_size * k)); if (do_transpose) { mxnet::TShape src_shape = src.shape_.FlatTo3D(axis); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } if (req[0] == kNullOp) { return; } else if (req[0] == kWriteTo) { mxnet_op::Kernel<fill_ind_to_one, xpu>::Launch(s, batch_size * k, sel_indices.dptr_, ret_mask.dptr_); } else { LOG(FATAL) << "req=" << req[0] << " is not supported yet."; } } else if (param.ret_typ == topk_enum::kReturnIndices) { if (do_transpose) { Tensor<xpu, 3, IDType> ret_indices = ret[0].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, IDType> ret_indices = ret[0].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } else { if (do_transpose) { Tensor<xpu, 3, DType> ret_value = ret[0].FlatTo3D<xpu, DType>(axis, axis, s); Tensor<xpu, 3, IDType> ret_indices = ret[1].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_value, req[0], transpose( slice<2>(inplace_reshape(sorted_dat, Shape3(ret_value.shape_[0], ret_value.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, DType> ret_value = ret[0].get_with_shape<xpu, 2, DType>(Shape2(batch_size, k), s); Tensor<xpu, 2, IDType> ret_indices = ret[1].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_value, req[0], slice<1>(inplace_reshape(sorted_dat, Shape2(batch_size, element_num)), 0, k)); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } } template<typename xpu, typename DType> size_t TopKWorkspaceSize(const TBlob& src, const TopKParam& param, size_t *temp_size_ptr) { using namespace mshadow; using namespace mshadow::expr; size_t batch_size = 0; size_t temp_size; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; size_t alignment = std::max(sizeof(DType), sizeof(index_t)); mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); // Temp space needed by the full sorts. temp_size = std::max( mxnet::op::SortByKeyWorkspaceSize<index_t, DType, xpu>(src.Size()), mxnet::op::SortByKeyWorkspaceSize<DType, index_t, xpu>(src.Size())); temp_size = std::max(temp_size, mxnet::op::SortByKeyWorkspaceSize<index_t, index_t, xpu>(src.Size())); // Additional temp space for gpu full sorts for batch ids. temp_size += PadBytes(sizeof(index_t) * src.Size(), alignment); // Temp space for cpu sorts. temp_size = std::max(temp_size, sizeof(DType) * src.Size()); *temp_size_ptr = temp_size; size_t workspace_size = temp_size + PadBytes(sizeof(DType) * src.Size(), alignment) + PadBytes(sizeof(index_t) * src.Size(), alignment); if (param.ret_typ == topk_enum::kReturnMask) { workspace_size += PadBytes(sizeof(index_t) * batch_size * k, alignment); } return workspace_size; } template<typename xpu, typename DType, typename IDType> void TopKImplwithWorkspace(const RunContext &ctx, const std::vector<OpReqType>& req, const TBlob& src, const std::vector<TBlob>& ret, const TopKParam& param, char* workspace_curr_ptr, const size_t &temp_size, Stream<xpu>* s) { using namespace mshadow; using namespace mshadow::expr; // 0. If input shape is 0-shape, directly return if (src.Size() == 0) return; // 1. Parse and initialize information Tensor<xpu, 1, char> workspace; Tensor<xpu, 1, char> temp_workspace; Tensor<xpu, 1, DType> sorted_dat; Tensor<xpu, 1, index_t> indices, sel_indices; size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; size_t alignment = std::max(sizeof(DType), sizeof(index_t)); mxnet::TShape target_shape; ParseTopKParam(src.shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<index_t>()) << "'index_t' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<index_t>() << " elements"; Tensor<xpu, 3, DType> dat = src.FlatTo3D<xpu, DType>(axis, axis, s); sorted_dat = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(src.Size()), s); // contain sorted dat workspace_curr_ptr += PadBytes(sizeof(DType) * src.Size(), alignment); indices = Tensor<xpu, 1, index_t>(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(src.Size()), s); // indices in the original matrix workspace_curr_ptr += PadBytes(sizeof(index_t) * src.Size(), alignment); if (param.ret_typ == topk_enum::kReturnMask) { sel_indices = Tensor<xpu, 1, index_t>(reinterpret_cast<index_t*>(workspace_curr_ptr), Shape1(batch_size * k), s); workspace_curr_ptr += PadBytes(sizeof(index_t) * batch_size * k, alignment); CHECK_EQ(sel_indices.CheckContiguous(), true); } if (std::is_same<xpu, cpu>::value) { Tensor<xpu, 1, DType> flattened_data; if (do_transpose) { flattened_data = Tensor<xpu, 1, DType>(reinterpret_cast<DType*>(workspace_curr_ptr), Shape1(src.Size()), s); workspace_curr_ptr += sizeof(DType) * src.Size(); flattened_data = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); CHECK_EQ(flattened_data.CheckContiguous(), true); } else { flattened_data = src.FlatTo1D<xpu, DType>(s); } // `temp_workspace` stores the flattened data temp_workspace = Tensor<xpu, 1, char>(reinterpret_cast<char*>(flattened_data.dptr_), Shape1(sizeof(DType)*src.Size()), s); CHECK_EQ(temp_workspace.CheckContiguous(), true); } else { if (do_transpose) { sorted_dat = reshape(transpose(dat, Shape3(0, 2, 1)), Shape1(src.Size())); } else { sorted_dat = reshape(dat, Shape1(src.Size())); } CHECK_EQ(sorted_dat.CheckContiguous(), true); temp_workspace = Tensor<xpu, 1, char>(workspace_curr_ptr, Shape1(temp_size), s); // temp space workspace_curr_ptr += temp_size; } mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size * element_num, 1, index_t{0}, index_t{1}, kWriteTo, indices.dptr_); CHECK_EQ(indices.CheckContiguous(), true); // 2. Perform inplace batch sort. // After sorting, each batch in `sorted_dat` will be sorted in the corresponding order // up to the k-th element and the `indices` will contain the corresponding index in `sorted_dat` // `temp_workspace` is used to store the flattend source data for CPU device, and it's used as // a temporal buffer for GPU device. TopKSort(sorted_dat, indices, temp_workspace, k, element_num, is_ascend, s); // 3. Assign results to the ret blob // When returning indices, only update(modulo) required elements instead of full elements // to avoid redundant calculation. // Cast `ret_indices` from int to real_t could introduce conversion error when the element_num // is large enough. if (param.ret_typ == topk_enum::kReturnMask) { Tensor<xpu, 1, DType> ret_mask = ret[0].FlatTo1D<xpu, DType>(s); ret_mask = scalar<DType>(0); sel_indices = reshape(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), Shape1(batch_size * k)); if (do_transpose) { mxnet::TShape src_shape = src.shape_.FlatTo3D(axis); CHECK_EQ(sel_indices.CheckContiguous(), true); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } if (req[0] == kNullOp) { return; } else if (req[0] == kWriteTo) { mxnet_op::Kernel<fill_ind_to_one, xpu>::Launch(s, batch_size * k, sel_indices.dptr_, ret_mask.dptr_); } else { LOG(FATAL) << "req=" << req[0] << " is not supported yet."; } } else if (param.ret_typ == topk_enum::kReturnIndices) { if (do_transpose) { Tensor<xpu, 3, IDType> ret_indices = ret[0].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, IDType> ret_indices = ret[0].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_indices, req[0], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } else { if (do_transpose) { Tensor<xpu, 3, DType> ret_value = ret[0].FlatTo3D<xpu, DType>(axis, axis, s); Tensor<xpu, 3, IDType> ret_indices = ret[1].FlatTo3D<xpu, IDType>(axis, axis, s); ASSIGN_DISPATCH(ret_value, req[0], transpose( slice<2>(inplace_reshape(sorted_dat, Shape3(ret_value.shape_[0], ret_value.shape_[2], element_num)), 0, k), Shape3(0, 2, 1))); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(transpose( slice<2>(inplace_reshape(indices, Shape3(ret_indices.shape_[0], ret_indices.shape_[2], element_num)), 0, k), Shape3(0, 2, 1)), element_num))); } else { Tensor<xpu, 2, DType> ret_value = ret[0].get_with_shape<xpu, 2, DType>(Shape2(batch_size, k), s); Tensor<xpu, 2, IDType> ret_indices = ret[1].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); ASSIGN_DISPATCH(ret_value, req[0], slice<1>(inplace_reshape(sorted_dat, Shape2(batch_size, element_num)), 0, k)); ASSIGN_DISPATCH(ret_indices, req[1], tcast<IDType>(F<mshadow_op::mod>(slice<1>( inplace_reshape(indices, Shape2(batch_size, element_num)), 0, k), element_num))); } } } template<typename xpu> void TopK(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnBoth) { MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { MSHADOW_TYPE_SWITCH(param.dtype, IDType, { TopKImpl<xpu, DType, IDType>(ctx.run_ctx, ctx.requested[0], req, inputs[0], outputs, param); }) }); } else { MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { TopKImpl<xpu, DType, index_t>(ctx.run_ctx, ctx.requested[0], req, inputs[0], outputs, param); }); } } template<typename xpu> void Sort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; MXNET_NO_FLOAT16_TYPE_SWITCH(inputs[0].type_flag_, DType, { TopKImpl<xpu, DType, index_t>(ctx.run_ctx, ctx.requested[0], req, inputs[0], outputs, topk_param); }); } template<typename xpu> void ArgSort(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.dtype = param.dtype; topk_param.ret_typ = topk_enum::kReturnIndices; MXNET_NO_FLOAT16_TYPE_SWITCH(inputs[0].type_flag_, DType, { MSHADOW_TYPE_SWITCH(param.dtype, IDType, { TopKImpl<xpu, DType, IDType>(ctx.run_ctx, ctx.requested[0], req, inputs[0], outputs, topk_param); }); }); } template<typename xpu, typename DType, typename IDType> void TopKBackwardImpl(const OpContext &ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const TopKParam& param) { CHECK_NE(req[0], kWriteInplace); using namespace mshadow; using namespace mshadow::expr; Stream<xpu> *s = ctx.run_ctx.get_stream<xpu>(); CHECK(param.ret_typ == topk_enum::kReturnValue || param.ret_typ == topk_enum::kReturnBoth); size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(outputs[0].shape_, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); CHECK_LE(element_num, mxnet::common::MaxIntegerValue<IDType>()) << "'IDType' does not have a sufficient precision to represent " << "the indices of the input array. The total element_num is " << element_num << ", but the selected index_t can only represent " << mxnet::common::MaxIntegerValue<IDType>() << " elements"; Tensor<xpu, 1, index_t> workspace = ctx.requested[0].get_space_typed<xpu, 1, index_t>(Shape1(batch_size * k + batch_size), s); Tensor<xpu, 1, index_t> sel_indices = Tensor<xpu, 1, index_t>(workspace.dptr_, Shape1(batch_size * k), s); Tensor<xpu, 1, index_t> batch_shift = Tensor<xpu, 1, index_t>(workspace.dptr_ + batch_size * k, Shape1(batch_size), s); Tensor<xpu, 2, DType> out_grad = inputs[0].get_with_shape<xpu, 2, DType>(Shape2(inputs[0].shape_.Size(), 1), s); Tensor<xpu, 2, DType> in_grad = outputs[0].get_with_shape<xpu, 2, DType>(Shape2(outputs[0].shape_.Size(), 1), s); mxnet_op::Kernel<range_fwd, xpu>::Launch(s, batch_size, 1, index_t{0}, element_num, kWriteTo, batch_shift.dptr_); if (do_transpose) { Tensor<xpu, 1, IDType> indices = inputs[2].FlatTo1D<xpu, IDType>(s); mxnet::TShape src_shape = outputs[0].shape_.FlatTo3D(axis); sel_indices = reshape(transpose( broadcast_to(inplace_reshape(batch_shift, Shape3(src_shape[0], src_shape[2], 1)), mxnet::TShape(Shape3(src_shape[0], src_shape[2], k))), Shape3(0, 2, 1)), Shape1(batch_size * k)); sel_indices += tcast<index_t>(indices); sel_indices = transpose_indices(sel_indices, Shape3(src_shape[0], src_shape[2], src_shape[1]), Shape3(0, 2, 1)); } else { Tensor<xpu, 2, IDType> indices = inputs[2].get_with_shape<xpu, 2, IDType>(Shape2(batch_size, k), s); sel_indices = reshape(tcast<index_t>(indices) + broadcast_to(inplace_reshape(batch_shift, Shape2(batch_size, 1)), mxnet::TShape(Shape2(batch_size, k))), Shape1(batch_size * k)); } CHECK_EQ(sel_indices.CheckContiguous(), true); if (kWriteTo == req[0] || kAddTo == req[0]) { if (kWriteTo == req[0]) { in_grad = scalar<DType>(0); } mxnet_op::Kernel<fill_ind, xpu>::Launch(s, batch_size * k, sel_indices.dptr_, out_grad.dptr_, req[0], in_grad.dptr_); } else { LOG(FATAL) << "Not Implemented!"; } } template<typename xpu> void TopKBackward_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnBoth) { MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { MSHADOW_TYPE_SWITCH(param.dtype, IDType, { TopKBackwardImpl<xpu, DType, IDType>(ctx, inputs, req, outputs, param); }); }); } else if (param.ret_typ == topk_enum::kReturnValue) { MSHADOW_TYPE_SWITCH(inputs[0].type_flag_, DType, { TopKBackwardImpl<xpu, DType, index_t>(ctx, inputs, req, outputs, param); }); } else { LOG(FATAL) << "Not Implemented"; } } inline uint32_t TopKNumOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { return static_cast<uint32_t>(1); } else { return static_cast<uint32_t>(2); } } inline uint32_t TopKNumVisibleOutputs(const NodeAttrs& attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); if (param.ret_typ == topk_enum::kReturnBoth) { return static_cast<uint32_t>(2); } else { return static_cast<uint32_t>(1); } } inline bool TopKType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); size_t in_size = in_attrs->size(); size_t out_size = out_attrs->size(); CHECK_EQ(in_size, 1); CHECK(out_size == 1 || out_size == 2); // out_attr[0] -> stores value // out_attr[1] -> stores indices if (out_size > 1) { if (param.ret_typ == topk_enum::kReturnValue) { #if MXNET_USE_INT64_TENSOR_SIZE == 1 CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt64)) #else CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt32)) #endif << "Failed to set the type of ret_indices."; } else { CHECK(type_assign(&(*out_attrs)[1], param.dtype)) << "Failed to set the type of ret_indices."; } } if (param.ret_typ == topk_enum::kReturnIndices) { CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices."; } else { TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return out_attrs->at(0) != -1; } return true; } inline bool TopKShapeImpl(const TopKParam& param, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { CHECK_EQ(out_attrs->size(), 1U); } else { CHECK_EQ(out_attrs->size(), 2U); } mxnet::TShape& in_shape = (*in_attrs)[0]; size_t batch_size = 0; index_t element_num = 0; // number of batches + the size of each batch int axis = 0; bool do_transpose = false; bool is_ascend = false; index_t k = 0; mxnet::TShape target_shape; ParseTopKParam(in_shape, param, &target_shape, &batch_size, &element_num, &axis, &k, &do_transpose, &is_ascend); if (param.ret_typ == topk_enum::kReturnIndices || param.ret_typ == topk_enum::kReturnMask) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); } else { SHAPE_ASSIGN_CHECK(*out_attrs, 0, target_shape); SHAPE_ASSIGN_CHECK(*out_attrs, 1, target_shape); } return true; } inline bool TopKShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const TopKParam& param = nnvm::get<TopKParam>(attrs.parsed); return TopKShapeImpl(param, in_attrs, out_attrs); } inline bool SortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { int data_type = -1; size_t in_size = in_attrs->size(); size_t out_size = out_attrs->size(); CHECK_EQ(in_size, 1); CHECK_EQ(out_size, 2); #if MXNET_USE_INT64_TENSOR_SIZE == 1 CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt64)) #else CHECK(type_assign(&(*out_attrs)[1], mshadow::kInt32)) #endif << "Failed to set the type of ret_indices"; CHECK(type_assign(&data_type, (*in_attrs)[0])) << "Incompatible dtype of input, in_attrs[0]=" << (*in_attrs)[0]; CHECK(type_assign(&data_type, (*out_attrs)[0])) << "Incompatible dtype of output, out_attrs[0]=" << (*out_attrs)[0]; CHECK(type_assign(&(*in_attrs)[0], data_type)) << "Incompatible dtype of input, in_attrs[0]=" << (*in_attrs)[0]; CHECK(type_assign(&(*out_attrs)[0], data_type)) << "Incompatible dtype of output, out_attrs[0]=" << (*out_attrs)[0]; if (data_type == -1) return false; return true; } inline bool SortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SortParam& param = nnvm::get<SortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnValue; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } inline bool ArgSortType(const nnvm::NodeAttrs& attrs, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); CHECK(type_assign(&(*out_attrs)[0], param.dtype)) << "Failed to set the type of ret_indices."; return true; } inline bool ArgSortShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const ArgSortParam& param = nnvm::get<ArgSortParam>(attrs.parsed); TopKParam topk_param; topk_param.axis = param.axis; topk_param.is_ascend = param.is_ascend; topk_param.k = 0; topk_param.ret_typ = topk_enum::kReturnIndices; return TopKShapeImpl(topk_param, in_attrs, out_attrs); } } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ORDERING_OP_INL_H_
PoW.c
#include "PoW.h" #include <stdio.h> #include <stdint.h> #include <string.h> #include <stdlib.h> #include <assert.h> #ifndef SYS_OS_MAC #include <omp.h> #endif #include "my_time.h" #include "sha256.h" #include "common.h" #include "my_rand48_r.h" #include "oneWayFunction.h" // #define SSE_VERSION extern void showbuf(const uint8_t * buf, int len); /* * Step 1: Initialize working memory. */ void initWorkMemory(uint8_t *input, uint32_t inputLen, uint8_t *Maddr, const uint32_t K) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[OUTPUT_LEN]; funcInfor[0].func(input, inputLen, a); uint64_t randSeed[4] = {0, 0, 0, 0}; #ifndef SSE_VERSION struct my_rand48_data randBuffer[4]; #else struct vrand48_data randBuffer[2]; #endif const uint32_t iterNum = WORK_MEMORY_SIZE >> 5; for (i = 0; i < iterNum; ++i) { if (i % K) { #ifndef SSE_VERSION uint64_t num = 0; for (j = 0; j < 4; ++j) { my_rand64_r(&randBuffer[j], &num); memcpy(b + (j << 3), (uint8_t *)&num, 8*sizeof(uint8_t)); } #else vrand64(b, randBuffer); #endif uint8_t shift_num; uint8_t result[OUTPUT_LEN]; reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); rrs(b, OUTPUT_LEN, result, shift_num); memcpy(Maddr + (i << 5), result, OUTPUT_LEN*sizeof(uint8_t)); for (j = 0; j < 32; ++j) { a[j] ^= result[j]; } } else { uint8_t t = 0, shift_num = 0; reduce_bit(a, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit((uint8_t *)&i, 4, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); reduce_bit(a, 8, (uint8_t *)&randSeed[0], 48); reduce_bit(a + 8, 8, (uint8_t *)&randSeed[1], 48); reduce_bit(a + 16, 8, (uint8_t *)&randSeed[2], 48); reduce_bit(a + 24, 8, (uint8_t *)&randSeed[3], 48); #ifndef SSE_VERSION my_seed48_r(randSeed[0], &randBuffer[0]); my_seed48_r(randSeed[1], &randBuffer[1]); my_seed48_r(randSeed[2], &randBuffer[2]); my_seed48_r(randSeed[3], &randBuffer[3]); #else vseed48(randSeed , &randBuffer[0]); vseed48(randSeed + 2, &randBuffer[1]); #endif memcpy(Maddr + (i << 5), a, 32*sizeof(uint8_t)); } } } /* * Step 2: Modify the working memory contents. */ void modifyWorkMemory(uint8_t *Maddr, const uint32_t L, const uint32_t C, uint8_t *result) { uint32_t i, j; uint8_t a[OUTPUT_LEN], b[64]; funcInfor[0].func(Maddr + WORK_MEMORY_SIZE - 32, 32, a); memcpy(result, a, OUTPUT_LEN*sizeof(uint8_t)); uint64_t r = 0; reduce_bit(a, 32, (uint8_t *)&r, 64); const uint32_t iterNum = L << 6; for (i = 0; i < C; ++i) { uint64_t randSeed = 0; reduce_bit(a, 32, (uint8_t *)&randSeed, 48); struct my_rand48_data randBuffer; my_seed48_r(randSeed, &randBuffer); uint8_t t1, t2, s; uint64_t randNum = 0, base = 0; for (j = 0; j < iterNum; ++j) { my_rand48_r(&randBuffer, &randNum); base = randNum + r; uint64_t offset = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&offset, 8); offset = (offset << 8) + 1; uint64_t addr1 = (base + WORK_MEMORY_SIZE - offset) % WORK_MEMORY_SIZE; uint64_t addr2 = (base + offset) % WORK_MEMORY_SIZE; t1 = Maddr[addr1]; t2 = Maddr[addr2]; s = a[j & 0x1f]; Maddr[addr1] = t2 ^ s; Maddr[addr2] = t1 ^ s; b[j & 0x3f] = t1 ^ t2; r = r + s + t1 + t2; } uint8_t t = 0; reduce_bit((uint8_t *)&r, 8, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(b, 64, a, 256); uint8_t shift_num = 0; uint64_t ir = r + i; reduce_bit((uint8_t *)&ir, 8, (uint8_t *)&shift_num, 8); uint8_t a_rrs[INPUT_LEN]; rrs(a, OUTPUT_LEN, a_rrs, shift_num); funcInfor[t].func(a_rrs, 32, a); for (j = 0; j < OUTPUT_LEN; ++j) { result[j] ^= a[j]; } } } /* * Step 3: Calculate the final result. */ void calculateFinalResult(uint8_t *Maddr, uint8_t *c, const uint32_t D, uint8_t *result) { uint32_t i = 0, j = 0, k = 0; memcpy(result, c, OUTPUT_LEN*sizeof(uint8_t)); const uint32_t num = (WORK_MEMORY_SIZE >> 5) - 1; uint32_t it = 0; uint8_t result_rrs[OUTPUT_LEN]; while(1) { uint8_t t = 0, shift_num = 0; uint32_t d = 0; reduce_bit(result, 32, (uint8_t *)&t, 8); t = (t & 0x0f) ^ (t >> 4); reduce_bit(result, 32, (uint8_t *)&d, D); ++d; for (j = 0; j < d; ++j) { uint32_t index = i << 5; for (k = 0; k < 32; ++k) { result[k] ^= Maddr[index + k]; } ++i; if (i == num) { it = i + t; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[0].func(result_rrs, 32, result); return; } } it = t + i; reduce_bit((uint8_t *)&it, 4, (uint8_t *)&shift_num, 8); rrs(result, OUTPUT_LEN, result_rrs, shift_num); funcInfor[t].func(result_rrs, 32, result); } } /* * Correctness & Performance test for Proof of work */ void testPowFunction(uint8_t *mess, uint32_t messLen, const int64_t iterNum) { uint32_t inputLen = messLen; uint8_t input[INPUT_LEN], output[OUTPUT_LEN]; memset(input, 0, INPUT_LEN*sizeof(uint8_t)); memcpy(input, mess, messLen*sizeof(char)); // Init all one-way function initOneWayFunction(); uint8_t *Maddr = (uint8_t *)malloc(64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, 64 * WORK_MEMORY_SIZE*sizeof(uint8_t)); printf("****************************** Correctness test (PoW function) ******************************\n"); printf("Test message: %s\n", mess); powFunction(input, inputLen, Maddr, output); //view_data_u8("PoW", output, OUTPUT_LEN); printf("*********************************************************************************************\n"); /* printf("*************************************************** Performance test (PoW function) ***************************************************\n"); uint8_t *result = (uint8_t *)malloc(iterNum * OUTPUT_LEN * sizeof(uint8_t)); assert(NULL != result); memset(result, 0, iterNum * OUTPUT_LEN * sizeof(uint8_t)); uint32_t threadNumArr[] = {1, 4, 8, 12, 16, 20, 24, 32, 48, 64}; uint32_t threadNumTypes = sizeof(threadNumArr) / sizeof(uint32_t); printf(" %-18s", "Algorithm"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) printf("%12d", threadNumArr[ix]); printf("\n"); printf("00 %-18s\t", "PoW"); for (uint32_t ix = 0; ix < threadNumTypes; ++ix) { omp_set_num_threads(threadNumArr[ix]); double startTime = get_wall_time(); if (threadNumArr[ix] == 1) { for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr, result + j * OUTPUT_LEN); } } else { #pragma omp parallel for firstprivate(input), private(j) shared(result) for (j = 0; j < iterNum; ++j) { powFunction(input, inputLen, Maddr + omp_get_thread_num() * WORK_MEMORY_SIZE, result + j * OUTPUT_LEN); } } double endTime = get_wall_time(); double costTime = endTime - startTime; printf("%5.0f bps ", iterNum / costTime); fflush(stdout); // Check result for (j = 0; j < iterNum; j += 1) { if (memcmp(output, result + j * OUTPUT_LEN, OUTPUT_LEN)) { printf("Thread num: %d, j: %ld\n", threadNumArr[ix], j); view_data_u8("output", output, OUTPUT_LEN); view_data_u8("result", result + j * OUTPUT_LEN, OUTPUT_LEN); abort(); } } } printf("\n"); printf("***************************************************************************************************************************************\n"); if (NULL != result) { free(result); result = NULL; } */ if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } #define OUTPUT_BUFFER_SIZE (32 * 1024UL * 1024UL) #define MAX_TEST_INPUT_LEN 140 #define MAX_OUT_FILE_NAME_LEN 25 const char testInputCase[][MAX_TEST_INPUT_LEN] = { "", "HelloWorld", "0123456789" }; void powNistTest(const char *outFileName) { const uint64_t iterNum = 1024UL * 1024UL; // const uint64_t iterNum = 1024UL; uint8_t *outputBuffer = (uint8_t *)malloc(OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); assert(NULL != outputBuffer); memset(outputBuffer, 0, OUTPUT_BUFFER_SIZE * sizeof(uint8_t)); uint8_t *Maddr = (uint8_t *)malloc(WORK_MEMORY_SIZE*sizeof(uint8_t)); assert(NULL != Maddr); memset(Maddr, 0, WORK_MEMORY_SIZE*sizeof(uint8_t)); initOneWayFunction(); uint32_t testInputCaseNum = sizeof(testInputCase) / sizeof(const char [MAX_TEST_INPUT_LEN]); for (uint32_t testCaseIx = 0; testCaseIx < testInputCaseNum; ++testCaseIx) { char curOutFileName[MAX_OUT_FILE_NAME_LEN] = ""; sprintf(curOutFileName, "%s-%u.txt", outFileName, testCaseIx); FILE *fp = NULL; if (NULL != (fp = fopen(curOutFileName, "wb"))) { const uint32_t testInputCaseLen = strlen((char *)testInputCase[testCaseIx]); uint8_t input[MAX_TEST_INPUT_LEN]; memset(input, 0, MAX_TEST_INPUT_LEN*sizeof(uint8_t)); memcpy(input, testInputCase[testCaseIx], testInputCaseLen*sizeof(uint8_t)); double startTime = get_wall_time(); powFunction(input, testInputCaseLen, Maddr, outputBuffer); for (uint64_t i = 1, j = 0; i < iterNum; ++i) { memcpy(input, outputBuffer + j, OUTPUT_LEN * sizeof(uint32_t)); j += OUTPUT_LEN; powFunction(input, OUTPUT_LEN, Maddr, outputBuffer + j); /* if (j == OUTPUT_BUFFER_SIZE) { fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); j = 0; } */ } double endTime = get_wall_time(); double costTime = endTime - startTime; fprintf(stdout, "TestCaseIx: %d, Input: %s, IterNum: %llu, Time: %4.2f, Performance: %5.2f bps\n", testCaseIx, \ testInputCase[testCaseIx], iterNum, costTime, ((double)(iterNum * OUTPUT_LEN)) / costTime); fflush(stdout); fwrite(outputBuffer, sizeof(uint8_t), OUTPUT_BUFFER_SIZE / sizeof(uint8_t), fp); fclose(fp); } else { fprintf(stderr, "Error: Open %s failed!\n", curOutFileName); abort(); } } if (NULL != outputBuffer) { free(outputBuffer); outputBuffer = NULL; } if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } void helloHash(uint8_t *mess, uint32_t messLen, uint8_t output[OUTPUT_LEN]) { //printf("Test message length: %lu\n", messLen); const int INPUT_LEN2 = 180; uint32_t inputLen = messLen; if(inputLen != INPUT_LEN && inputLen != INPUT_LEN2){ //won't get in return; } uint8_t input[inputLen]; memset(input, 0, inputLen*sizeof(uint8_t)); memcpy(input, mess, inputLen*sizeof(char)); //operation: input if(inputLen == INPUT_LEN2) { sha256(input, inputLen, output); //view_data_u8("PoW", output, OUTPUT_LEN); //output return; } initOneWayFunction(); uint8_t *Maddr = (uint8_t *)malloc(WORK_MEMORY_SIZE*sizeof(uint8_t)); //1024*1024*1 assert(NULL != Maddr); memset(Maddr, 0, WORK_MEMORY_SIZE*sizeof(uint8_t)); //printf("Test message: %s\n", mess); powFunction(input, inputLen,Maddr, output); //view_data_u8("PoW", output, OUTPUT_LEN); //output if (NULL != Maddr) { free(Maddr); Maddr = NULL; } } int my_rand64_r (struct my_rand48_data *buffer, uint64_t *result) { uint64_t X = buffer->__x; X = (X * buffer->__a + buffer->__c) & 0xffffffffffffULL; buffer->__x = X; buffer->__x = (X * buffer->__a + buffer->__c) & 0xffffffffffffULL; X ^= buffer->__x << 16; *result = X; return 0; } int my_seed48_r (uint64_t seedval, struct my_rand48_data *buffer) { buffer->__x = seedval & 0xffffffffffffULL; buffer->__a = 0x5deece66dULL; buffer->__c = 0xb; return 0; } void powFunction(uint8_t *input, uint32_t inputLen, uint8_t *Maddr, uint8_t *output) { uint8_t c[OUTPUT_LEN]; // Step 1: Initialize working memory. initWorkMemory(input, inputLen, Maddr, 128); // view_data_u8("Maddr", Maddr, OUTPUT_LEN); // Step 2: Modify the working memory contents. modifyWorkMemory(Maddr, 4, WORK_MEMORY_SIZE >> 11, c); // view_data_u8("c", c, OUTPUT_LEN); // Step 3: Calculate the final result. calculateFinalResult(Maddr, c, 8, output); // view_data_u8("output", output, OUTPUT_LEN); } int my_rand48_r (struct my_rand48_data *buffer, uint64_t *result) { *result = (buffer->__x * buffer->__a + buffer->__c) & 0xffffffffffffULL; buffer->__x = *result; return 0; }
transform.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT RRRR AAA N N SSSSS FFFFF OOO RRRR M M % % T R R A A NN N SS F O O R R MM MM % % T RRRR AAAAA N N N SSS FFF O O RRRR M M M % % T R R A A N NN SS F O O R R M M % % T R R A A N N SSSSS F OOO R R M M % % % % % % MagickCore Image Transform Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 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/attribute.h" #include "MagickCore/cache.h" #include "MagickCore/cache-view.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/effect.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/memory_.h" #include "MagickCore/layer.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.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" #include "MagickCore/transform-private.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A u t o O r i e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AutoOrientImage() adjusts an image so that its orientation is suitable for % viewing (i.e. top-left orientation). % % The format of the AutoOrientImage method is: % % Image *AutoOrientImage(const Image *image, % const OrientationType orientation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: The image. % % o orientation: Current image orientation. % % o exception: Return any errors or warnings in this structure. % */ MagickExport Image *AutoOrientImage(const Image *image, const OrientationType orientation,ExceptionInfo *exception) { Image *orient_image; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); orient_image=(Image *) NULL; switch(orientation) { case UndefinedOrientation: case TopLeftOrientation: default: { orient_image=CloneImage(image,0,0,MagickTrue,exception); break; } case TopRightOrientation: { orient_image=FlopImage(image,exception); break; } case BottomRightOrientation: { orient_image=RotateImage(image,180.0,exception); break; } case BottomLeftOrientation: { orient_image=FlipImage(image,exception); break; } case LeftTopOrientation: { orient_image=TransposeImage(image,exception); break; } case RightTopOrientation: { orient_image=RotateImage(image,90.0,exception); break; } case RightBottomOrientation: { orient_image=TransverseImage(image,exception); break; } case LeftBottomOrientation: { orient_image=RotateImage(image,270.0,exception); break; } } if (orient_image != (Image *) NULL) orient_image->orientation=TopLeftOrientation; return(orient_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C h o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ChopImage() removes a region of an image and collapses the image to occupy % the removed portion. % % The format of the ChopImage method is: % % Image *ChopImage(const Image *image,const RectangleInfo *chop_info) % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o chop_info: Define the region of the image to chop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ChopImage(const Image *image,const RectangleInfo *chop_info, ExceptionInfo *exception) { #define ChopImageTag "Chop/Image" CacheView *chop_view, *image_view; Image *chop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo extent; ssize_t y; /* Check chop geometry. */ 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(chop_info != (RectangleInfo *) NULL); if (((chop_info->x+(ssize_t) chop_info->width) < 0) || ((chop_info->y+(ssize_t) chop_info->height) < 0) || (chop_info->x > (ssize_t) image->columns) || (chop_info->y > (ssize_t) image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); extent=(*chop_info); if ((extent.x+(ssize_t) extent.width) > (ssize_t) image->columns) extent.width=(size_t) ((ssize_t) image->columns-extent.x); if ((extent.y+(ssize_t) extent.height) > (ssize_t) image->rows) extent.height=(size_t) ((ssize_t) image->rows-extent.y); if (extent.x < 0) { extent.width-=(size_t) (-extent.x); extent.x=0; } if (extent.y < 0) { extent.height-=(size_t) (-extent.y); extent.y=0; } chop_image=CloneImage(image,image->columns-extent.width,image->rows- extent.height,MagickTrue,exception); if (chop_image == (Image *) NULL) return((Image *) NULL); /* Extract chop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); chop_view=AcquireAuthenticCacheView(chop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,chop_image,extent.y,1) #endif for (y=0; y < (ssize_t) extent.y; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,y,chop_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel); if ((traits == UndefinedPixelTrait) || (chop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(chop_image,channel,p[i],q); } q+=GetPixelChannels(chop_image); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ChopImage) #endif proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } /* Extract chop image. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,chop_image,image->rows-(extent.y+extent.height),1) #endif for (y=0; y < (ssize_t) (image->rows-(extent.y+extent.height)); y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,extent.y+extent.height+y, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(chop_view,0,extent.y+y,chop_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { if ((x < extent.x) || (x >= (ssize_t) (extent.x+extent.width))) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait chop_traits=GetPixelChannelTraits(chop_image,channel); if ((traits == UndefinedPixelTrait) || (chop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(chop_image,channel,p[i],q); } q+=GetPixelChannels(chop_image); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(chop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ChopImage) #endif proceed=SetImageProgress(image,ChopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } chop_view=DestroyCacheView(chop_view); image_view=DestroyCacheView(image_view); chop_image->type=image->type; if (status == MagickFalse) chop_image=DestroyImage(chop_image); return(chop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C M Y K I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCMYKImage() consolidates separate C, M, Y, and K planes into a % single image. % % The format of the ConsolidateCMYKImage method is: % % Image *ConsolidateCMYKImage(const 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 *ConsolidateCMYKImages(const Image *images, ExceptionInfo *exception) { CacheView *cmyk_view, *image_view; Image *cmyk_image, *cmyk_images; register ssize_t j; ssize_t y; /* Consolidate separate C, M, Y, and K planes into a single image. */ 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); cmyk_images=NewImageList(); for (j=0; j < (ssize_t) GetImageListLength(images); j+=4) { register ssize_t i; assert(images != (Image *) NULL); cmyk_image=CloneImage(images,images->columns,images->rows,MagickTrue, exception); if (cmyk_image == (Image *) NULL) break; if (SetImageStorageClass(cmyk_image,DirectClass,exception) == MagickFalse) break; (void) SetImageColorspace(cmyk_image,CMYKColorspace,exception); for (i=0; i < 4; i++) { image_view=AcquireVirtualCacheView(images,exception); cmyk_view=AcquireAuthenticCacheView(cmyk_image,exception); for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; p=GetCacheViewVirtualPixels(image_view,0,y,images->columns,1,exception); q=QueueCacheViewAuthenticPixels(cmyk_view,0,y,cmyk_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) images->columns; x++) { Quantum pixel; pixel=QuantumRange-GetPixelIntensity(images,p); switch (i) { case 0: SetPixelCyan(cmyk_image,pixel,q); break; case 1: SetPixelMagenta(cmyk_image,pixel,q); break; case 2: SetPixelYellow(cmyk_image,pixel,q); break; case 3: SetPixelBlack(cmyk_image,pixel,q); break; default: break; } p+=GetPixelChannels(images); q+=GetPixelChannels(cmyk_image); } if (SyncCacheViewAuthenticPixels(cmyk_view,exception) == MagickFalse) break; } cmyk_view=DestroyCacheView(cmyk_view); image_view=DestroyCacheView(image_view); images=GetNextImageInList(images); if (images == (Image *) NULL) break; } AppendImageToList(&cmyk_images,cmyk_image); } return(cmyk_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImage() extracts a region of the image starting at the offset defined % by geometry. Region must be fully defined, and no special handling of % geometry flags is performed. % % The format of the CropImage method is: % % Image *CropImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to crop with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *CropImage(const Image *image,const RectangleInfo *geometry, ExceptionInfo *exception) { #define CropImageTag "Crop/Image" CacheView *crop_view, *image_view; Image *crop_image; MagickBooleanType status; MagickOffsetType progress; OffsetInfo offset; RectangleInfo bounding_box, page; ssize_t y; /* Check crop geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); bounding_box=image->page; if ((bounding_box.width == 0) || (bounding_box.height == 0)) { bounding_box.width=image->columns; bounding_box.height=image->rows; } page=(*geometry); if (page.width == 0) page.width=bounding_box.width; if (page.height == 0) page.height=bounding_box.height; if (((bounding_box.x-page.x) >= (ssize_t) page.width) || ((bounding_box.y-page.y) >= (ssize_t) page.height) || ((page.x-bounding_box.x) > (ssize_t) image->columns) || ((page.y-bounding_box.y) > (ssize_t) image->rows)) { /* Crop is not within virtual canvas, return 1 pixel transparent image. */ (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.alpha=(Quantum) TransparentAlpha; crop_image->alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(crop_image,exception); crop_image->page=bounding_box; crop_image->page.x=(-1); crop_image->page.y=(-1); if (crop_image->dispose == BackgroundDispose) crop_image->dispose=NoneDispose; return(crop_image); } if ((page.x < 0) && (bounding_box.x >= 0)) { page.width+=page.x-bounding_box.x; page.x=0; } else { page.width-=bounding_box.x-page.x; page.x-=bounding_box.x; if (page.x < 0) page.x=0; } if ((page.y < 0) && (bounding_box.y >= 0)) { page.height+=page.y-bounding_box.y; page.y=0; } else { page.height-=bounding_box.y-page.y; page.y-=bounding_box.y; if (page.y < 0) page.y=0; } if ((page.x+(ssize_t) page.width) > (ssize_t) image->columns) page.width=image->columns-page.x; if ((geometry->width != 0) && (page.width > geometry->width)) page.width=geometry->width; if ((page.y+(ssize_t) page.height) > (ssize_t) image->rows) page.height=image->rows-page.y; if ((geometry->height != 0) && (page.height > geometry->height)) page.height=geometry->height; bounding_box.x+=page.x; bounding_box.y+=page.y; if ((page.width == 0) || (page.height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "GeometryDoesNotContainImage","`%s'",image->filename); return((Image *) NULL); } /* Initialize crop image attributes. */ crop_image=CloneImage(image,page.width,page.height,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->page.width=image->page.width; crop_image->page.height=image->page.height; offset.x=(ssize_t) (bounding_box.x+bounding_box.width); offset.y=(ssize_t) (bounding_box.y+bounding_box.height); if ((offset.x > (ssize_t) image->page.width) || (offset.y > (ssize_t) image->page.height)) { crop_image->page.width=bounding_box.width; crop_image->page.height=bounding_box.height; } crop_image->page.x=bounding_box.x; crop_image->page.y=bounding_box.y; /* Crop image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); crop_view=AcquireAuthenticCacheView(crop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,crop_image,crop_image->rows,1) #endif for (y=0; y < (ssize_t) crop_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,page.x,page.y+y,crop_image->columns, 1,exception); q=QueueCacheViewAuthenticPixels(crop_view,0,y,crop_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) crop_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(crop_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(crop_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait crop_traits=GetPixelChannelTraits(crop_image,channel); if ((traits == UndefinedPixelTrait) || (crop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(crop_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(crop_image); } if (SyncCacheViewAuthenticPixels(crop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CropImage) #endif proceed=SetImageProgress(image,CropImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } crop_view=DestroyCacheView(crop_view); image_view=DestroyCacheView(image_view); crop_image->type=image->type; if (status == MagickFalse) crop_image=DestroyImage(crop_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C r o p I m a g e T o T i l e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropImageToTiles() crops a single image, into a possible list of tiles. % This may include a single sub-region of the image. This basically applies % all the normal geometry flags for Crop. % % Image *CropImageToTiles(const Image *image, % const RectangleInfo *crop_geometry, ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. % % o exception: return any errors or warnings in this structure. % */ static inline double MagickRound(double x) { /* Round the fraction to nearest integer. */ if ((x-floor(x)) < (ceil(x)-x)) return(floor(x)); return(ceil(x)); } MagickExport Image *CropImageToTiles(const Image *image, const char *crop_geometry,ExceptionInfo *exception) { Image *next, *crop_image; MagickStatusType flags; RectangleInfo geometry; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); crop_image=NewImageList(); next=NewImageList(); flags=ParseGravityGeometry(image,crop_geometry,&geometry,exception); if ((flags & AreaValue) != 0) { PointInfo delta, offset; RectangleInfo crop; size_t height, width; /* Crop into NxM tiles (@ flag). */ width=image->columns; height=image->rows; if (geometry.width == 0) geometry.width=1; if (geometry.height == 0) geometry.height=1; if ((flags & AspectValue) == 0) { width-=(geometry.x < 0 ? -1 : 1)*geometry.x; height-=(geometry.y < 0 ? -1 : 1)*geometry.y; } else { width+=(geometry.x < 0 ? -1 : 1)*geometry.x; height+=(geometry.y < 0 ? -1 : 1)*geometry.y; } delta.x=(double) width/geometry.width; delta.y=(double) height/geometry.height; if (delta.x < 1.0) delta.x=1.0; if (delta.y < 1.0) delta.y=1.0; for (offset.y=0; offset.y < (double) height; ) { if ((flags & AspectValue) == 0) { crop.y=(ssize_t) MagickRound((double) (offset.y- (geometry.y > 0 ? 0 : geometry.y))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) MagickRound((double) (offset.y+ (geometry.y < 0 ? 0 : geometry.y))); } else { crop.y=(ssize_t) MagickRound((double) (offset.y- (geometry.y > 0 ? geometry.y : 0))); offset.y+=delta.y; /* increment now to find width */ crop.height=(size_t) MagickRound((double) (offset.y+(geometry.y < -1 ? geometry.y : 0))); } crop.height-=crop.y; crop.y+=image->page.y; for (offset.x=0; offset.x < (double) width; ) { if ((flags & AspectValue) == 0) { crop.x=(ssize_t) MagickRound((double) (offset.x- (geometry.x > 0 ? 0 : geometry.x))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) MagickRound((double) (offset.x+ (geometry.x < 0 ? 0 : geometry.x))); } else { crop.x=(ssize_t) MagickRound((double) (offset.x- (geometry.x > 0 ? geometry.x : 0))); offset.x+=delta.x; /* increment now to find height */ crop.width=(size_t) MagickRound((double) (offset.x+ (geometry.x < 0 ? geometry.x : 0))); } crop.width-=crop.x; crop.x+=image->page.x; next=CropImage(image,&crop,exception); if (next != (Image *) NULL) AppendImageToList(&crop_image,next); } } ClearMagickException(exception); return(crop_image); } if (((geometry.width == 0) && (geometry.height == 0)) || ((flags & XValue) != 0) || ((flags & YValue) != 0)) { /* Crop a single region at +X+Y. */ crop_image=CropImage(image,&geometry,exception); if ((crop_image != (Image *) NULL) && ((flags & AspectValue) != 0)) { crop_image->page.width=geometry.width; crop_image->page.height=geometry.height; crop_image->page.x-=geometry.x; crop_image->page.y-=geometry.y; } return(crop_image); } if ((image->columns > geometry.width) || (image->rows > geometry.height)) { RectangleInfo page; size_t height, width; ssize_t x, y; /* Crop into tiles of fixed size WxH. */ page=image->page; if (page.width == 0) page.width=image->columns; if (page.height == 0) page.height=image->rows; width=geometry.width; if (width == 0) width=page.width; height=geometry.height; if (height == 0) height=page.height; next=NewImageList(); for (y=0; y < (ssize_t) page.height; y+=(ssize_t) height) { for (x=0; x < (ssize_t) page.width; x+=(ssize_t) width) { geometry.width=width; geometry.height=height; geometry.x=x; geometry.y=y; next=CropImage(image,&geometry,exception); if (next == (Image *) NULL) break; AppendImageToList(&crop_image,next); } if (next == (Image *) NULL) break; } return(crop_image); } return(CloneImage(image,0,0,MagickTrue,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x c e r p t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExcerptImage() returns a excerpt of the image as defined by the geometry. % % The format of the ExcerptImage method is: % % Image *ExcerptImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExcerptImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define ExcerptImageTag "Excerpt/Image" CacheView *excerpt_view, *image_view; Image *excerpt_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Allocate excerpt image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); excerpt_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (excerpt_image == (Image *) NULL) return((Image *) NULL); /* Excerpt each row. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); excerpt_view=AcquireAuthenticCacheView(excerpt_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,excerpt_image,excerpt_image->rows,1) #endif for (y=0; y < (ssize_t) excerpt_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,geometry->x,geometry->y+y, geometry->width,1,exception); q=GetCacheViewAuthenticPixels(excerpt_view,0,y,excerpt_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) excerpt_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(excerpt_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(excerpt_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait excerpt_traits=GetPixelChannelTraits(excerpt_image,channel); if ((traits == UndefinedPixelTrait) || (excerpt_traits == UndefinedPixelTrait)) continue; SetPixelChannel(excerpt_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(excerpt_image); } if (SyncCacheViewAuthenticPixels(excerpt_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ExcerptImage) #endif proceed=SetImageProgress(image,ExcerptImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } excerpt_view=DestroyCacheView(excerpt_view); image_view=DestroyCacheView(image_view); excerpt_image->type=image->type; if (status == MagickFalse) excerpt_image=DestroyImage(excerpt_image); return(excerpt_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x t e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExtentImage() extends the image as defined by the geometry, gravity, and % image background color. Set the (x,y) offset of the geometry to move the % original image relative to the extended image. % % The format of the ExtentImage method is: % % Image *ExtentImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to extend with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ExtentImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { Image *extent_image; /* Allocate extent image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if ((image->columns == geometry->width) && (image->rows == geometry->height) && (geometry->x == 0) && (geometry->y == 0)) return(CloneImage(image,0,0,MagickTrue,exception)); extent_image=CloneImage(image,geometry->width,geometry->height,MagickTrue, exception); if (extent_image == (Image *) NULL) return((Image *) NULL); (void) SetImageBackgroundColor(extent_image,exception); (void) CompositeImage(extent_image,image,image->compose,MagickTrue, -geometry->x,-geometry->y,exception); return(extent_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l i p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlipImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis. % % The format of the FlipImage method is: % % Image *FlipImage(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 *FlipImage(const Image *image,ExceptionInfo *exception) { #define FlipImageTag "Flip/Image" CacheView *flip_view, *image_view; Image *flip_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flip_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (flip_image == (Image *) NULL) return((Image *) NULL); /* Flip image. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flip_view=AcquireAuthenticCacheView(flip_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,flip_image,flip_image->rows,1) #endif for (y=0; y < (ssize_t) flip_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=QueueCacheViewAuthenticPixels(flip_view,0,(ssize_t) (flip_image->rows-y- 1),flip_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) flip_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(flip_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(flip_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait flip_traits=GetPixelChannelTraits(flip_image,channel); if ((traits == UndefinedPixelTrait) || (flip_traits == UndefinedPixelTrait)) continue; SetPixelChannel(flip_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(flip_image); } if (SyncCacheViewAuthenticPixels(flip_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FlipImage) #endif proceed=SetImageProgress(image,FlipImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flip_view=DestroyCacheView(flip_view); image_view=DestroyCacheView(image_view); flip_image->type=image->type; if (page.height != 0) page.y=(ssize_t) (page.height-flip_image->rows-page.y); flip_image->page=page; if (status == MagickFalse) flip_image=DestroyImage(flip_image); return(flip_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F l o p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FlopImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis. % % The format of the FlopImage method is: % % Image *FlopImage(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 *FlopImage(const Image *image,ExceptionInfo *exception) { #define FlopImageTag "Flop/Image" CacheView *flop_view, *image_view; Image *flop_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); flop_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (flop_image == (Image *) NULL) return((Image *) NULL); /* Flop each row. */ status=MagickTrue; progress=0; page=image->page; image_view=AcquireVirtualCacheView(image,exception); flop_view=AcquireAuthenticCacheView(flop_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(image,flop_image,flop_image->rows,1) #endif for (y=0; y < (ssize_t) flop_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); q=QueueCacheViewAuthenticPixels(flop_view,0,y,flop_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(flop_image)*flop_image->columns; for (x=0; x < (ssize_t) flop_image->columns; x++) { register ssize_t i; q-=GetPixelChannels(flop_image); if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait flop_traits=GetPixelChannelTraits(flop_image,channel); if ((traits == UndefinedPixelTrait) || (flop_traits == UndefinedPixelTrait)) continue; SetPixelChannel(flop_image,channel,p[i],q); } p+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(flop_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_FlopImage) #endif proceed=SetImageProgress(image,FlopImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } flop_view=DestroyCacheView(flop_view); image_view=DestroyCacheView(image_view); flop_image->type=image->type; if (page.width != 0) page.x=(ssize_t) (page.width-flop_image->columns-page.x); flop_image->page=page; if (status == MagickFalse) flop_image=DestroyImage(flop_image); return(flop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R o l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RollImage() offsets an image as defined by x_offset and y_offset. % % The format of the RollImage method is: % % Image *RollImage(const Image *image,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x_offset: the number of columns to roll in the horizontal direction. % % o y_offset: the number of rows to roll in the vertical direction. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CopyImageRegion(Image *destination,const Image *source, const size_t columns,const size_t rows,const ssize_t sx,const ssize_t sy, const ssize_t dx,const ssize_t dy,ExceptionInfo *exception) { CacheView *source_view, *destination_view; MagickBooleanType status; ssize_t y; if (columns == 0) return(MagickTrue); status=MagickTrue; source_view=AcquireVirtualCacheView(source,exception); destination_view=AcquireAuthenticCacheView(destination,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_number_threads(source,destination,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t x; /* Transfer scanline. */ if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,sx,sy+y,columns,1,exception); q=GetCacheViewAuthenticPixels(destination_view,dx,dy+y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) columns; x++) { register ssize_t i; if (GetPixelWriteMask(source,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(destination,q); p+=GetPixelChannels(source); q+=GetPixelChannels(destination); continue; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait source_traits=GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((source_traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; SetPixelChannel(destination,channel,p[i],q); } p+=GetPixelChannels(source); q+=GetPixelChannels(destination); } sync=SyncCacheViewAuthenticPixels(destination_view,exception); if (sync == MagickFalse) status=MagickFalse; } destination_view=DestroyCacheView(destination_view); source_view=DestroyCacheView(source_view); return(status); } MagickExport Image *RollImage(const Image *image,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define RollImageTag "Roll/Image" Image *roll_image; MagickStatusType status; RectangleInfo offset; /* Initialize roll 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); roll_image=CloneImage(image,image->columns,image->rows,MagickTrue,exception); if (roll_image == (Image *) NULL) return((Image *) NULL); offset.x=x_offset; offset.y=y_offset; while (offset.x < 0) offset.x+=(ssize_t) image->columns; while (offset.x >= (ssize_t) image->columns) offset.x-=(ssize_t) image->columns; while (offset.y < 0) offset.y+=(ssize_t) image->rows; while (offset.y >= (ssize_t) image->rows) offset.y-=(ssize_t) image->rows; /* Roll image. */ status=CopyImageRegion(roll_image,image,(size_t) offset.x, (size_t) offset.y,(ssize_t) image->columns-offset.x,(ssize_t) image->rows- offset.y,0,0,exception); (void) SetImageProgress(image,RollImageTag,0,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x, (size_t) offset.y,0,(ssize_t) image->rows-offset.y,offset.x,0, exception); (void) SetImageProgress(image,RollImageTag,1,3); status&=CopyImageRegion(roll_image,image,(size_t) offset.x,image->rows- offset.y,(ssize_t) image->columns-offset.x,0,0,offset.y,exception); (void) SetImageProgress(image,RollImageTag,2,3); status&=CopyImageRegion(roll_image,image,image->columns-offset.x,image->rows- offset.y,0,0,offset.x,offset.y,exception); (void) SetImageProgress(image,RollImageTag,3,3); roll_image->type=image->type; if (status == MagickFalse) roll_image=DestroyImage(roll_image); return(roll_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h a v e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShaveImage() shaves pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the ShaveImage method is: % % Image *ShaveImage(const Image *image,const RectangleInfo *shave_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o shave_image: Method ShaveImage returns a pointer to the shaved % image. A null image is returned if there is a memory shortage or % if the image width or height is zero. % % o image: the image. % % o shave_info: Specifies a pointer to a RectangleInfo which defines the % region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShaveImage(const Image *image, const RectangleInfo *shave_info,ExceptionInfo *exception) { Image *shave_image; RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (((2*shave_info->width) >= image->columns) || ((2*shave_info->height) >= image->rows)) ThrowImageException(OptionWarning,"GeometryDoesNotContainImage"); SetGeometry(image,&geometry); geometry.width-=2*shave_info->width; geometry.height-=2*shave_info->height; geometry.x=(ssize_t) shave_info->width+image->page.x; geometry.y=(ssize_t) shave_info->height+image->page.y; shave_image=CropImage(image,&geometry,exception); if (shave_image == (Image *) NULL) return((Image *) NULL); shave_image->page.width-=2*shave_info->width; shave_image->page.height-=2*shave_info->height; shave_image->page.x-=(ssize_t) shave_info->width; shave_image->page.y-=(ssize_t) shave_info->height; return(shave_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S p l i c e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SpliceImage() splices a solid color into the image as defined by the % geometry. % % The format of the SpliceImage method is: % % Image *SpliceImage(const Image *image,const RectangleInfo *geometry, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o geometry: Define the region of the image to splice with members % x, y, width, and height. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *SpliceImage(const Image *image, const RectangleInfo *geometry,ExceptionInfo *exception) { #define SpliceImageTag "Splice/Image" CacheView *image_view, *splice_view; Image *splice_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo splice_geometry; ssize_t columns, y; /* Allocate splice image. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(geometry != (const RectangleInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); splice_geometry=(*geometry); splice_image=CloneImage(image,image->columns+splice_geometry.width, image->rows+splice_geometry.height,MagickTrue,exception); if (splice_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(splice_image,DirectClass,exception) == MagickFalse) { splice_image=DestroyImage(splice_image); return((Image *) NULL); } if ((IsPixelInfoGray(&splice_image->background_color) == MagickFalse) && (IsGrayColorspace(splice_image->colorspace) != MagickFalse)) (void) SetImageColorspace(splice_image,sRGBColorspace,exception); if ((splice_image->background_color.alpha_trait != UndefinedPixelTrait) && (splice_image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlpha(splice_image,OpaqueAlpha,exception); (void) SetImageBackgroundColor(splice_image,exception); /* Respect image geometry. */ switch (image->gravity) { default: case UndefinedGravity: case NorthWestGravity: break; case NorthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; break; } case NorthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; break; } case WestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.width/2; break; } case CenterGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case EastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height/2; break; } case SouthWestGravity: { splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width/2; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } case SouthEastGravity: { splice_geometry.x+=(ssize_t) splice_geometry.width; splice_geometry.y+=(ssize_t) splice_geometry.height; break; } } /* Splice image. */ status=MagickTrue; progress=0; columns=MagickMin(splice_geometry.x,(ssize_t) splice_image->columns); image_view=AcquireVirtualCacheView(image,exception); splice_view=AcquireAuthenticCacheView(splice_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,splice_image,splice_geometry.y,1) #endif for (y=0; y < (ssize_t) splice_geometry.y; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,splice_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,splice_image,splice_image->rows,2) #endif for (y=(ssize_t) (splice_geometry.y+splice_geometry.height); y < (ssize_t) splice_image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; register Quantum *magick_restrict q; if (status == MagickFalse) continue; if ((y < 0) || (y >= (ssize_t)splice_image->rows)) continue; p=GetCacheViewVirtualPixels(image_view,0,y-(ssize_t) splice_geometry.height, splice_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(splice_view,0,y,splice_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } for ( ; x < (ssize_t) (splice_geometry.x+splice_geometry.width); x++) q+=GetPixelChannels(splice_image); for ( ; x < (ssize_t) splice_image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { SetPixelBackgoundColor(splice_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait splice_traits=GetPixelChannelTraits(splice_image,channel); if ((traits == UndefinedPixelTrait) || (splice_traits == UndefinedPixelTrait)) continue; SetPixelChannel(splice_image,channel,p[i],q); } SetPixelRed(splice_image,GetPixelRed(image,p),q); SetPixelGreen(splice_image,GetPixelGreen(image,p),q); SetPixelBlue(splice_image,GetPixelBlue(image,p),q); SetPixelAlpha(splice_image,GetPixelAlpha(image,p),q); p+=GetPixelChannels(image); q+=GetPixelChannels(splice_image); } if (SyncCacheViewAuthenticPixels(splice_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,SpliceImageTag,progress++, splice_image->rows); if (proceed == MagickFalse) status=MagickFalse; } } splice_view=DestroyCacheView(splice_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) splice_image=DestroyImage(splice_image); return(splice_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransformImage() is a convenience method that behaves like ResizeImage() or % CropImage() but accepts scaling and/or cropping information as a region % geometry specification. If the operation fails, the original image handle % is left as is. % % This should only be used for single images. % % This function destroys what it assumes to be a single image list. % If the input image is part of a larger list, all other images in that list % will be simply 'lost', not destroyed. % % Also if the crop generates a list of images only the first image is resized. % And finally if the crop succeeds and the resize failed, you will get a % cropped image, as well as a 'false' or 'failed' report. % % This function and should probably be deprecated in favor of direct calls % to CropImageToTiles() or ResizeImage(), as appropriate. % % The format of the TransformImage method is: % % MagickBooleanType TransformImage(Image **image,const char *crop_geometry, % const char *image_geometry,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image The transformed image is returned as this parameter. % % o crop_geometry: A crop geometry string. This geometry defines a % subregion of the image to crop. % % o image_geometry: An image geometry string. This geometry defines the % final size of the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType TransformImage(Image **image, const char *crop_geometry,const char *image_geometry,ExceptionInfo *exception) { Image *resize_image, *transform_image; RectangleInfo geometry; assert(image != (Image **) NULL); assert((*image)->signature == MagickCoreSignature); if ((*image)->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",(*image)->filename); transform_image=(*image); if (crop_geometry != (const char *) NULL) { Image *crop_image; /* Crop image to a user specified size. */ crop_image=CropImageToTiles(*image,crop_geometry,exception); if (crop_image == (Image *) NULL) transform_image=CloneImage(*image,0,0,MagickTrue,exception); else { transform_image=DestroyImage(transform_image); transform_image=GetFirstImageInList(crop_image); } *image=transform_image; } if (image_geometry == (const char *) NULL) return(MagickTrue); /* Scale image to a user specified size. */ (void) ParseRegionGeometry(transform_image,image_geometry,&geometry, exception); if ((transform_image->columns == geometry.width) && (transform_image->rows == geometry.height)) return(MagickTrue); resize_image=ResizeImage(transform_image,geometry.width,geometry.height, transform_image->filter,exception); if (resize_image == (Image *) NULL) return(MagickFalse); transform_image=DestroyImage(transform_image); transform_image=resize_image; *image=transform_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s p o s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransposeImage() creates a horizontal mirror image by reflecting the pixels % around the central y-axis while rotating them by 90 degrees. % % The format of the TransposeImage method is: % % Image *TransposeImage(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 *TransposeImage(const Image *image,ExceptionInfo *exception) { #define TransposeImageTag "Transpose/Image" CacheView *image_view, *transpose_view; Image *transpose_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transpose_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transpose_image == (Image *) NULL) return((Image *) NULL); /* Transpose image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transpose_view=AcquireAuthenticCacheView(transpose_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,transpose_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(image_view,0,(ssize_t) image->rows-y-1, image->columns,1,exception); q=QueueCacheViewAuthenticPixels(transpose_view,(ssize_t) (image->rows-y-1), 0,1,transpose_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { SetPixelBackgoundColor(transpose_image,q); p+=GetPixelChannels(image); q+=GetPixelChannels(transpose_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait transpose_traits=GetPixelChannelTraits(transpose_image, channel); if ((traits == UndefinedPixelTrait) || (transpose_traits == UndefinedPixelTrait)) continue; SetPixelChannel(transpose_image,channel,p[i],q); } p+=GetPixelChannels(image); q+=GetPixelChannels(transpose_image); } if (SyncCacheViewAuthenticPixels(transpose_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransposeImage) #endif proceed=SetImageProgress(image,TransposeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transpose_view=DestroyCacheView(transpose_view); image_view=DestroyCacheView(image_view); transpose_image->type=image->type; page=transpose_image->page; Swap(page.width,page.height); Swap(page.x,page.y); transpose_image->page=page; if (status == MagickFalse) transpose_image=DestroyImage(transpose_image); return(transpose_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s v e r s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransverseImage() creates a vertical mirror image by reflecting the pixels % around the central x-axis while rotating them by 270 degrees. % % The format of the TransverseImage method is: % % Image *TransverseImage(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 *TransverseImage(const Image *image,ExceptionInfo *exception) { #define TransverseImageTag "Transverse/Image" CacheView *image_view, *transverse_view; Image *transverse_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; ssize_t y; 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); transverse_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); if (transverse_image == (Image *) NULL) return((Image *) NULL); /* Transverse image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); transverse_view=AcquireAuthenticCacheView(transverse_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(image,transverse_image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; 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=QueueCacheViewAuthenticPixels(transverse_view,(ssize_t) (image->rows-y-1), 0,1,transverse_image->rows,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(transverse_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; q-=GetPixelChannels(transverse_image); if (GetPixelWriteMask(image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait transverse_traits=GetPixelChannelTraits(transverse_image, channel); if ((traits == UndefinedPixelTrait) || (transverse_traits == UndefinedPixelTrait)) continue; SetPixelChannel(transverse_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(transverse_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TransverseImage) #endif proceed=SetImageProgress(image,TransverseImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } transverse_view=DestroyCacheView(transverse_view); image_view=DestroyCacheView(image_view); transverse_image->type=image->type; page=transverse_image->page; Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-transverse_image->columns-page.x); if (page.height != 0) page.y=(ssize_t) (page.height-transverse_image->rows-page.y); transverse_image->page=page; if (status == MagickFalse) transverse_image=DestroyImage(transverse_image); return(transverse_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r i m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TrimImage() trims pixels from the image edges. It allocates the memory % necessary for the new Image structure and returns a pointer to the new % image. % % The format of the TrimImage method is: % % Image *TrimImage(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 *TrimImage(const Image *image,ExceptionInfo *exception) { RectangleInfo geometry; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); geometry=GetImageBoundingBox(image,exception); if ((geometry.width == 0) || (geometry.height == 0)) { Image *crop_image; crop_image=CloneImage(image,1,1,MagickTrue,exception); if (crop_image == (Image *) NULL) return((Image *) NULL); crop_image->background_color.alpha=(Quantum) TransparentAlpha; crop_image->alpha_trait=BlendPixelTrait; (void) SetImageBackgroundColor(crop_image,exception); crop_image->page=image->page; crop_image->page.x=(-1); crop_image->page.y=(-1); return(crop_image); } geometry.x+=image->page.x; geometry.y+=image->page.y; return(CropImage(image,&geometry,exception)); }
mxEvaluateStrongFromEdgeRHS.c
#ifdef _OPENMP #include <omp.h> #endif #include "mex.h" #include "blas.h" #if !defined(_WIN32) #define dgemm dgemm_ #endif // #if !defined(_WIN32) // #define dgemm dgemm_ // #endif #define DEBUG 0 #define NRHS 10 #define NLHS 1 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* check input & output */ if (nrhs != NRHS) { mexPrintf("Matlab:%s:InvalidNumberInput,\n", __FILE__); mexPrintf("%d inputs required.\n", NRHS); } if (nlhs != NLHS) { mexPrintf("Matlab:%s:InvalidNumberOutput,\n", __FILE__); mexPrintf("%d inputs required.\n", NLHS); } double *invM = mxGetPr(prhs[0]); double *Mb = mxGetPr(prhs[1]); double *FToE = mxGetPr(prhs[2]); double *FToN1 = mxGetPr(prhs[3]); double *FToN2 = mxGetPr(prhs[4]); double *Js = mxGetPr(prhs[5]); double *J = mxGetPr(prhs[6]); double *fluxM = mxGetPr(prhs[7]); double *fluxP = mxGetPr(prhs[8]); double *fluxS = mxGetPr(prhs[9]); // dims = mxGetDimensions(prhs[6]); const int Np = mxGetM(prhs[6]); // num of interp nodes const int K = mxGetN(prhs[6]); // num of elements const mwSize *dims = mxGetDimensions(prhs[7]); const int Nfp = dims[0]; const int Ne = dims[1]; // num of edges int Nfield; if (mxGetNumberOfDimensions(prhs[7]) > 2) { Nfield = dims[2]; } else { Nfield = 1; // fluxM is a 2D matrix } const size_t ndimOut = 3; const mwSize dimOut[3] = {Np, K, Nfield}; plhs[0] = mxCreateNumericArray(ndimOut, dimOut, mxDOUBLE_CLASS, mxREAL); double *frhs = mxGetPr(plhs[0]); char *chn = "N"; double one = 1.0, zero = 0.0; ptrdiff_t oneI = 1; ptrdiff_t np = Np; #ifdef _OPENMP #pragma omp parallel for num_threads(DG_THREADS) #endif for (int fld = 0; fld < Nfield; fld++) { double *rhs = frhs + Np * K * fld; double *fluxM_ = fluxM + Nfp * Ne * fld; double *fluxP_ = fluxP + Nfp * Ne * fld; double *fluxS_ = fluxS + Nfp * Ne * fld; for (int k = 0; k < Ne; k++) { // evaluate rhs on each edge const int e1 = (int)FToE[2 * k] - 1; const int e2 = (int)FToE[2 * k + 1] - 1; const int ind1 = e1 * Np - 1; const int ind2 = e2 * Np - 1; const int ind = k * Nfp; double rhsM[Nfp], rhsP[Nfp]; for (int n = 0; n < Nfp; n++) { rhsM[n] = 0; rhsP[n] = 0; } for (int n = 0; n < Nfp; n++) { const int sk = n + ind; double dfM = fluxM_[sk] - fluxS_[sk]; double dfP = fluxP_[sk] - fluxS_[sk]; double j = Js[sk]; double *mb = Mb + n * Nfp; for (int m = 0; m < Nfp; m++) { rhsM[m] += mb[m] * j * dfM; rhsP[m] -= mb[m] * j * dfP; } } for (int n = 0; n < Nfp; n++) { const int sk = n + ind; const int m1 = (int)FToN1[sk] + ind1; const int m2 = (int)FToN2[sk] + ind2; rhs[m1] += rhsM[n]; rhs[m2] += rhsP[n]; } } double temp[Np]; for (int k = 0; k < K; k++) { double *rhs_ = rhs + k * Np; double *j = J + k * Np; dgemm(chn, chn, &np, &oneI, &np, &one, invM, &np, rhs_, &np, &zero, temp, &np); // copy rhs for (int n = 0; n < Np; n++) { rhs_[n] = temp[n] / j[n]; } } } return; }
mxnet_op.h
#include "hip/hip_runtime.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. */ /*! * Copyright (c) 2017 by Contributors * \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> #include "./operator_tune.h" #include "../engine/openmp.h" #ifdef __HIPCC__ #include "../common/cuda_utils.h" #endif // __HIPCC__ 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 __HIPCC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline hipDeviceProp_t cuda_get_device_prop() { int device; CUDA_CALL(hipGetDevice(&device)); hipDeviceProp_t deviceProp; CUDA_CALL(hipGetDeviceProperties(&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 // __HIPCC__ template<> inline int get_num_threads<cpu>(const int N) { return engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); } /*! \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 operator request type switch */ #define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ { \ const OpReqType ReqType = kNullOp; \ {__VA_ARGS__} \ } \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } #define MXNET_NDIM_SWITCH(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ LOG(FATAL) << "This operation does not " \ "support float16"; \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_REAL_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ break; \ case mshadow::kInt32: \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32"; \ break; \ case mshadow::kInt64: \ LOG(FATAL) << "This operation only support " \ "floating point types, not int64"; \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } /*! * \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; \ } \ } #define MXNET_ADD_ALL_TYPES \ .add_enum("float32", mshadow::kFloat32) \ .add_enum("float64", mshadow::kFloat64) \ .add_enum("float16", mshadow::kFloat16) \ .add_enum("uint8", mshadow::kUint8) \ .add_enum("int8", mshadow::kInt8) \ .add_enum("int32", mshadow::kInt32) \ .add_enum("int64", mshadow::kInt64) /* \brief Compute flattened index given coordinates and shape. */ template<int ndim> MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { index_t 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 index_t idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto 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 index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { index_t 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 index_t unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto 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; } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx, const Shape<ndim>& stride) { ++(*coord)[ndim-1]; *idx += stride[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx = *idx + stride[i-1] - shape[i] * stride[i]; } } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx1, const Shape<ndim>& stride1, index_t* idx2, const Shape<ndim>& stride2) { ++(*coord)[ndim-1]; *idx1 += stride1[ndim-1]; *idx2 += stride2[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx1 = *idx1 + stride1[i-1] - shape[i] * stride1[i]; *idx2 = *idx2 + stride2[i-1] - shape[i] * stride2[i]; } } /*! * \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>(s), from.FlatTo1D<xpu, DType>(s), 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 Binary op backward gradient OP wrapper (tuned) */ template<typename GRAD_OP> struct backward_grad_tuned : public backward_grad<GRAD_OP>, public tunable { using backward_grad<GRAD_OP>::Map; }; /*! \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(index_t 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(index_t 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(index_t i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief input is tensor and two scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value_1, const DType value_2) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value_1, value_2)); } /*! \brief No inputs (ie fill to constant value) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t 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(index_t 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(index_t 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])); } }; template<typename OP, typename xpu> struct Kernel; /*! * \brief CPU Kernel launcher * \tparam OP Operator to launch */ template<typename OP> struct Kernel<OP, cpu> { /*! * \brief Launch a generic CPU kernel. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool Launch(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch a generic CPU kernel with dynamic schedule. This is recommended * for irregular workloads such as spmv. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool LaunchDynamic(mshadow::Stream<cpu> *, const int64_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(false); if (omp_threads < 2) { for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) schedule(dynamic) for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch CPU kernel which has OMP tuning data available. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam PRIMITIVE_OP The primitive operation to use for tuning * \tparam DType Data type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param dest Destination pointer (used to infer DType) * \param args Varargs to eventually pass to the OP::Map() function */ template<typename PRIMITIVE_OP, typename DType, typename ...Args> static void LaunchTuned(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP( N, static_cast<size_t>(omp_threads))) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif } /*! * \brief Launch custom-tuned kernel where each thread is set to * operate on a contiguous partition * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the UseOMP() and OP::Map() functions */ template<typename ...Args> inline static void LaunchEx(mshadow::Stream<cpu> *s, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { OP::Map(0, N, args...); } else { const auto length = (N + omp_threads - 1) / omp_threads; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); i += length) { OP::Map(i, i + length > N ? N - i : length, args...); } } #else OP::Map(0, N, args...); #endif } /*! * \brief Launch a tunable OP with implicitly-supplied data type * \tparam DType Data type * \tparam T OP type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, T>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<T, DType>(s, N, dest, args...); return true; } /*! * \brief Launch a tunable OP wrapper with explicitly-supplied data type (ie op_with_req) * \tparam DType Data type * \tparam T Wrapper type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, typename T::Operation>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<typename T::Operation, DType>(s, N, dest, args...); return true; } }; #ifdef __HIPCC__ 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, typename ...Args> __global__ void mxnet_generic_kernel_ex(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, 1, args...); } } template<typename OP> struct Kernel<OP, gpu> { /*! \brief Launch GPU kernel */ 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); hipLaunchKernelGGL((mxnet_generic_kernel<OP, Args...>), dim3(ngrid), dim3(kBaseThreadNum), 0, mshadow::Stream<gpu>::GetStream(s), N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel); } template<typename ...Args> inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) { using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); hipLaunchKernelGGL((mxnet_generic_kernel_ex<OP, Args...>), dim3(ngrid), dim3(kBaseThreadNum), 0, mshadow::Stream<gpu>::GetStream(s), N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex); } }; #endif // __HIPCC__ /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t 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 and one */ using set_zero = set_to_int<0>; using set_one = set_to_int<1>; } // namespace mxnet_op } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_MXNET_OP_H_
train3.c
#define _GNU_SOURCE #include <syscall.h> #include <sched.h> #include "graph.h" #include "mainFunctions.h" #include "powerperformacetracking.h" #include "print.h" #include <stdlib.h> #include<unistd.h> #define NO_OF_ARGS 2 //#define REPEAT 25 #define REPEAT 25 long long iters[8]; struct timeval start, end; // We define all additional paramemter here void setaffinity() { /* #pragma omp parallel { cpu_set_t newcpu; int threadid = omp_get_thread_num(); CPU_ZERO(&newcpu); CPU_SET ( threadid , &newcpu) ; int __t = sched_setaffinity ( syscall ( SYS_gettid ) , sizeof ( newcpu ) , &newcpu ) ; assert(__t == 0); } */ } void MultipleArrayParsePerIteration(graph *G, int id) { printf("The parse multiple Array %d \n", id); node_t * G_member = (int*)malloc (G->numNodes * sizeof(int)); srand(0); int i; for(i = 0; i< G->numNodes; i++) { G_member[i] = rand() % G->numNodes; } char title[50]; sprintf(title, "parsemult_%d.csv",id); gettimeofday(&start, NULL); inittracking(title); int tShared= 0; for(int abc=0; abc < REPEAT; abc ++) { #pragma omp parallel { int threadid = omp_get_thread_num(); iters[threadid] = 0; int t = 0; #pragma omp for schedule(dynamic, 1024) for (node_t u1 = 0; u1 < G->numNodes; u1 ++) for (edge_t j_idx = G->begin[u1];j_idx < G->begin[u1+1] ; j_idx ++) { iters[threadid]++; node_t j = G->node_idx [j_idx]; for (edge_t k_idx = G->begin[u1];k_idx < G->begin[u1+1] ; k_idx ++) { node_t k = G_member[j]; if(k > j) { for (edge_t l_idx = G->begin[k];l_idx < G->begin[k+1] ; l_idx ++) { t++; } } } } #pragma omp atomic tShared += t; } tShared /= 1000; } printf("TSHared %d\n", tShared); endtracking(); gettimeofday(&end, NULL); printTiming(ALGO_KERNEL,((end.tv_sec - start.tv_sec)*1000 + ((double)(end.tv_usec - start.tv_usec))/1000)); free(G_member); } #define numTimes 7 /*** * Common entry point for all algorithms, **/ int runalgo(int argc,char** argv) { int i; //setaffinity(); graph* G = readGraph(argv[1], argv[2]); for(i = 0;i< numTimes; i++) { printf("Run %d \n", i); MultipleArrayParsePerIteration(G,i); sleep(5); } return 0; } inline void kernel(graph *G) { }
tinyexr.h
/* Copyright (c) 2014 - 2018, Syoyo Fujita All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Syoyo Fujita 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 <COPYRIGHT HOLDER> 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. */ // TinyEXR contains some OpenEXR code, which is licensed under ------------ /////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2002, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Industrial Light & Magic 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 // OWNER 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. // /////////////////////////////////////////////////////////////////////////// // End of OpenEXR license ------------------------------------------------- #ifndef TINYEXR_H_ #define TINYEXR_H_ // // // Do this: // #define TINYEXR_IMPLEMENTATION // before you include this file in *one* C or C++ file to create the // implementation. // // // i.e. it should look like this: // #include ... // #include ... // #include ... // #define TINYEXR_IMPLEMENTATION // #include "tinyexr.h" // // #include <stddef.h> // for size_t #include <stdint.h> // guess stdint.h is available(C99) #ifdef __cplusplus extern "C" { #endif // Use embedded miniz or not to decode ZIP format pixel. Linking with zlib // required if this flas is 0. #ifndef TINYEXR_USE_MINIZ #define TINYEXR_USE_MINIZ (1) #endif // Disable PIZ comporession when applying cpplint. #ifndef TINYEXR_USE_PIZ #define TINYEXR_USE_PIZ (1) #endif #ifndef TINYEXR_USE_ZFP #define TINYEXR_USE_ZFP (0) // TinyEXR extension. // http://computation.llnl.gov/projects/floating-point-compression #endif #define TINYEXR_SUCCESS (0) #define TINYEXR_ERROR_INVALID_MAGIC_NUMBER (-1) #define TINYEXR_ERROR_INVALID_EXR_VERSION (-2) #define TINYEXR_ERROR_INVALID_ARGUMENT (-3) #define TINYEXR_ERROR_INVALID_DATA (-4) #define TINYEXR_ERROR_INVALID_FILE (-5) #define TINYEXR_ERROR_INVALID_PARAMETER (-5) #define TINYEXR_ERROR_CANT_OPEN_FILE (-6) #define TINYEXR_ERROR_UNSUPPORTED_FORMAT (-7) #define TINYEXR_ERROR_INVALID_HEADER (-8) #define TINYEXR_ERROR_UNSUPPORTED_FEATURE (-9) // @note { OpenEXR file format: http://www.openexr.com/openexrfilelayout.pdf } // pixel type: possible values are: UINT = 0 HALF = 1 FLOAT = 2 #define TINYEXR_PIXELTYPE_UINT (0) #define TINYEXR_PIXELTYPE_HALF (1) #define TINYEXR_PIXELTYPE_FLOAT (2) #define TINYEXR_MAX_ATTRIBUTES (128) #define TINYEXR_COMPRESSIONTYPE_NONE (0) #define TINYEXR_COMPRESSIONTYPE_RLE (1) #define TINYEXR_COMPRESSIONTYPE_ZIPS (2) #define TINYEXR_COMPRESSIONTYPE_ZIP (3) #define TINYEXR_COMPRESSIONTYPE_PIZ (4) #define TINYEXR_COMPRESSIONTYPE_ZFP (128) // TinyEXR extension #define TINYEXR_ZFP_COMPRESSIONTYPE_RATE (0) #define TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION (1) #define TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY (2) #define TINYEXR_TILE_ONE_LEVEL (0) #define TINYEXR_TILE_MIPMAP_LEVELS (1) #define TINYEXR_TILE_RIPMAP_LEVELS (2) #define TINYEXR_TILE_ROUND_DOWN (0) #define TINYEXR_TILE_ROUND_UP (1) typedef struct _EXRVersion { int version; // this must be 2 int tiled; // tile format image int long_name; // long name attribute int non_image; // deep image(EXR 2.0) int multipart; // multi-part(EXR 2.0) } EXRVersion; typedef struct _EXRAttribute { char name[256]; // name and type are up to 255 chars long. char type[256]; unsigned char *value; // uint8_t* int size; int pad0; } EXRAttribute; typedef struct _EXRChannelInfo { char name[256]; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } EXRChannelInfo; typedef struct _EXRTile { int offset_x; int offset_y; int level_x; int level_y; int width; // actual width in a tile. int height; // actual height int a tile. unsigned char **images; // image[channels][pixels] } EXRTile; typedef struct _EXRHeader { float pixel_aspect_ratio; int line_order; int data_window[4]; int display_window[4]; float screen_window_center[2]; float screen_window_width; int chunk_count; // Properties for tiled format(`tiledesc`). int tiled; int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; int long_name; int non_image; int multipart; unsigned int header_len; // Custom attributes(exludes required attributes(e.g. `channels`, // `compression`, etc) int num_custom_attributes; EXRAttribute custom_attributes[TINYEXR_MAX_ATTRIBUTES]; EXRChannelInfo *channels; // [num_channels] int *pixel_types; // Loaded pixel type(TINYEXR_PIXELTYPE_*) of `images` for // each channel. This is overwritten with `requested_pixel_types` when // loading. int num_channels; int compression_type; // compression type(TINYEXR_COMPRESSIONTYPE_*) int *requested_pixel_types; // Filled initially by // ParseEXRHeaderFrom(Meomory|File), then users // can edit it(only valid for HALF pixel type // channel) } EXRHeader; typedef struct _EXRMultiPartHeader { int num_headers; EXRHeader *headers; } EXRMultiPartHeader; typedef struct _EXRImage { EXRTile *tiles; // Tiled pixel data. The application must reconstruct image // from tiles manually. NULL if scanline format. unsigned char **images; // image[channels][pixels]. NULL if tiled format. int width; int height; int num_channels; // Properties for tile format. int num_tiles; } EXRImage; typedef struct _EXRMultiPartImage { int num_images; EXRImage *images; } EXRMultiPartImage; typedef struct _DeepImage { const char **channel_names; float ***image; // image[channels][scanlines][samples] int **offset_table; // offset_table[scanline][offsets] int num_channels; int width; int height; int pad0; } DeepImage; // @deprecated { to be removed. } // Loads single-frame OpenEXR image. Assume EXR image contains A(single channel // alpha) or RGB(A) channels. // Application must free image data as returned by `out_rgba` // Result image format is: float x RGBA x width x hight // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err); // @deprecated { to be removed. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // Parse EXR version header of a file. extern int ParseEXRVersionFromFile(EXRVersion *version, const char *filename); // Parse EXR version header from memory-mapped EXR data. extern int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size); // Parse single-part OpenEXR header from a file and initialize `EXRHeader`. extern int ParseEXRHeaderFromFile(EXRHeader *header, const EXRVersion *version, const char *filename, const char **err); // Parse single-part OpenEXR header from a memory and initialize `EXRHeader`. extern int ParseEXRHeaderFromMemory(EXRHeader *header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Parse multi-part OpenEXR headers from a file and initialize `EXRHeader*` // array. extern int ParseEXRMultipartHeaderFromFile(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const char *filename, const char **err); // Parse multi-part OpenEXR headers from a memory and initialize `EXRHeader*` // array extern int ParseEXRMultipartHeaderFromMemory(EXRHeader ***headers, int *num_headers, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err); // Loads single-part OpenEXR image from a file. // Application must setup `ParseEXRHeaderFromFile` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXRImageFromFile(EXRImage *image, const EXRHeader *header, const char *filename, const char **err); // Loads single-part OpenEXR image from a memory. // Application must setup `EXRHeader` with // `ParseEXRHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXRImageFromMemory(EXRImage *image, const EXRHeader *header, const unsigned char *memory, const size_t size, const char **err); // Loads multi-part OpenEXR image from a file. // Application must setup `ParseEXRMultipartHeaderFromFile` before calling this // function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXRMultipartImageFromFile(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const char *filename, const char **err); // Loads multi-part OpenEXR image from a memory. // Application must setup `EXRHeader*` array with // `ParseEXRMultipartHeaderFromMemory` before calling this function. // Application can free EXRImage using `FreeEXRImage` // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXRMultipartImageFromMemory(EXRImage *images, const EXRHeader **headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err); // Saves multi-channel, single-frame OpenEXR image to a file. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXRImageToFile(const EXRImage *image, const EXRHeader *exr_header, const char *filename, const char **err); // Saves multi-channel, single-frame OpenEXR image to a memory. // Image is compressed using EXRImage.compression value. // Return the number of bytes if succes. // Returns negative value and may set error string in `err` when there's an // error extern size_t SaveEXRImageToMemory(const EXRImage *image, const EXRHeader *exr_header, unsigned char **memory, const char **err); // Loads single-frame OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // Returns negative value and may set error string in `err` when there's an // error extern int LoadDeepEXR(DeepImage *out_image, const char *filename, const char **err); // NOT YET IMPLEMENTED: // Saves single-frame OpenEXR deep image. // Returns negative value and may set error string in `err` when there's an // error // extern int SaveDeepEXR(const DeepImage *in_image, const char *filename, // const char **err); // NOT YET IMPLEMENTED: // Loads multi-part OpenEXR deep image. // Application must free memory of variables in DeepImage(image, offset_table) // extern int LoadMultiPartDeepEXR(DeepImage **out_image, int num_parts, const // char *filename, // const char **err); // For emscripten. // Loads single-frame OpenEXR image from memory. Assume EXR image contains // RGB(A) channels. // Returns negative value and may set error string in `err` when there's an // error extern int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err); #ifdef __cplusplus } #endif #endif // TINYEXR_H_ #ifdef TINYEXR_IMPLEMENTATION #ifndef TINYEXR_IMPLEMENTATION_DEIFNED #define TINYEXR_IMPLEMENTATION_DEIFNED #include <algorithm> #include <cassert> #include <cstdio> #include <cstdlib> #include <cstring> #include <sstream> #include <string> #include <vector> #include <limits> #if __cplusplus > 199711L // C++11 #include <cstdint> #endif // __cplusplus > 199711L #ifdef _OPENMP #include <omp.h> #endif #if TINYEXR_USE_MINIZ #else // Issue #46. Please include your own zlib-compatible API header before // including `tinyexr.h` //#include "zlib.h" #endif #if TINYEXR_USE_ZFP #include "zfp.h" #endif namespace tinyexr { #if __cplusplus > 199711L // C++11 typedef uint64_t tinyexr_uint64; typedef int64_t tinyexr_int64; #else // Although `long long` is not a standard type pre C++11, assume it is defined // as a compiler's extension. #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #endif typedef unsigned long long tinyexr_uint64; typedef long long tinyexr_int64; #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #if TINYEXR_USE_MINIZ namespace miniz { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wunused-function" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #pragma clang diagnostic ignored "-Wundef" #if __has_warning("-Wcomma") #pragma clang diagnostic ignored "-Wcomma" #endif #if __has_warning("-Wmacro-redefined") #pragma clang diagnostic ignored "-Wmacro-redefined" #endif #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif /* miniz.c v1.15 - public domain deflate/inflate, zlib-subset, ZIP reading/writing/appending, PNG writing See "unlicense" statement at the end of this file. Rich Geldreich <richgel99@gmail.com>, last updated Oct. 13, 2013 Implements RFC 1950: http://www.ietf.org/rfc/rfc1950.txt and RFC 1951: http://www.ietf.org/rfc/rfc1951.txt Most API's defined in miniz.c are optional. For example, to disable the archive related functions just define MINIZ_NO_ARCHIVE_APIS, or to get rid of all stdio usage define MINIZ_NO_STDIO (see the list below for more macros). * Change History 10/13/13 v1.15 r4 - Interim bugfix release while I work on the next major release with Zip64 support (almost there!): - Critical fix for the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY bug (thanks kahmyong.moon@hp.com) which could cause locate files to not find files. This bug would only have occured in earlier versions if you explicitly used this flag, OR if you used mz_zip_extract_archive_file_to_heap() or mz_zip_add_mem_to_archive_file_in_place() (which used this flag). If you can't switch to v1.15 but want to fix this bug, just remove the uses of this flag from both helper funcs (and of course don't use the flag). - Bugfix in mz_zip_reader_extract_to_mem_no_alloc() from kymoon when pUser_read_buf is not NULL and compressed size is > uncompressed size - Fixing mz_zip_reader_extract_*() funcs so they don't try to extract compressed data from directory entries, to account for weird zipfiles which contain zero-size compressed data on dir entries. Hopefully this fix won't cause any issues on weird zip archives, because it assumes the low 16-bits of zip external attributes are DOS attributes (which I believe they always are in practice). - Fixing mz_zip_reader_is_file_a_directory() so it doesn't check the internal attributes, just the filename and external attributes - mz_zip_reader_init_file() - missing MZ_FCLOSE() call if the seek failed - Added cmake support for Linux builds which builds all the examples, tested with clang v3.3 and gcc v4.6. - Clang fix for tdefl_write_image_to_png_file_in_memory() from toffaletti - Merged MZ_FORCEINLINE fix from hdeanclark - Fix <time.h> include before config #ifdef, thanks emil.brink - Added tdefl_write_image_to_png_file_in_memory_ex(): supports Y flipping (super useful for OpenGL apps), and explicit control over the compression level (so you can set it to 1 for real-time compression). - Merged in some compiler fixes from paulharris's github repro. - Retested this build under Windows (VS 2010, including static analysis), tcc 0.9.26, gcc v4.6 and clang v3.3. - Added example6.c, which dumps an image of the mandelbrot set to a PNG file. - Modified example2 to help test the MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY flag more. - In r3: Bugfix to mz_zip_writer_add_file() found during merge: Fix possible src file fclose() leak if alignment bytes+local header file write faiiled - In r4: Minor bugfix to mz_zip_writer_add_from_zip_reader(): Was pushing the wrong central dir header offset, appears harmless in this release, but it became a problem in the zip64 branch 5/20/12 v1.14 - MinGW32/64 GCC 4.6.1 compiler fixes: added MZ_FORCEINLINE, #include <time.h> (thanks fermtect). 5/19/12 v1.13 - From jason@cornsyrup.org and kelwert@mtu.edu - Fix mz_crc32() so it doesn't compute the wrong CRC-32's when mz_ulong is 64-bit. - Temporarily/locally slammed in "typedef unsigned long mz_ulong" and re-ran a randomized regression test on ~500k files. - Eliminated a bunch of warnings when compiling with GCC 32-bit/64. - Ran all examples, miniz.c, and tinfl.c through MSVC 2008's /analyze (static analysis) option and fixed all warnings (except for the silly "Use of the comma-operator in a tested expression.." analysis warning, which I purposely use to work around a MSVC compiler warning). - Created 32-bit and 64-bit Codeblocks projects/workspace. Built and tested Linux executables. The codeblocks workspace is compatible with Linux+Win32/x64. - Added miniz_tester solution/project, which is a useful little app derived from LZHAM's tester app that I use as part of the regression test. - Ran miniz.c and tinfl.c through another series of regression testing on ~500,000 files and archives. - Modified example5.c so it purposely disables a bunch of high-level functionality (MINIZ_NO_STDIO, etc.). (Thanks to corysama for the MINIZ_NO_STDIO bug report.) - Fix ftell() usage in examples so they exit with an error on files which are too large (a limitation of the examples, not miniz itself). 4/12/12 v1.12 - More comments, added low-level example5.c, fixed a couple minor level_and_flags issues in the archive API's. level_and_flags can now be set to MZ_DEFAULT_COMPRESSION. Thanks to Bruce Dawson <bruced@valvesoftware.com> for the feedback/bug report. 5/28/11 v1.11 - Added statement from unlicense.org 5/27/11 v1.10 - Substantial compressor optimizations: - Level 1 is now ~4x faster than before. The L1 compressor's throughput now varies between 70-110MB/sec. on a - Core i7 (actual throughput varies depending on the type of data, and x64 vs. x86). - Improved baseline L2-L9 compression perf. Also, greatly improved compression perf. issues on some file types. - Refactored the compression code for better readability and maintainability. - Added level 10 compression level (L10 has slightly better ratio than level 9, but could have a potentially large drop in throughput on some files). 5/15/11 v1.09 - Initial stable release. * Low-level Deflate/Inflate implementation notes: Compression: Use the "tdefl" API's. The compressor supports raw, static, and dynamic blocks, lazy or greedy parsing, match length filtering, RLE-only, and Huffman-only streams. It performs and compresses approximately as well as zlib. Decompression: Use the "tinfl" API's. The entire decompressor is implemented as a single function coroutine: see tinfl_decompress(). It supports decompression into a 32KB (or larger power of 2) wrapping buffer, or into a memory block large enough to hold the entire file. The low-level tdefl/tinfl API's do not make any use of dynamic memory allocation. * zlib-style API notes: miniz.c implements a fairly large subset of zlib. There's enough functionality present for it to be a drop-in zlib replacement in many apps: The z_stream struct, optional memory allocation callbacks deflateInit/deflateInit2/deflate/deflateReset/deflateEnd/deflateBound inflateInit/inflateInit2/inflate/inflateEnd compress, compress2, compressBound, uncompress CRC-32, Adler-32 - Using modern, minimal code size, CPU cache friendly routines. Supports raw deflate streams or standard zlib streams with adler-32 checking. Limitations: The callback API's are not implemented yet. No support for gzip headers or zlib static dictionaries. I've tried to closely emulate zlib's various flavors of stream flushing and return status codes, but there are no guarantees that miniz.c pulls this off perfectly. * PNG writing: See the tdefl_write_image_to_png_file_in_memory() function, originally written by Alex Evans. Supports 1-4 bytes/pixel images. * ZIP archive API notes: The ZIP archive API's where designed with simplicity and efficiency in mind, with just enough abstraction to get the job done with minimal fuss. There are simple API's to retrieve file information, read files from existing archives, create new archives, append new files to existing archives, or clone archive data from one archive to another. It supports archives located in memory or the heap, on disk (using stdio.h), or you can specify custom file read/write callbacks. - Archive reading: Just call this function to read a single file from a disk archive: void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); For more complex cases, use the "mz_zip_reader" functions. Upon opening an archive, the entire central directory is located and read as-is into memory, and subsequent file access only occurs when reading individual files. - Archives file scanning: The simple way is to use this function to scan a loaded archive for a specific file: int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); The locate operation can optionally check file comments too, which (as one example) can be used to identify multiple versions of the same file in an archive. This function uses a simple linear search through the central directory, so it's not very fast. Alternately, you can iterate through all the files in an archive (using mz_zip_reader_get_num_files()) and retrieve detailed info on each file by calling mz_zip_reader_file_stat(). - Archive creation: Use the "mz_zip_writer" functions. The ZIP writer immediately writes compressed file data to disk and builds an exact image of the central directory in memory. The central directory image is written all at once at the end of the archive file when the archive is finalized. The archive writer can optionally align each file's local header and file data to any power of 2 alignment, which can be useful when the archive will be read from optical media. Also, the writer supports placing arbitrary data blobs at the very beginning of ZIP archives. Archives written using either feature are still readable by any ZIP tool. - Archive appending: The simple way to add a single file to an archive is to call this function: mz_bool mz_zip_add_mem_to_archive_file_in_place(const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); The archive will be created if it doesn't already exist, otherwise it'll be appended to. Note the appending is done in-place and is not an atomic operation, so if something goes wrong during the operation it's possible the archive could be left without a central directory (although the local file headers and file data will be fine, so the archive will be recoverable). For more complex archive modification scenarios: 1. The safest way is to use a mz_zip_reader to read the existing archive, cloning only those bits you want to preserve into a new archive using using the mz_zip_writer_add_from_zip_reader() function (which compiles the compressed file data as-is). When you're done, delete the old archive and rename the newly written archive, and you're done. This is safe but requires a bunch of temporary disk space or heap memory. 2. Or, you can convert an mz_zip_reader in-place to an mz_zip_writer using mz_zip_writer_init_from_reader(), append new files as needed, then finalize the archive which will write an updated central directory to the original archive. (This is basically what mz_zip_add_mem_to_archive_file_in_place() does.) There's a possibility that the archive's central directory could be lost with this method if anything goes wrong, though. - ZIP archive support limitations: No zip64 or spanning support. Extraction functions can only handle unencrypted, stored or deflated files. Requires streams capable of seeking. * This is a header file library, like stb_image.c. To get only a header file, either cut and paste the below header, or create miniz.h, #define MINIZ_HEADER_FILE_ONLY, and then include miniz.c from it. * Important: For best perf. be sure to customize the below macros for your target platform: #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_LITTLE_ENDIAN 1 #define MINIZ_HAS_64BIT_REGISTERS 1 * On platforms using glibc, Be sure to "#define _LARGEFILE64_SOURCE 1" before including miniz.c to ensure miniz uses the 64-bit variants: fopen64(), stat64(), etc. Otherwise you won't be able to process large files (i.e. 32-bit stat() fails for me on files > 0x7FFFFFFF bytes). */ #ifndef MINIZ_HEADER_INCLUDED #define MINIZ_HEADER_INCLUDED //#include <stdlib.h> // Defines to completely disable specific portions of miniz.c: // If all macros here are defined the only functionality remaining will be // CRC-32, adler-32, tinfl, and tdefl. // Define MINIZ_NO_STDIO to disable all usage and any functions which rely on // stdio for file I/O. //#define MINIZ_NO_STDIO // If MINIZ_NO_TIME is specified then the ZIP archive functions will not be able // to get the current time, or // get/set file times, and the C run-time funcs that get/set times won't be // called. // The current downside is the times written to your archives will be from 1979. #define MINIZ_NO_TIME // Define MINIZ_NO_ARCHIVE_APIS to disable all ZIP archive API's. #define MINIZ_NO_ARCHIVE_APIS // Define MINIZ_NO_ARCHIVE_APIS to disable all writing related ZIP archive // API's. //#define MINIZ_NO_ARCHIVE_WRITING_APIS // Define MINIZ_NO_ZLIB_APIS to remove all ZLIB-style compression/decompression // API's. //#define MINIZ_NO_ZLIB_APIS // Define MINIZ_NO_ZLIB_COMPATIBLE_NAME to disable zlib names, to prevent // conflicts against stock zlib. //#define MINIZ_NO_ZLIB_COMPATIBLE_NAMES // Define MINIZ_NO_MALLOC to disable all calls to malloc, free, and realloc. // Note if MINIZ_NO_MALLOC is defined then the user must always provide custom // user alloc/free/realloc // callbacks to the zlib and archive API's, and a few stand-alone helper API's // which don't provide custom user // functions (such as tdefl_compress_mem_to_heap() and // tinfl_decompress_mem_to_heap()) won't work. //#define MINIZ_NO_MALLOC #if defined(__TINYC__) && (defined(__linux) || defined(__linux__)) // TODO: Work around "error: include file 'sys\utime.h' when compiling with tcc // on Linux #define MINIZ_NO_TIME #endif #if !defined(MINIZ_NO_TIME) && !defined(MINIZ_NO_ARCHIVE_APIS) //#include <time.h> #endif #if defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \ defined(__i386) || defined(__i486__) || defined(__i486) || \ defined(i386) || defined(__ia64__) || defined(__x86_64__) // MINIZ_X86_OR_X64_CPU is only used to help set the below macros. #define MINIZ_X86_OR_X64_CPU 1 #endif #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #if MINIZ_X86_OR_X64_CPU // Set MINIZ_USE_UNALIGNED_LOADS_AND_STORES to 1 on CPU's that permit efficient // integer loads and stores from unaligned addresses. //#define MINIZ_USE_UNALIGNED_LOADS_AND_STORES 1 #define MINIZ_USE_UNALIGNED_LOADS_AND_STORES \ 0 // disable to suppress compiler warnings #endif #if defined(_M_X64) || defined(_WIN64) || defined(__MINGW64__) || \ defined(_LP64) || defined(__LP64__) || defined(__ia64__) || \ defined(__x86_64__) // Set MINIZ_HAS_64BIT_REGISTERS to 1 if operations on 64-bit integers are // reasonably fast (and don't involve compiler generated calls to helper // functions). #define MINIZ_HAS_64BIT_REGISTERS 1 #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API Definitions. // For more compatibility with zlib, miniz.c uses unsigned long for some // parameters/struct members. Beware: mz_ulong can be either 32 or 64-bits! typedef unsigned long mz_ulong; // mz_free() internally uses the MZ_FREE() macro (which by default calls free() // unless you've modified the MZ_MALLOC macro) to release a block allocated from // the heap. void mz_free(void *p); #define MZ_ADLER32_INIT (1) // mz_adler32() returns the initial adler-32 value to use when called with // ptr==NULL. mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len); #define MZ_CRC32_INIT (0) // mz_crc32() returns the initial CRC-32 value to use when called with // ptr==NULL. mz_ulong mz_crc32(mz_ulong crc, const unsigned char *ptr, size_t buf_len); // Compression strategies. enum { MZ_DEFAULT_STRATEGY = 0, MZ_FILTERED = 1, MZ_HUFFMAN_ONLY = 2, MZ_RLE = 3, MZ_FIXED = 4 }; // Method #define MZ_DEFLATED 8 #ifndef MINIZ_NO_ZLIB_APIS // Heap allocation callbacks. // Note that mz_alloc_func parameter types purpsosely differ from zlib's: // items/size is size_t, not unsigned long. typedef void *(*mz_alloc_func)(void *opaque, size_t items, size_t size); typedef void (*mz_free_func)(void *opaque, void *address); typedef void *(*mz_realloc_func)(void *opaque, void *address, size_t items, size_t size); #define MZ_VERSION "9.1.15" #define MZ_VERNUM 0x91F0 #define MZ_VER_MAJOR 9 #define MZ_VER_MINOR 1 #define MZ_VER_REVISION 15 #define MZ_VER_SUBREVISION 0 // Flush values. For typical usage you only need MZ_NO_FLUSH and MZ_FINISH. The // other values are for advanced use (refer to the zlib docs). enum { MZ_NO_FLUSH = 0, MZ_PARTIAL_FLUSH = 1, MZ_SYNC_FLUSH = 2, MZ_FULL_FLUSH = 3, MZ_FINISH = 4, MZ_BLOCK = 5 }; // Return status codes. MZ_PARAM_ERROR is non-standard. enum { MZ_OK = 0, MZ_STREAM_END = 1, MZ_NEED_DICT = 2, MZ_ERRNO = -1, MZ_STREAM_ERROR = -2, MZ_DATA_ERROR = -3, MZ_MEM_ERROR = -4, MZ_BUF_ERROR = -5, MZ_VERSION_ERROR = -6, MZ_PARAM_ERROR = -10000 }; // Compression levels: 0-9 are the standard zlib-style levels, 10 is best // possible compression (not zlib compatible, and may be very slow), // MZ_DEFAULT_COMPRESSION=MZ_DEFAULT_LEVEL. enum { MZ_NO_COMPRESSION = 0, MZ_BEST_SPEED = 1, MZ_BEST_COMPRESSION = 9, MZ_UBER_COMPRESSION = 10, MZ_DEFAULT_LEVEL = 6, MZ_DEFAULT_COMPRESSION = -1 }; // Window bits #define MZ_DEFAULT_WINDOW_BITS 15 struct mz_internal_state; // Compression/decompression stream struct. typedef struct mz_stream_s { const unsigned char *next_in; // pointer to next byte to read unsigned int avail_in; // number of bytes available at next_in mz_ulong total_in; // total number of bytes consumed so far unsigned char *next_out; // pointer to next byte to write unsigned int avail_out; // number of bytes that can be written to next_out mz_ulong total_out; // total number of bytes produced so far char *msg; // error msg (unused) struct mz_internal_state *state; // internal state, allocated by zalloc/zfree mz_alloc_func zalloc; // optional heap allocation function (defaults to malloc) mz_free_func zfree; // optional heap free function (defaults to free) void *opaque; // heap alloc function user pointer int data_type; // data_type (unused) mz_ulong adler; // adler32 of the source or uncompressed data mz_ulong reserved; // not used } mz_stream; typedef mz_stream *mz_streamp; // Returns the version string of miniz.c. const char *mz_version(void); // mz_deflateInit() initializes a compressor with default options: // Parameters: // pStream must point to an initialized mz_stream struct. // level must be between [MZ_NO_COMPRESSION, MZ_BEST_COMPRESSION]. // level 1 enables a specially optimized compression function that's been // optimized purely for performance, not ratio. // (This special func. is currently only enabled when // MINIZ_USE_UNALIGNED_LOADS_AND_STORES and MINIZ_LITTLE_ENDIAN are defined.) // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if the input parameters are bogus. // MZ_MEM_ERROR on out of memory. int mz_deflateInit(mz_streamp pStream, int level); // mz_deflateInit2() is like mz_deflate(), except with more control: // Additional parameters: // method must be MZ_DEFLATED // window_bits must be MZ_DEFAULT_WINDOW_BITS (to wrap the deflate stream with // zlib header/adler-32 footer) or -MZ_DEFAULT_WINDOW_BITS (raw deflate/no // header or footer) // mem_level must be between [1, 9] (it's checked but ignored by miniz.c) int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy); // Quickly resets a compressor without having to reallocate anything. Same as // calling mz_deflateEnd() followed by mz_deflateInit()/mz_deflateInit2(). int mz_deflateReset(mz_streamp pStream); // mz_deflate() compresses the input to output, consuming as much of the input // and producing as much output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_PARTIAL_FLUSH/MZ_SYNC_FLUSH, MZ_FULL_FLUSH, or // MZ_FINISH. // Return values: // MZ_OK on success (when flushing, or if more input is needed but not // available, and/or there's more output to be written but the output buffer // is full). // MZ_STREAM_END if all input has been consumed and all output bytes have been // written. Don't call mz_deflate() on the stream anymore. // MZ_STREAM_ERROR if the stream is bogus. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input and/or // output buffers are empty. (Fill up the input buffer or free up some output // space and try again.) int mz_deflate(mz_streamp pStream, int flush); // mz_deflateEnd() deinitializes a compressor: // Return values: // MZ_OK on success. // MZ_STREAM_ERROR if the stream is bogus. int mz_deflateEnd(mz_streamp pStream); // mz_deflateBound() returns a (very) conservative upper bound on the amount of // data that could be generated by deflate(), assuming flush is set to only // MZ_NO_FLUSH or MZ_FINISH. mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len); // Single-call compression functions mz_compress() and mz_compress2(): // Returns MZ_OK on success, or one of the error codes from mz_deflate() on // failure. int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level); // mz_compressBound() returns a (very) conservative upper bound on the amount of // data that could be generated by calling mz_compress(). mz_ulong mz_compressBound(mz_ulong source_len); // Initializes a decompressor. int mz_inflateInit(mz_streamp pStream); // mz_inflateInit2() is like mz_inflateInit() with an additional option that // controls the window size and whether or not the stream has been wrapped with // a zlib header/footer: // window_bits must be MZ_DEFAULT_WINDOW_BITS (to parse zlib header/footer) or // -MZ_DEFAULT_WINDOW_BITS (raw deflate). int mz_inflateInit2(mz_streamp pStream, int window_bits); // Decompresses the input stream to the output, consuming only as much of the // input as needed, and writing as much to the output as possible. // Parameters: // pStream is the stream to read from and write to. You must initialize/update // the next_in, avail_in, next_out, and avail_out members. // flush may be MZ_NO_FLUSH, MZ_SYNC_FLUSH, or MZ_FINISH. // On the first call, if flush is MZ_FINISH it's assumed the input and output // buffers are both sized large enough to decompress the entire stream in a // single call (this is slightly faster). // MZ_FINISH implies that there are no more source bytes available beside // what's already in the input buffer, and that the output buffer is large // enough to hold the rest of the decompressed data. // Return values: // MZ_OK on success. Either more input is needed but not available, and/or // there's more output to be written but the output buffer is full. // MZ_STREAM_END if all needed input has been consumed and all output bytes // have been written. For zlib streams, the adler-32 of the decompressed data // has also been verified. // MZ_STREAM_ERROR if the stream is bogus. // MZ_DATA_ERROR if the deflate stream is invalid. // MZ_PARAM_ERROR if one of the parameters is invalid. // MZ_BUF_ERROR if no forward progress is possible because the input buffer is // empty but the inflater needs more input to continue, or if the output // buffer is not large enough. Call mz_inflate() again // with more input data, or with more room in the output buffer (except when // using single call decompression, described above). int mz_inflate(mz_streamp pStream, int flush); // Deinitializes a decompressor. int mz_inflateEnd(mz_streamp pStream); // Single-call decompression. // Returns MZ_OK on success, or one of the error codes from mz_inflate() on // failure. int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len); // Returns a string description of the specified error code, or NULL if the // error code is invalid. const char *mz_error(int err); // Redefine zlib-compatible names to miniz equivalents, so miniz.c can be used // as a drop-in replacement for the subset of zlib that miniz.c supports. // Define MINIZ_NO_ZLIB_COMPATIBLE_NAMES to disable zlib-compatibility if you // use zlib in the same project. #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES typedef unsigned char Byte; typedef unsigned int uInt; typedef mz_ulong uLong; typedef Byte Bytef; typedef uInt uIntf; typedef char charf; typedef int intf; typedef void *voidpf; typedef uLong uLongf; typedef void *voidp; typedef void *const voidpc; #define Z_NULL 0 #define Z_NO_FLUSH MZ_NO_FLUSH #define Z_PARTIAL_FLUSH MZ_PARTIAL_FLUSH #define Z_SYNC_FLUSH MZ_SYNC_FLUSH #define Z_FULL_FLUSH MZ_FULL_FLUSH #define Z_FINISH MZ_FINISH #define Z_BLOCK MZ_BLOCK #define Z_OK MZ_OK #define Z_STREAM_END MZ_STREAM_END #define Z_NEED_DICT MZ_NEED_DICT #define Z_ERRNO MZ_ERRNO #define Z_STREAM_ERROR MZ_STREAM_ERROR #define Z_DATA_ERROR MZ_DATA_ERROR #define Z_MEM_ERROR MZ_MEM_ERROR #define Z_BUF_ERROR MZ_BUF_ERROR #define Z_VERSION_ERROR MZ_VERSION_ERROR #define Z_PARAM_ERROR MZ_PARAM_ERROR #define Z_NO_COMPRESSION MZ_NO_COMPRESSION #define Z_BEST_SPEED MZ_BEST_SPEED #define Z_BEST_COMPRESSION MZ_BEST_COMPRESSION #define Z_DEFAULT_COMPRESSION MZ_DEFAULT_COMPRESSION #define Z_DEFAULT_STRATEGY MZ_DEFAULT_STRATEGY #define Z_FILTERED MZ_FILTERED #define Z_HUFFMAN_ONLY MZ_HUFFMAN_ONLY #define Z_RLE MZ_RLE #define Z_FIXED MZ_FIXED #define Z_DEFLATED MZ_DEFLATED #define Z_DEFAULT_WINDOW_BITS MZ_DEFAULT_WINDOW_BITS #define alloc_func mz_alloc_func #define free_func mz_free_func #define internal_state mz_internal_state #define z_stream mz_stream #define deflateInit mz_deflateInit #define deflateInit2 mz_deflateInit2 #define deflateReset mz_deflateReset #define deflate mz_deflate #define deflateEnd mz_deflateEnd #define deflateBound mz_deflateBound #define compress mz_compress #define compress2 mz_compress2 #define compressBound mz_compressBound #define inflateInit mz_inflateInit #define inflateInit2 mz_inflateInit2 #define inflate mz_inflate #define inflateEnd mz_inflateEnd #define uncompress mz_uncompress #define crc32 mz_crc32 #define adler32 mz_adler32 #define MAX_WBITS 15 #define MAX_MEM_LEVEL 9 #define zError mz_error #define ZLIB_VERSION MZ_VERSION #define ZLIB_VERNUM MZ_VERNUM #define ZLIB_VER_MAJOR MZ_VER_MAJOR #define ZLIB_VER_MINOR MZ_VER_MINOR #define ZLIB_VER_REVISION MZ_VER_REVISION #define ZLIB_VER_SUBREVISION MZ_VER_SUBREVISION #define zlibVersion mz_version #define zlib_version mz_version() #endif // #ifndef MINIZ_NO_ZLIB_COMPATIBLE_NAMES #endif // MINIZ_NO_ZLIB_APIS // ------------------- Types and macros typedef unsigned char mz_uint8; typedef signed short mz_int16; typedef unsigned short mz_uint16; typedef unsigned int mz_uint32; typedef unsigned int mz_uint; typedef long long mz_int64; typedef unsigned long long mz_uint64; typedef int mz_bool; #define MZ_FALSE (0) #define MZ_TRUE (1) // An attempt to work around MSVC's spammy "warning C4127: conditional // expression is constant" message. #ifdef _MSC_VER #define MZ_MACRO_END while (0, 0) #else #define MZ_MACRO_END while (0) #endif // ------------------- ZIP archive reading/writing #ifndef MINIZ_NO_ARCHIVE_APIS enum { MZ_ZIP_MAX_IO_BUF_SIZE = 64 * 1024, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE = 260, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE = 256 }; typedef struct { mz_uint32 m_file_index; mz_uint32 m_central_dir_ofs; mz_uint16 m_version_made_by; mz_uint16 m_version_needed; mz_uint16 m_bit_flag; mz_uint16 m_method; #ifndef MINIZ_NO_TIME time_t m_time; #endif mz_uint32 m_crc32; mz_uint64 m_comp_size; mz_uint64 m_uncomp_size; mz_uint16 m_internal_attr; mz_uint32 m_external_attr; mz_uint64 m_local_header_ofs; mz_uint32 m_comment_size; char m_filename[MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE]; char m_comment[MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE]; } mz_zip_archive_file_stat; typedef size_t (*mz_file_read_func)(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n); typedef size_t (*mz_file_write_func)(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n); struct mz_zip_internal_state_tag; typedef struct mz_zip_internal_state_tag mz_zip_internal_state; typedef enum { MZ_ZIP_MODE_INVALID = 0, MZ_ZIP_MODE_READING = 1, MZ_ZIP_MODE_WRITING = 2, MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED = 3 } mz_zip_mode; typedef struct mz_zip_archive_tag { mz_uint64 m_archive_size; mz_uint64 m_central_directory_file_ofs; mz_uint m_total_files; mz_zip_mode m_zip_mode; mz_uint m_file_offset_alignment; mz_alloc_func m_pAlloc; mz_free_func m_pFree; mz_realloc_func m_pRealloc; void *m_pAlloc_opaque; mz_file_read_func m_pRead; mz_file_write_func m_pWrite; void *m_pIO_opaque; mz_zip_internal_state *m_pState; } mz_zip_archive; typedef enum { MZ_ZIP_FLAG_CASE_SENSITIVE = 0x0100, MZ_ZIP_FLAG_IGNORE_PATH = 0x0200, MZ_ZIP_FLAG_COMPRESSED_DATA = 0x0400, MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY = 0x0800 } mz_zip_flags; // ZIP archive reading // Inits a ZIP archive reader. // These functions read and validate the archive's central directory. mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags); mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags); #endif // Returns the total number of files in the archive. mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip); // Returns detailed information about an archive file entry. mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat); // Determines if an archive file entry is a directory entry. mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index); mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index); // Retrieves the filename of an archive file entry. // Returns the number of bytes written to pFilename, or if filename_buf_size is // 0 this function returns the number of bytes needed to fully store the // filename. mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size); // Attempts to locates a file in the archive's central directory. // Valid flags: MZ_ZIP_FLAG_CASE_SENSITIVE, MZ_ZIP_FLAG_IGNORE_PATH // Returns -1 if the file cannot be found. int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags); // Extracts a archive file to a memory buffer using no memory allocation. mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size); // Extracts a archive file to a memory buffer. mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags); // Extracts a archive file to a dynamically allocated heap buffer. void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags); void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags); // Extracts a archive file using a callback function to output the file's data. mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags); #ifndef MINIZ_NO_STDIO // Extracts a archive file to a disk file and sets its last accessed and // modified times. // This function only extracts files, not archive directory records. mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags); mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags); #endif // Ends archive reading, freeing all allocations, and closing the input archive // file if mz_zip_reader_init_file() was used. mz_bool mz_zip_reader_end(mz_zip_archive *pZip); // ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS // Inits a ZIP archive writer. mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size); mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size); #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning); #endif // Converts a ZIP archive reader object into a writer object, to allow efficient // in-place file appends to occur on an existing archive. // For archives opened using mz_zip_reader_init_file, pFilename must be the // archive's filename so it can be reopened for writing. If the file can't be // reopened, mz_zip_reader_end() will be called. // For archives opened using mz_zip_reader_init_mem, the memory block must be // growable using the realloc callback (which defaults to realloc unless you've // overridden it). // Finally, for archives opened using mz_zip_reader_init, the mz_zip_archive's // user provided m_pWrite function cannot be NULL. // Note: In-place archive modification is not recommended unless you know what // you're doing, because if execution stops or something goes wrong before // the archive is finalized the file's central directory will be hosed. mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename); // Adds the contents of a memory buffer to an archive. These functions record // the current local time into the archive. // To add a directory entry, call this method with an archive name ending in a // forwardslash with empty buffer. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags); mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32); #ifndef MINIZ_NO_STDIO // Adds the contents of a disk file to an archive. This function also records // the disk file's modified time into the archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); #endif // Adds a file to an archive by fully cloning the data from another archive. // This function fully clones the source file's compressed data (no // recompression), along with its full filename, extra data, and comment fields. mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index); // Finalizes the archive by writing the central directory records followed by // the end of central directory record. // After an archive is finalized, the only valid call on the mz_zip_archive // struct is mz_zip_writer_end(). // An archive must be manually finalized by calling this function for it to be // valid. mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip); mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize); // Ends archive writing, freeing all allocations, and closing the output file if // mz_zip_writer_init_file() was used. // Note for the archive to be valid, it must have been finalized before ending. mz_bool mz_zip_writer_end(mz_zip_archive *pZip); // Misc. high-level helper functions: // mz_zip_add_mem_to_archive_file_in_place() efficiently (but not atomically) // appends a memory blob to a ZIP archive. // level_and_flags - compression level (0-10, see MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc.) logically OR'd with zero or more mz_zip_flags, or // just set to MZ_DEFAULT_COMPRESSION. mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags); // Reads a single file from an archive into a heap block. // Returns NULL on failure. void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint zip_flags); #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS // ------------------- Low-level Decompression API Definitions // Decompression flags used by tinfl_decompress(). // TINFL_FLAG_PARSE_ZLIB_HEADER: If set, the input has a valid zlib header and // ends with an adler32 checksum (it's a valid zlib stream). Otherwise, the // input is a raw deflate stream. // TINFL_FLAG_HAS_MORE_INPUT: If set, there are more input bytes available // beyond the end of the supplied input buffer. If clear, the input buffer // contains all remaining input. // TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF: If set, the output buffer is large // enough to hold the entire decompressed stream. If clear, the output buffer is // at least the size of the dictionary (typically 32KB). // TINFL_FLAG_COMPUTE_ADLER32: Force adler-32 checksum computation of the // decompressed bytes. enum { TINFL_FLAG_PARSE_ZLIB_HEADER = 1, TINFL_FLAG_HAS_MORE_INPUT = 2, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF = 4, TINFL_FLAG_COMPUTE_ADLER32 = 8 }; // High level decompression functions: // tinfl_decompress_mem_to_heap() decompresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of the Deflate or zlib source data // to decompress. // On return: // Function returns a pointer to the decompressed data, or NULL on failure. // *pOut_len will be set to the decompressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must call mz_free() on the returned block when it's no longer // needed. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tinfl_decompress_mem_to_mem() decompresses a block in memory to another block // in memory. // Returns TINFL_DECOMPRESS_MEM_TO_MEM_FAILED on failure, or the number of bytes // written on success. #define TINFL_DECOMPRESS_MEM_TO_MEM_FAILED ((size_t)(-1)) size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // tinfl_decompress_mem_to_callback() decompresses a block in memory to an // internal 32KB buffer, and a user provided callback function will be called to // flush the buffer. // Returns 1 on success or 0 on failure. typedef int (*tinfl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); struct tinfl_decompressor_tag; typedef struct tinfl_decompressor_tag tinfl_decompressor; // Max size of LZ dictionary. #define TINFL_LZ_DICT_SIZE 32768 // Return status. typedef enum { TINFL_STATUS_BAD_PARAM = -3, TINFL_STATUS_ADLER32_MISMATCH = -2, TINFL_STATUS_FAILED = -1, TINFL_STATUS_DONE = 0, TINFL_STATUS_NEEDS_MORE_INPUT = 1, TINFL_STATUS_HAS_MORE_OUTPUT = 2 } tinfl_status; // Initializes the decompressor to its initial state. #define tinfl_init(r) \ do { \ (r)->m_state = 0; \ } \ MZ_MACRO_END #define tinfl_get_adler32(r) (r)->m_check_adler32 // Main low-level decompressor coroutine function. This is the only function // actually needed for decompression. All the other functions are just // high-level helpers for improved usability. // This is a universal API, i.e. it can be used as a building block to build any // desired higher level decompression API. In the limit case, it can be called // once per every byte input or output. tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags); // Internal/private bits follow. enum { TINFL_MAX_HUFF_TABLES = 3, TINFL_MAX_HUFF_SYMBOLS_0 = 288, TINFL_MAX_HUFF_SYMBOLS_1 = 32, TINFL_MAX_HUFF_SYMBOLS_2 = 19, TINFL_FAST_LOOKUP_BITS = 10, TINFL_FAST_LOOKUP_SIZE = 1 << TINFL_FAST_LOOKUP_BITS }; typedef struct { mz_uint8 m_code_size[TINFL_MAX_HUFF_SYMBOLS_0]; mz_int16 m_look_up[TINFL_FAST_LOOKUP_SIZE], m_tree[TINFL_MAX_HUFF_SYMBOLS_0 * 2]; } tinfl_huff_table; #if MINIZ_HAS_64BIT_REGISTERS #define TINFL_USE_64BIT_BITBUF 1 #endif #if TINFL_USE_64BIT_BITBUF typedef mz_uint64 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (64) #else typedef mz_uint32 tinfl_bit_buf_t; #define TINFL_BITBUF_SIZE (32) #endif struct tinfl_decompressor_tag { mz_uint32 m_state, m_num_bits, m_zhdr0, m_zhdr1, m_z_adler32, m_final, m_type, m_check_adler32, m_dist, m_counter, m_num_extra, m_table_sizes[TINFL_MAX_HUFF_TABLES]; tinfl_bit_buf_t m_bit_buf; size_t m_dist_from_out_buf_start; tinfl_huff_table m_tables[TINFL_MAX_HUFF_TABLES]; mz_uint8 m_raw_header[4], m_len_codes[TINFL_MAX_HUFF_SYMBOLS_0 + TINFL_MAX_HUFF_SYMBOLS_1 + 137]; }; // ------------------- Low-level Compression API Definitions // Set TDEFL_LESS_MEMORY to 1 to use less memory (compression will be slightly // slower, and raw/dynamic blocks will be output more frequently). #define TDEFL_LESS_MEMORY 0 // tdefl_init() compression flags logically OR'd together (low 12 bits contain // the max. number of probes per dictionary search): // TDEFL_DEFAULT_MAX_PROBES: The compressor defaults to 128 dictionary probes // per dictionary search. 0=Huffman only, 1=Huffman+LZ (fastest/crap // compression), 4095=Huffman+LZ (slowest/best compression). enum { TDEFL_HUFFMAN_ONLY = 0, TDEFL_DEFAULT_MAX_PROBES = 128, TDEFL_MAX_PROBES_MASK = 0xFFF }; // TDEFL_WRITE_ZLIB_HEADER: If set, the compressor outputs a zlib header before // the deflate data, and the Adler-32 of the source data at the end. Otherwise, // you'll get raw deflate data. // TDEFL_COMPUTE_ADLER32: Always compute the adler-32 of the input data (even // when not writing zlib headers). // TDEFL_GREEDY_PARSING_FLAG: Set to use faster greedy parsing, instead of more // efficient lazy parsing. // TDEFL_NONDETERMINISTIC_PARSING_FLAG: Enable to decrease the compressor's // initialization time to the minimum, but the output may vary from run to run // given the same input (depending on the contents of memory). // TDEFL_RLE_MATCHES: Only look for RLE matches (matches with a distance of 1) // TDEFL_FILTER_MATCHES: Discards matches <= 5 chars if enabled. // TDEFL_FORCE_ALL_STATIC_BLOCKS: Disable usage of optimized Huffman tables. // TDEFL_FORCE_ALL_RAW_BLOCKS: Only use raw (uncompressed) deflate blocks. // The low 12 bits are reserved to control the max # of hash probes per // dictionary lookup (see TDEFL_MAX_PROBES_MASK). enum { TDEFL_WRITE_ZLIB_HEADER = 0x01000, TDEFL_COMPUTE_ADLER32 = 0x02000, TDEFL_GREEDY_PARSING_FLAG = 0x04000, TDEFL_NONDETERMINISTIC_PARSING_FLAG = 0x08000, TDEFL_RLE_MATCHES = 0x10000, TDEFL_FILTER_MATCHES = 0x20000, TDEFL_FORCE_ALL_STATIC_BLOCKS = 0x40000, TDEFL_FORCE_ALL_RAW_BLOCKS = 0x80000 }; // High level compression functions: // tdefl_compress_mem_to_heap() compresses a block in memory to a heap block // allocated via malloc(). // On entry: // pSrc_buf, src_buf_len: Pointer and size of source block to compress. // flags: The max match finder probes (default is 128) logically OR'd against // the above flags. Higher probes are slower but improve compression. // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pOut_len will be set to the compressed data's size, which could be larger // than src_buf_len on uncompressible data. // The caller must free() the returned block when it's no longer needed. void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags); // tdefl_compress_mem_to_mem() compresses a block in memory to another block in // memory. // Returns 0 on failure. size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags); // Compresses an image to a compressed PNG file in memory. // On entry: // pImage, w, h, and num_chans describe the image to compress. num_chans may be // 1, 2, 3, or 4. // The image pitch in bytes per scanline will be w*num_chans. The leftmost // pixel on the top scanline is stored first in memory. // level may range from [0,10], use MZ_NO_COMPRESSION, MZ_BEST_SPEED, // MZ_BEST_COMPRESSION, etc. or a decent default is MZ_DEFAULT_LEVEL // If flip is true, the image will be flipped on the Y axis (useful for OpenGL // apps). // On return: // Function returns a pointer to the compressed data, or NULL on failure. // *pLen_out will be set to the size of the PNG image file. // The caller must mz_free() the returned heap block (which will typically be // larger than *pLen_out) when it's no longer needed. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip); void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out); // Output stream interface. The compressor uses this interface to write // compressed data. It'll typically be called TDEFL_OUT_BUF_SIZE at a time. typedef mz_bool (*tdefl_put_buf_func_ptr)(const void *pBuf, int len, void *pUser); // tdefl_compress_mem_to_output() compresses a block to an output stream. The // above helpers use this function internally. mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); enum { TDEFL_MAX_HUFF_TABLES = 3, TDEFL_MAX_HUFF_SYMBOLS_0 = 288, TDEFL_MAX_HUFF_SYMBOLS_1 = 32, TDEFL_MAX_HUFF_SYMBOLS_2 = 19, TDEFL_LZ_DICT_SIZE = 32768, TDEFL_LZ_DICT_SIZE_MASK = TDEFL_LZ_DICT_SIZE - 1, TDEFL_MIN_MATCH_LEN = 3, TDEFL_MAX_MATCH_LEN = 258 }; // TDEFL_OUT_BUF_SIZE MUST be large enough to hold a single entire compressed // output block (using static/fixed Huffman codes). #if TDEFL_LESS_MEMORY enum { TDEFL_LZ_CODE_BUF_SIZE = 24 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 12, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #else enum { TDEFL_LZ_CODE_BUF_SIZE = 64 * 1024, TDEFL_OUT_BUF_SIZE = (TDEFL_LZ_CODE_BUF_SIZE * 13) / 10, TDEFL_MAX_HUFF_SYMBOLS = 288, TDEFL_LZ_HASH_BITS = 15, TDEFL_LEVEL1_HASH_SIZE_MASK = 4095, TDEFL_LZ_HASH_SHIFT = (TDEFL_LZ_HASH_BITS + 2) / 3, TDEFL_LZ_HASH_SIZE = 1 << TDEFL_LZ_HASH_BITS }; #endif // The low-level tdefl functions below may be used directly if the above helper // functions aren't flexible enough. The low-level functions don't make any heap // allocations, unlike the above helper functions. typedef enum { TDEFL_STATUS_BAD_PARAM = -2, TDEFL_STATUS_PUT_BUF_FAILED = -1, TDEFL_STATUS_OKAY = 0, TDEFL_STATUS_DONE = 1 } tdefl_status; // Must map to MZ_NO_FLUSH, MZ_SYNC_FLUSH, etc. enums typedef enum { TDEFL_NO_FLUSH = 0, TDEFL_SYNC_FLUSH = 2, TDEFL_FULL_FLUSH = 3, TDEFL_FINISH = 4 } tdefl_flush; // tdefl's compression state structure. typedef struct { tdefl_put_buf_func_ptr m_pPut_buf_func; void *m_pPut_buf_user; mz_uint m_flags, m_max_probes[2]; int m_greedy_parsing; mz_uint m_adler32, m_lookahead_pos, m_lookahead_size, m_dict_size; mz_uint8 *m_pLZ_code_buf, *m_pLZ_flags, *m_pOutput_buf, *m_pOutput_buf_end; mz_uint m_num_flags_left, m_total_lz_bytes, m_lz_code_buf_dict_pos, m_bits_in, m_bit_buffer; mz_uint m_saved_match_dist, m_saved_match_len, m_saved_lit, m_output_flush_ofs, m_output_flush_remaining, m_finished, m_block_index, m_wants_to_finish; tdefl_status m_prev_return_status; const void *m_pIn_buf; void *m_pOut_buf; size_t *m_pIn_buf_size, *m_pOut_buf_size; tdefl_flush m_flush; const mz_uint8 *m_pSrc; size_t m_src_buf_left, m_out_buf_ofs; mz_uint8 m_dict[TDEFL_LZ_DICT_SIZE + TDEFL_MAX_MATCH_LEN - 1]; mz_uint16 m_huff_count[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint16 m_huff_codes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_huff_code_sizes[TDEFL_MAX_HUFF_TABLES][TDEFL_MAX_HUFF_SYMBOLS]; mz_uint8 m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE]; mz_uint16 m_next[TDEFL_LZ_DICT_SIZE]; mz_uint16 m_hash[TDEFL_LZ_HASH_SIZE]; mz_uint8 m_output_buf[TDEFL_OUT_BUF_SIZE]; } tdefl_compressor; // Initializes the compressor. // There is no corresponding deinit() function because the tdefl API's do not // dynamically allocate memory. // pBut_buf_func: If NULL, output data will be supplied to the specified // callback. In this case, the user should call the tdefl_compress_buffer() API // for compression. // If pBut_buf_func is NULL the user should always call the tdefl_compress() // API. // flags: See the above enums (TDEFL_HUFFMAN_ONLY, TDEFL_WRITE_ZLIB_HEADER, // etc.) tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags); // Compresses a block of data, consuming as much of the specified input buffer // as possible, and writing as much compressed data to the specified output // buffer as possible. tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush); // tdefl_compress_buffer() is only usable when the tdefl_init() is called with a // non-NULL tdefl_put_buf_func_ptr. // tdefl_compress_buffer() always consumes the entire input buffer. tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush); tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d); mz_uint32 tdefl_get_adler32(tdefl_compressor *d); // Can't use tdefl_create_comp_flags_from_zip_params if MINIZ_NO_ZLIB_APIS isn't // defined, because it uses some of its macros. #ifndef MINIZ_NO_ZLIB_APIS // Create tdefl_compress() flags given zlib-style compression parameters. // level may range from [0,10] (where 10 is absolute max compression, but may be // much slower on some files) // window_bits may be -15 (raw deflate) or 15 (zlib) // strategy may be either MZ_DEFAULT_STRATEGY, MZ_FILTERED, MZ_HUFFMAN_ONLY, // MZ_RLE, or MZ_FIXED mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy); #endif // #ifndef MINIZ_NO_ZLIB_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_INCLUDED // ------------------- End of Header: Implementation follows. (If you only want // the header, define MINIZ_HEADER_FILE_ONLY.) #ifndef MINIZ_HEADER_FILE_ONLY typedef unsigned char mz_validate_uint16[sizeof(mz_uint16) == 2 ? 1 : -1]; typedef unsigned char mz_validate_uint32[sizeof(mz_uint32) == 4 ? 1 : -1]; typedef unsigned char mz_validate_uint64[sizeof(mz_uint64) == 8 ? 1 : -1]; //#include <assert.h> //#include <string.h> #define MZ_ASSERT(x) assert(x) #ifdef MINIZ_NO_MALLOC #define MZ_MALLOC(x) NULL #define MZ_FREE(x) (void)x, ((void)0) #define MZ_REALLOC(p, x) NULL #else #define MZ_MALLOC(x) malloc(x) #define MZ_FREE(x) free(x) #define MZ_REALLOC(p, x) realloc(p, x) #endif #define MZ_MAX(a, b) (((a) > (b)) ? (a) : (b)) #define MZ_MIN(a, b) (((a) < (b)) ? (a) : (b)) #define MZ_CLEAR_OBJ(obj) memset(&(obj), 0, sizeof(obj)) #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN #define MZ_READ_LE16(p) *((const mz_uint16 *)(p)) #define MZ_READ_LE32(p) *((const mz_uint32 *)(p)) #else #define MZ_READ_LE16(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U)) #define MZ_READ_LE32(p) \ ((mz_uint32)(((const mz_uint8 *)(p))[0]) | \ ((mz_uint32)(((const mz_uint8 *)(p))[1]) << 8U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[2]) << 16U) | \ ((mz_uint32)(((const mz_uint8 *)(p))[3]) << 24U)) #endif #ifdef _MSC_VER #define MZ_FORCEINLINE __forceinline #elif defined(__GNUC__) #define MZ_FORCEINLINE inline __attribute__((__always_inline__)) #else #define MZ_FORCEINLINE inline #endif #ifdef __cplusplus extern "C" { #endif // ------------------- zlib-style API's mz_ulong mz_adler32(mz_ulong adler, const unsigned char *ptr, size_t buf_len) { mz_uint32 i, s1 = (mz_uint32)(adler & 0xffff), s2 = (mz_uint32)(adler >> 16); size_t block_len = buf_len % 5552; if (!ptr) return MZ_ADLER32_INIT; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } return (s2 << 16) + s1; } // Karl Malbrain's compact CRC-32. See "A compact CCITT crc16 and crc32 C // implementation that balances processor cache usage against speed": // http://www.geocities.com/malbrain/ mz_ulong mz_crc32(mz_ulong crc, const mz_uint8 *ptr, size_t buf_len) { static const mz_uint32 s_crc32[16] = { 0, 0x1db71064, 0x3b6e20c8, 0x26d930ac, 0x76dc4190, 0x6b6b51f4, 0x4db26158, 0x5005713c, 0xedb88320, 0xf00f9344, 0xd6d6a3e8, 0xcb61b38c, 0x9b64c2b0, 0x86d3d2d4, 0xa00ae278, 0xbdbdf21c}; mz_uint32 crcu32 = (mz_uint32)crc; if (!ptr) return MZ_CRC32_INIT; crcu32 = ~crcu32; while (buf_len--) { mz_uint8 b = *ptr++; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b & 0xF)]; crcu32 = (crcu32 >> 4) ^ s_crc32[(crcu32 & 0xF) ^ (b >> 4)]; } return ~crcu32; } void mz_free(void *p) { MZ_FREE(p); } #ifndef MINIZ_NO_ZLIB_APIS static void *def_alloc_func(void *opaque, size_t items, size_t size) { (void)opaque, (void)items, (void)size; return MZ_MALLOC(items * size); } static void def_free_func(void *opaque, void *address) { (void)opaque, (void)address; MZ_FREE(address); } // static void *def_realloc_func(void *opaque, void *address, size_t items, // size_t size) { // (void)opaque, (void)address, (void)items, (void)size; // return MZ_REALLOC(address, items * size); //} const char *mz_version(void) { return MZ_VERSION; } int mz_deflateInit(mz_streamp pStream, int level) { return mz_deflateInit2(pStream, level, MZ_DEFLATED, MZ_DEFAULT_WINDOW_BITS, 9, MZ_DEFAULT_STRATEGY); } int mz_deflateInit2(mz_streamp pStream, int level, int method, int window_bits, int mem_level, int strategy) { tdefl_compressor *pComp; mz_uint comp_flags = TDEFL_COMPUTE_ADLER32 | tdefl_create_comp_flags_from_zip_params(level, window_bits, strategy); if (!pStream) return MZ_STREAM_ERROR; if ((method != MZ_DEFLATED) || ((mem_level < 1) || (mem_level > 9)) || ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS))) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = MZ_ADLER32_INIT; pStream->msg = NULL; pStream->reserved = 0; pStream->total_in = 0; pStream->total_out = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pComp = (tdefl_compressor *)pStream->zalloc(pStream->opaque, 1, sizeof(tdefl_compressor)); if (!pComp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pComp; if (tdefl_init(pComp, NULL, NULL, comp_flags) != TDEFL_STATUS_OKAY) { mz_deflateEnd(pStream); return MZ_PARAM_ERROR; } return MZ_OK; } int mz_deflateReset(mz_streamp pStream) { if ((!pStream) || (!pStream->state) || (!pStream->zalloc) || (!pStream->zfree)) return MZ_STREAM_ERROR; pStream->total_in = pStream->total_out = 0; tdefl_init((tdefl_compressor *)pStream->state, NULL, NULL, ((tdefl_compressor *)pStream->state)->m_flags); return MZ_OK; } int mz_deflate(mz_streamp pStream, int flush) { size_t in_bytes, out_bytes; mz_ulong orig_total_in, orig_total_out; int mz_status = MZ_OK; if ((!pStream) || (!pStream->state) || (flush < 0) || (flush > MZ_FINISH) || (!pStream->next_out)) return MZ_STREAM_ERROR; if (!pStream->avail_out) return MZ_BUF_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if (((tdefl_compressor *)pStream->state)->m_prev_return_status == TDEFL_STATUS_DONE) return (flush == MZ_FINISH) ? MZ_STREAM_END : MZ_BUF_ERROR; orig_total_in = pStream->total_in; orig_total_out = pStream->total_out; for (;;) { tdefl_status defl_status; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; defl_status = tdefl_compress((tdefl_compressor *)pStream->state, pStream->next_in, &in_bytes, pStream->next_out, &out_bytes, (tdefl_flush)flush); pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tdefl_get_adler32((tdefl_compressor *)pStream->state); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (defl_status < 0) { mz_status = MZ_STREAM_ERROR; break; } else if (defl_status == TDEFL_STATUS_DONE) { mz_status = MZ_STREAM_END; break; } else if (!pStream->avail_out) break; else if ((!pStream->avail_in) && (flush != MZ_FINISH)) { if ((flush) || (pStream->total_in != orig_total_in) || (pStream->total_out != orig_total_out)) break; return MZ_BUF_ERROR; // Can't make forward progress without some input. } } return mz_status; } int mz_deflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } mz_ulong mz_deflateBound(mz_streamp pStream, mz_ulong source_len) { (void)pStream; // This is really over conservative. (And lame, but it's actually pretty // tricky to compute a true upper bound given the way tdefl's blocking works.) return MZ_MAX(128 + (source_len * 110) / 100, 128 + source_len + ((source_len / (31 * 1024)) + 1) * 5); } int mz_compress2(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len, int level) { int status; mz_stream stream; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_deflateInit(&stream, level); if (status != MZ_OK) return status; status = mz_deflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_deflateEnd(&stream); return (status == MZ_OK) ? MZ_BUF_ERROR : status; } *pDest_len = stream.total_out; return mz_deflateEnd(&stream); } int mz_compress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { return mz_compress2(pDest, pDest_len, pSource, source_len, MZ_DEFAULT_COMPRESSION); } mz_ulong mz_compressBound(mz_ulong source_len) { return mz_deflateBound(NULL, source_len); } typedef struct { tinfl_decompressor m_decomp; mz_uint m_dict_ofs, m_dict_avail, m_first_call, m_has_flushed; int m_window_bits; mz_uint8 m_dict[TINFL_LZ_DICT_SIZE]; tinfl_status m_last_status; } inflate_state; int mz_inflateInit2(mz_streamp pStream, int window_bits) { inflate_state *pDecomp; if (!pStream) return MZ_STREAM_ERROR; if ((window_bits != MZ_DEFAULT_WINDOW_BITS) && (-window_bits != MZ_DEFAULT_WINDOW_BITS)) return MZ_PARAM_ERROR; pStream->data_type = 0; pStream->adler = 0; pStream->msg = NULL; pStream->total_in = 0; pStream->total_out = 0; pStream->reserved = 0; if (!pStream->zalloc) pStream->zalloc = def_alloc_func; if (!pStream->zfree) pStream->zfree = def_free_func; pDecomp = (inflate_state *)pStream->zalloc(pStream->opaque, 1, sizeof(inflate_state)); if (!pDecomp) return MZ_MEM_ERROR; pStream->state = (struct mz_internal_state *)pDecomp; tinfl_init(&pDecomp->m_decomp); pDecomp->m_dict_ofs = 0; pDecomp->m_dict_avail = 0; pDecomp->m_last_status = TINFL_STATUS_NEEDS_MORE_INPUT; pDecomp->m_first_call = 1; pDecomp->m_has_flushed = 0; pDecomp->m_window_bits = window_bits; return MZ_OK; } int mz_inflateInit(mz_streamp pStream) { return mz_inflateInit2(pStream, MZ_DEFAULT_WINDOW_BITS); } int mz_inflate(mz_streamp pStream, int flush) { inflate_state *pState; mz_uint n, first_call, decomp_flags = TINFL_FLAG_COMPUTE_ADLER32; size_t in_bytes, out_bytes, orig_avail_in; tinfl_status status; if ((!pStream) || (!pStream->state)) return MZ_STREAM_ERROR; if (flush == MZ_PARTIAL_FLUSH) flush = MZ_SYNC_FLUSH; if ((flush) && (flush != MZ_SYNC_FLUSH) && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState = (inflate_state *)pStream->state; if (pState->m_window_bits > 0) decomp_flags |= TINFL_FLAG_PARSE_ZLIB_HEADER; orig_avail_in = pStream->avail_in; first_call = pState->m_first_call; pState->m_first_call = 0; if (pState->m_last_status < 0) return MZ_DATA_ERROR; if (pState->m_has_flushed && (flush != MZ_FINISH)) return MZ_STREAM_ERROR; pState->m_has_flushed |= (flush == MZ_FINISH); if ((flush == MZ_FINISH) && (first_call)) { // MZ_FINISH on the first call implies that the input and output buffers are // large enough to hold the entire compressed/decompressed file. decomp_flags |= TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF; in_bytes = pStream->avail_in; out_bytes = pStream->avail_out; status = tinfl_decompress(&pState->m_decomp, pStream->next_in, &in_bytes, pStream->next_out, pStream->next_out, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pStream->next_out += (mz_uint)out_bytes; pStream->avail_out -= (mz_uint)out_bytes; pStream->total_out += (mz_uint)out_bytes; if (status < 0) return MZ_DATA_ERROR; else if (status != TINFL_STATUS_DONE) { pState->m_last_status = TINFL_STATUS_FAILED; return MZ_BUF_ERROR; } return MZ_STREAM_END; } // flush != MZ_FINISH then we must assume there's more input. if (flush != MZ_FINISH) decomp_flags |= TINFL_FLAG_HAS_MORE_INPUT; if (pState->m_dict_avail) { n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); return ((pState->m_last_status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } for (;;) { in_bytes = pStream->avail_in; out_bytes = TINFL_LZ_DICT_SIZE - pState->m_dict_ofs; status = tinfl_decompress( &pState->m_decomp, pStream->next_in, &in_bytes, pState->m_dict, pState->m_dict + pState->m_dict_ofs, &out_bytes, decomp_flags); pState->m_last_status = status; pStream->next_in += (mz_uint)in_bytes; pStream->avail_in -= (mz_uint)in_bytes; pStream->total_in += (mz_uint)in_bytes; pStream->adler = tinfl_get_adler32(&pState->m_decomp); pState->m_dict_avail = (mz_uint)out_bytes; n = MZ_MIN(pState->m_dict_avail, pStream->avail_out); memcpy(pStream->next_out, pState->m_dict + pState->m_dict_ofs, n); pStream->next_out += n; pStream->avail_out -= n; pStream->total_out += n; pState->m_dict_avail -= n; pState->m_dict_ofs = (pState->m_dict_ofs + n) & (TINFL_LZ_DICT_SIZE - 1); if (status < 0) return MZ_DATA_ERROR; // Stream is corrupted (there could be some // uncompressed data left in the output dictionary - // oh well). else if ((status == TINFL_STATUS_NEEDS_MORE_INPUT) && (!orig_avail_in)) return MZ_BUF_ERROR; // Signal caller that we can't make forward progress // without supplying more input or by setting flush // to MZ_FINISH. else if (flush == MZ_FINISH) { // The output buffer MUST be large to hold the remaining uncompressed data // when flush==MZ_FINISH. if (status == TINFL_STATUS_DONE) return pState->m_dict_avail ? MZ_BUF_ERROR : MZ_STREAM_END; // status here must be TINFL_STATUS_HAS_MORE_OUTPUT, which means there's // at least 1 more byte on the way. If there's no more room left in the // output buffer then something is wrong. else if (!pStream->avail_out) return MZ_BUF_ERROR; } else if ((status == TINFL_STATUS_DONE) || (!pStream->avail_in) || (!pStream->avail_out) || (pState->m_dict_avail)) break; } return ((status == TINFL_STATUS_DONE) && (!pState->m_dict_avail)) ? MZ_STREAM_END : MZ_OK; } int mz_inflateEnd(mz_streamp pStream) { if (!pStream) return MZ_STREAM_ERROR; if (pStream->state) { pStream->zfree(pStream->opaque, pStream->state); pStream->state = NULL; } return MZ_OK; } int mz_uncompress(unsigned char *pDest, mz_ulong *pDest_len, const unsigned char *pSource, mz_ulong source_len) { mz_stream stream; int status; memset(&stream, 0, sizeof(stream)); // In case mz_ulong is 64-bits (argh I hate longs). if ((source_len | *pDest_len) > 0xFFFFFFFFU) return MZ_PARAM_ERROR; stream.next_in = pSource; stream.avail_in = (mz_uint32)source_len; stream.next_out = pDest; stream.avail_out = (mz_uint32)*pDest_len; status = mz_inflateInit(&stream); if (status != MZ_OK) return status; status = mz_inflate(&stream, MZ_FINISH); if (status != MZ_STREAM_END) { mz_inflateEnd(&stream); return ((status == MZ_BUF_ERROR) && (!stream.avail_in)) ? MZ_DATA_ERROR : status; } *pDest_len = stream.total_out; return mz_inflateEnd(&stream); } const char *mz_error(int err) { static struct { int m_err; const char *m_pDesc; } s_error_descs[] = {{MZ_OK, ""}, {MZ_STREAM_END, "stream end"}, {MZ_NEED_DICT, "need dictionary"}, {MZ_ERRNO, "file error"}, {MZ_STREAM_ERROR, "stream error"}, {MZ_DATA_ERROR, "data error"}, {MZ_MEM_ERROR, "out of memory"}, {MZ_BUF_ERROR, "buf error"}, {MZ_VERSION_ERROR, "version error"}, {MZ_PARAM_ERROR, "parameter error"}}; mz_uint i; for (i = 0; i < sizeof(s_error_descs) / sizeof(s_error_descs[0]); ++i) if (s_error_descs[i].m_err == err) return s_error_descs[i].m_pDesc; return NULL; } #endif // MINIZ_NO_ZLIB_APIS // ------------------- Low-level Decompression (completely independent from all // compression API's) #define TINFL_MEMCPY(d, s, l) memcpy(d, s, l) #define TINFL_MEMSET(p, c, l) memset(p, c, l) #define TINFL_CR_BEGIN \ switch (r->m_state) { \ case 0: #define TINFL_CR_RETURN(state_index, result) \ do { \ status = result; \ r->m_state = state_index; \ goto common_exit; \ case state_index:; \ } \ MZ_MACRO_END #define TINFL_CR_RETURN_FOREVER(state_index, result) \ do { \ for (;;) { \ TINFL_CR_RETURN(state_index, result); \ } \ } \ MZ_MACRO_END #define TINFL_CR_FINISH } // TODO: If the caller has indicated that there's no more input, and we attempt // to read beyond the input buf, then something is wrong with the input because // the inflator never // reads ahead more than it needs to. Currently TINFL_GET_BYTE() pads the end of // the stream with 0's in this scenario. #define TINFL_GET_BYTE(state_index, c) \ do { \ if (pIn_buf_cur >= pIn_buf_end) { \ for (;;) { \ if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { \ TINFL_CR_RETURN(state_index, TINFL_STATUS_NEEDS_MORE_INPUT); \ if (pIn_buf_cur < pIn_buf_end) { \ c = *pIn_buf_cur++; \ break; \ } \ } else { \ c = 0; \ break; \ } \ } \ } else \ c = *pIn_buf_cur++; \ } \ MZ_MACRO_END #define TINFL_NEED_BITS(state_index, n) \ do { \ mz_uint c; \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < (mz_uint)(n)) #define TINFL_SKIP_BITS(state_index, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END #define TINFL_GET_BITS(state_index, b, n) \ do { \ if (num_bits < (mz_uint)(n)) { \ TINFL_NEED_BITS(state_index, n); \ } \ b = bit_buf & ((1 << (n)) - 1); \ bit_buf >>= (n); \ num_bits -= (n); \ } \ MZ_MACRO_END // TINFL_HUFF_BITBUF_FILL() is only used rarely, when the number of bytes // remaining in the input buffer falls below 2. // It reads just enough bytes from the input stream that are needed to decode // the next Huffman code (and absolutely no more). It works by trying to fully // decode a // Huffman code by using whatever bits are currently present in the bit buffer. // If this fails, it reads another byte, and tries again until it succeeds or // until the // bit buffer contains >=15 bits (deflate's max. Huffman code size). #define TINFL_HUFF_BITBUF_FILL(state_index, pHuff) \ do { \ temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]; \ if (temp >= 0) { \ code_len = temp >> 9; \ if ((code_len) && (num_bits >= code_len)) break; \ } else if (num_bits > TINFL_FAST_LOOKUP_BITS) { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while ((temp < 0) && (num_bits >= (code_len + 1))); \ if (temp >= 0) break; \ } \ TINFL_GET_BYTE(state_index, c); \ bit_buf |= (((tinfl_bit_buf_t)c) << num_bits); \ num_bits += 8; \ } while (num_bits < 15); // TINFL_HUFF_DECODE() decodes the next Huffman coded symbol. It's more complex // than you would initially expect because the zlib API expects the decompressor // to never read // beyond the final byte of the deflate stream. (In other words, when this macro // wants to read another byte from the input, it REALLY needs another byte in // order to fully // decode the next Huffman code.) Handling this properly is particularly // important on raw deflate (non-zlib) streams, which aren't followed by a byte // aligned adler-32. // The slow path is only executed at the very end of the input buffer. #define TINFL_HUFF_DECODE(state_index, sym, pHuff) \ do { \ int temp; \ mz_uint code_len, c; \ if (num_bits < 15) { \ if ((pIn_buf_end - pIn_buf_cur) < 2) { \ TINFL_HUFF_BITBUF_FILL(state_index, pHuff); \ } else { \ bit_buf |= (((tinfl_bit_buf_t)pIn_buf_cur[0]) << num_bits) | \ (((tinfl_bit_buf_t)pIn_buf_cur[1]) << (num_bits + 8)); \ pIn_buf_cur += 2; \ num_bits += 16; \ } \ } \ if ((temp = (pHuff)->m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= \ 0) \ code_len = temp >> 9, temp &= 511; \ else { \ code_len = TINFL_FAST_LOOKUP_BITS; \ do { \ temp = (pHuff)->m_tree[~temp + ((bit_buf >> code_len++) & 1)]; \ } while (temp < 0); \ } \ sym = temp; \ bit_buf >>= code_len; \ num_bits -= code_len; \ } \ MZ_MACRO_END tinfl_status tinfl_decompress(tinfl_decompressor *r, const mz_uint8 *pIn_buf_next, size_t *pIn_buf_size, mz_uint8 *pOut_buf_start, mz_uint8 *pOut_buf_next, size_t *pOut_buf_size, const mz_uint32 decomp_flags) { static const int s_length_base[31] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0}; static const int s_length_extra[31] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 0, 0}; static const int s_dist_base[32] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0}; static const int s_dist_extra[32] = {0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; static const mz_uint8 s_length_dezigzag[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static const int s_min_table_sizes[3] = {257, 1, 4}; tinfl_status status = TINFL_STATUS_FAILED; mz_uint32 num_bits, dist, counter, num_extra; tinfl_bit_buf_t bit_buf; const mz_uint8 *pIn_buf_cur = pIn_buf_next, *const pIn_buf_end = pIn_buf_next + *pIn_buf_size; mz_uint8 *pOut_buf_cur = pOut_buf_next, *const pOut_buf_end = pOut_buf_next + *pOut_buf_size; size_t out_buf_size_mask = (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF) ? (size_t)-1 : ((pOut_buf_next - pOut_buf_start) + *pOut_buf_size) - 1, dist_from_out_buf_start; // Ensure the output buffer's size is a power of 2, unless the output buffer // is large enough to hold the entire output file (in which case it doesn't // matter). if (((out_buf_size_mask + 1) & out_buf_size_mask) || (pOut_buf_next < pOut_buf_start)) { *pIn_buf_size = *pOut_buf_size = 0; return TINFL_STATUS_BAD_PARAM; } num_bits = r->m_num_bits; bit_buf = r->m_bit_buf; dist = r->m_dist; counter = r->m_counter; num_extra = r->m_num_extra; dist_from_out_buf_start = r->m_dist_from_out_buf_start; TINFL_CR_BEGIN bit_buf = num_bits = dist = counter = num_extra = r->m_zhdr0 = r->m_zhdr1 = 0; r->m_z_adler32 = r->m_check_adler32 = 1; if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_GET_BYTE(1, r->m_zhdr0); TINFL_GET_BYTE(2, r->m_zhdr1); counter = (((r->m_zhdr0 * 256 + r->m_zhdr1) % 31 != 0) || (r->m_zhdr1 & 32) || ((r->m_zhdr0 & 15) != 8)); if (!(decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) counter |= (((1U << (8U + (r->m_zhdr0 >> 4))) > 32768U) || ((out_buf_size_mask + 1) < (size_t)(1ULL << (8U + (r->m_zhdr0 >> 4))))); if (counter) { TINFL_CR_RETURN_FOREVER(36, TINFL_STATUS_FAILED); } } do { TINFL_GET_BITS(3, r->m_final, 3); r->m_type = r->m_final >> 1; if (r->m_type == 0) { TINFL_SKIP_BITS(5, num_bits & 7); for (counter = 0; counter < 4; ++counter) { if (num_bits) TINFL_GET_BITS(6, r->m_raw_header[counter], 8); else TINFL_GET_BYTE(7, r->m_raw_header[counter]); } if ((counter = (r->m_raw_header[0] | (r->m_raw_header[1] << 8))) != (mz_uint)(0xFFFF ^ (r->m_raw_header[2] | (r->m_raw_header[3] << 8)))) { TINFL_CR_RETURN_FOREVER(39, TINFL_STATUS_FAILED); } while ((counter) && (num_bits)) { TINFL_GET_BITS(51, dist, 8); while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(52, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)dist; counter--; } while (counter) { size_t n; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(9, TINFL_STATUS_HAS_MORE_OUTPUT); } while (pIn_buf_cur >= pIn_buf_end) { if (decomp_flags & TINFL_FLAG_HAS_MORE_INPUT) { TINFL_CR_RETURN(38, TINFL_STATUS_NEEDS_MORE_INPUT); } else { TINFL_CR_RETURN_FOREVER(40, TINFL_STATUS_FAILED); } } n = MZ_MIN(MZ_MIN((size_t)(pOut_buf_end - pOut_buf_cur), (size_t)(pIn_buf_end - pIn_buf_cur)), counter); TINFL_MEMCPY(pOut_buf_cur, pIn_buf_cur, n); pIn_buf_cur += n; pOut_buf_cur += n; counter -= (mz_uint)n; } } else if (r->m_type == 3) { TINFL_CR_RETURN_FOREVER(10, TINFL_STATUS_FAILED); } else { if (r->m_type == 1) { mz_uint8 *p = r->m_tables[0].m_code_size; mz_uint i; r->m_table_sizes[0] = 288; r->m_table_sizes[1] = 32; TINFL_MEMSET(r->m_tables[1].m_code_size, 5, 32); for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; } else { for (counter = 0; counter < 3; counter++) { TINFL_GET_BITS(11, r->m_table_sizes[counter], "\05\05\04"[counter]); r->m_table_sizes[counter] += s_min_table_sizes[counter]; } MZ_CLEAR_OBJ(r->m_tables[2].m_code_size); for (counter = 0; counter < r->m_table_sizes[2]; counter++) { mz_uint s; TINFL_GET_BITS(14, s, 3); r->m_tables[2].m_code_size[s_length_dezigzag[counter]] = (mz_uint8)s; } r->m_table_sizes[2] = 19; } for (; (int)r->m_type >= 0; r->m_type--) { int tree_next, tree_cur; tinfl_huff_table *pTable; mz_uint i, j, used_syms, total, sym_index, next_code[17], total_syms[16]; pTable = &r->m_tables[r->m_type]; MZ_CLEAR_OBJ(total_syms); MZ_CLEAR_OBJ(pTable->m_look_up); MZ_CLEAR_OBJ(pTable->m_tree); for (i = 0; i < r->m_table_sizes[r->m_type]; ++i) total_syms[pTable->m_code_size[i]]++; used_syms = 0, total = 0; next_code[0] = next_code[1] = 0; for (i = 1; i <= 15; ++i) { used_syms += total_syms[i]; next_code[i + 1] = (total = ((total + total_syms[i]) << 1)); } if ((65536 != total) && (used_syms > 1)) { TINFL_CR_RETURN_FOREVER(35, TINFL_STATUS_FAILED); } for (tree_next = -1, sym_index = 0; sym_index < r->m_table_sizes[r->m_type]; ++sym_index) { mz_uint rev_code = 0, l, cur_code, code_size = pTable->m_code_size[sym_index]; if (!code_size) continue; cur_code = next_code[code_size]++; for (l = code_size; l > 0; l--, cur_code >>= 1) rev_code = (rev_code << 1) | (cur_code & 1); if (code_size <= TINFL_FAST_LOOKUP_BITS) { mz_int16 k = (mz_int16)((code_size << 9) | sym_index); while (rev_code < TINFL_FAST_LOOKUP_SIZE) { pTable->m_look_up[rev_code] = k; rev_code += (1 << code_size); } continue; } if (0 == (tree_cur = pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)])) { pTable->m_look_up[rev_code & (TINFL_FAST_LOOKUP_SIZE - 1)] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } rev_code >>= (TINFL_FAST_LOOKUP_BITS - 1); for (j = code_size; j > (TINFL_FAST_LOOKUP_BITS + 1); j--) { tree_cur -= ((rev_code >>= 1) & 1); if (!pTable->m_tree[-tree_cur - 1]) { pTable->m_tree[-tree_cur - 1] = (mz_int16)tree_next; tree_cur = tree_next; tree_next -= 2; } else tree_cur = pTable->m_tree[-tree_cur - 1]; } tree_cur -= ((rev_code >>= 1) & 1); pTable->m_tree[-tree_cur - 1] = (mz_int16)sym_index; } if (r->m_type == 2) { for (counter = 0; counter < (r->m_table_sizes[0] + r->m_table_sizes[1]);) { mz_uint s; TINFL_HUFF_DECODE(16, dist, &r->m_tables[2]); if (dist < 16) { r->m_len_codes[counter++] = (mz_uint8)dist; continue; } if ((dist == 16) && (!counter)) { TINFL_CR_RETURN_FOREVER(17, TINFL_STATUS_FAILED); } num_extra = "\02\03\07"[dist - 16]; TINFL_GET_BITS(18, s, num_extra); s += "\03\03\013"[dist - 16]; TINFL_MEMSET(r->m_len_codes + counter, (dist == 16) ? r->m_len_codes[counter - 1] : 0, s); counter += s; } if ((r->m_table_sizes[0] + r->m_table_sizes[1]) != counter) { TINFL_CR_RETURN_FOREVER(21, TINFL_STATUS_FAILED); } TINFL_MEMCPY(r->m_tables[0].m_code_size, r->m_len_codes, r->m_table_sizes[0]); TINFL_MEMCPY(r->m_tables[1].m_code_size, r->m_len_codes + r->m_table_sizes[0], r->m_table_sizes[1]); } } for (;;) { mz_uint8 *pSrc; for (;;) { if (((pIn_buf_end - pIn_buf_cur) < 4) || ((pOut_buf_end - pOut_buf_cur) < 2)) { TINFL_HUFF_DECODE(23, counter, &r->m_tables[0]); if (counter >= 256) break; while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(24, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = (mz_uint8)counter; } else { int sym2; mz_uint code_len; #if TINFL_USE_64BIT_BITBUF if (num_bits < 30) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE32(pIn_buf_cur)) << num_bits); pIn_buf_cur += 4; num_bits += 32; } #else if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } counter = sym2; bit_buf >>= code_len; num_bits -= code_len; if (counter & 256) break; #if !TINFL_USE_64BIT_BITBUF if (num_bits < 15) { bit_buf |= (((tinfl_bit_buf_t)MZ_READ_LE16(pIn_buf_cur)) << num_bits); pIn_buf_cur += 2; num_bits += 16; } #endif if ((sym2 = r->m_tables[0] .m_look_up[bit_buf & (TINFL_FAST_LOOKUP_SIZE - 1)]) >= 0) code_len = sym2 >> 9; else { code_len = TINFL_FAST_LOOKUP_BITS; do { sym2 = r->m_tables[0] .m_tree[~sym2 + ((bit_buf >> code_len++) & 1)]; } while (sym2 < 0); } bit_buf >>= code_len; num_bits -= code_len; pOut_buf_cur[0] = (mz_uint8)counter; if (sym2 & 256) { pOut_buf_cur++; counter = sym2; break; } pOut_buf_cur[1] = (mz_uint8)sym2; pOut_buf_cur += 2; } } if ((counter &= 511) == 256) break; num_extra = s_length_extra[counter - 257]; counter = s_length_base[counter - 257]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(25, extra_bits, num_extra); counter += extra_bits; } TINFL_HUFF_DECODE(26, dist, &r->m_tables[1]); num_extra = s_dist_extra[dist]; dist = s_dist_base[dist]; if (num_extra) { mz_uint extra_bits; TINFL_GET_BITS(27, extra_bits, num_extra); dist += extra_bits; } dist_from_out_buf_start = pOut_buf_cur - pOut_buf_start; if ((dist > dist_from_out_buf_start) && (decomp_flags & TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF)) { TINFL_CR_RETURN_FOREVER(37, TINFL_STATUS_FAILED); } pSrc = pOut_buf_start + ((dist_from_out_buf_start - dist) & out_buf_size_mask); if ((MZ_MAX(pOut_buf_cur, pSrc) + counter) > pOut_buf_end) { while (counter--) { while (pOut_buf_cur >= pOut_buf_end) { TINFL_CR_RETURN(53, TINFL_STATUS_HAS_MORE_OUTPUT); } *pOut_buf_cur++ = pOut_buf_start[(dist_from_out_buf_start++ - dist) & out_buf_size_mask]; } continue; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES else if ((counter >= 9) && (counter <= dist)) { const mz_uint8 *pSrc_end = pSrc + (counter & ~7); do { ((mz_uint32 *)pOut_buf_cur)[0] = ((const mz_uint32 *)pSrc)[0]; ((mz_uint32 *)pOut_buf_cur)[1] = ((const mz_uint32 *)pSrc)[1]; pOut_buf_cur += 8; } while ((pSrc += 8) < pSrc_end); if ((counter &= 7) < 3) { if (counter) { pOut_buf_cur[0] = pSrc[0]; if (counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } continue; } } #endif do { pOut_buf_cur[0] = pSrc[0]; pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur[2] = pSrc[2]; pOut_buf_cur += 3; pSrc += 3; } while ((int)(counter -= 3) > 2); if ((int)counter > 0) { pOut_buf_cur[0] = pSrc[0]; if ((int)counter > 1) pOut_buf_cur[1] = pSrc[1]; pOut_buf_cur += counter; } } } } while (!(r->m_final & 1)); if (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) { TINFL_SKIP_BITS(32, num_bits & 7); for (counter = 0; counter < 4; ++counter) { mz_uint s; if (num_bits) TINFL_GET_BITS(41, s, 8); else TINFL_GET_BYTE(42, s); r->m_z_adler32 = (r->m_z_adler32 << 8) | s; } } TINFL_CR_RETURN_FOREVER(34, TINFL_STATUS_DONE); TINFL_CR_FINISH common_exit: r->m_num_bits = num_bits; r->m_bit_buf = bit_buf; r->m_dist = dist; r->m_counter = counter; r->m_num_extra = num_extra; r->m_dist_from_out_buf_start = dist_from_out_buf_start; *pIn_buf_size = pIn_buf_cur - pIn_buf_next; *pOut_buf_size = pOut_buf_cur - pOut_buf_next; if ((decomp_flags & (TINFL_FLAG_PARSE_ZLIB_HEADER | TINFL_FLAG_COMPUTE_ADLER32)) && (status >= 0)) { const mz_uint8 *ptr = pOut_buf_next; size_t buf_len = *pOut_buf_size; mz_uint32 i, s1 = r->m_check_adler32 & 0xffff, s2 = r->m_check_adler32 >> 16; size_t block_len = buf_len % 5552; while (buf_len) { for (i = 0; i + 7 < block_len; i += 8, ptr += 8) { s1 += ptr[0], s2 += s1; s1 += ptr[1], s2 += s1; s1 += ptr[2], s2 += s1; s1 += ptr[3], s2 += s1; s1 += ptr[4], s2 += s1; s1 += ptr[5], s2 += s1; s1 += ptr[6], s2 += s1; s1 += ptr[7], s2 += s1; } for (; i < block_len; ++i) s1 += *ptr++, s2 += s1; s1 %= 65521U, s2 %= 65521U; buf_len -= block_len; block_len = 5552; } r->m_check_adler32 = (s2 << 16) + s1; if ((status == TINFL_STATUS_DONE) && (decomp_flags & TINFL_FLAG_PARSE_ZLIB_HEADER) && (r->m_check_adler32 != r->m_z_adler32)) status = TINFL_STATUS_ADLER32_MISMATCH; } return status; } // Higher level helper functions. void *tinfl_decompress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tinfl_decompressor decomp; void *pBuf = NULL, *pNew_buf; size_t src_buf_ofs = 0, out_buf_capacity = 0; *pOut_len = 0; tinfl_init(&decomp); for (;;) { size_t src_buf_size = src_buf_len - src_buf_ofs, dst_buf_size = out_buf_capacity - *pOut_len, new_out_buf_capacity; tinfl_status status = tinfl_decompress( &decomp, (const mz_uint8 *)pSrc_buf + src_buf_ofs, &src_buf_size, (mz_uint8 *)pBuf, pBuf ? (mz_uint8 *)pBuf + *pOut_len : NULL, &dst_buf_size, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); if ((status < 0) || (status == TINFL_STATUS_NEEDS_MORE_INPUT)) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } src_buf_ofs += src_buf_size; *pOut_len += dst_buf_size; if (status == TINFL_STATUS_DONE) break; new_out_buf_capacity = out_buf_capacity * 2; if (new_out_buf_capacity < 128) new_out_buf_capacity = 128; pNew_buf = MZ_REALLOC(pBuf, new_out_buf_capacity); if (!pNew_buf) { MZ_FREE(pBuf); *pOut_len = 0; return NULL; } pBuf = pNew_buf; out_buf_capacity = new_out_buf_capacity; } return pBuf; } size_t tinfl_decompress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tinfl_decompressor decomp; tinfl_status status; tinfl_init(&decomp); status = tinfl_decompress(&decomp, (const mz_uint8 *)pSrc_buf, &src_buf_len, (mz_uint8 *)pOut_buf, (mz_uint8 *)pOut_buf, &out_buf_len, (flags & ~TINFL_FLAG_HAS_MORE_INPUT) | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF); return (status != TINFL_STATUS_DONE) ? TINFL_DECOMPRESS_MEM_TO_MEM_FAILED : out_buf_len; } int tinfl_decompress_mem_to_callback(const void *pIn_buf, size_t *pIn_buf_size, tinfl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { int result = 0; tinfl_decompressor decomp; mz_uint8 *pDict = (mz_uint8 *)MZ_MALLOC(TINFL_LZ_DICT_SIZE); size_t in_buf_ofs = 0, dict_ofs = 0; if (!pDict) return TINFL_STATUS_FAILED; tinfl_init(&decomp); for (;;) { size_t in_buf_size = *pIn_buf_size - in_buf_ofs, dst_buf_size = TINFL_LZ_DICT_SIZE - dict_ofs; tinfl_status status = tinfl_decompress(&decomp, (const mz_uint8 *)pIn_buf + in_buf_ofs, &in_buf_size, pDict, pDict + dict_ofs, &dst_buf_size, (flags & ~(TINFL_FLAG_HAS_MORE_INPUT | TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF))); in_buf_ofs += in_buf_size; if ((dst_buf_size) && (!(*pPut_buf_func)(pDict + dict_ofs, (int)dst_buf_size, pPut_buf_user))) break; if (status != TINFL_STATUS_HAS_MORE_OUTPUT) { result = (status == TINFL_STATUS_DONE); break; } dict_ofs = (dict_ofs + dst_buf_size) & (TINFL_LZ_DICT_SIZE - 1); } MZ_FREE(pDict); *pIn_buf_size = in_buf_ofs; return result; } // ------------------- Low-level Compression (independent from all decompression // API's) // Purposely making these tables static for faster init and thread safety. static const mz_uint16 s_tdefl_len_sym[256] = { 257, 258, 259, 260, 261, 262, 263, 264, 265, 265, 266, 266, 267, 267, 268, 268, 269, 269, 269, 269, 270, 270, 270, 270, 271, 271, 271, 271, 272, 272, 272, 272, 273, 273, 273, 273, 273, 273, 273, 273, 274, 274, 274, 274, 274, 274, 274, 274, 275, 275, 275, 275, 275, 275, 275, 275, 276, 276, 276, 276, 276, 276, 276, 276, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 277, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 278, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 279, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 280, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 281, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 282, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 283, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 284, 285}; static const mz_uint8 s_tdefl_len_extra[256] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 0}; static const mz_uint8 s_tdefl_small_dist_sym[512] = { 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17}; static const mz_uint8 s_tdefl_small_dist_extra[512] = { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}; static const mz_uint8 s_tdefl_large_dist_sym[128] = { 0, 0, 18, 19, 20, 20, 21, 21, 22, 22, 22, 22, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29}; static const mz_uint8 s_tdefl_large_dist_extra[128] = { 0, 0, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}; // Radix sorts tdefl_sym_freq[] array by 16-bit key m_key. Returns ptr to sorted // values. typedef struct { mz_uint16 m_key, m_sym_index; } tdefl_sym_freq; static tdefl_sym_freq *tdefl_radix_sort_syms(mz_uint num_syms, tdefl_sym_freq *pSyms0, tdefl_sym_freq *pSyms1) { mz_uint32 total_passes = 2, pass_shift, pass, i, hist[256 * 2]; tdefl_sym_freq *pCur_syms = pSyms0, *pNew_syms = pSyms1; MZ_CLEAR_OBJ(hist); for (i = 0; i < num_syms; i++) { mz_uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; } while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--; for (pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8) { const mz_uint32 *pHist = &hist[pass << 8]; mz_uint offsets[256], cur_ofs = 0; for (i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; } for (i = 0; i < num_syms; i++) pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i]; { tdefl_sym_freq *t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t; } } return pCur_syms; } // tdefl_calculate_minimum_redundancy() originally written by: Alistair Moffat, // alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996. static void tdefl_calculate_minimum_redundancy(tdefl_sym_freq *A, int n) { int root, leaf, next, avbl, used, dpth; if (n == 0) return; else if (n == 1) { A[0].m_key = 1; return; } A[0].m_key += A[1].m_key; root = 0; leaf = 2; for (next = 1; next < n - 1; next++) { if (leaf >= n || A[root].m_key < A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = (mz_uint16)next; } else A[next].m_key = A[leaf++].m_key; if (leaf >= n || (root < next && A[root].m_key < A[leaf].m_key)) { A[next].m_key = (mz_uint16)(A[next].m_key + A[root].m_key); A[root++].m_key = (mz_uint16)next; } else A[next].m_key = (mz_uint16)(A[next].m_key + A[leaf++].m_key); } A[n - 2].m_key = 0; for (next = n - 3; next >= 0; next--) A[next].m_key = A[A[next].m_key].m_key + 1; avbl = 1; used = dpth = 0; root = n - 2; next = n - 1; while (avbl > 0) { while (root >= 0 && (int)A[root].m_key == dpth) { used++; root--; } while (avbl > used) { A[next--].m_key = (mz_uint16)(dpth); avbl--; } avbl = 2 * used; dpth++; used = 0; } } // Limits canonical Huffman code table's max code size. enum { TDEFL_MAX_SUPPORTED_HUFF_CODESIZE = 32 }; static void tdefl_huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size) { int i; mz_uint32 total = 0; if (code_list_len <= 1) return; for (i = max_code_size + 1; i <= TDEFL_MAX_SUPPORTED_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i]; for (i = max_code_size; i > 0; i--) total += (((mz_uint32)pNum_codes[i]) << (max_code_size - i)); while (total != (1UL << max_code_size)) { pNum_codes[max_code_size]--; for (i = max_code_size - 1; i > 0; i--) if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; } total--; } } static void tdefl_optimize_huffman_table(tdefl_compressor *d, int table_num, int table_len, int code_size_limit, int static_table) { int i, j, l, num_codes[1 + TDEFL_MAX_SUPPORTED_HUFF_CODESIZE]; mz_uint next_code[TDEFL_MAX_SUPPORTED_HUFF_CODESIZE + 1]; MZ_CLEAR_OBJ(num_codes); if (static_table) { for (i = 0; i < table_len; i++) num_codes[d->m_huff_code_sizes[table_num][i]]++; } else { tdefl_sym_freq syms0[TDEFL_MAX_HUFF_SYMBOLS], syms1[TDEFL_MAX_HUFF_SYMBOLS], *pSyms; int num_used_syms = 0; const mz_uint16 *pSym_count = &d->m_huff_count[table_num][0]; for (i = 0; i < table_len; i++) if (pSym_count[i]) { syms0[num_used_syms].m_key = (mz_uint16)pSym_count[i]; syms0[num_used_syms++].m_sym_index = (mz_uint16)i; } pSyms = tdefl_radix_sort_syms(num_used_syms, syms0, syms1); tdefl_calculate_minimum_redundancy(pSyms, num_used_syms); for (i = 0; i < num_used_syms; i++) num_codes[pSyms[i].m_key]++; tdefl_huffman_enforce_max_code_size(num_codes, num_used_syms, code_size_limit); MZ_CLEAR_OBJ(d->m_huff_code_sizes[table_num]); MZ_CLEAR_OBJ(d->m_huff_codes[table_num]); for (i = 1, j = num_used_syms; i <= code_size_limit; i++) for (l = num_codes[i]; l > 0; l--) d->m_huff_code_sizes[table_num][pSyms[--j].m_sym_index] = (mz_uint8)(i); } next_code[1] = 0; for (j = 0, i = 2; i <= code_size_limit; i++) next_code[i] = j = ((j + num_codes[i - 1]) << 1); for (i = 0; i < table_len; i++) { mz_uint rev_code = 0, code, code_size; if ((code_size = d->m_huff_code_sizes[table_num][i]) == 0) continue; code = next_code[code_size]++; for (l = code_size; l > 0; l--, code >>= 1) rev_code = (rev_code << 1) | (code & 1); d->m_huff_codes[table_num][i] = (mz_uint16)rev_code; } } #define TDEFL_PUT_BITS(b, l) \ do { \ mz_uint bits = b; \ mz_uint len = l; \ MZ_ASSERT(bits <= ((1U << len) - 1U)); \ d->m_bit_buffer |= (bits << d->m_bits_in); \ d->m_bits_in += len; \ while (d->m_bits_in >= 8) { \ if (d->m_pOutput_buf < d->m_pOutput_buf_end) \ *d->m_pOutput_buf++ = (mz_uint8)(d->m_bit_buffer); \ d->m_bit_buffer >>= 8; \ d->m_bits_in -= 8; \ } \ } \ MZ_MACRO_END #define TDEFL_RLE_PREV_CODE_SIZE() \ { \ if (rle_repeat_count) { \ if (rle_repeat_count < 3) { \ d->m_huff_count[2][prev_code_size] = (mz_uint16)( \ d->m_huff_count[2][prev_code_size] + rle_repeat_count); \ while (rle_repeat_count--) \ packed_code_sizes[num_packed_code_sizes++] = prev_code_size; \ } else { \ d->m_huff_count[2][16] = (mz_uint16)(d->m_huff_count[2][16] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 16; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_repeat_count - 3); \ } \ rle_repeat_count = 0; \ } \ } #define TDEFL_RLE_ZERO_CODE_SIZE() \ { \ if (rle_z_count) { \ if (rle_z_count < 3) { \ d->m_huff_count[2][0] = \ (mz_uint16)(d->m_huff_count[2][0] + rle_z_count); \ while (rle_z_count--) packed_code_sizes[num_packed_code_sizes++] = 0; \ } else if (rle_z_count <= 10) { \ d->m_huff_count[2][17] = (mz_uint16)(d->m_huff_count[2][17] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 17; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 3); \ } else { \ d->m_huff_count[2][18] = (mz_uint16)(d->m_huff_count[2][18] + 1); \ packed_code_sizes[num_packed_code_sizes++] = 18; \ packed_code_sizes[num_packed_code_sizes++] = \ (mz_uint8)(rle_z_count - 11); \ } \ rle_z_count = 0; \ } \ } static mz_uint8 s_tdefl_packed_code_size_syms_swizzle[] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; static void tdefl_start_dynamic_block(tdefl_compressor *d) { int num_lit_codes, num_dist_codes, num_bit_lengths; mz_uint i, total_code_sizes_to_pack, num_packed_code_sizes, rle_z_count, rle_repeat_count, packed_code_sizes_index; mz_uint8 code_sizes_to_pack[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], packed_code_sizes[TDEFL_MAX_HUFF_SYMBOLS_0 + TDEFL_MAX_HUFF_SYMBOLS_1], prev_code_size = 0xFF; d->m_huff_count[0][256] = 1; tdefl_optimize_huffman_table(d, 0, TDEFL_MAX_HUFF_SYMBOLS_0, 15, MZ_FALSE); tdefl_optimize_huffman_table(d, 1, TDEFL_MAX_HUFF_SYMBOLS_1, 15, MZ_FALSE); for (num_lit_codes = 286; num_lit_codes > 257; num_lit_codes--) if (d->m_huff_code_sizes[0][num_lit_codes - 1]) break; for (num_dist_codes = 30; num_dist_codes > 1; num_dist_codes--) if (d->m_huff_code_sizes[1][num_dist_codes - 1]) break; memcpy(code_sizes_to_pack, &d->m_huff_code_sizes[0][0], num_lit_codes); memcpy(code_sizes_to_pack + num_lit_codes, &d->m_huff_code_sizes[1][0], num_dist_codes); total_code_sizes_to_pack = num_lit_codes + num_dist_codes; num_packed_code_sizes = 0; rle_z_count = 0; rle_repeat_count = 0; memset(&d->m_huff_count[2][0], 0, sizeof(d->m_huff_count[2][0]) * TDEFL_MAX_HUFF_SYMBOLS_2); for (i = 0; i < total_code_sizes_to_pack; i++) { mz_uint8 code_size = code_sizes_to_pack[i]; if (!code_size) { TDEFL_RLE_PREV_CODE_SIZE(); if (++rle_z_count == 138) { TDEFL_RLE_ZERO_CODE_SIZE(); } } else { TDEFL_RLE_ZERO_CODE_SIZE(); if (code_size != prev_code_size) { TDEFL_RLE_PREV_CODE_SIZE(); d->m_huff_count[2][code_size] = (mz_uint16)(d->m_huff_count[2][code_size] + 1); packed_code_sizes[num_packed_code_sizes++] = code_size; } else if (++rle_repeat_count == 6) { TDEFL_RLE_PREV_CODE_SIZE(); } } prev_code_size = code_size; } if (rle_repeat_count) { TDEFL_RLE_PREV_CODE_SIZE(); } else { TDEFL_RLE_ZERO_CODE_SIZE(); } tdefl_optimize_huffman_table(d, 2, TDEFL_MAX_HUFF_SYMBOLS_2, 7, MZ_FALSE); TDEFL_PUT_BITS(2, 2); TDEFL_PUT_BITS(num_lit_codes - 257, 5); TDEFL_PUT_BITS(num_dist_codes - 1, 5); for (num_bit_lengths = 18; num_bit_lengths >= 0; num_bit_lengths--) if (d->m_huff_code_sizes [2][s_tdefl_packed_code_size_syms_swizzle[num_bit_lengths]]) break; num_bit_lengths = MZ_MAX(4, (num_bit_lengths + 1)); TDEFL_PUT_BITS(num_bit_lengths - 4, 4); for (i = 0; (int)i < num_bit_lengths; i++) TDEFL_PUT_BITS( d->m_huff_code_sizes[2][s_tdefl_packed_code_size_syms_swizzle[i]], 3); for (packed_code_sizes_index = 0; packed_code_sizes_index < num_packed_code_sizes;) { mz_uint code = packed_code_sizes[packed_code_sizes_index++]; MZ_ASSERT(code < TDEFL_MAX_HUFF_SYMBOLS_2); TDEFL_PUT_BITS(d->m_huff_codes[2][code], d->m_huff_code_sizes[2][code]); if (code >= 16) TDEFL_PUT_BITS(packed_code_sizes[packed_code_sizes_index++], "\02\03\07"[code - 16]); } } static void tdefl_start_static_block(tdefl_compressor *d) { mz_uint i; mz_uint8 *p = &d->m_huff_code_sizes[0][0]; for (i = 0; i <= 143; ++i) *p++ = 8; for (; i <= 255; ++i) *p++ = 9; for (; i <= 279; ++i) *p++ = 7; for (; i <= 287; ++i) *p++ = 8; memset(d->m_huff_code_sizes[1], 5, 32); tdefl_optimize_huffman_table(d, 0, 288, 15, MZ_TRUE); tdefl_optimize_huffman_table(d, 1, 32, 15, MZ_TRUE); TDEFL_PUT_BITS(1, 2); } static const mz_uint mz_bitmasks[17] = { 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF, 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF}; #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && \ MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; mz_uint8 *pOutput_buf = d->m_pOutput_buf; mz_uint8 *pLZ_code_buf_end = d->m_pLZ_code_buf; mz_uint64 bit_buffer = d->m_bit_buffer; mz_uint bits_in = d->m_bits_in; #define TDEFL_PUT_BITS_FAST(b, l) \ { \ bit_buffer |= (((mz_uint64)(b)) << bits_in); \ bits_in += (l); \ } flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < pLZ_code_buf_end; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint s0, s1, n0, n1, sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = *(const mz_uint16 *)(pLZ_codes + 1); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS_FAST(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); // This sequence coaxes MSVC into using cmov's vs. jmp's. s0 = s_tdefl_small_dist_sym[match_dist & 511]; n0 = s_tdefl_small_dist_extra[match_dist & 511]; s1 = s_tdefl_large_dist_sym[match_dist >> 8]; n1 = s_tdefl_large_dist_extra[match_dist >> 8]; sym = (match_dist < 512) ? s0 : s1; num_extra_bits = (match_dist < 512) ? n0 : n1; MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS_FAST(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); if (((flags & 2) == 0) && (pLZ_codes < pLZ_code_buf_end)) { flags >>= 1; lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS_FAST(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } } if (pOutput_buf >= d->m_pOutput_buf_end) return MZ_FALSE; *(mz_uint64 *)pOutput_buf = bit_buffer; pOutput_buf += (bits_in >> 3); bit_buffer >>= (bits_in & ~7); bits_in &= 7; } #undef TDEFL_PUT_BITS_FAST d->m_pOutput_buf = pOutput_buf; d->m_bits_in = 0; d->m_bit_buffer = 0; while (bits_in) { mz_uint32 n = MZ_MIN(bits_in, 16); TDEFL_PUT_BITS((mz_uint)bit_buffer & mz_bitmasks[n], n); bit_buffer >>= n; bits_in -= n; } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #else static mz_bool tdefl_compress_lz_codes(tdefl_compressor *d) { mz_uint flags; mz_uint8 *pLZ_codes; flags = 1; for (pLZ_codes = d->m_lz_code_buf; pLZ_codes < d->m_pLZ_code_buf; flags >>= 1) { if (flags == 1) flags = *pLZ_codes++ | 0x100; if (flags & 1) { mz_uint sym, num_extra_bits; mz_uint match_len = pLZ_codes[0], match_dist = (pLZ_codes[1] | (pLZ_codes[2] << 8)); pLZ_codes += 3; MZ_ASSERT(d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(d->m_huff_codes[0][s_tdefl_len_sym[match_len]], d->m_huff_code_sizes[0][s_tdefl_len_sym[match_len]]); TDEFL_PUT_BITS(match_len & mz_bitmasks[s_tdefl_len_extra[match_len]], s_tdefl_len_extra[match_len]); if (match_dist < 512) { sym = s_tdefl_small_dist_sym[match_dist]; num_extra_bits = s_tdefl_small_dist_extra[match_dist]; } else { sym = s_tdefl_large_dist_sym[match_dist >> 8]; num_extra_bits = s_tdefl_large_dist_extra[match_dist >> 8]; } MZ_ASSERT(d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(d->m_huff_codes[1][sym], d->m_huff_code_sizes[1][sym]); TDEFL_PUT_BITS(match_dist & mz_bitmasks[num_extra_bits], num_extra_bits); } else { mz_uint lit = *pLZ_codes++; MZ_ASSERT(d->m_huff_code_sizes[0][lit]); TDEFL_PUT_BITS(d->m_huff_codes[0][lit], d->m_huff_code_sizes[0][lit]); } } TDEFL_PUT_BITS(d->m_huff_codes[0][256], d->m_huff_code_sizes[0][256]); return (d->m_pOutput_buf < d->m_pOutput_buf_end); } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN && // MINIZ_HAS_64BIT_REGISTERS static mz_bool tdefl_compress_block(tdefl_compressor *d, mz_bool static_block) { if (static_block) tdefl_start_static_block(d); else tdefl_start_dynamic_block(d); return tdefl_compress_lz_codes(d); } static int tdefl_flush_block(tdefl_compressor *d, int flush) { mz_uint saved_bit_buf, saved_bits_in; mz_uint8 *pSaved_output_buf; mz_bool comp_block_succeeded = MZ_FALSE; int n, use_raw_block = ((d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS) != 0) && (d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size; mz_uint8 *pOutput_buf_start = ((d->m_pPut_buf_func == NULL) && ((*d->m_pOut_buf_size - d->m_out_buf_ofs) >= TDEFL_OUT_BUF_SIZE)) ? ((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs) : d->m_output_buf; d->m_pOutput_buf = pOutput_buf_start; d->m_pOutput_buf_end = d->m_pOutput_buf + TDEFL_OUT_BUF_SIZE - 16; MZ_ASSERT(!d->m_output_flush_remaining); d->m_output_flush_ofs = 0; d->m_output_flush_remaining = 0; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> d->m_num_flags_left); d->m_pLZ_code_buf -= (d->m_num_flags_left == 8); if ((d->m_flags & TDEFL_WRITE_ZLIB_HEADER) && (!d->m_block_index)) { TDEFL_PUT_BITS(0x78, 8); TDEFL_PUT_BITS(0x01, 8); } TDEFL_PUT_BITS(flush == TDEFL_FINISH, 1); pSaved_output_buf = d->m_pOutput_buf; saved_bit_buf = d->m_bit_buffer; saved_bits_in = d->m_bits_in; if (!use_raw_block) comp_block_succeeded = tdefl_compress_block(d, (d->m_flags & TDEFL_FORCE_ALL_STATIC_BLOCKS) || (d->m_total_lz_bytes < 48)); // If the block gets expanded, forget the current contents of the output // buffer and send a raw block instead. if (((use_raw_block) || ((d->m_total_lz_bytes) && ((d->m_pOutput_buf - pSaved_output_buf + 1U) >= d->m_total_lz_bytes))) && ((d->m_lookahead_pos - d->m_lz_code_buf_dict_pos) <= d->m_dict_size)) { mz_uint i; d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; TDEFL_PUT_BITS(0, 2); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, d->m_total_lz_bytes ^= 0xFFFF) { TDEFL_PUT_BITS(d->m_total_lz_bytes & 0xFFFF, 16); } for (i = 0; i < d->m_total_lz_bytes; ++i) { TDEFL_PUT_BITS( d->m_dict[(d->m_lz_code_buf_dict_pos + i) & TDEFL_LZ_DICT_SIZE_MASK], 8); } } // Check for the extremely unlikely (if not impossible) case of the compressed // block not fitting into the output buffer when using dynamic codes. else if (!comp_block_succeeded) { d->m_pOutput_buf = pSaved_output_buf; d->m_bit_buffer = saved_bit_buf, d->m_bits_in = saved_bits_in; tdefl_compress_block(d, MZ_TRUE); } if (flush) { if (flush == TDEFL_FINISH) { if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } if (d->m_flags & TDEFL_WRITE_ZLIB_HEADER) { mz_uint i, a = d->m_adler32; for (i = 0; i < 4; i++) { TDEFL_PUT_BITS((a >> 24) & 0xFF, 8); a <<= 8; } } } else { mz_uint i, z = 0; TDEFL_PUT_BITS(0, 3); if (d->m_bits_in) { TDEFL_PUT_BITS(0, 8 - d->m_bits_in); } for (i = 2; i; --i, z ^= 0xFFFF) { TDEFL_PUT_BITS(z & 0xFFFF, 16); } } } MZ_ASSERT(d->m_pOutput_buf < d->m_pOutput_buf_end); memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_lz_code_buf_dict_pos += d->m_total_lz_bytes; d->m_total_lz_bytes = 0; d->m_block_index++; if ((n = (int)(d->m_pOutput_buf - pOutput_buf_start)) != 0) { if (d->m_pPut_buf_func) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; if (!(*d->m_pPut_buf_func)(d->m_output_buf, n, d->m_pPut_buf_user)) return (d->m_prev_return_status = TDEFL_STATUS_PUT_BUF_FAILED); } else if (pOutput_buf_start == d->m_output_buf) { int bytes_to_copy = (int)MZ_MIN( (size_t)n, (size_t)(*d->m_pOut_buf_size - d->m_out_buf_ofs)); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf, bytes_to_copy); d->m_out_buf_ofs += bytes_to_copy; if ((n -= bytes_to_copy) != 0) { d->m_output_flush_ofs = bytes_to_copy; d->m_output_flush_remaining = n; } } else { d->m_out_buf_ofs += n; } } return d->m_output_flush_remaining; } #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #define TDEFL_READ_UNALIGNED_WORD(p) *(const mz_uint16 *)(p) static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint16 *s = (const mz_uint16 *)(d->m_dict + pos), *p, *q; mz_uint16 c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]), s01 = TDEFL_READ_UNALIGNED_WORD(s); MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if (TDEFL_READ_UNALIGNED_WORD(&d->m_dict[probe_pos + match_len - 1]) == c01) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; q = (const mz_uint16 *)(d->m_dict + probe_pos); if (TDEFL_READ_UNALIGNED_WORD(q) != s01) continue; p = s; probe_len = 32; do { } while ( (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); if (!probe_len) { *pMatch_dist = dist; *pMatch_len = MZ_MIN(max_match_len, TDEFL_MAX_MATCH_LEN); break; } else if ((probe_len = ((mz_uint)(p - s) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q)) > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = MZ_MIN(max_match_len, probe_len)) == max_match_len) break; c01 = TDEFL_READ_UNALIGNED_WORD(&d->m_dict[pos + match_len - 1]); } } } #else static MZ_FORCEINLINE void tdefl_find_match( tdefl_compressor *d, mz_uint lookahead_pos, mz_uint max_dist, mz_uint max_match_len, mz_uint *pMatch_dist, mz_uint *pMatch_len) { mz_uint dist, pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK, match_len = *pMatch_len, probe_pos = pos, next_probe_pos, probe_len; mz_uint num_probes_left = d->m_max_probes[match_len >= 32]; const mz_uint8 *s = d->m_dict + pos, *p, *q; mz_uint8 c0 = d->m_dict[pos + match_len], c1 = d->m_dict[pos + match_len - 1]; MZ_ASSERT(max_match_len <= TDEFL_MAX_MATCH_LEN); if (max_match_len <= match_len) return; for (;;) { for (;;) { if (--num_probes_left == 0) return; #define TDEFL_PROBE \ next_probe_pos = d->m_next[probe_pos]; \ if ((!next_probe_pos) || \ ((dist = (mz_uint16)(lookahead_pos - next_probe_pos)) > max_dist)) \ return; \ probe_pos = next_probe_pos & TDEFL_LZ_DICT_SIZE_MASK; \ if ((d->m_dict[probe_pos + match_len] == c0) && \ (d->m_dict[probe_pos + match_len - 1] == c1)) \ break; TDEFL_PROBE; TDEFL_PROBE; TDEFL_PROBE; } if (!dist) break; p = s; q = d->m_dict + probe_pos; for (probe_len = 0; probe_len < max_match_len; probe_len++) if (*p++ != *q++) break; if (probe_len > match_len) { *pMatch_dist = dist; if ((*pMatch_len = match_len = probe_len) == max_match_len) return; c0 = d->m_dict[pos + match_len]; c1 = d->m_dict[pos + match_len - 1]; } } } #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static mz_bool tdefl_compress_fast(tdefl_compressor *d) { // Faster, minimally featured LZRW1-style match+parse loop with better // register utilization. Intended for applications where raw throughput is // valued more highly than ratio. mz_uint lookahead_pos = d->m_lookahead_pos, lookahead_size = d->m_lookahead_size, dict_size = d->m_dict_size, total_lz_bytes = d->m_total_lz_bytes, num_flags_left = d->m_num_flags_left; mz_uint8 *pLZ_code_buf = d->m_pLZ_code_buf, *pLZ_flags = d->m_pLZ_flags; mz_uint cur_pos = lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; while ((d->m_src_buf_left) || ((d->m_flush) && (lookahead_size))) { const mz_uint TDEFL_COMP_FAST_LOOKAHEAD_SIZE = 4096; mz_uint dst_pos = (lookahead_pos + lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( d->m_src_buf_left, TDEFL_COMP_FAST_LOOKAHEAD_SIZE - lookahead_size); d->m_src_buf_left -= num_bytes_to_process; lookahead_size += num_bytes_to_process; while (num_bytes_to_process) { mz_uint32 n = MZ_MIN(TDEFL_LZ_DICT_SIZE - dst_pos, num_bytes_to_process); memcpy(d->m_dict + dst_pos, d->m_pSrc, n); if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) memcpy(d->m_dict + TDEFL_LZ_DICT_SIZE + dst_pos, d->m_pSrc, MZ_MIN(n, (TDEFL_MAX_MATCH_LEN - 1) - dst_pos)); d->m_pSrc += n; dst_pos = (dst_pos + n) & TDEFL_LZ_DICT_SIZE_MASK; num_bytes_to_process -= n; } dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - lookahead_size, dict_size); if ((!d->m_flush) && (lookahead_size < TDEFL_COMP_FAST_LOOKAHEAD_SIZE)) break; while (lookahead_size >= 4) { mz_uint cur_match_dist, cur_match_len = 1; mz_uint8 *pCur_dict = d->m_dict + cur_pos; mz_uint first_trigram = (*(const mz_uint32 *)pCur_dict) & 0xFFFFFF; mz_uint hash = (first_trigram ^ (first_trigram >> (24 - (TDEFL_LZ_HASH_BITS - 8)))) & TDEFL_LEVEL1_HASH_SIZE_MASK; mz_uint probe_pos = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)lookahead_pos; if (((cur_match_dist = (mz_uint16)(lookahead_pos - probe_pos)) <= dict_size) && ((*(const mz_uint32 *)(d->m_dict + (probe_pos &= TDEFL_LZ_DICT_SIZE_MASK)) & 0xFFFFFF) == first_trigram)) { const mz_uint16 *p = (const mz_uint16 *)pCur_dict; const mz_uint16 *q = (const mz_uint16 *)(d->m_dict + probe_pos); mz_uint32 probe_len = 32; do { } while ((TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (TDEFL_READ_UNALIGNED_WORD(++p) == TDEFL_READ_UNALIGNED_WORD(++q)) && (--probe_len > 0)); cur_match_len = ((mz_uint)(p - (const mz_uint16 *)pCur_dict) * 2) + (mz_uint)(*(const mz_uint8 *)p == *(const mz_uint8 *)q); if (!probe_len) cur_match_len = cur_match_dist ? TDEFL_MAX_MATCH_LEN : 0; if ((cur_match_len < TDEFL_MIN_MATCH_LEN) || ((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U))) { cur_match_len = 1; *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } else { mz_uint32 s0, s1; cur_match_len = MZ_MIN(cur_match_len, lookahead_size); MZ_ASSERT((cur_match_len >= TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 1) && (cur_match_dist <= TDEFL_LZ_DICT_SIZE)); cur_match_dist--; pLZ_code_buf[0] = (mz_uint8)(cur_match_len - TDEFL_MIN_MATCH_LEN); *(mz_uint16 *)(&pLZ_code_buf[1]) = (mz_uint16)cur_match_dist; pLZ_code_buf += 3; *pLZ_flags = (mz_uint8)((*pLZ_flags >> 1) | 0x80); s0 = s_tdefl_small_dist_sym[cur_match_dist & 511]; s1 = s_tdefl_large_dist_sym[cur_match_dist >> 8]; d->m_huff_count[1][(cur_match_dist < 512) ? s0 : s1]++; d->m_huff_count[0][s_tdefl_len_sym[cur_match_len - TDEFL_MIN_MATCH_LEN]]++; } } else { *pLZ_code_buf++ = (mz_uint8)first_trigram; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); d->m_huff_count[0][(mz_uint8)first_trigram]++; } if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } total_lz_bytes += cur_match_len; lookahead_pos += cur_match_len; dict_size = MZ_MIN(dict_size + cur_match_len, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + cur_match_len) & TDEFL_LZ_DICT_SIZE_MASK; MZ_ASSERT(lookahead_size >= cur_match_len); lookahead_size -= cur_match_len; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } while (lookahead_size) { mz_uint8 lit = d->m_dict[cur_pos]; total_lz_bytes++; *pLZ_code_buf++ = lit; *pLZ_flags = (mz_uint8)(*pLZ_flags >> 1); if (--num_flags_left == 0) { num_flags_left = 8; pLZ_flags = pLZ_code_buf++; } d->m_huff_count[0][lit]++; lookahead_pos++; dict_size = MZ_MIN(dict_size + 1, TDEFL_LZ_DICT_SIZE); cur_pos = (cur_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; lookahead_size--; if (pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) { int n; d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; total_lz_bytes = d->m_total_lz_bytes; pLZ_code_buf = d->m_pLZ_code_buf; pLZ_flags = d->m_pLZ_flags; num_flags_left = d->m_num_flags_left; } } } d->m_lookahead_pos = lookahead_pos; d->m_lookahead_size = lookahead_size; d->m_dict_size = dict_size; d->m_total_lz_bytes = total_lz_bytes; d->m_pLZ_code_buf = pLZ_code_buf; d->m_pLZ_flags = pLZ_flags; d->m_num_flags_left = num_flags_left; return MZ_TRUE; } #endif // MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN static MZ_FORCEINLINE void tdefl_record_literal(tdefl_compressor *d, mz_uint8 lit) { d->m_total_lz_bytes++; *d->m_pLZ_code_buf++ = lit; *d->m_pLZ_flags = (mz_uint8)(*d->m_pLZ_flags >> 1); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } d->m_huff_count[0][lit]++; } static MZ_FORCEINLINE void tdefl_record_match(tdefl_compressor *d, mz_uint match_len, mz_uint match_dist) { mz_uint32 s0, s1; MZ_ASSERT((match_len >= TDEFL_MIN_MATCH_LEN) && (match_dist >= 1) && (match_dist <= TDEFL_LZ_DICT_SIZE)); d->m_total_lz_bytes += match_len; d->m_pLZ_code_buf[0] = (mz_uint8)(match_len - TDEFL_MIN_MATCH_LEN); match_dist -= 1; d->m_pLZ_code_buf[1] = (mz_uint8)(match_dist & 0xFF); d->m_pLZ_code_buf[2] = (mz_uint8)(match_dist >> 8); d->m_pLZ_code_buf += 3; *d->m_pLZ_flags = (mz_uint8)((*d->m_pLZ_flags >> 1) | 0x80); if (--d->m_num_flags_left == 0) { d->m_num_flags_left = 8; d->m_pLZ_flags = d->m_pLZ_code_buf++; } s0 = s_tdefl_small_dist_sym[match_dist & 511]; s1 = s_tdefl_large_dist_sym[(match_dist >> 8) & 127]; d->m_huff_count[1][(match_dist < 512) ? s0 : s1]++; if (match_len >= TDEFL_MIN_MATCH_LEN) d->m_huff_count[0][s_tdefl_len_sym[match_len - TDEFL_MIN_MATCH_LEN]]++; } static mz_bool tdefl_compress_normal(tdefl_compressor *d) { const mz_uint8 *pSrc = d->m_pSrc; size_t src_buf_left = d->m_src_buf_left; tdefl_flush flush = d->m_flush; while ((src_buf_left) || ((flush) && (d->m_lookahead_size))) { mz_uint len_to_move, cur_match_dist, cur_match_len, cur_pos; // Update dictionary and hash chains. Keeps the lookahead size equal to // TDEFL_MAX_MATCH_LEN. if ((d->m_lookahead_size + d->m_dict_size) >= (TDEFL_MIN_MATCH_LEN - 1)) { mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK, ins_pos = d->m_lookahead_pos + d->m_lookahead_size - 2; mz_uint hash = (d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK]; mz_uint num_bytes_to_process = (mz_uint)MZ_MIN( src_buf_left, TDEFL_MAX_MATCH_LEN - d->m_lookahead_size); const mz_uint8 *pSrc_end = pSrc + num_bytes_to_process; src_buf_left -= num_bytes_to_process; d->m_lookahead_size += num_bytes_to_process; while (pSrc != pSrc_end) { mz_uint8 c = *pSrc++; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; hash = ((hash << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); dst_pos = (dst_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK; ins_pos++; } } else { while ((src_buf_left) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) { mz_uint8 c = *pSrc++; mz_uint dst_pos = (d->m_lookahead_pos + d->m_lookahead_size) & TDEFL_LZ_DICT_SIZE_MASK; src_buf_left--; d->m_dict[dst_pos] = c; if (dst_pos < (TDEFL_MAX_MATCH_LEN - 1)) d->m_dict[TDEFL_LZ_DICT_SIZE + dst_pos] = c; if ((++d->m_lookahead_size + d->m_dict_size) >= TDEFL_MIN_MATCH_LEN) { mz_uint ins_pos = d->m_lookahead_pos + (d->m_lookahead_size - 1) - 2; mz_uint hash = ((d->m_dict[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] << (TDEFL_LZ_HASH_SHIFT * 2)) ^ (d->m_dict[(ins_pos + 1) & TDEFL_LZ_DICT_SIZE_MASK] << TDEFL_LZ_HASH_SHIFT) ^ c) & (TDEFL_LZ_HASH_SIZE - 1); d->m_next[ins_pos & TDEFL_LZ_DICT_SIZE_MASK] = d->m_hash[hash]; d->m_hash[hash] = (mz_uint16)(ins_pos); } } } d->m_dict_size = MZ_MIN(TDEFL_LZ_DICT_SIZE - d->m_lookahead_size, d->m_dict_size); if ((!flush) && (d->m_lookahead_size < TDEFL_MAX_MATCH_LEN)) break; // Simple lazy/greedy parsing state machine. len_to_move = 1; cur_match_dist = 0; cur_match_len = d->m_saved_match_len ? d->m_saved_match_len : (TDEFL_MIN_MATCH_LEN - 1); cur_pos = d->m_lookahead_pos & TDEFL_LZ_DICT_SIZE_MASK; if (d->m_flags & (TDEFL_RLE_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS)) { if ((d->m_dict_size) && (!(d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS))) { mz_uint8 c = d->m_dict[(cur_pos - 1) & TDEFL_LZ_DICT_SIZE_MASK]; cur_match_len = 0; while (cur_match_len < d->m_lookahead_size) { if (d->m_dict[cur_pos + cur_match_len] != c) break; cur_match_len++; } if (cur_match_len < TDEFL_MIN_MATCH_LEN) cur_match_len = 0; else cur_match_dist = 1; } } else { tdefl_find_match(d, d->m_lookahead_pos, d->m_dict_size, d->m_lookahead_size, &cur_match_dist, &cur_match_len); } if (((cur_match_len == TDEFL_MIN_MATCH_LEN) && (cur_match_dist >= 8U * 1024U)) || (cur_pos == cur_match_dist) || ((d->m_flags & TDEFL_FILTER_MATCHES) && (cur_match_len <= 5))) { cur_match_dist = cur_match_len = 0; } if (d->m_saved_match_len) { if (cur_match_len > d->m_saved_match_len) { tdefl_record_literal(d, (mz_uint8)d->m_saved_lit); if (cur_match_len >= 128) { tdefl_record_match(d, cur_match_len, cur_match_dist); d->m_saved_match_len = 0; len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[cur_pos]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } } else { tdefl_record_match(d, d->m_saved_match_len, d->m_saved_match_dist); len_to_move = d->m_saved_match_len - 1; d->m_saved_match_len = 0; } } else if (!cur_match_dist) tdefl_record_literal(d, d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]); else if ((d->m_greedy_parsing) || (d->m_flags & TDEFL_RLE_MATCHES) || (cur_match_len >= 128)) { tdefl_record_match(d, cur_match_len, cur_match_dist); len_to_move = cur_match_len; } else { d->m_saved_lit = d->m_dict[MZ_MIN(cur_pos, sizeof(d->m_dict) - 1)]; d->m_saved_match_dist = cur_match_dist; d->m_saved_match_len = cur_match_len; } // Move the lookahead forward by len_to_move bytes. d->m_lookahead_pos += len_to_move; MZ_ASSERT(d->m_lookahead_size >= len_to_move); d->m_lookahead_size -= len_to_move; d->m_dict_size = MZ_MIN(d->m_dict_size + len_to_move, (mz_uint)TDEFL_LZ_DICT_SIZE); // Check if it's time to flush the current LZ codes to the internal output // buffer. if ((d->m_pLZ_code_buf > &d->m_lz_code_buf[TDEFL_LZ_CODE_BUF_SIZE - 8]) || ((d->m_total_lz_bytes > 31 * 1024) && (((((mz_uint)(d->m_pLZ_code_buf - d->m_lz_code_buf) * 115) >> 7) >= d->m_total_lz_bytes) || (d->m_flags & TDEFL_FORCE_ALL_RAW_BLOCKS)))) { int n; d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; if ((n = tdefl_flush_block(d, 0)) != 0) return (n < 0) ? MZ_FALSE : MZ_TRUE; } } d->m_pSrc = pSrc; d->m_src_buf_left = src_buf_left; return MZ_TRUE; } static tdefl_status tdefl_flush_output_buffer(tdefl_compressor *d) { if (d->m_pIn_buf_size) { *d->m_pIn_buf_size = d->m_pSrc - (const mz_uint8 *)d->m_pIn_buf; } if (d->m_pOut_buf_size) { size_t n = MZ_MIN(*d->m_pOut_buf_size - d->m_out_buf_ofs, d->m_output_flush_remaining); memcpy((mz_uint8 *)d->m_pOut_buf + d->m_out_buf_ofs, d->m_output_buf + d->m_output_flush_ofs, n); d->m_output_flush_ofs += (mz_uint)n; d->m_output_flush_remaining -= (mz_uint)n; d->m_out_buf_ofs += n; *d->m_pOut_buf_size = d->m_out_buf_ofs; } return (d->m_finished && !d->m_output_flush_remaining) ? TDEFL_STATUS_DONE : TDEFL_STATUS_OKAY; } tdefl_status tdefl_compress(tdefl_compressor *d, const void *pIn_buf, size_t *pIn_buf_size, void *pOut_buf, size_t *pOut_buf_size, tdefl_flush flush) { if (!d) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return TDEFL_STATUS_BAD_PARAM; } d->m_pIn_buf = pIn_buf; d->m_pIn_buf_size = pIn_buf_size; d->m_pOut_buf = pOut_buf; d->m_pOut_buf_size = pOut_buf_size; d->m_pSrc = (const mz_uint8 *)(pIn_buf); d->m_src_buf_left = pIn_buf_size ? *pIn_buf_size : 0; d->m_out_buf_ofs = 0; d->m_flush = flush; if (((d->m_pPut_buf_func != NULL) == ((pOut_buf != NULL) || (pOut_buf_size != NULL))) || (d->m_prev_return_status != TDEFL_STATUS_OKAY) || (d->m_wants_to_finish && (flush != TDEFL_FINISH)) || (pIn_buf_size && *pIn_buf_size && !pIn_buf) || (pOut_buf_size && *pOut_buf_size && !pOut_buf)) { if (pIn_buf_size) *pIn_buf_size = 0; if (pOut_buf_size) *pOut_buf_size = 0; return (d->m_prev_return_status = TDEFL_STATUS_BAD_PARAM); } d->m_wants_to_finish |= (flush == TDEFL_FINISH); if ((d->m_output_flush_remaining) || (d->m_finished)) return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN if (((d->m_flags & TDEFL_MAX_PROBES_MASK) == 1) && ((d->m_flags & TDEFL_GREEDY_PARSING_FLAG) != 0) && ((d->m_flags & (TDEFL_FILTER_MATCHES | TDEFL_FORCE_ALL_RAW_BLOCKS | TDEFL_RLE_MATCHES)) == 0)) { if (!tdefl_compress_fast(d)) return d->m_prev_return_status; } else #endif // #if MINIZ_USE_UNALIGNED_LOADS_AND_STORES && MINIZ_LITTLE_ENDIAN { if (!tdefl_compress_normal(d)) return d->m_prev_return_status; } if ((d->m_flags & (TDEFL_WRITE_ZLIB_HEADER | TDEFL_COMPUTE_ADLER32)) && (pIn_buf)) d->m_adler32 = (mz_uint32)mz_adler32(d->m_adler32, (const mz_uint8 *)pIn_buf, d->m_pSrc - (const mz_uint8 *)pIn_buf); if ((flush) && (!d->m_lookahead_size) && (!d->m_src_buf_left) && (!d->m_output_flush_remaining)) { if (tdefl_flush_block(d, flush) < 0) return d->m_prev_return_status; d->m_finished = (flush == TDEFL_FINISH); if (flush == TDEFL_FULL_FLUSH) { MZ_CLEAR_OBJ(d->m_hash); MZ_CLEAR_OBJ(d->m_next); d->m_dict_size = 0; } } return (d->m_prev_return_status = tdefl_flush_output_buffer(d)); } tdefl_status tdefl_compress_buffer(tdefl_compressor *d, const void *pIn_buf, size_t in_buf_size, tdefl_flush flush) { MZ_ASSERT(d->m_pPut_buf_func); return tdefl_compress(d, pIn_buf, &in_buf_size, NULL, NULL, flush); } tdefl_status tdefl_init(tdefl_compressor *d, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { d->m_pPut_buf_func = pPut_buf_func; d->m_pPut_buf_user = pPut_buf_user; d->m_flags = (mz_uint)(flags); d->m_max_probes[0] = 1 + ((flags & 0xFFF) + 2) / 3; d->m_greedy_parsing = (flags & TDEFL_GREEDY_PARSING_FLAG) != 0; d->m_max_probes[1] = 1 + (((flags & 0xFFF) >> 2) + 2) / 3; if (!(flags & TDEFL_NONDETERMINISTIC_PARSING_FLAG)) MZ_CLEAR_OBJ(d->m_hash); d->m_lookahead_pos = d->m_lookahead_size = d->m_dict_size = d->m_total_lz_bytes = d->m_lz_code_buf_dict_pos = d->m_bits_in = 0; d->m_output_flush_ofs = d->m_output_flush_remaining = d->m_finished = d->m_block_index = d->m_bit_buffer = d->m_wants_to_finish = 0; d->m_pLZ_code_buf = d->m_lz_code_buf + 1; d->m_pLZ_flags = d->m_lz_code_buf; d->m_num_flags_left = 8; d->m_pOutput_buf = d->m_output_buf; d->m_pOutput_buf_end = d->m_output_buf; d->m_prev_return_status = TDEFL_STATUS_OKAY; d->m_saved_match_dist = d->m_saved_match_len = d->m_saved_lit = 0; d->m_adler32 = 1; d->m_pIn_buf = NULL; d->m_pOut_buf = NULL; d->m_pIn_buf_size = NULL; d->m_pOut_buf_size = NULL; d->m_flush = TDEFL_NO_FLUSH; d->m_pSrc = NULL; d->m_src_buf_left = 0; d->m_out_buf_ofs = 0; memset(&d->m_huff_count[0][0], 0, sizeof(d->m_huff_count[0][0]) * TDEFL_MAX_HUFF_SYMBOLS_0); memset(&d->m_huff_count[1][0], 0, sizeof(d->m_huff_count[1][0]) * TDEFL_MAX_HUFF_SYMBOLS_1); return TDEFL_STATUS_OKAY; } tdefl_status tdefl_get_prev_return_status(tdefl_compressor *d) { return d->m_prev_return_status; } mz_uint32 tdefl_get_adler32(tdefl_compressor *d) { return d->m_adler32; } mz_bool tdefl_compress_mem_to_output(const void *pBuf, size_t buf_len, tdefl_put_buf_func_ptr pPut_buf_func, void *pPut_buf_user, int flags) { tdefl_compressor *pComp; mz_bool succeeded; if (((buf_len) && (!pBuf)) || (!pPut_buf_func)) return MZ_FALSE; pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); if (!pComp) return MZ_FALSE; succeeded = (tdefl_init(pComp, pPut_buf_func, pPut_buf_user, flags) == TDEFL_STATUS_OKAY); succeeded = succeeded && (tdefl_compress_buffer(pComp, pBuf, buf_len, TDEFL_FINISH) == TDEFL_STATUS_DONE); MZ_FREE(pComp); return succeeded; } typedef struct { size_t m_size, m_capacity; mz_uint8 *m_pBuf; mz_bool m_expandable; } tdefl_output_buffer; static mz_bool tdefl_output_buffer_putter(const void *pBuf, int len, void *pUser) { tdefl_output_buffer *p = (tdefl_output_buffer *)pUser; size_t new_size = p->m_size + len; if (new_size > p->m_capacity) { size_t new_capacity = p->m_capacity; mz_uint8 *pNew_buf; if (!p->m_expandable) return MZ_FALSE; do { new_capacity = MZ_MAX(128U, new_capacity << 1U); } while (new_size > new_capacity); pNew_buf = (mz_uint8 *)MZ_REALLOC(p->m_pBuf, new_capacity); if (!pNew_buf) return MZ_FALSE; p->m_pBuf = pNew_buf; p->m_capacity = new_capacity; } memcpy((mz_uint8 *)p->m_pBuf + p->m_size, pBuf, len); p->m_size = new_size; return MZ_TRUE; } void *tdefl_compress_mem_to_heap(const void *pSrc_buf, size_t src_buf_len, size_t *pOut_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_len) return MZ_FALSE; else *pOut_len = 0; out_buf.m_expandable = MZ_TRUE; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return NULL; *pOut_len = out_buf.m_size; return out_buf.m_pBuf; } size_t tdefl_compress_mem_to_mem(void *pOut_buf, size_t out_buf_len, const void *pSrc_buf, size_t src_buf_len, int flags) { tdefl_output_buffer out_buf; MZ_CLEAR_OBJ(out_buf); if (!pOut_buf) return 0; out_buf.m_pBuf = (mz_uint8 *)pOut_buf; out_buf.m_capacity = out_buf_len; if (!tdefl_compress_mem_to_output( pSrc_buf, src_buf_len, tdefl_output_buffer_putter, &out_buf, flags)) return 0; return out_buf.m_size; } #ifndef MINIZ_NO_ZLIB_APIS static const mz_uint s_tdefl_num_probes[11] = {0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; // level may actually range from [0,10] (10 is a "hidden" max level, where we // want a bit more compression and it's fine if throughput to fall off a cliff // on some files). mz_uint tdefl_create_comp_flags_from_zip_params(int level, int window_bits, int strategy) { mz_uint comp_flags = s_tdefl_num_probes[(level >= 0) ? MZ_MIN(10, level) : MZ_DEFAULT_LEVEL] | ((level <= 3) ? TDEFL_GREEDY_PARSING_FLAG : 0); if (window_bits > 0) comp_flags |= TDEFL_WRITE_ZLIB_HEADER; if (!level) comp_flags |= TDEFL_FORCE_ALL_RAW_BLOCKS; else if (strategy == MZ_FILTERED) comp_flags |= TDEFL_FILTER_MATCHES; else if (strategy == MZ_HUFFMAN_ONLY) comp_flags &= ~TDEFL_MAX_PROBES_MASK; else if (strategy == MZ_FIXED) comp_flags |= TDEFL_FORCE_ALL_STATIC_BLOCKS; else if (strategy == MZ_RLE) comp_flags |= TDEFL_RLE_MATCHES; return comp_flags; } #endif // MINIZ_NO_ZLIB_APIS #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning( \ disable : 4267) // 'argument': conversion from '__int64' to 'int', // possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif // Simple PNG writer function by Alex Evans, 2011. Released into the public // domain: https://gist.github.com/908299, more context at // http://altdevblogaday.org/2011/04/06/a-smaller-jpg-encoder/. // This is actually a modification of Alex's original code so PNG files // generated by this function pass pngcheck. void *tdefl_write_image_to_png_file_in_memory_ex(const void *pImage, int w, int h, int num_chans, size_t *pLen_out, mz_uint level, mz_bool flip) { // Using a local copy of this array here in case MINIZ_NO_ZLIB_APIS was // defined. static const mz_uint s_tdefl_png_num_probes[11] = { 0, 1, 6, 32, 16, 32, 128, 256, 512, 768, 1500}; tdefl_compressor *pComp = (tdefl_compressor *)MZ_MALLOC(sizeof(tdefl_compressor)); tdefl_output_buffer out_buf; int i, bpl = w * num_chans, y, z; mz_uint32 c; *pLen_out = 0; if (!pComp) return NULL; MZ_CLEAR_OBJ(out_buf); out_buf.m_expandable = MZ_TRUE; out_buf.m_capacity = 57 + MZ_MAX(64, (1 + bpl) * h); if (NULL == (out_buf.m_pBuf = (mz_uint8 *)MZ_MALLOC(out_buf.m_capacity))) { MZ_FREE(pComp); return NULL; } // write dummy header for (z = 41; z; --z) tdefl_output_buffer_putter(&z, 1, &out_buf); // compress image data tdefl_init( pComp, tdefl_output_buffer_putter, &out_buf, s_tdefl_png_num_probes[MZ_MIN(10, level)] | TDEFL_WRITE_ZLIB_HEADER); for (y = 0; y < h; ++y) { tdefl_compress_buffer(pComp, &z, 1, TDEFL_NO_FLUSH); tdefl_compress_buffer(pComp, (mz_uint8 *)pImage + (flip ? (h - 1 - y) : y) * bpl, bpl, TDEFL_NO_FLUSH); } if (tdefl_compress_buffer(pComp, NULL, 0, TDEFL_FINISH) != TDEFL_STATUS_DONE) { MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } // write real header *pLen_out = out_buf.m_size - 41; { static const mz_uint8 chans[] = {0x00, 0x00, 0x04, 0x02, 0x06}; mz_uint8 pnghdr[41] = {0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0, 0, (mz_uint8)(w >> 8), (mz_uint8)w, 0, 0, (mz_uint8)(h >> 8), (mz_uint8)h, 8, chans[num_chans], 0, 0, 0, 0, 0, 0, 0, (mz_uint8)(*pLen_out >> 24), (mz_uint8)(*pLen_out >> 16), (mz_uint8)(*pLen_out >> 8), (mz_uint8)*pLen_out, 0x49, 0x44, 0x41, 0x54}; c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, pnghdr + 12, 17); for (i = 0; i < 4; ++i, c <<= 8) ((mz_uint8 *)(pnghdr + 29))[i] = (mz_uint8)(c >> 24); memcpy(out_buf.m_pBuf, pnghdr, 41); } // write footer (IDAT CRC-32, followed by IEND chunk) if (!tdefl_output_buffer_putter( "\0\0\0\0\0\0\0\0\x49\x45\x4e\x44\xae\x42\x60\x82", 16, &out_buf)) { *pLen_out = 0; MZ_FREE(pComp); MZ_FREE(out_buf.m_pBuf); return NULL; } c = (mz_uint32)mz_crc32(MZ_CRC32_INIT, out_buf.m_pBuf + 41 - 4, *pLen_out + 4); for (i = 0; i < 4; ++i, c <<= 8) (out_buf.m_pBuf + out_buf.m_size - 16)[i] = (mz_uint8)(c >> 24); // compute final size of file, grab compressed data buffer and return *pLen_out += 57; MZ_FREE(pComp); return out_buf.m_pBuf; } void *tdefl_write_image_to_png_file_in_memory(const void *pImage, int w, int h, int num_chans, size_t *pLen_out) { // Level 6 corresponds to TDEFL_DEFAULT_MAX_PROBES or MZ_DEFAULT_LEVEL (but we // can't depend on MZ_DEFAULT_LEVEL being available in case the zlib API's // where #defined out) return tdefl_write_image_to_png_file_in_memory_ex(pImage, w, h, num_chans, pLen_out, 6, MZ_FALSE); } // ------------------- .ZIP archive reading #ifndef MINIZ_NO_ARCHIVE_APIS #error "No arvhive APIs" #ifdef MINIZ_NO_STDIO #define MZ_FILE void * #else #include <stdio.h> #include <sys/stat.h> #if defined(_MSC_VER) || defined(__MINGW64__) static FILE *mz_fopen(const char *pFilename, const char *pMode) { FILE *pFile = NULL; fopen_s(&pFile, pFilename, pMode); return pFile; } static FILE *mz_freopen(const char *pPath, const char *pMode, FILE *pStream) { FILE *pFile = NULL; if (freopen_s(&pFile, pPath, pMode, pStream)) return NULL; return pFile; } #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN mz_fopen #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 _ftelli64 #define MZ_FSEEK64 _fseeki64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN mz_freopen #define MZ_DELETE_FILE remove #elif defined(__MINGW32__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT _stat #define MZ_FILE_STAT _stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__TINYC__) #ifndef MINIZ_NO_TIME #include <sys/utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftell #define MZ_FSEEK64 fseek #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #elif defined(__GNUC__) && defined(_LARGEFILE64_SOURCE) && _LARGEFILE64_SOURCE #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen64(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello64 #define MZ_FSEEK64 fseeko64 #define MZ_FILE_STAT_STRUCT stat64 #define MZ_FILE_STAT stat64 #define MZ_FFLUSH fflush #define MZ_FREOPEN(p, m, s) freopen64(p, m, s) #define MZ_DELETE_FILE remove #else #ifndef MINIZ_NO_TIME #include <utime.h> #endif #define MZ_FILE FILE #define MZ_FOPEN(f, m) fopen(f, m) #define MZ_FCLOSE fclose #define MZ_FREAD fread #define MZ_FWRITE fwrite #define MZ_FTELL64 ftello #define MZ_FSEEK64 fseeko #define MZ_FILE_STAT_STRUCT stat #define MZ_FILE_STAT stat #define MZ_FFLUSH fflush #define MZ_FREOPEN(f, m, s) freopen(f, m, s) #define MZ_DELETE_FILE remove #endif // #ifdef _MSC_VER #endif // #ifdef MINIZ_NO_STDIO #define MZ_TOLOWER(c) ((((c) >= 'A') && ((c) <= 'Z')) ? ((c) - 'A' + 'a') : (c)) // Various ZIP archive enums. To completely avoid cross platform compiler // alignment and platform endian issues, miniz.c doesn't use structs for any of // this stuff. enum { // ZIP archive identifiers and record sizes MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG = 0x06054b50, MZ_ZIP_CENTRAL_DIR_HEADER_SIG = 0x02014b50, MZ_ZIP_LOCAL_DIR_HEADER_SIG = 0x04034b50, MZ_ZIP_LOCAL_DIR_HEADER_SIZE = 30, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE = 46, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE = 22, // Central directory header record offsets MZ_ZIP_CDH_SIG_OFS = 0, MZ_ZIP_CDH_VERSION_MADE_BY_OFS = 4, MZ_ZIP_CDH_VERSION_NEEDED_OFS = 6, MZ_ZIP_CDH_BIT_FLAG_OFS = 8, MZ_ZIP_CDH_METHOD_OFS = 10, MZ_ZIP_CDH_FILE_TIME_OFS = 12, MZ_ZIP_CDH_FILE_DATE_OFS = 14, MZ_ZIP_CDH_CRC32_OFS = 16, MZ_ZIP_CDH_COMPRESSED_SIZE_OFS = 20, MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS = 24, MZ_ZIP_CDH_FILENAME_LEN_OFS = 28, MZ_ZIP_CDH_EXTRA_LEN_OFS = 30, MZ_ZIP_CDH_COMMENT_LEN_OFS = 32, MZ_ZIP_CDH_DISK_START_OFS = 34, MZ_ZIP_CDH_INTERNAL_ATTR_OFS = 36, MZ_ZIP_CDH_EXTERNAL_ATTR_OFS = 38, MZ_ZIP_CDH_LOCAL_HEADER_OFS = 42, // Local directory header offsets MZ_ZIP_LDH_SIG_OFS = 0, MZ_ZIP_LDH_VERSION_NEEDED_OFS = 4, MZ_ZIP_LDH_BIT_FLAG_OFS = 6, MZ_ZIP_LDH_METHOD_OFS = 8, MZ_ZIP_LDH_FILE_TIME_OFS = 10, MZ_ZIP_LDH_FILE_DATE_OFS = 12, MZ_ZIP_LDH_CRC32_OFS = 14, MZ_ZIP_LDH_COMPRESSED_SIZE_OFS = 18, MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS = 22, MZ_ZIP_LDH_FILENAME_LEN_OFS = 26, MZ_ZIP_LDH_EXTRA_LEN_OFS = 28, // End of central directory offsets MZ_ZIP_ECDH_SIG_OFS = 0, MZ_ZIP_ECDH_NUM_THIS_DISK_OFS = 4, MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS = 6, MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS = 8, MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS = 10, MZ_ZIP_ECDH_CDIR_SIZE_OFS = 12, MZ_ZIP_ECDH_CDIR_OFS_OFS = 16, MZ_ZIP_ECDH_COMMENT_SIZE_OFS = 20, }; typedef struct { void *m_p; size_t m_size, m_capacity; mz_uint m_element_size; } mz_zip_array; struct mz_zip_internal_state_tag { mz_zip_array m_central_dir; mz_zip_array m_central_dir_offsets; mz_zip_array m_sorted_central_dir_offsets; MZ_FILE *m_pFile; void *m_pMem; size_t m_mem_size; size_t m_mem_capacity; }; #define MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(array_ptr, element_size) \ (array_ptr)->m_element_size = element_size #define MZ_ZIP_ARRAY_ELEMENT(array_ptr, element_type, index) \ ((element_type *)((array_ptr)->m_p))[index] static MZ_FORCEINLINE void mz_zip_array_clear(mz_zip_archive *pZip, mz_zip_array *pArray) { pZip->m_pFree(pZip->m_pAlloc_opaque, pArray->m_p); memset(pArray, 0, sizeof(mz_zip_array)); } static mz_bool mz_zip_array_ensure_capacity(mz_zip_archive *pZip, mz_zip_array *pArray, size_t min_new_capacity, mz_uint growing) { void *pNew_p; size_t new_capacity = min_new_capacity; MZ_ASSERT(pArray->m_element_size); if (pArray->m_capacity >= min_new_capacity) return MZ_TRUE; if (growing) { new_capacity = MZ_MAX(1, pArray->m_capacity); while (new_capacity < min_new_capacity) new_capacity *= 2; } if (NULL == (pNew_p = pZip->m_pRealloc(pZip->m_pAlloc_opaque, pArray->m_p, pArray->m_element_size, new_capacity))) return MZ_FALSE; pArray->m_p = pNew_p; pArray->m_capacity = new_capacity; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_reserve(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_capacity, mz_uint growing) { if (new_capacity > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_capacity, growing)) return MZ_FALSE; } return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_resize(mz_zip_archive *pZip, mz_zip_array *pArray, size_t new_size, mz_uint growing) { if (new_size > pArray->m_capacity) { if (!mz_zip_array_ensure_capacity(pZip, pArray, new_size, growing)) return MZ_FALSE; } pArray->m_size = new_size; return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_array_ensure_room(mz_zip_archive *pZip, mz_zip_array *pArray, size_t n) { return mz_zip_array_reserve(pZip, pArray, pArray->m_size + n, MZ_TRUE); } static MZ_FORCEINLINE mz_bool mz_zip_array_push_back(mz_zip_archive *pZip, mz_zip_array *pArray, const void *pElements, size_t n) { size_t orig_size = pArray->m_size; if (!mz_zip_array_resize(pZip, pArray, orig_size + n, MZ_TRUE)) return MZ_FALSE; memcpy((mz_uint8 *)pArray->m_p + orig_size * pArray->m_element_size, pElements, n * pArray->m_element_size); return MZ_TRUE; } #ifndef MINIZ_NO_TIME static time_t mz_zip_dos_to_time_t(int dos_time, int dos_date) { struct tm tm; memset(&tm, 0, sizeof(tm)); tm.tm_isdst = -1; tm.tm_year = ((dos_date >> 9) & 127) + 1980 - 1900; tm.tm_mon = ((dos_date >> 5) & 15) - 1; tm.tm_mday = dos_date & 31; tm.tm_hour = (dos_time >> 11) & 31; tm.tm_min = (dos_time >> 5) & 63; tm.tm_sec = (dos_time << 1) & 62; return mktime(&tm); } static void mz_zip_time_to_dos_time(time_t time, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef _MSC_VER struct tm tm_struct; struct tm *tm = &tm_struct; errno_t err = localtime_s(tm, &time); if (err) { *pDOS_date = 0; *pDOS_time = 0; return; } #else struct tm *tm = localtime(&time); #endif *pDOS_time = (mz_uint16)(((tm->tm_hour) << 11) + ((tm->tm_min) << 5) + ((tm->tm_sec) >> 1)); *pDOS_date = (mz_uint16)(((tm->tm_year + 1900 - 1980) << 9) + ((tm->tm_mon + 1) << 5) + tm->tm_mday); } #endif #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_get_file_modified_time(const char *pFilename, mz_uint16 *pDOS_time, mz_uint16 *pDOS_date) { #ifdef MINIZ_NO_TIME (void)pFilename; *pDOS_date = *pDOS_time = 0; #else struct MZ_FILE_STAT_STRUCT file_stat; // On Linux with x86 glibc, this call will fail on large files (>= 0x80000000 // bytes) unless you compiled with _LARGEFILE64_SOURCE. Argh. if (MZ_FILE_STAT(pFilename, &file_stat) != 0) return MZ_FALSE; mz_zip_time_to_dos_time(file_stat.st_mtime, pDOS_time, pDOS_date); #endif // #ifdef MINIZ_NO_TIME return MZ_TRUE; } #ifndef MINIZ_NO_TIME static mz_bool mz_zip_set_file_times(const char *pFilename, time_t access_time, time_t modified_time) { struct utimbuf t; t.actime = access_time; t.modtime = modified_time; return !utime(pFilename, &t); } #endif // #ifndef MINIZ_NO_TIME #endif // #ifndef MINIZ_NO_STDIO static mz_bool mz_zip_reader_init_internal(mz_zip_archive *pZip, mz_uint32 flags) { (void)flags; if ((!pZip) || (pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_READING; pZip->m_archive_size = 0; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static MZ_FORCEINLINE mz_bool mz_zip_reader_filename_less(const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, mz_uint r_index) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; const mz_uint8 *pR = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, r_index)); mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS), r_len = MZ_READ_LE16(pR + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pR += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (l_len < r_len) : (l < r); } #define MZ_SWAP_UINT32(a, b) \ do { \ mz_uint32 t = a; \ a = b; \ b = t; \ } \ MZ_MACRO_END // Heap sort of lowercased filenames, used to help accelerate plain central // directory searches by mz_zip_reader_locate_file(). (Could also use qsort(), // but it could allocate memory.) static void mz_zip_reader_sort_central_dir_offsets_by_filename( mz_zip_archive *pZip) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; int start = (size - 2) >> 1, end; while (start >= 0) { int child, root = start; for (;;) { if ((child = (root << 1) + 1) >= size) break; child += (((child + 1) < size) && (mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1]))); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } start--; } end = size - 1; while (end > 0) { int child, root = 0; MZ_SWAP_UINT32(pIndices[end], pIndices[0]); for (;;) { if ((child = (root << 1) + 1) >= end) break; child += (((child + 1) < end) && mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[child], pIndices[child + 1])); if (!mz_zip_reader_filename_less(pCentral_dir, pCentral_dir_offsets, pIndices[root], pIndices[child])) break; MZ_SWAP_UINT32(pIndices[root], pIndices[child]); root = child; } end--; } } static mz_bool mz_zip_reader_read_central_dir(mz_zip_archive *pZip, mz_uint32 flags) { mz_uint cdir_size, num_this_disk, cdir_disk_index; mz_uint64 cdir_ofs; mz_int64 cur_file_ofs; const mz_uint8 *p; mz_uint32 buf_u32[4096 / sizeof(mz_uint32)]; mz_uint8 *pBuf = (mz_uint8 *)buf_u32; mz_bool sort_central_dir = ((flags & MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY) == 0); // Basic sanity checks - reject files which are too small, and check the first // 4 bytes of the file to make sure a local header is there. if (pZip->m_archive_size < MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; // Find the end of central directory record by scanning the file from the end // towards the beginning. cur_file_ofs = MZ_MAX((mz_int64)pZip->m_archive_size - (mz_int64)sizeof(buf_u32), 0); for (;;) { int i, n = (int)MZ_MIN(sizeof(buf_u32), pZip->m_archive_size - cur_file_ofs); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, n) != (mz_uint)n) return MZ_FALSE; for (i = n - 4; i >= 0; --i) if (MZ_READ_LE32(pBuf + i) == MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) break; if (i >= 0) { cur_file_ofs += i; break; } if ((!cur_file_ofs) || ((pZip->m_archive_size - cur_file_ofs) >= (0xFFFF + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE))) return MZ_FALSE; cur_file_ofs = MZ_MAX(cur_file_ofs - (sizeof(buf_u32) - 3), 0); } // Read and verify the end of central directory record. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; if ((MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_SIG_OFS) != MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG) || ((pZip->m_total_files = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS)) != MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS))) return MZ_FALSE; num_this_disk = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_THIS_DISK_OFS); cdir_disk_index = MZ_READ_LE16(pBuf + MZ_ZIP_ECDH_NUM_DISK_CDIR_OFS); if (((num_this_disk | cdir_disk_index) != 0) && ((num_this_disk != 1) || (cdir_disk_index != 1))) return MZ_FALSE; if ((cdir_size = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_SIZE_OFS)) < pZip->m_total_files * MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) return MZ_FALSE; cdir_ofs = MZ_READ_LE32(pBuf + MZ_ZIP_ECDH_CDIR_OFS_OFS); if ((cdir_ofs + (mz_uint64)cdir_size) > pZip->m_archive_size) return MZ_FALSE; pZip->m_central_directory_file_ofs = cdir_ofs; if (pZip->m_total_files) { mz_uint i, n; // Read the entire central directory into a heap block, and allocate another // heap block to hold the unsorted central dir file record offsets, and // another to hold the sorted indices. if ((!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir, cdir_size, MZ_FALSE)) || (!mz_zip_array_resize(pZip, &pZip->m_pState->m_central_dir_offsets, pZip->m_total_files, MZ_FALSE))) return MZ_FALSE; if (sort_central_dir) { if (!mz_zip_array_resize(pZip, &pZip->m_pState->m_sorted_central_dir_offsets, pZip->m_total_files, MZ_FALSE)) return MZ_FALSE; } if (pZip->m_pRead(pZip->m_pIO_opaque, cdir_ofs, pZip->m_pState->m_central_dir.m_p, cdir_size) != cdir_size) return MZ_FALSE; // Now create an index into the central directory file records, do some // basic sanity checking on each record, and check for zip64 entries (which // are not yet supported). p = (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p; for (n = cdir_size, i = 0; i < pZip->m_total_files; ++i) { mz_uint total_header_size, comp_size, decomp_size, disk_index; if ((n < MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) || (MZ_READ_LE32(p) != MZ_ZIP_CENTRAL_DIR_HEADER_SIG)) return MZ_FALSE; MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, i) = (mz_uint32)(p - (const mz_uint8 *)pZip->m_pState->m_central_dir.m_p); if (sort_central_dir) MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_sorted_central_dir_offsets, mz_uint32, i) = i; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); decomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); if (((!MZ_READ_LE32(p + MZ_ZIP_CDH_METHOD_OFS)) && (decomp_size != comp_size)) || (decomp_size && !comp_size) || (decomp_size == 0xFFFFFFFF) || (comp_size == 0xFFFFFFFF)) return MZ_FALSE; disk_index = MZ_READ_LE16(p + MZ_ZIP_CDH_DISK_START_OFS); if ((disk_index != num_this_disk) && (disk_index != 1)) return MZ_FALSE; if (((mz_uint64)MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS) + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((total_header_size = MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS)) > n) return MZ_FALSE; n -= total_header_size; p += total_header_size; } } if (sort_central_dir) mz_zip_reader_sort_central_dir_offsets_by_filename(pZip); return MZ_TRUE; } mz_bool mz_zip_reader_init(mz_zip_archive *pZip, mz_uint64 size, mz_uint32 flags) { if ((!pZip) || (!pZip->m_pRead)) return MZ_FALSE; if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } static size_t mz_zip_mem_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; size_t s = (file_ofs >= pZip->m_archive_size) ? 0 : (size_t)MZ_MIN(pZip->m_archive_size - file_ofs, n); memcpy(pBuf, (const mz_uint8 *)pZip->m_pState->m_pMem + file_ofs, s); return s; } mz_bool mz_zip_reader_init_mem(mz_zip_archive *pZip, const void *pMem, size_t size, mz_uint32 flags) { if (!mz_zip_reader_init_internal(pZip, flags)) return MZ_FALSE; pZip->m_archive_size = size; pZip->m_pRead = mz_zip_mem_read_func; pZip->m_pIO_opaque = pZip; #ifdef __cplusplus pZip->m_pState->m_pMem = const_cast<void *>(pMem); #else pZip->m_pState->m_pMem = (void *)pMem; #endif pZip->m_pState->m_mem_size = size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_read_func(void *pOpaque, mz_uint64 file_ofs, void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FREAD(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_reader_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint32 flags) { mz_uint64 file_size; MZ_FILE *pFile = MZ_FOPEN(pFilename, "rb"); if (!pFile) return MZ_FALSE; if (MZ_FSEEK64(pFile, 0, SEEK_END)) { MZ_FCLOSE(pFile); return MZ_FALSE; } file_size = MZ_FTELL64(pFile); if (!mz_zip_reader_init_internal(pZip, flags)) { MZ_FCLOSE(pFile); return MZ_FALSE; } pZip->m_pRead = mz_zip_file_read_func; pZip->m_pIO_opaque = pZip; pZip->m_pState->m_pFile = pFile; pZip->m_archive_size = file_size; if (!mz_zip_reader_read_central_dir(pZip, flags)) { mz_zip_reader_end(pZip); return MZ_FALSE; } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_uint mz_zip_reader_get_num_files(mz_zip_archive *pZip) { return pZip ? pZip->m_total_files : 0; } static MZ_FORCEINLINE const mz_uint8 *mz_zip_reader_get_cdh( mz_zip_archive *pZip, mz_uint file_index) { if ((!pZip) || (!pZip->m_pState) || (file_index >= pZip->m_total_files) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return NULL; return &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); } mz_bool mz_zip_reader_is_file_encrypted(mz_zip_archive *pZip, mz_uint file_index) { mz_uint m_bit_flag; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); return (m_bit_flag & 1); } mz_bool mz_zip_reader_is_file_a_directory(mz_zip_archive *pZip, mz_uint file_index) { mz_uint filename_len, external_attr; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) return MZ_FALSE; // First see if the filename ends with a '/' character. filename_len = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_len) { if (*(p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_len - 1) == '/') return MZ_TRUE; } // Bugfix: This code was also checking if the internal attribute was non-zero, // which wasn't correct. // Most/all zip writers (hopefully) set DOS file/directory attributes in the // low 16-bits, so check for the DOS directory flag and ignore the source OS // ID in the created by field. // FIXME: Remove this check? Is it necessary - we already check the filename. external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); if ((external_attr & 0x10) != 0) return MZ_TRUE; return MZ_FALSE; } mz_bool mz_zip_reader_file_stat(mz_zip_archive *pZip, mz_uint file_index, mz_zip_archive_file_stat *pStat) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if ((!p) || (!pStat)) return MZ_FALSE; // Unpack the central directory record. pStat->m_file_index = file_index; pStat->m_central_dir_ofs = MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index); pStat->m_version_made_by = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_MADE_BY_OFS); pStat->m_version_needed = MZ_READ_LE16(p + MZ_ZIP_CDH_VERSION_NEEDED_OFS); pStat->m_bit_flag = MZ_READ_LE16(p + MZ_ZIP_CDH_BIT_FLAG_OFS); pStat->m_method = MZ_READ_LE16(p + MZ_ZIP_CDH_METHOD_OFS); #ifndef MINIZ_NO_TIME pStat->m_time = mz_zip_dos_to_time_t(MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_TIME_OFS), MZ_READ_LE16(p + MZ_ZIP_CDH_FILE_DATE_OFS)); #endif pStat->m_crc32 = MZ_READ_LE32(p + MZ_ZIP_CDH_CRC32_OFS); pStat->m_comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); pStat->m_uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); pStat->m_internal_attr = MZ_READ_LE16(p + MZ_ZIP_CDH_INTERNAL_ATTR_OFS); pStat->m_external_attr = MZ_READ_LE32(p + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS); pStat->m_local_header_ofs = MZ_READ_LE32(p + MZ_ZIP_CDH_LOCAL_HEADER_OFS); // Copy as much of the filename and comment as possible. n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILENAME_SIZE - 1); memcpy(pStat->m_filename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pStat->m_filename[n] = '\0'; n = MZ_READ_LE16(p + MZ_ZIP_CDH_COMMENT_LEN_OFS); n = MZ_MIN(n, MZ_ZIP_MAX_ARCHIVE_FILE_COMMENT_SIZE - 1); pStat->m_comment_size = n; memcpy(pStat->m_comment, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(p + MZ_ZIP_CDH_EXTRA_LEN_OFS), n); pStat->m_comment[n] = '\0'; return MZ_TRUE; } mz_uint mz_zip_reader_get_filename(mz_zip_archive *pZip, mz_uint file_index, char *pFilename, mz_uint filename_buf_size) { mz_uint n; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); if (!p) { if (filename_buf_size) pFilename[0] = '\0'; return 0; } n = MZ_READ_LE16(p + MZ_ZIP_CDH_FILENAME_LEN_OFS); if (filename_buf_size) { n = MZ_MIN(n, filename_buf_size - 1); memcpy(pFilename, p + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n); pFilename[n] = '\0'; } return n + 1; } static MZ_FORCEINLINE mz_bool mz_zip_reader_string_equal(const char *pA, const char *pB, mz_uint len, mz_uint flags) { mz_uint i; if (flags & MZ_ZIP_FLAG_CASE_SENSITIVE) return 0 == memcmp(pA, pB, len); for (i = 0; i < len; ++i) if (MZ_TOLOWER(pA[i]) != MZ_TOLOWER(pB[i])) return MZ_FALSE; return MZ_TRUE; } static MZ_FORCEINLINE int mz_zip_reader_filename_compare( const mz_zip_array *pCentral_dir_array, const mz_zip_array *pCentral_dir_offsets, mz_uint l_index, const char *pR, mz_uint r_len) { const mz_uint8 *pL = &MZ_ZIP_ARRAY_ELEMENT( pCentral_dir_array, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(pCentral_dir_offsets, mz_uint32, l_index)), *pE; mz_uint l_len = MZ_READ_LE16(pL + MZ_ZIP_CDH_FILENAME_LEN_OFS); mz_uint8 l = 0, r = 0; pL += MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; pE = pL + MZ_MIN(l_len, r_len); while (pL < pE) { if ((l = MZ_TOLOWER(*pL)) != (r = MZ_TOLOWER(*pR))) break; pL++; pR++; } return (pL == pE) ? (int)(l_len - r_len) : (l - r); } static int mz_zip_reader_locate_file_binary_search(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState = pZip->m_pState; const mz_zip_array *pCentral_dir_offsets = &pState->m_central_dir_offsets; const mz_zip_array *pCentral_dir = &pState->m_central_dir; mz_uint32 *pIndices = &MZ_ZIP_ARRAY_ELEMENT( &pState->m_sorted_central_dir_offsets, mz_uint32, 0); const int size = pZip->m_total_files; const mz_uint filename_len = (mz_uint)strlen(pFilename); int l = 0, h = size - 1; while (l <= h) { int m = (l + h) >> 1, file_index = pIndices[m], comp = mz_zip_reader_filename_compare(pCentral_dir, pCentral_dir_offsets, file_index, pFilename, filename_len); if (!comp) return file_index; else if (comp < 0) l = m + 1; else h = m - 1; } return -1; } int mz_zip_reader_locate_file(mz_zip_archive *pZip, const char *pName, const char *pComment, mz_uint flags) { mz_uint file_index; size_t name_len, comment_len; if ((!pZip) || (!pZip->m_pState) || (!pName) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return -1; if (((flags & (MZ_ZIP_FLAG_IGNORE_PATH | MZ_ZIP_FLAG_CASE_SENSITIVE)) == 0) && (!pComment) && (pZip->m_pState->m_sorted_central_dir_offsets.m_size)) return mz_zip_reader_locate_file_binary_search(pZip, pName); name_len = strlen(pName); if (name_len > 0xFFFF) return -1; comment_len = pComment ? strlen(pComment) : 0; if (comment_len > 0xFFFF) return -1; for (file_index = 0; file_index < pZip->m_total_files; file_index++) { const mz_uint8 *pHeader = &MZ_ZIP_ARRAY_ELEMENT( &pZip->m_pState->m_central_dir, mz_uint8, MZ_ZIP_ARRAY_ELEMENT(&pZip->m_pState->m_central_dir_offsets, mz_uint32, file_index)); mz_uint filename_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_FILENAME_LEN_OFS); const char *pFilename = (const char *)pHeader + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE; if (filename_len < name_len) continue; if (comment_len) { mz_uint file_extra_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_EXTRA_LEN_OFS), file_comment_len = MZ_READ_LE16(pHeader + MZ_ZIP_CDH_COMMENT_LEN_OFS); const char *pFile_comment = pFilename + filename_len + file_extra_len; if ((file_comment_len != comment_len) || (!mz_zip_reader_string_equal(pComment, pFile_comment, file_comment_len, flags))) continue; } if ((flags & MZ_ZIP_FLAG_IGNORE_PATH) && (filename_len)) { int ofs = filename_len - 1; do { if ((pFilename[ofs] == '/') || (pFilename[ofs] == '\\') || (pFilename[ofs] == ':')) break; } while (--ofs >= 0); ofs++; pFilename += ofs; filename_len -= ofs; } if ((filename_len == name_len) && (mz_zip_reader_string_equal(pName, pFilename, filename_len, flags))) return file_index; } return -1; } mz_bool mz_zip_reader_extract_to_mem_no_alloc(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int status = TINFL_STATUS_DONE; mz_uint64 needed_size, cur_file_ofs, comp_remaining, out_buf_ofs = 0, read_buf_size, read_buf_ofs = 0, read_buf_avail; mz_zip_archive_file_stat file_stat; void *pRead_buf; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; tinfl_decompressor inflator; if ((buf_size) && (!pBuf)) return MZ_FALSE; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Ensure supplied output buffer is large enough. needed_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? file_stat.m_comp_size : file_stat.m_uncomp_size; if (buf_size < needed_size) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pBuf, (size_t)needed_size) != needed_size) return MZ_FALSE; return ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) != 0) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) == file_stat.m_crc32); } // Decompress the file either directly from memory or from a file input // buffer. tinfl_init(&inflator); if (pZip->m_pState->m_pMem) { // Read directly from the archive in memory. pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else if (pUser_read_buf) { // Use a user provided read buffer. if (!user_read_buf_size) return MZ_FALSE; pRead_buf = (mz_uint8 *)pUser_read_buf; read_buf_size = user_read_buf_size; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } else { // Temporarily allocate a read buffer. read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (read_buf_size > 0x7FFFFFFF)) #endif return MZ_FALSE; if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } do { size_t in_buf_size, out_buf_size = (size_t)(file_stat.m_uncomp_size - out_buf_ofs); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pBuf, (mz_uint8 *)pBuf + out_buf_ofs, &out_buf_size, TINFL_FLAG_USING_NON_WRAPPING_OUTPUT_BUF | (comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0)); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; out_buf_ofs += out_buf_size; } while (status == TINFL_STATUS_NEEDS_MORE_INPUT); if (status == TINFL_STATUS_DONE) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, (size_t)file_stat.m_uncomp_size) != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if ((!pZip->m_pState->m_pMem) && (!pUser_read_buf)) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_mem_no_alloc( mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags, void *pUser_read_buf, size_t user_read_buf_size) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, pUser_read_buf, user_read_buf_size); } mz_bool mz_zip_reader_extract_to_mem(mz_zip_archive *pZip, mz_uint file_index, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_to_mem_no_alloc(pZip, file_index, pBuf, buf_size, flags, NULL, 0); } mz_bool mz_zip_reader_extract_file_to_mem(mz_zip_archive *pZip, const char *pFilename, void *pBuf, size_t buf_size, mz_uint flags) { return mz_zip_reader_extract_file_to_mem_no_alloc(pZip, pFilename, pBuf, buf_size, flags, NULL, 0); } void *mz_zip_reader_extract_to_heap(mz_zip_archive *pZip, mz_uint file_index, size_t *pSize, mz_uint flags) { mz_uint64 comp_size, uncomp_size, alloc_size; const mz_uint8 *p = mz_zip_reader_get_cdh(pZip, file_index); void *pBuf; if (pSize) *pSize = 0; if (!p) return NULL; comp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); uncomp_size = MZ_READ_LE32(p + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS); alloc_size = (flags & MZ_ZIP_FLAG_COMPRESSED_DATA) ? comp_size : uncomp_size; #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (alloc_size > 0x7FFFFFFF)) #endif return NULL; if (NULL == (pBuf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)alloc_size))) return NULL; if (!mz_zip_reader_extract_to_mem(pZip, file_index, pBuf, (size_t)alloc_size, flags)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return NULL; } if (pSize) *pSize = (size_t)alloc_size; return pBuf; } void *mz_zip_reader_extract_file_to_heap(mz_zip_archive *pZip, const char *pFilename, size_t *pSize, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) { if (pSize) *pSize = 0; return MZ_FALSE; } return mz_zip_reader_extract_to_heap(pZip, file_index, pSize, flags); } mz_bool mz_zip_reader_extract_to_callback(mz_zip_archive *pZip, mz_uint file_index, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int status = TINFL_STATUS_DONE; mz_uint file_crc32 = MZ_CRC32_INIT; mz_uint64 read_buf_size, read_buf_ofs = 0, read_buf_avail, comp_remaining, out_buf_ofs = 0, cur_file_ofs; mz_zip_archive_file_stat file_stat; void *pRead_buf = NULL; void *pWrite_buf = NULL; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; // Empty file, or a directory (but not always a directory - I've seen odd zips // with directories that have compressed data which inflates to 0 bytes) if (!file_stat.m_comp_size) return MZ_TRUE; // Entry is a subdirectory (I've seen old zips with dir entries which have // compressed deflate data which inflates to 0 bytes, but these entries claim // to uncompress to 512 bytes in the headers). // I'm torn how to handle this case - should it fail instead? if (mz_zip_reader_is_file_a_directory(pZip, file_index)) return MZ_TRUE; // Encryption and patch files are not supported. if (file_stat.m_bit_flag & (1 | 32)) return MZ_FALSE; // This function only supports stored and deflate. if ((!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (file_stat.m_method != 0) && (file_stat.m_method != MZ_DEFLATED)) return MZ_FALSE; // Read and parse the local directory entry. cur_file_ofs = file_stat.m_local_header_ofs; if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); if ((cur_file_ofs + file_stat.m_comp_size) > pZip->m_archive_size) return MZ_FALSE; // Decompress the file either directly from memory or from a file input // buffer. if (pZip->m_pState->m_pMem) { pRead_buf = (mz_uint8 *)pZip->m_pState->m_pMem + cur_file_ofs; read_buf_size = read_buf_avail = file_stat.m_comp_size; comp_remaining = 0; } else { read_buf_size = MZ_MIN(file_stat.m_comp_size, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); if (NULL == (pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, (size_t)read_buf_size))) return MZ_FALSE; read_buf_avail = 0; comp_remaining = file_stat.m_comp_size; } if ((flags & MZ_ZIP_FLAG_COMPRESSED_DATA) || (!file_stat.m_method)) { // The file is stored or the caller has requested the compressed data. if (pZip->m_pState->m_pMem) { #ifdef _MSC_VER if (((0, sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #else if (((sizeof(size_t) == sizeof(mz_uint32))) && (file_stat.m_comp_size > 0xFFFFFFFF)) #endif return MZ_FALSE; if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)file_stat.m_comp_size) != file_stat.m_comp_size) status = TINFL_STATUS_FAILED; else if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32(file_crc32, (const mz_uint8 *)pRead_buf, (size_t)file_stat.m_comp_size); cur_file_ofs += file_stat.m_comp_size; out_buf_ofs += file_stat.m_comp_size; comp_remaining = 0; } else { while (comp_remaining) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } if (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) file_crc32 = (mz_uint32)mz_crc32( file_crc32, (const mz_uint8 *)pRead_buf, (size_t)read_buf_avail); if (pCallback(pOpaque, out_buf_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; out_buf_ofs += read_buf_avail; comp_remaining -= read_buf_avail; } } } else { tinfl_decompressor inflator; tinfl_init(&inflator); if (NULL == (pWrite_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, TINFL_LZ_DICT_SIZE))) status = TINFL_STATUS_FAILED; else { do { mz_uint8 *pWrite_buf_cur = (mz_uint8 *)pWrite_buf + (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); size_t in_buf_size, out_buf_size = TINFL_LZ_DICT_SIZE - (out_buf_ofs & (TINFL_LZ_DICT_SIZE - 1)); if ((!read_buf_avail) && (!pZip->m_pState->m_pMem)) { read_buf_avail = MZ_MIN(read_buf_size, comp_remaining); if (pZip->m_pRead(pZip->m_pIO_opaque, cur_file_ofs, pRead_buf, (size_t)read_buf_avail) != read_buf_avail) { status = TINFL_STATUS_FAILED; break; } cur_file_ofs += read_buf_avail; comp_remaining -= read_buf_avail; read_buf_ofs = 0; } in_buf_size = (size_t)read_buf_avail; status = tinfl_decompress( &inflator, (const mz_uint8 *)pRead_buf + read_buf_ofs, &in_buf_size, (mz_uint8 *)pWrite_buf, pWrite_buf_cur, &out_buf_size, comp_remaining ? TINFL_FLAG_HAS_MORE_INPUT : 0); read_buf_avail -= in_buf_size; read_buf_ofs += in_buf_size; if (out_buf_size) { if (pCallback(pOpaque, out_buf_ofs, pWrite_buf_cur, out_buf_size) != out_buf_size) { status = TINFL_STATUS_FAILED; break; } file_crc32 = (mz_uint32)mz_crc32(file_crc32, pWrite_buf_cur, out_buf_size); if ((out_buf_ofs += out_buf_size) > file_stat.m_uncomp_size) { status = TINFL_STATUS_FAILED; break; } } } while ((status == TINFL_STATUS_NEEDS_MORE_INPUT) || (status == TINFL_STATUS_HAS_MORE_OUTPUT)); } } if ((status == TINFL_STATUS_DONE) && (!(flags & MZ_ZIP_FLAG_COMPRESSED_DATA))) { // Make sure the entire file was decompressed, and check its CRC. if ((out_buf_ofs != file_stat.m_uncomp_size) || (file_crc32 != file_stat.m_crc32)) status = TINFL_STATUS_FAILED; } if (!pZip->m_pState->m_pMem) pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); if (pWrite_buf) pZip->m_pFree(pZip->m_pAlloc_opaque, pWrite_buf); return status == TINFL_STATUS_DONE; } mz_bool mz_zip_reader_extract_file_to_callback(mz_zip_archive *pZip, const char *pFilename, mz_file_write_func pCallback, void *pOpaque, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pFilename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_callback(pZip, file_index, pCallback, pOpaque, flags); } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_callback(void *pOpaque, mz_uint64 ofs, const void *pBuf, size_t n) { (void)ofs; return MZ_FWRITE(pBuf, 1, n, (MZ_FILE *)pOpaque); } mz_bool mz_zip_reader_extract_to_file(mz_zip_archive *pZip, mz_uint file_index, const char *pDst_filename, mz_uint flags) { mz_bool status; mz_zip_archive_file_stat file_stat; MZ_FILE *pFile; if (!mz_zip_reader_file_stat(pZip, file_index, &file_stat)) return MZ_FALSE; pFile = MZ_FOPEN(pDst_filename, "wb"); if (!pFile) return MZ_FALSE; status = mz_zip_reader_extract_to_callback( pZip, file_index, mz_zip_file_write_callback, pFile, flags); if (MZ_FCLOSE(pFile) == EOF) return MZ_FALSE; #ifndef MINIZ_NO_TIME if (status) mz_zip_set_file_times(pDst_filename, file_stat.m_time, file_stat.m_time); #endif return status; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_end(mz_zip_archive *pZip) { if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; if (pZip->m_pState) { mz_zip_internal_state *pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO pZip->m_pFree(pZip->m_pAlloc_opaque, pState); } pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_reader_extract_file_to_file(mz_zip_archive *pZip, const char *pArchive_filename, const char *pDst_filename, mz_uint flags) { int file_index = mz_zip_reader_locate_file(pZip, pArchive_filename, NULL, flags); if (file_index < 0) return MZ_FALSE; return mz_zip_reader_extract_to_file(pZip, file_index, pDst_filename, flags); } #endif // ------------------- .ZIP archive writing #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS static void mz_write_le16(mz_uint8 *p, mz_uint16 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); } static void mz_write_le32(mz_uint8 *p, mz_uint32 v) { p[0] = (mz_uint8)v; p[1] = (mz_uint8)(v >> 8); p[2] = (mz_uint8)(v >> 16); p[3] = (mz_uint8)(v >> 24); } #define MZ_WRITE_LE16(p, v) mz_write_le16((mz_uint8 *)(p), (mz_uint16)(v)) #define MZ_WRITE_LE32(p, v) mz_write_le32((mz_uint8 *)(p), (mz_uint32)(v)) mz_bool mz_zip_writer_init(mz_zip_archive *pZip, mz_uint64 existing_size) { if ((!pZip) || (pZip->m_pState) || (!pZip->m_pWrite) || (pZip->m_zip_mode != MZ_ZIP_MODE_INVALID)) return MZ_FALSE; if (pZip->m_file_offset_alignment) { // Ensure user specified file offset alignment is a power of 2. if (pZip->m_file_offset_alignment & (pZip->m_file_offset_alignment - 1)) return MZ_FALSE; } if (!pZip->m_pAlloc) pZip->m_pAlloc = def_alloc_func; if (!pZip->m_pFree) pZip->m_pFree = def_free_func; if (!pZip->m_pRealloc) pZip->m_pRealloc = def_realloc_func; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_archive_size = existing_size; pZip->m_central_directory_file_ofs = 0; pZip->m_total_files = 0; if (NULL == (pZip->m_pState = (mz_zip_internal_state *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(mz_zip_internal_state)))) return MZ_FALSE; memset(pZip->m_pState, 0, sizeof(mz_zip_internal_state)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir, sizeof(mz_uint8)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_central_dir_offsets, sizeof(mz_uint32)); MZ_ZIP_ARRAY_SET_ELEMENT_SIZE(&pZip->m_pState->m_sorted_central_dir_offsets, sizeof(mz_uint32)); return MZ_TRUE; } static size_t mz_zip_heap_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_zip_internal_state *pState = pZip->m_pState; mz_uint64 new_size = MZ_MAX(file_ofs + n, pState->m_mem_size); #ifdef _MSC_VER if ((!n) || ((0, sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #else if ((!n) || ((sizeof(size_t) == sizeof(mz_uint32)) && (new_size > 0x7FFFFFFF))) #endif return 0; if (new_size > pState->m_mem_capacity) { void *pNew_block; size_t new_capacity = MZ_MAX(64, pState->m_mem_capacity); while (new_capacity < new_size) new_capacity *= 2; if (NULL == (pNew_block = pZip->m_pRealloc( pZip->m_pAlloc_opaque, pState->m_pMem, 1, new_capacity))) return 0; pState->m_pMem = pNew_block; pState->m_mem_capacity = new_capacity; } memcpy((mz_uint8 *)pState->m_pMem + file_ofs, pBuf, n); pState->m_mem_size = (size_t)new_size; return n; } mz_bool mz_zip_writer_init_heap(mz_zip_archive *pZip, size_t size_to_reserve_at_beginning, size_t initial_allocation_size) { pZip->m_pWrite = mz_zip_heap_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (0 != (initial_allocation_size = MZ_MAX(initial_allocation_size, size_to_reserve_at_beginning))) { if (NULL == (pZip->m_pState->m_pMem = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, initial_allocation_size))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_mem_capacity = initial_allocation_size; } return MZ_TRUE; } #ifndef MINIZ_NO_STDIO static size_t mz_zip_file_write_func(void *pOpaque, mz_uint64 file_ofs, const void *pBuf, size_t n) { mz_zip_archive *pZip = (mz_zip_archive *)pOpaque; mz_int64 cur_ofs = MZ_FTELL64(pZip->m_pState->m_pFile); if (((mz_int64)file_ofs < 0) || (((cur_ofs != (mz_int64)file_ofs)) && (MZ_FSEEK64(pZip->m_pState->m_pFile, (mz_int64)file_ofs, SEEK_SET)))) return 0; return MZ_FWRITE(pBuf, 1, n, pZip->m_pState->m_pFile); } mz_bool mz_zip_writer_init_file(mz_zip_archive *pZip, const char *pFilename, mz_uint64 size_to_reserve_at_beginning) { MZ_FILE *pFile; pZip->m_pWrite = mz_zip_file_write_func; pZip->m_pIO_opaque = pZip; if (!mz_zip_writer_init(pZip, size_to_reserve_at_beginning)) return MZ_FALSE; if (NULL == (pFile = MZ_FOPEN(pFilename, "wb"))) { mz_zip_writer_end(pZip); return MZ_FALSE; } pZip->m_pState->m_pFile = pFile; if (size_to_reserve_at_beginning) { mz_uint64 cur_ofs = 0; char buf[4096]; MZ_CLEAR_OBJ(buf); do { size_t n = (size_t)MZ_MIN(sizeof(buf), size_to_reserve_at_beginning); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_ofs, buf, n) != n) { mz_zip_writer_end(pZip); return MZ_FALSE; } cur_ofs += n; size_to_reserve_at_beginning -= n; } while (size_to_reserve_at_beginning); } return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_init_from_reader(mz_zip_archive *pZip, const char *pFilename) { mz_zip_internal_state *pState; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_READING)) return MZ_FALSE; // No sense in trying to write to an archive that's already at the support max // size if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + MZ_ZIP_LOCAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; pState = pZip->m_pState; if (pState->m_pFile) { #ifdef MINIZ_NO_STDIO pFilename; return MZ_FALSE; #else // Archive is being read from stdio - try to reopen as writable. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; if (!pFilename) return MZ_FALSE; pZip->m_pWrite = mz_zip_file_write_func; if (NULL == (pState->m_pFile = MZ_FREOPEN(pFilename, "r+b", pState->m_pFile))) { // The mz_zip_archive is now in a bogus state because pState->m_pFile is // NULL, so just close it. mz_zip_reader_end(pZip); return MZ_FALSE; } #endif // #ifdef MINIZ_NO_STDIO } else if (pState->m_pMem) { // Archive lives in a memory block. Assume it's from the heap that we can // resize using the realloc callback. if (pZip->m_pIO_opaque != pZip) return MZ_FALSE; pState->m_mem_capacity = pState->m_mem_size; pZip->m_pWrite = mz_zip_heap_write_func; } // Archive is being read via a user provided read function - make sure the // user has specified a write function too. else if (!pZip->m_pWrite) return MZ_FALSE; // Start writing new files at the archive's current central directory // location. pZip->m_archive_size = pZip->m_central_directory_file_ofs; pZip->m_zip_mode = MZ_ZIP_MODE_WRITING; pZip->m_central_directory_file_ofs = 0; return MZ_TRUE; } mz_bool mz_zip_writer_add_mem(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, mz_uint level_and_flags) { return mz_zip_writer_add_mem_ex(pZip, pArchive_name, pBuf, buf_size, NULL, 0, level_and_flags, 0, 0); } typedef struct { mz_zip_archive *m_pZip; mz_uint64 m_cur_archive_file_ofs; mz_uint64 m_comp_size; } mz_zip_writer_add_state; static mz_bool mz_zip_writer_add_put_buf_callback(const void *pBuf, int len, void *pUser) { mz_zip_writer_add_state *pState = (mz_zip_writer_add_state *)pUser; if ((int)pState->m_pZip->m_pWrite(pState->m_pZip->m_pIO_opaque, pState->m_cur_archive_file_ofs, pBuf, len) != len) return MZ_FALSE; pState->m_cur_archive_file_ofs += len; pState->m_comp_size += len; return MZ_TRUE; } static mz_bool mz_zip_writer_create_local_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date) { (void)pZip; memset(pDst, 0, MZ_ZIP_LOCAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_SIG_OFS, MZ_ZIP_LOCAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_LDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_LDH_EXTRA_LEN_OFS, extra_size); return MZ_TRUE; } static mz_bool mz_zip_writer_create_central_dir_header( mz_zip_archive *pZip, mz_uint8 *pDst, mz_uint16 filename_size, mz_uint16 extra_size, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { (void)pZip; memset(pDst, 0, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_SIG_OFS, MZ_ZIP_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_VERSION_NEEDED_OFS, method ? 20 : 0); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_BIT_FLAG_OFS, bit_flags); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_METHOD_OFS, method); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_TIME_OFS, dos_time); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILE_DATE_OFS, dos_date); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_CRC32_OFS, uncomp_crc32); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS, comp_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_DECOMPRESSED_SIZE_OFS, uncomp_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_FILENAME_LEN_OFS, filename_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_EXTRA_LEN_OFS, extra_size); MZ_WRITE_LE16(pDst + MZ_ZIP_CDH_COMMENT_LEN_OFS, comment_size); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_EXTERNAL_ATTR_OFS, ext_attributes); MZ_WRITE_LE32(pDst + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_header_ofs); return MZ_TRUE; } static mz_bool mz_zip_writer_add_to_central_dir( mz_zip_archive *pZip, const char *pFilename, mz_uint16 filename_size, const void *pExtra, mz_uint16 extra_size, const void *pComment, mz_uint16 comment_size, mz_uint64 uncomp_size, mz_uint64 comp_size, mz_uint32 uncomp_crc32, mz_uint16 method, mz_uint16 bit_flags, mz_uint16 dos_time, mz_uint16 dos_date, mz_uint64 local_header_ofs, mz_uint32 ext_attributes) { mz_zip_internal_state *pState = pZip->m_pState; mz_uint32 central_dir_ofs = (mz_uint32)pState->m_central_dir.m_size; size_t orig_central_dir_size = pState->m_central_dir.m_size; mz_uint8 central_dir_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; // No zip64 support yet if ((local_header_ofs > 0xFFFFFFFF) || (((mz_uint64)pState->m_central_dir.m_size + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + filename_size + extra_size + comment_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_central_dir_header( pZip, central_dir_header, filename_size, extra_size, comment_size, uncomp_size, comp_size, uncomp_crc32, method, bit_flags, dos_time, dos_date, local_header_ofs, ext_attributes)) return MZ_FALSE; if ((!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_dir_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pFilename, filename_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pExtra, extra_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir, pComment, comment_size)) || (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &central_dir_ofs, 1))) { // Try to push the central directory array back into its original state. mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } return MZ_TRUE; } static mz_bool mz_zip_writer_validate_archive_name(const char *pArchive_name) { // Basic ZIP archive filename validity checks: Valid filenames cannot start // with a forward slash, cannot contain a drive letter, and cannot use // DOS-style backward slashes. if (*pArchive_name == '/') return MZ_FALSE; while (*pArchive_name) { if ((*pArchive_name == '\\') || (*pArchive_name == ':')) return MZ_FALSE; pArchive_name++; } return MZ_TRUE; } static mz_uint mz_zip_writer_compute_padding_needed_for_file_alignment( mz_zip_archive *pZip) { mz_uint32 n; if (!pZip->m_file_offset_alignment) return 0; n = (mz_uint32)(pZip->m_archive_size & (pZip->m_file_offset_alignment - 1)); return (pZip->m_file_offset_alignment - n) & (pZip->m_file_offset_alignment - 1); } static mz_bool mz_zip_writer_write_zeros(mz_zip_archive *pZip, mz_uint64 cur_file_ofs, mz_uint32 n) { char buf[4096]; memset(buf, 0, MZ_MIN(sizeof(buf), n)); while (n) { mz_uint32 s = MZ_MIN(sizeof(buf), n); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_file_ofs, buf, s) != s) return MZ_FALSE; cur_file_ofs += s; n -= s; } return MZ_TRUE; } mz_bool mz_zip_writer_add_mem_ex(mz_zip_archive *pZip, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags, mz_uint64 uncomp_size, mz_uint32 uncomp_crc32) { mz_uint16 method = 0, dos_time = 0, dos_date = 0; mz_uint level, ext_attributes = 0, num_alignment_padding_bytes; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; tdefl_compressor *pComp = NULL; mz_bool store_data_uncompressed; mz_zip_internal_state *pState; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; store_data_uncompressed = ((!level) || (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)); if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || ((buf_size) && (!pBuf)) || (!pArchive_name) || ((comment_size) && (!pComment)) || (pZip->m_total_files == 0xFFFF) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; pState = pZip->m_pState; if ((!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) && (uncomp_size)) return MZ_FALSE; // No zip64 support yet if ((buf_size > 0xFFFFFFFF) || (uncomp_size > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; #ifndef MINIZ_NO_TIME { time_t cur_time; time(&cur_time); mz_zip_time_to_dos_time(cur_time, &dos_time, &dos_date); } #endif // #ifndef MINIZ_NO_TIME archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if ((archive_name_size) && (pArchive_name[archive_name_size - 1] == '/')) { // Set DOS Subdirectory attribute bit. ext_attributes |= 0x10; // Subdirectories cannot contain data. if ((buf_size) || (uncomp_size)) return MZ_FALSE; } // Try to do any allocations before writing to the archive, so if an // allocation fails the file remains unmodified. (A good idea if we're doing // an in-place modification.) if ((!mz_zip_array_ensure_room( pZip, &pState->m_central_dir, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + archive_name_size + comment_size)) || (!mz_zip_array_ensure_room(pZip, &pState->m_central_dir_offsets, 1))) return MZ_FALSE; if ((!store_data_uncompressed) && (buf_size)) { if (NULL == (pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)))) return MZ_FALSE; } if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (!(level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA)) { uncomp_crc32 = (mz_uint32)mz_crc32(MZ_CRC32_INIT, (const mz_uint8 *)pBuf, buf_size); uncomp_size = buf_size; if (uncomp_size <= 3) { level = 0; store_data_uncompressed = MZ_TRUE; } } if (store_data_uncompressed) { if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pBuf, buf_size) != buf_size) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } cur_archive_file_ofs += buf_size; comp_size = buf_size; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) method = MZ_DEFLATED; } else if (buf_size) { mz_zip_writer_add_state state; state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if ((tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) || (tdefl_compress_buffer(pComp, pBuf, buf_size, TDEFL_FINISH) != TDEFL_STATUS_DONE)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pComp = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_file(mz_zip_archive *pZip, const char *pArchive_name, const char *pSrc_filename, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_uint uncomp_crc32 = MZ_CRC32_INIT, level, num_alignment_padding_bytes; mz_uint16 method = 0, dos_time = 0, dos_date = 0, ext_attributes = 0; mz_uint64 local_dir_header_ofs = pZip->m_archive_size, cur_archive_file_ofs = pZip->m_archive_size, uncomp_size = 0, comp_size = 0; size_t archive_name_size; mz_uint8 local_dir_header[MZ_ZIP_LOCAL_DIR_HEADER_SIZE]; MZ_FILE *pSrc_file = NULL; if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; level = level_and_flags & 0xF; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) || (!pArchive_name) || ((comment_size) && (!pComment)) || (level > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (level_and_flags & MZ_ZIP_FLAG_COMPRESSED_DATA) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; archive_name_size = strlen(pArchive_name); if (archive_name_size > 0xFFFF) return MZ_FALSE; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE + comment_size + archive_name_size) > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_get_file_modified_time(pSrc_filename, &dos_time, &dos_date)) return MZ_FALSE; pSrc_file = MZ_FOPEN(pSrc_filename, "rb"); if (!pSrc_file) return MZ_FALSE; MZ_FSEEK64(pSrc_file, 0, SEEK_END); uncomp_size = MZ_FTELL64(pSrc_file); MZ_FSEEK64(pSrc_file, 0, SEEK_SET); if (uncomp_size > 0xFFFFFFFF) { // No zip64 support yet MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (uncomp_size <= 3) level = 0; if (!mz_zip_writer_write_zeros( pZip, cur_archive_file_ofs, num_alignment_padding_bytes + sizeof(local_dir_header))) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } local_dir_header_ofs += num_alignment_padding_bytes; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } cur_archive_file_ofs += num_alignment_padding_bytes + sizeof(local_dir_header); MZ_CLEAR_OBJ(local_dir_header); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pArchive_name, archive_name_size) != archive_name_size) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } cur_archive_file_ofs += archive_name_size; if (uncomp_size) { mz_uint64 uncomp_remaining = uncomp_size; void *pRead_buf = pZip->m_pAlloc(pZip->m_pAlloc_opaque, 1, MZ_ZIP_MAX_IO_BUF_SIZE); if (!pRead_buf) { MZ_FCLOSE(pSrc_file); return MZ_FALSE; } if (!level) { while (uncomp_remaining) { mz_uint n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, uncomp_remaining); if ((MZ_FREAD(pRead_buf, 1, n, pSrc_file) != n) || (pZip->m_pWrite(pZip->m_pIO_opaque, cur_archive_file_ofs, pRead_buf, n) != n)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } uncomp_crc32 = (mz_uint32)mz_crc32(uncomp_crc32, (const mz_uint8 *)pRead_buf, n); uncomp_remaining -= n; cur_archive_file_ofs += n; } comp_size = uncomp_size; } else { mz_bool result = MZ_FALSE; mz_zip_writer_add_state state; tdefl_compressor *pComp = (tdefl_compressor *)pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, sizeof(tdefl_compressor)); if (!pComp) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } state.m_pZip = pZip; state.m_cur_archive_file_ofs = cur_archive_file_ofs; state.m_comp_size = 0; if (tdefl_init(pComp, mz_zip_writer_add_put_buf_callback, &state, tdefl_create_comp_flags_from_zip_params( level, -15, MZ_DEFAULT_STRATEGY)) != TDEFL_STATUS_OKAY) { pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } for (;;) { size_t in_buf_size = (mz_uint32)MZ_MIN(uncomp_remaining, (mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE); tdefl_status status; if (MZ_FREAD(pRead_buf, 1, in_buf_size, pSrc_file) != in_buf_size) break; uncomp_crc32 = (mz_uint32)mz_crc32( uncomp_crc32, (const mz_uint8 *)pRead_buf, in_buf_size); uncomp_remaining -= in_buf_size; status = tdefl_compress_buffer( pComp, pRead_buf, in_buf_size, uncomp_remaining ? TDEFL_NO_FLUSH : TDEFL_FINISH); if (status == TDEFL_STATUS_DONE) { result = MZ_TRUE; break; } else if (status != TDEFL_STATUS_OKAY) break; } pZip->m_pFree(pZip->m_pAlloc_opaque, pComp); if (!result) { pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); MZ_FCLOSE(pSrc_file); return MZ_FALSE; } comp_size = state.m_comp_size; cur_archive_file_ofs = state.m_cur_archive_file_ofs; method = MZ_DEFLATED; } pZip->m_pFree(pZip->m_pAlloc_opaque, pRead_buf); } MZ_FCLOSE(pSrc_file); pSrc_file = NULL; // no zip64 support yet if ((comp_size > 0xFFFFFFFF) || (cur_archive_file_ofs > 0xFFFFFFFF)) return MZ_FALSE; if (!mz_zip_writer_create_local_dir_header( pZip, local_dir_header, (mz_uint16)archive_name_size, 0, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date)) return MZ_FALSE; if (pZip->m_pWrite(pZip->m_pIO_opaque, local_dir_header_ofs, local_dir_header, sizeof(local_dir_header)) != sizeof(local_dir_header)) return MZ_FALSE; if (!mz_zip_writer_add_to_central_dir( pZip, pArchive_name, (mz_uint16)archive_name_size, NULL, 0, pComment, comment_size, uncomp_size, comp_size, uncomp_crc32, method, 0, dos_time, dos_date, local_dir_header_ofs, ext_attributes)) return MZ_FALSE; pZip->m_total_files++; pZip->m_archive_size = cur_archive_file_ofs; return MZ_TRUE; } #endif // #ifndef MINIZ_NO_STDIO mz_bool mz_zip_writer_add_from_zip_reader(mz_zip_archive *pZip, mz_zip_archive *pSource_zip, mz_uint file_index) { mz_uint n, bit_flags, num_alignment_padding_bytes; mz_uint64 comp_bytes_remaining, local_dir_header_ofs; mz_uint64 cur_src_file_ofs, cur_dst_file_ofs; mz_uint32 local_header_u32[(MZ_ZIP_LOCAL_DIR_HEADER_SIZE + sizeof(mz_uint32) - 1) / sizeof(mz_uint32)]; mz_uint8 *pLocal_header = (mz_uint8 *)local_header_u32; mz_uint8 central_header[MZ_ZIP_CENTRAL_DIR_HEADER_SIZE]; size_t orig_central_dir_size; mz_zip_internal_state *pState; void *pBuf; const mz_uint8 *pSrc_central_header; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; if (NULL == (pSrc_central_header = mz_zip_reader_get_cdh(pSource_zip, file_index))) return MZ_FALSE; pState = pZip->m_pState; num_alignment_padding_bytes = mz_zip_writer_compute_padding_needed_for_file_alignment(pZip); // no zip64 support yet if ((pZip->m_total_files == 0xFFFF) || ((pZip->m_archive_size + num_alignment_padding_bytes + MZ_ZIP_LOCAL_DIR_HEADER_SIZE + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; cur_src_file_ofs = MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS); cur_dst_file_ofs = pZip->m_archive_size; if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; if (MZ_READ_LE32(pLocal_header) != MZ_ZIP_LOCAL_DIR_HEADER_SIG) return MZ_FALSE; cur_src_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; if (!mz_zip_writer_write_zeros(pZip, cur_dst_file_ofs, num_alignment_padding_bytes)) return MZ_FALSE; cur_dst_file_ofs += num_alignment_padding_bytes; local_dir_header_ofs = cur_dst_file_ofs; if (pZip->m_file_offset_alignment) { MZ_ASSERT((local_dir_header_ofs & (pZip->m_file_offset_alignment - 1)) == 0); } if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pLocal_header, MZ_ZIP_LOCAL_DIR_HEADER_SIZE) != MZ_ZIP_LOCAL_DIR_HEADER_SIZE) return MZ_FALSE; cur_dst_file_ofs += MZ_ZIP_LOCAL_DIR_HEADER_SIZE; n = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_EXTRA_LEN_OFS); comp_bytes_remaining = n + MZ_READ_LE32(pSrc_central_header + MZ_ZIP_CDH_COMPRESSED_SIZE_OFS); if (NULL == (pBuf = pZip->m_pAlloc( pZip->m_pAlloc_opaque, 1, (size_t)MZ_MAX(sizeof(mz_uint32) * 4, MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining))))) return MZ_FALSE; while (comp_bytes_remaining) { n = (mz_uint)MZ_MIN((mz_uint)MZ_ZIP_MAX_IO_BUF_SIZE, comp_bytes_remaining); if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_dst_file_ofs += n; comp_bytes_remaining -= n; } bit_flags = MZ_READ_LE16(pLocal_header + MZ_ZIP_LDH_BIT_FLAG_OFS); if (bit_flags & 8) { // Copy data descriptor if (pSource_zip->m_pRead(pSource_zip->m_pIO_opaque, cur_src_file_ofs, pBuf, sizeof(mz_uint32) * 4) != sizeof(mz_uint32) * 4) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } n = sizeof(mz_uint32) * ((MZ_READ_LE32(pBuf) == 0x08074b50) ? 4 : 3); if (pZip->m_pWrite(pZip->m_pIO_opaque, cur_dst_file_ofs, pBuf, n) != n) { pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); return MZ_FALSE; } cur_src_file_ofs += n; cur_dst_file_ofs += n; } pZip->m_pFree(pZip->m_pAlloc_opaque, pBuf); // no zip64 support yet if (cur_dst_file_ofs > 0xFFFFFFFF) return MZ_FALSE; orig_central_dir_size = pState->m_central_dir.m_size; memcpy(central_header, pSrc_central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE); MZ_WRITE_LE32(central_header + MZ_ZIP_CDH_LOCAL_HEADER_OFS, local_dir_header_ofs); if (!mz_zip_array_push_back(pZip, &pState->m_central_dir, central_header, MZ_ZIP_CENTRAL_DIR_HEADER_SIZE)) return MZ_FALSE; n = MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_FILENAME_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_EXTRA_LEN_OFS) + MZ_READ_LE16(pSrc_central_header + MZ_ZIP_CDH_COMMENT_LEN_OFS); if (!mz_zip_array_push_back( pZip, &pState->m_central_dir, pSrc_central_header + MZ_ZIP_CENTRAL_DIR_HEADER_SIZE, n)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } if (pState->m_central_dir.m_size > 0xFFFFFFFF) return MZ_FALSE; n = (mz_uint32)orig_central_dir_size; if (!mz_zip_array_push_back(pZip, &pState->m_central_dir_offsets, &n, 1)) { mz_zip_array_resize(pZip, &pState->m_central_dir, orig_central_dir_size, MZ_FALSE); return MZ_FALSE; } pZip->m_total_files++; pZip->m_archive_size = cur_dst_file_ofs; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_archive(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_uint64 central_dir_ofs, central_dir_size; mz_uint8 hdr[MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE]; if ((!pZip) || (!pZip->m_pState) || (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING)) return MZ_FALSE; pState = pZip->m_pState; // no zip64 support yet if ((pZip->m_total_files > 0xFFFF) || ((pZip->m_archive_size + pState->m_central_dir.m_size + MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIZE) > 0xFFFFFFFF)) return MZ_FALSE; central_dir_ofs = 0; central_dir_size = 0; if (pZip->m_total_files) { // Write central directory central_dir_ofs = pZip->m_archive_size; central_dir_size = pState->m_central_dir.m_size; pZip->m_central_directory_file_ofs = central_dir_ofs; if (pZip->m_pWrite(pZip->m_pIO_opaque, central_dir_ofs, pState->m_central_dir.m_p, (size_t)central_dir_size) != central_dir_size) return MZ_FALSE; pZip->m_archive_size += central_dir_size; } // Write end of central directory record MZ_CLEAR_OBJ(hdr); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_SIG_OFS, MZ_ZIP_END_OF_CENTRAL_DIR_HEADER_SIG); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_NUM_ENTRIES_ON_DISK_OFS, pZip->m_total_files); MZ_WRITE_LE16(hdr + MZ_ZIP_ECDH_CDIR_TOTAL_ENTRIES_OFS, pZip->m_total_files); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_SIZE_OFS, central_dir_size); MZ_WRITE_LE32(hdr + MZ_ZIP_ECDH_CDIR_OFS_OFS, central_dir_ofs); if (pZip->m_pWrite(pZip->m_pIO_opaque, pZip->m_archive_size, hdr, sizeof(hdr)) != sizeof(hdr)) return MZ_FALSE; #ifndef MINIZ_NO_STDIO if ((pState->m_pFile) && (MZ_FFLUSH(pState->m_pFile) == EOF)) return MZ_FALSE; #endif // #ifndef MINIZ_NO_STDIO pZip->m_archive_size += sizeof(hdr); pZip->m_zip_mode = MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED; return MZ_TRUE; } mz_bool mz_zip_writer_finalize_heap_archive(mz_zip_archive *pZip, void **pBuf, size_t *pSize) { if ((!pZip) || (!pZip->m_pState) || (!pBuf) || (!pSize)) return MZ_FALSE; if (pZip->m_pWrite != mz_zip_heap_write_func) return MZ_FALSE; if (!mz_zip_writer_finalize_archive(pZip)) return MZ_FALSE; *pBuf = pZip->m_pState->m_pMem; *pSize = pZip->m_pState->m_mem_size; pZip->m_pState->m_pMem = NULL; pZip->m_pState->m_mem_size = pZip->m_pState->m_mem_capacity = 0; return MZ_TRUE; } mz_bool mz_zip_writer_end(mz_zip_archive *pZip) { mz_zip_internal_state *pState; mz_bool status = MZ_TRUE; if ((!pZip) || (!pZip->m_pState) || (!pZip->m_pAlloc) || (!pZip->m_pFree) || ((pZip->m_zip_mode != MZ_ZIP_MODE_WRITING) && (pZip->m_zip_mode != MZ_ZIP_MODE_WRITING_HAS_BEEN_FINALIZED))) return MZ_FALSE; pState = pZip->m_pState; pZip->m_pState = NULL; mz_zip_array_clear(pZip, &pState->m_central_dir); mz_zip_array_clear(pZip, &pState->m_central_dir_offsets); mz_zip_array_clear(pZip, &pState->m_sorted_central_dir_offsets); #ifndef MINIZ_NO_STDIO if (pState->m_pFile) { MZ_FCLOSE(pState->m_pFile); pState->m_pFile = NULL; } #endif // #ifndef MINIZ_NO_STDIO if ((pZip->m_pWrite == mz_zip_heap_write_func) && (pState->m_pMem)) { pZip->m_pFree(pZip->m_pAlloc_opaque, pState->m_pMem); pState->m_pMem = NULL; } pZip->m_pFree(pZip->m_pAlloc_opaque, pState); pZip->m_zip_mode = MZ_ZIP_MODE_INVALID; return status; } #ifndef MINIZ_NO_STDIO mz_bool mz_zip_add_mem_to_archive_file_in_place( const char *pZip_filename, const char *pArchive_name, const void *pBuf, size_t buf_size, const void *pComment, mz_uint16 comment_size, mz_uint level_and_flags) { mz_bool status, created_new_archive = MZ_FALSE; mz_zip_archive zip_archive; struct MZ_FILE_STAT_STRUCT file_stat; MZ_CLEAR_OBJ(zip_archive); if ((int)level_and_flags < 0) level_and_flags = MZ_DEFAULT_LEVEL; if ((!pZip_filename) || (!pArchive_name) || ((buf_size) && (!pBuf)) || ((comment_size) && (!pComment)) || ((level_and_flags & 0xF) > MZ_UBER_COMPRESSION)) return MZ_FALSE; if (!mz_zip_writer_validate_archive_name(pArchive_name)) return MZ_FALSE; if (MZ_FILE_STAT(pZip_filename, &file_stat) != 0) { // Create a new archive. if (!mz_zip_writer_init_file(&zip_archive, pZip_filename, 0)) return MZ_FALSE; created_new_archive = MZ_TRUE; } else { // Append to an existing archive. if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, level_and_flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return MZ_FALSE; if (!mz_zip_writer_init_from_reader(&zip_archive, pZip_filename)) { mz_zip_reader_end(&zip_archive); return MZ_FALSE; } } status = mz_zip_writer_add_mem_ex(&zip_archive, pArchive_name, pBuf, buf_size, pComment, comment_size, level_and_flags, 0, 0); // Always finalize, even if adding failed for some reason, so we have a valid // central directory. (This may not always succeed, but we can try.) if (!mz_zip_writer_finalize_archive(&zip_archive)) status = MZ_FALSE; if (!mz_zip_writer_end(&zip_archive)) status = MZ_FALSE; if ((!status) && (created_new_archive)) { // It's a new archive and something went wrong, so just delete it. int ignoredStatus = MZ_DELETE_FILE(pZip_filename); (void)ignoredStatus; } return status; } void *mz_zip_extract_archive_file_to_heap(const char *pZip_filename, const char *pArchive_name, size_t *pSize, mz_uint flags) { int file_index; mz_zip_archive zip_archive; void *p = NULL; if (pSize) *pSize = 0; if ((!pZip_filename) || (!pArchive_name)) return NULL; MZ_CLEAR_OBJ(zip_archive); if (!mz_zip_reader_init_file( &zip_archive, pZip_filename, flags | MZ_ZIP_FLAG_DO_NOT_SORT_CENTRAL_DIRECTORY)) return NULL; if ((file_index = mz_zip_reader_locate_file(&zip_archive, pArchive_name, NULL, flags)) >= 0) p = mz_zip_reader_extract_to_heap(&zip_archive, file_index, pSize, flags); mz_zip_reader_end(&zip_archive); return p; } #endif // #ifndef MINIZ_NO_STDIO #endif // #ifndef MINIZ_NO_ARCHIVE_WRITING_APIS #endif // #ifndef MINIZ_NO_ARCHIVE_APIS #ifdef __cplusplus } #endif #endif // MINIZ_HEADER_FILE_ONLY /* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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. For more information, please refer to <http://unlicense.org/> */ // ---------------------- end of miniz ---------------------------------------- #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef _MSC_VER #pragma warning(pop) #endif } #else // Reuse MINIZ_LITTE_ENDIAN macro #if defined(__sparcv9) // Big endian #else #if (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) || MINIZ_X86_OR_X64_CPU // Set MINIZ_LITTLE_ENDIAN to 1 if the processor is little endian. #define MINIZ_LITTLE_ENDIAN 1 #endif #endif #endif // TINYEXR_USE_MINIZ // static bool IsBigEndian(void) { // union { // unsigned int i; // char c[4]; // } bint = {0x01020304}; // // return bint.c[0] == 1; //} static const int kEXRVersionSize = 8; static void swap2(unsigned short *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned short tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[1]; dst[1] = src[0]; #endif } static void swap4(unsigned int *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else unsigned int tmp = *val; unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[3]; dst[1] = src[2]; dst[2] = src[1]; dst[3] = src[0]; #endif } static void swap8(tinyexr::tinyexr_uint64 *val) { #ifdef MINIZ_LITTLE_ENDIAN (void)val; #else tinyexr::tinyexr_uint64 tmp = (*val); unsigned char *dst = reinterpret_cast<unsigned char *>(val); unsigned char *src = reinterpret_cast<unsigned char *>(&tmp); dst[0] = src[7]; dst[1] = src[6]; dst[2] = src[5]; dst[3] = src[4]; dst[4] = src[3]; dst[5] = src[2]; dst[6] = src[1]; dst[7] = src[0]; #endif } // https://gist.github.com/rygorous/2156668 // Reuse MINIZ_LITTLE_ENDIAN flag from miniz. union FP32 { unsigned int u; float f; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 23; unsigned int Exponent : 8; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 8; unsigned int Mantissa : 23; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wpadded" #endif union FP16 { unsigned short u; struct { #if MINIZ_LITTLE_ENDIAN unsigned int Mantissa : 10; unsigned int Exponent : 5; unsigned int Sign : 1; #else unsigned int Sign : 1; unsigned int Exponent : 5; unsigned int Mantissa : 10; #endif } s; }; #ifdef __clang__ #pragma clang diagnostic pop #endif static FP32 half_to_float(FP16 h) { static const FP32 magic = {113 << 23}; static const unsigned int shifted_exp = 0x7c00 << 13; // exponent mask after shift FP32 o; o.u = (h.u & 0x7fffU) << 13U; // exponent/mantissa bits unsigned int exp_ = shifted_exp & o.u; // just the exponent o.u += (127 - 15) << 23; // exponent adjust // handle exponent special cases if (exp_ == shifted_exp) // Inf/NaN? o.u += (128 - 16) << 23; // extra exp adjust else if (exp_ == 0) // Zero/Denormal? { o.u += 1 << 23; // extra exp adjust o.f -= magic.f; // renormalize } o.u |= (h.u & 0x8000U) << 16U; // sign bit return o; } static FP16 float_to_half_full(FP32 f) { FP16 o = {0}; // Based on ISPC reference code (with minor modifications) if (f.s.Exponent == 0) // Signed zero/denormal (which will underflow) o.s.Exponent = 0; else if (f.s.Exponent == 255) // Inf or NaN (all exponent bits set) { o.s.Exponent = 31; o.s.Mantissa = f.s.Mantissa ? 0x200 : 0; // NaN->qNaN and Inf->Inf } else // Normalized number { // Exponent unbias the single, then bias the halfp int newexp = f.s.Exponent - 127 + 15; if (newexp >= 31) // Overflow, return signed infinity o.s.Exponent = 31; else if (newexp <= 0) // Underflow { if ((14 - newexp) <= 24) // Mantissa might be non-zero { unsigned int mant = f.s.Mantissa | 0x800000; // Hidden 1 bit o.s.Mantissa = mant >> (14 - newexp); if ((mant >> (13 - newexp)) & 1) // Check for rounding o.u++; // Round, might overflow into exp bit, but this is OK } } else { o.s.Exponent = static_cast<unsigned int>(newexp); o.s.Mantissa = f.s.Mantissa >> 13; if (f.s.Mantissa & 0x1000) // Check for rounding o.u++; // Round, might overflow to inf, this is OK } } o.s.Sign = f.s.Sign; return o; } // NOTE: From OpenEXR code // #define IMF_INCREASING_Y 0 // #define IMF_DECREASING_Y 1 // #define IMF_RAMDOM_Y 2 // // #define IMF_NO_COMPRESSION 0 // #define IMF_RLE_COMPRESSION 1 // #define IMF_ZIPS_COMPRESSION 2 // #define IMF_ZIP_COMPRESSION 3 // #define IMF_PIZ_COMPRESSION 4 // #define IMF_PXR24_COMPRESSION 5 // #define IMF_B44_COMPRESSION 6 // #define IMF_B44A_COMPRESSION 7 #ifdef __clang__ #pragma clang diagnostic push #if __has_warning("-Wzero-as-null-pointer-constant") #pragma clang diagnostic ignored "-Wzero-as-null-pointer-constant" #endif #endif static const char *ReadString(std::string *s, const char *ptr, size_t len) { // Read untile NULL(\0). const char *p = ptr; const char *q = ptr; while ((size_t(q - ptr) < len) && (*q) != 0) { q++; } if (size_t(q - ptr) >= len) { (*s) = std::string(); return NULL; } (*s) = std::string(p, q); return q + 1; // skip '\0' } static bool ReadAttribute(std::string *name, std::string *type, std::vector<unsigned char> *data, size_t *marker_size, const char *marker, size_t size) { size_t name_len = strnlen(marker, size); if (name_len == size) { // String does not have a terminating character. return false; } *name = std::string(marker, name_len); marker += name_len + 1; size -= name_len + 1; size_t type_len = strnlen(marker, size); if (type_len == size) { return false; } *type = std::string(marker, type_len); marker += type_len + 1; size -= type_len + 1; if (size < sizeof(uint32_t)) { return false; } uint32_t data_len; memcpy(&data_len, marker, sizeof(uint32_t)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len == 0) { return false; } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; struct HeaderInfo { std::vector<tinyexr::ChannelInfo> channels; std::vector<EXRAttribute> attributes; int data_window[4]; int line_order; int display_window[4]; float screen_window_center[2]; float screen_window_width; float pixel_aspect_ratio; int chunk_count; // Tiled format int tile_size_x; int tile_size_y; int tile_level_mode; int tile_rounding_mode; unsigned int header_len; int compression_type; void clear() { channels.clear(); attributes.clear(); data_window[0] = 0; data_window[1] = 0; data_window[2] = 0; data_window[3] = 0; line_order = 0; display_window[0] = 0; display_window[1] = 0; display_window[2] = 0; display_window[3] = 0; screen_window_center[0] = 0.0f; screen_window_center[1] = 0.0f; screen_window_width = 0.0f; pixel_aspect_ratio = 0.0f; chunk_count = 0; // Tiled format tile_size_x = 0; tile_size_y = 0; tile_level_mode = 0; tile_rounding_mode = 0; header_len = 0; compression_type = 0; } }; static bool ReadChannelInfo(std::vector<ChannelInfo> &channels, const std::vector<unsigned char> &data) { const char *p = reinterpret_cast<const char *>(&data.at(0)); for (;;) { if ((*p) == 0) { break; } ChannelInfo info; tinyexr_int64 data_len = static_cast<tinyexr_int64>(data.size()) - (p - reinterpret_cast<const char *>(data.data())); if (data_len < 0) { return false; } p = ReadString( &info.name, p, size_t(data_len)); if ((p == NULL) && (info.name.empty())) { // Buffer overrun. Issue #51. return false; } memcpy(&info.pixel_type, p, sizeof(int)); p += 4; info.p_linear = static_cast<unsigned char>(p[0]); // uchar p += 1 + 3; // reserved: uchar[3] memcpy(&info.x_sampling, p, sizeof(int)); // int p += 4; memcpy(&info.y_sampling, p, sizeof(int)); // int p += 4; tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info.y_sampling)); channels.push_back(info); } return true; } static void WriteChannelInfo(std::vector<unsigned char> &data, const std::vector<ChannelInfo> &channels) { size_t sz = 0; // Calculate total size. for (size_t c = 0; c < channels.size(); c++) { sz += strlen(channels[c].name.c_str()) + 1; // +1 for \0 sz += 16; // 4 * int } data.resize(sz + 1); unsigned char *p = &data.at(0); for (size_t c = 0; c < channels.size(); c++) { memcpy(p, channels[c].name.c_str(), strlen(channels[c].name.c_str())); p += strlen(channels[c].name.c_str()); (*p) = '\0'; p++; int pixel_type = channels[c].pixel_type; int x_sampling = channels[c].x_sampling; int y_sampling = channels[c].y_sampling; tinyexr::swap4(reinterpret_cast<unsigned int *>(&pixel_type)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x_sampling)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y_sampling)); memcpy(p, &pixel_type, sizeof(int)); p += sizeof(int); (*p) = channels[c].p_linear; p += 4; memcpy(p, &x_sampling, sizeof(int)); p += sizeof(int); memcpy(p, &y_sampling, sizeof(int)); p += sizeof(int); } (*p) = '\0'; } static void CompressZip(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } #if TINYEXR_USE_MINIZ // // Compress the data using miniz // miniz::mz_ulong outSize = miniz::mz_compressBound(src_size); int ret = miniz::mz_compress( dst, &outSize, static_cast<const unsigned char *>(&tmpBuf.at(0)), src_size); assert(ret == miniz::MZ_OK); (void)ret; compressedSize = outSize; #else uLong outSize = compressBound(static_cast<uLong>(src_size)); int ret = compress(dst, &outSize, static_cast<const Bytef *>(&tmpBuf.at(0)), src_size); assert(ret == Z_OK); compressedSize = outSize; #endif // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static bool DecompressZip(unsigned char *dst, unsigned long *uncompressed_size /* inout */, const unsigned char *src, unsigned long src_size) { if ((*uncompressed_size) == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return true; } std::vector<unsigned char> tmpBuf(*uncompressed_size); #if TINYEXR_USE_MINIZ int ret = miniz::mz_uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (miniz::MZ_OK != ret) { return false; } #else int ret = uncompress(&tmpBuf.at(0), uncompressed_size, src, src_size); if (Z_OK != ret) { return false; } #endif // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfZipCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + (*uncompressed_size); while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (*uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + (*uncompressed_size); for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } return true; } // RLE code from OpenEXR -------------------------------------- #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wsign-conversion" #endif #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 4204) // nonstandard extension used : non-constant // aggregate initializer (also supported by GNU // C and C99, so no big deal) #pragma warning(disable : 4244) // 'initializing': conversion from '__int64' to // 'int', possible loss of data #pragma warning( \ disable : 4267) // 'argument': conversion from '__int64' to 'int', // possible loss of data #pragma warning(disable : 4996) // 'strdup': The POSIX name for this item is // deprecated. Instead, use the ISO C and C++ // conformant name: _strdup. #endif const int MIN_RUN_LENGTH = 3; const int MAX_RUN_LENGTH = 127; // // Compress an array of bytes, using run-length encoding, // and return the length of the compressed data. // static int rleCompress(int inLength, const char in[], signed char out[]) { const char *inEnd = in + inLength; const char *runStart = in; const char *runEnd = in + 1; signed char *outWrite = out; while (runStart < inEnd) { while (runEnd < inEnd && *runStart == *runEnd && runEnd - runStart - 1 < MAX_RUN_LENGTH) { ++runEnd; } if (runEnd - runStart >= MIN_RUN_LENGTH) { // // Compressable run // *outWrite++ = static_cast<char>(runEnd - runStart) - 1; *outWrite++ = *(reinterpret_cast<const signed char *>(runStart)); runStart = runEnd; } else { // // Uncompressable run // while (runEnd < inEnd && ((runEnd + 1 >= inEnd || *runEnd != *(runEnd + 1)) || (runEnd + 2 >= inEnd || *(runEnd + 1) != *(runEnd + 2))) && runEnd - runStart < MAX_RUN_LENGTH) { ++runEnd; } *outWrite++ = static_cast<char>(runStart - runEnd); while (runStart < runEnd) { *outWrite++ = *(reinterpret_cast<const signed char *>(runStart++)); } } ++runEnd; } return static_cast<int>(outWrite - out); } // // Uncompress an array of bytes compressed with rleCompress(). // Returns the length of the oncompressed data, or 0 if the // length of the uncompressed data would be more than maxLength. // static int rleUncompress(int inLength, int maxLength, const signed char in[], char out[]) { char *outStart = out; while (inLength > 0) { if (*in < 0) { int count = -(static_cast<int>(*in++)); inLength -= count + 1; if (0 > (maxLength -= count)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static void DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); assert(ret == static_cast<int>(uncompressed_size)); (void)ret; // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // int hlink[HUF_ENCSIZE]; long long *fHeap[HUF_ENCSIZE]; *im = 0; while (!frq[*im]) (*im)++; int nf = 0; for (int i = *im; i < HUF_ENCSIZE; i++) { hlink[i] = i; if (frq[i]) { fHeap[nf] = &frq[i]; nf++; *iM = i; } } // // Add a pseudo-symbol, with a frequency count of 1, to frq; // adjust the fHeap and hlink array accordingly. Function // hufEncode() uses the pseudo-symbol for run-length encoding. // (*iM)++; frq[*iM] = 1; fHeap[nf] = &frq[*iM]; nf++; // // Build an array, scode, such that scode[i] contains the number // of bits assigned to symbol i. Conceptually this is done by // constructing a tree whose leaves are the symbols with non-zero // frequency: // // Make a heap that contains all symbols with a non-zero frequency, // with the least frequent symbol on top. // // Repeat until only one symbol is left on the heap: // // Take the two least frequent symbols off the top of the heap. // Create a new node that has first two nodes as children, and // whose frequency is the sum of the frequencies of the first // two nodes. Put the new node back into the heap. // // The last node left on the heap is the root of the tree. For each // leaf node, the distance between the root and the leaf is the length // of the code for the corresponding symbol. // // The loop below doesn't actually build the tree; instead we compute // the distances of the leaves from the root on the fly. When a new // node is added to the heap, then that node's descendants are linked // into a single linear list that starts at the new node, and the code // lengths of the descendants (that is, their distance from the root // of the tree) are incremented by one. // std::make_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); long long scode[HUF_ENCSIZE]; memset(scode, 0, sizeof(long long) * HUF_ENCSIZE); while (nf > 1) { // // Find the indices, mm and m, of the two smallest non-zero frq // values in fHeap, add the smallest frq to the second-smallest // frq, and remove the smallest frq value from fHeap. // int mm = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); --nf; int m = fHeap[0] - frq; std::pop_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); frq[m] += frq[mm]; std::push_heap(&fHeap[0], &fHeap[nf], FHeapCompare()); // // The entries in scode are linked into lists with the // entries in hlink serving as "next" pointers and with // the end of a list marked by hlink[j] == j. // // Traverse the lists that start at scode[m] and scode[mm]. // For each element visited, increment the length of the // corresponding code by one bit. (If we visit scode[j] // during the traversal, then the code for symbol j becomes // one bit longer.) // // Merge the lists that start at scode[m] and scode[mm] // into a single list that starts at scode[m]. // // // Add a bit to all codes in the first list. // for (int j = m;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) { // // Merge the two lists. // hlink[j] = mm; break; } } // // Add a bit to all codes in the second list // for (int j = mm;; j = hlink[j]) { scode[j]++; assert(scode[j] <= 58); if (hlink[j] == j) break; } } // // Build a canonical Huffman code table, replacing the code // lengths in scode with (code, code length) pairs. Copy the // code table from scode into frq. // hufCanonicalCodeTable(scode); memcpy(frq, scode, sizeof(long long) * HUF_ENCSIZE); } // // Pack an encoding table: // - only code lengths, not actual codes, are stored // - runs of zeroes are compressed as follows: // // unpacked packed // -------------------------------- // 1 zero 0 (6 bits) // 2 zeroes 59 // 3 zeroes 60 // 4 zeroes 61 // 5 zeroes 62 // n zeroes (6 or more) 63 n-6 (6 + 8 bits) // const int SHORT_ZEROCODE_RUN = 59; const int LONG_ZEROCODE_RUN = 63; const int SHORTEST_LONG_RUN = 2 + LONG_ZEROCODE_RUN - SHORT_ZEROCODE_RUN; const int LONGEST_LONG_RUN = 255 + SHORTEST_LONG_RUN; static void hufPackEncTable( const long long *hcode, // i : encoding table [HUF_ENCSIZE] int im, // i : min hcode index int iM, // i : max hcode index char **pcode) // o: ptr to packed table (updated) { char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { int l = hufLength(hcode[im]); if (l == 0) { int zerun = 1; while ((im < iM) && (zerun < LONGEST_LONG_RUN)) { if (hufLength(hcode[im + 1]) > 0) break; im++; zerun++; } if (zerun >= 2) { if (zerun >= SHORTEST_LONG_RUN) { outputBits(6, LONG_ZEROCODE_RUN, c, lc, p); outputBits(8, zerun - SHORTEST_LONG_RUN, c, lc, p); } else { outputBits(6, SHORT_ZEROCODE_RUN + zerun - 2, c, lc, p); } continue; } } outputBits(6, l, c, lc, p); } if (lc > 0) *p++ = (unsigned char)(c << (8 - lc)); *pcode = p; } // // Unpack an encoding table packed by hufPackEncTable(): // static bool hufUnpackEncTable( const char **pcode, // io: ptr to packed table (updated) int ni, // i : input size (in bytes) int im, // i : min hcode index int iM, // i : max hcode index long long *hcode) // o: encoding table [HUF_ENCSIZE] { memset(hcode, 0, sizeof(long long) * HUF_ENCSIZE); const char *p = *pcode; long long c = 0; int lc = 0; for (; im <= iM; im++) { if (p - *pcode > ni) { return false; } long long l = hcode[im] = getBits(6, c, lc, p); // code length if (l == (long long)LONG_ZEROCODE_RUN) { if (p - *pcode > ni) { return false; } int zerun = getBits(8, c, lc, p) + SHORTEST_LONG_RUN; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } else if (l >= (long long)SHORT_ZEROCODE_RUN) { int zerun = l - SHORT_ZEROCODE_RUN + 2; if (im + zerun > iM + 1) { return false; } while (zerun--) hcode[im++] = 0; im--; } } *pcode = const_cast<char *>(p); hufCanonicalCodeTable(hcode); return true; } // // DECODING TABLE BUILDING // // // Clear a newly allocated decoding table so that it contains only zeroes. // static void hufClearDecTable(HufDec *hdecod) // io: (allocated by caller) // decoding table [HUF_DECSIZE] { for (int i = 0; i < HUF_DECSIZE; i++) { hdecod[i].len = 0; hdecod[i].lit = 0; hdecod[i].p = NULL; } // memset(hdecod, 0, sizeof(HufDec) * HUF_DECSIZE); } // // Build a decoding hash table based on the encoding table hcode: // - short codes (<= HUF_DECBITS) are resolved with a single table access; // - long code entry allocations are not optimized, because long codes are // unfrequent; // - decoding tables are used by hufDecode(); // static bool hufBuildDecTable(const long long *hcode, // i : encoding table int im, // i : min index in hcode int iM, // i : max index in hcode HufDec *hdecod) // o: (allocated by caller) // decoding table [HUF_DECSIZE] { // // Init hashtable & loop on all codes. // Assumes that hufClearDecTable(hdecod) has already been called. // for (; im <= iM; im++) { long long c = hufCode(hcode[im]); int l = hufLength(hcode[im]); if (c >> l) { // // Error: c is supposed to be an l-bit code, // but c contains a value that is greater // than the largest l-bit number. // // invalidTableEntry(); return false; } if (l > HUF_DECBITS) { // // Long code: add a secondary entry // HufDec *pl = hdecod + (c >> (l - HUF_DECBITS)); if (pl->len) { // // Error: a short code has already // been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->lit++; if (pl->p) { int *p = pl->p; pl->p = new int[pl->lit]; for (int i = 0; i < pl->lit - 1; ++i) pl->p[i] = p[i]; delete[] p; } else { pl->p = new int[1]; } pl->p[pl->lit - 1] = im; } else if (l) { // // Short code: init all primary entries // HufDec *pl = hdecod + (c << (HUF_DECBITS - l)); for (long long i = 1ULL << (HUF_DECBITS - l); i > 0; i--, pl++) { if (pl->len || pl->p) { // // Error: a short code or a long code has // already been stored in table entry *pl. // // invalidTableEntry(); return false; } pl->len = l; pl->lit = im; } } } return true; } // // Free the long code entries of a decoding table built by hufBuildDecTable() // static void hufFreeDecTable(HufDec *hdecod) // io: Decoding table { for (int i = 0; i < HUF_DECSIZE; i++) { if (hdecod[i].p) { delete[] hdecod[i].p; hdecod[i].p = 0; } } } // // ENCODING // inline void outputCode(long long code, long long &c, int &lc, char *&out) { outputBits(hufLength(code), hufCode(code), c, lc, out); } inline void sendCode(long long sCode, int runCount, long long runCode, long long &c, int &lc, char *&out) { // // Output a run of runCount instances of the symbol sCount. // Output the symbols explicitly, or if that is shorter, output // the sCode symbol once followed by a runCode symbol and runCount // expressed as an 8-bit number. // if (hufLength(sCode) + hufLength(runCode) + 8 < hufLength(sCode) * runCount) { outputCode(sCode, c, lc, out); outputCode(runCode, c, lc, out); outputBits(8, runCount, c, lc, out); } else { while (runCount-- >= 0) outputCode(sCode, c, lc, out); } } // // Encode (compress) ni values based on the Huffman encoding table hcode: // static int hufEncode // return: output size (in bits) (const long long *hcode, // i : encoding table const unsigned short *in, // i : uncompressed input buffer const int ni, // i : input buffer size (in bytes) int rlc, // i : rl code char *out) // o: compressed output buffer { char *outStart = out; long long c = 0; // bits not yet written to out int lc = 0; // number of valid bits in c (LSB) int s = in[0]; int cs = 0; // // Loop on input values // for (int i = 1; i < ni; i++) { // // Count same values or send code // if (s == in[i] && cs < 255) { cs++; } else { sendCode(hcode[s], cs, hcode[rlc], c, lc, out); cs = 0; } s = in[i]; } // // Send remaining code // sendCode(hcode[s], cs, hcode[rlc], c, lc, out); if (lc) *out = (c << (8 - lc)) & 0xff; return (out - outStart) * 8 + lc; } // // DECODING // // // In order to force the compiler to inline them, // getChar() and getCode() are implemented as macros // instead of "inline" functions. // #define getChar(c, lc, in) \ { \ c = (c << 8) | *(unsigned char *)(in++); \ lc += 8; \ } #define getCode(po, rlc, c, lc, in, out, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } // // Decode (uncompress) ni bits based on encoding & decoding tables: // static bool hufDecode(const long long *hcode, // i : encoding table const HufDec *hdecod, // i : decoding table const char *in, // i : compressed input buffer int ni, // i : input size (in bits) int rlc, // i : run-length code int no, // i : expected output size (in bytes) unsigned short *out) // o: uncompressed output buffer { long long c = 0; int lc = 0; unsigned short *outb = out; unsigned short *oe = out + no; const char *ie = in + (ni + 7) / 8; // input byte size // // Loop on input bytes // while (in < ie) { getChar(c, lc, in); // // Access decoding table // while (lc >= HUF_DECBITS) { const HufDec pl = hdecod[(c >> (lc - HUF_DECBITS)) & HUF_DECMASK]; if (pl.len) { // // Get short code // lc -= pl.len; getCode(pl.lit, rlc, c, lc, in, out, oe); } else { if (!pl.p) { return false; } // invalidCode(); // wrong code // // Search long code // int j; for (j = 0; j < pl.lit; j++) { int l = hufLength(hcode[pl.p[j]]); while (lc < l && in < ie) // get more bits getChar(c, lc, in); if (lc >= l) { if (hufCode(hcode[pl.p[j]]) == ((c >> (lc - l)) & (((long long)(1) << l) - 1))) { // // Found : get long code // lc -= l; getCode(pl.p[j], rlc, c, lc, in, out, oe); break; } } } if (j == pl.lit) { return false; // invalidCode(); // Not found } } } } // // Get remaining (short) codes // int i = (8 - ni) & 7; c >>= i; lc -= i; while (lc > 0) { const HufDec pl = hdecod[(c << (HUF_DECBITS - lc)) & HUF_DECMASK]; if (pl.len) { lc -= pl.len; getCode(pl.lit, rlc, c, lc, in, out, oe); } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(long long freq[HUF_ENCSIZE], const unsigned short data[/*n*/], int n) { for (int i = 0; i < HUF_ENCSIZE; ++i) freq[i] = 0; for (int i = 0; i < n; ++i) ++freq[data[i]]; } static void writeUInt(char buf[4], unsigned int i) { unsigned char *b = (unsigned char *)buf; b[0] = i; b[1] = i >> 8; b[2] = i >> 16; b[3] = i >> 24; } static unsigned int readUInt(const char buf[4]) { const unsigned char *b = (const unsigned char *)buf; return (b[0] & 0x000000ff) | ((b[1] << 8) & 0x0000ff00) | ((b[2] << 16) & 0x00ff0000) | ((b[3] << 24) & 0xff000000); } // // EXTERNAL INTERFACE // static int hufCompress(const unsigned short raw[], int nRaw, char compressed[]) { if (nRaw == 0) return 0; long long freq[HUF_ENCSIZE]; countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq, &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq, im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq, raw, nRaw, iM, dataStart); int data_length = (nBits + 7) / 8; writeUInt(compressed, im); writeUInt(compressed + 4, iM); writeUInt(compressed + 8, tableLength); writeUInt(compressed + 12, nBits); writeUInt(compressed + 16, 0); // room for future extensions return dataStart + data_length - compressed; } static bool hufUncompress(const char compressed[], int nCompressed, unsigned short raw[], int nRaw) { if (nCompressed == 0) { if (nRaw != 0) return false; return false; } int im = readUInt(compressed); int iM = readUInt(compressed + 4); // int tableLength = readUInt (compressed + 8); int nBits = readUInt(compressed + 12); if (im < 0 || im >= HUF_ENCSIZE || iM < 0 || iM >= HUF_ENCSIZE) return false; const char *ptr = compressed + 20; // // Fast decoder needs at least 2x64-bits of compressed data, and // needs to be run-able on this platform. Otherwise, fall back // to the original decoder // // if (FastHufDecoder::enabled() && nBits > 128) //{ // FastHufDecoder fhd (ptr, nCompressed - (ptr - compressed), im, iM, iM); // fhd.decode ((unsigned char*)ptr, nBits, raw, nRaw); //} // else { std::vector<long long> freq(HUF_ENCSIZE); std::vector<HufDec> hdec(HUF_DECSIZE); hufClearDecTable(&hdec.at(0)); hufUnpackEncTable(&ptr, nCompressed - (ptr - compressed), im, iM, &freq.at(0)); { if (nBits > 8 * (nCompressed - (ptr - compressed))) { return false; } hufBuildDecTable(&freq.at(0), im, iM, &hdec.at(0)); hufDecode(&freq.at(0), &hdec.at(0), ptr, nBits, iM, nRaw, raw); } // catch (...) //{ // hufFreeDecTable (hdec); // throw; //} hufFreeDecTable(&hdec.at(0)); } return true; } // // Functions to compress the range of values in the pixel data // const int USHORT_RANGE = (1 << 16); const int BITMAP_SIZE = (USHORT_RANGE >> 3); static void bitmapFromData(const unsigned short data[/*nData*/], int nData, unsigned char bitmap[BITMAP_SIZE], unsigned short &minNonZero, unsigned short &maxNonZero) { for (int i = 0; i < BITMAP_SIZE; ++i) bitmap[i] = 0; for (int i = 0; i < nData; ++i) bitmap[data[i] >> 3] |= (1 << (data[i] & 7)); bitmap[0] &= ~1; // zero is not explicitly stored in // the bitmap; we assume that the // data always contain zeroes minNonZero = BITMAP_SIZE - 1; maxNonZero = 0; for (int i = 0; i < BITMAP_SIZE; ++i) { if (bitmap[i]) { if (minNonZero > i) minNonZero = i; if (maxNonZero < i) maxNonZero = i; } } } static unsigned short forwardLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[i] = k++; else lut[i] = 0; } return k - 1; // maximum value stored in lut[], } // i.e. number of ones in bitmap minus 1 static unsigned short reverseLutFromBitmap( const unsigned char bitmap[BITMAP_SIZE], unsigned short lut[USHORT_RANGE]) { int k = 0; for (int i = 0; i < USHORT_RANGE; ++i) { if ((i == 0) || (bitmap[i >> 3] & (1 << (i & 7)))) lut[k++] = i; } int n = k - 1; while (k < USHORT_RANGE) lut[k++] = 0; return n; // maximum k where lut[k] is non-zero, } // i.e. number of ones in bitmap minus 1 static void applyLut(const unsigned short lut[USHORT_RANGE], unsigned short data[/*nData*/], int nData) { for (int i = 0; i < nData; ++i) data[i] = lut[data[i]]; } #ifdef __clang__ #pragma clang diagnostic pop #endif // __clang__ #ifdef _MSC_VER #pragma warning(pop) #endif static bool CompressPiz(unsigned char *outPtr, unsigned int *outSize, const unsigned char *inPtr, size_t inSize, const std::vector<ChannelInfo> &channelInfo, int data_width, int num_lines) { unsigned char bitmap[BITMAP_SIZE]; unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif // Assume `inSize` is multiple of 2 or 4. std::vector<unsigned short> tmpBuffer(inSize / sizeof(unsigned short)); std::vector<PIZChannelData> channelData(channelInfo.size()); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t c = 0; c < channelData.size(); c++) { PIZChannelData &cd = channelData[c]; cd.start = tmpBufferEnd; cd.end = cd.start; cd.nx = data_width; cd.ny = num_lines; // cd.ys = c.channel().ySampling; size_t pixelSize = sizeof(int); // UINT and FLOAT if (channelInfo[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } cd.size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += cd.nx * cd.ny * cd.size; } const unsigned char *ptr = inPtr; for (int y = 0; y < num_lines; ++y) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(cd.end, ptr, n * sizeof(unsigned short)); ptr += n * sizeof(unsigned short); cd.end += n; } } bitmapFromData(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), bitmap, minNonZero, maxNonZero); unsigned short lut[USHORT_RANGE]; unsigned short maxValue = forwardLutFromBitmap(bitmap, lut); applyLut(lut, &tmpBuffer.at(0), static_cast<int>(tmpBuffer.size())); // // Store range compression info in _outBuffer // char *buf = reinterpret_cast<char *>(outPtr); memcpy(buf, &minNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); memcpy(buf, &maxNonZero, sizeof(unsigned short)); buf += sizeof(unsigned short); if (minNonZero <= maxNonZero) { memcpy(buf, reinterpret_cast<char *>(&bitmap[0] + minNonZero), maxNonZero - minNonZero + 1); buf += maxNonZero - minNonZero + 1; } // // Apply wavelet encoding // for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Encode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Apply Huffman encoding; append the result to _outBuffer // // length header(4byte), then huff data. Initialize length header with zero, // then later fill it by `length`. char *lengthPtr = buf; int zero = 0; memcpy(buf, &zero, sizeof(int)); buf += sizeof(int); int length = hufCompress(&tmpBuffer.at(0), static_cast<int>(tmpBuffer.size()), buf); memcpy(lengthPtr, &length, sizeof(int)); (*outSize) = static_cast<unsigned int>( (reinterpret_cast<unsigned char *>(buf) - outPtr) + static_cast<unsigned int>(length)); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if ((*outSize) >= inSize) { (*outSize) = static_cast<unsigned int>(inSize); memcpy(outPtr, inPtr, inSize); } return true; } static bool DecompressPiz(unsigned char *outPtr, const unsigned char *inPtr, size_t tmpBufSize, size_t inLen, int num_channels, const EXRChannelInfo *channels, int data_width, int num_lines) { if (inLen == tmpBufSize) { // Data is not compressed(Issue 40). memcpy(outPtr, inPtr, inLen); return true; } unsigned char bitmap[BITMAP_SIZE]; unsigned short minNonZero; unsigned short maxNonZero; #if !MINIZ_LITTLE_ENDIAN // @todo { PIZ compression on BigEndian architecture. } assert(0); return false; #endif memset(bitmap, 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); ptr += 4; if (maxNonZero >= BITMAP_SIZE) { return false; } if (minNonZero <= maxNonZero) { memcpy(reinterpret_cast<char *>(&bitmap[0] + minNonZero), ptr, maxNonZero - minNonZero + 1); ptr += maxNonZero - minNonZero + 1; } unsigned short lut[USHORT_RANGE]; memset(lut, 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap, lut); // // Huffman decoding // int length; length = *(reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); // // Wavelet decoding // std::vector<PIZChannelData> channelData(static_cast<size_t>(num_channels)); unsigned short *tmpBufferEnd = &tmpBuffer.at(0); for (size_t i = 0; i < static_cast<size_t>(num_channels); ++i) { const EXRChannelInfo &chan = channels[i]; size_t pixelSize = sizeof(int); // UINT and FLOAT if (chan.pixel_type == TINYEXR_PIXELTYPE_HALF) { pixelSize = sizeof(short); } channelData[i].start = tmpBufferEnd; channelData[i].end = channelData[i].start; channelData[i].nx = data_width; channelData[i].ny = num_lines; // channelData[i].ys = 1; channelData[i].size = static_cast<int>(pixelSize / sizeof(short)); tmpBufferEnd += channelData[i].nx * channelData[i].ny * channelData[i].size; } for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; for (int j = 0; j < cd.size; ++j) { wav2Decode(cd.start + j, cd.nx, cd.size, cd.ny, cd.nx * cd.size, maxValue); } } // // Expand the pixel data to their original range // applyLut(lut, &tmpBuffer.at(0), static_cast<int>(tmpBufSize)); for (int y = 0; y < num_lines; y++) { for (size_t i = 0; i < channelData.size(); ++i) { PIZChannelData &cd = channelData[i]; // if (modp (y, cd.ys) != 0) // continue; size_t n = static_cast<size_t>(cd.nx * cd.size); memcpy(outPtr, cd.end, static_cast<size_t>(n * sizeof(unsigned short))); outPtr += n * sizeof(unsigned short); cd.end += n; } } return true; } #endif // TINYEXR_USE_PIZ #if TINYEXR_USE_ZFP struct ZFPCompressionParam { double rate; int precision; double tolerance; int type; // TINYEXR_ZFP_COMPRESSIONTYPE_* ZFPCompressionParam() { type = TINYEXR_ZFP_COMPRESSIONTYPE_RATE; rate = 2.0; precision = 0; tolerance = 0.0f; } }; bool FindZFPCompressionParam(ZFPCompressionParam *param, const EXRAttribute *attributes, int num_attributes) { bool foundType = false; for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionType") == 0) && (attributes[i].size == 1)) { param->type = static_cast<int>(attributes[i].value[0]); foundType = true; } } if (!foundType) { return false; } if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionRate") == 0) && (attributes[i].size == 8)) { param->rate = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionPrecision") == 0) && (attributes[i].size == 4)) { param->rate = *(reinterpret_cast<int *>(attributes[i].value)); return true; } } } else if (param->type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { for (int i = 0; i < num_attributes; i++) { if ((strcmp(attributes[i].name, "zfpCompressionTolerance") == 0) && (attributes[i].size == 8)) { param->tolerance = *(reinterpret_cast<double *>(attributes[i].value)); return true; } } } else { assert(0); } return false; } // Assume pixel format is FLOAT for all channels. static bool DecompressZfp(float *dst, int dst_width, int dst_num_lines, int num_channels, const unsigned char *src, unsigned long src_size, const ZFPCompressionParam &param) { size_t uncompressed_size = dst_width * dst_num_lines * num_channels; if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); } zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((dst_width % 4) == 0); assert((dst_num_lines % 4) == 0); if ((dst_width & 3U) || (dst_num_lines & 3U)) { return false; } field = zfp_field_2d(reinterpret_cast<void *>(const_cast<unsigned char *>(src)), zfp_type_float, dst_width, dst_num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, /* dimention */ 2, /* write random access */ 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); std::vector<unsigned char> buf(buf_size); memcpy(&buf.at(0), src, src_size); bitstream *stream = stream_open(&buf.at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_stream_rewind(zfp); size_t image_size = dst_width * dst_num_lines; for (int c = 0; c < num_channels; c++) { // decompress 4x4 pixel block. for (int y = 0; y < dst_num_lines; y += 4) { for (int x = 0; x < dst_width; x += 4) { float fblock[16]; zfp_decode_block_float_2(zfp, fblock); for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { dst[c * image_size + ((y + j) * dst_width + (x + i))] = fblock[j * 4 + i]; } } } } } zfp_field_free(field); zfp_stream_close(zfp); stream_close(stream); return true; } // Assume pixel format is FLOAT for all channels. bool CompressZfp(std::vector<unsigned char> *outBuf, unsigned int *outSize, const float *inPtr, int width, int num_lines, int num_channels, const ZFPCompressionParam &param) { zfp_stream *zfp = NULL; zfp_field *field = NULL; assert((width % 4) == 0); assert((num_lines % 4) == 0); if ((width & 3U) || (num_lines & 3U)) { return false; } // create input array. field = zfp_field_2d(reinterpret_cast<void *>(const_cast<float *>(inPtr)), zfp_type_float, width, num_lines * num_channels); zfp = zfp_stream_open(NULL); if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_RATE) { zfp_stream_set_rate(zfp, param.rate, zfp_type_float, 2, 0); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_PRECISION) { zfp_stream_set_precision(zfp, param.precision, zfp_type_float); } else if (param.type == TINYEXR_ZFP_COMPRESSIONTYPE_ACCURACY) { zfp_stream_set_accuracy(zfp, param.tolerance, zfp_type_float); } else { assert(0); } size_t buf_size = zfp_stream_maximum_size(zfp, field); outBuf->resize(buf_size); bitstream *stream = stream_open(&outBuf->at(0), buf_size); zfp_stream_set_bit_stream(zfp, stream); zfp_field_free(field); size_t image_size = width * num_lines; for (int c = 0; c < num_channels; c++) { // compress 4x4 pixel block. for (int y = 0; y < num_lines; y += 4) { for (int x = 0; x < width; x += 4) { float fblock[16]; for (int j = 0; j < 4; j++) { for (int i = 0; i < 4; i++) { fblock[j * 4 + i] = inPtr[c * image_size + ((y + j) * width + (x + i))]; } } zfp_encode_block_float_2(zfp, fblock); } } } zfp_stream_flush(zfp); (*outSize) = zfp_stream_compressed_size(zfp); zfp_stream_close(zfp); return true; } #endif // // ----------------------------------------------------------------- // static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); assert(ret); (void)ret; // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; hf.u = line_ptr[u]; tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val = line_ptr[u]; tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>(&outBuf.at( v * pixel_data_size * static_cast<size_t>(x_stride) + channel_offset_list[c] * static_cast<size_t>(x_stride))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); } } #else assert(0 && "PIZ is enabled in this build"); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS || compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); if (!tinyexr::DecompressZip(reinterpret_cast<unsigned char *>(&outBuf.at(0)), &dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // For ZIP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; hf.u = line_ptr[u]; tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val = line_ptr[u]; tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len)); // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; hf.u = line_ptr[u]; tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *image = reinterpret_cast<unsigned short **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = hf.u; } else { // HALF -> FLOAT tinyexr::FP32 f32 = half_to_float(hf); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val = line_ptr[u]; tinyexr::swap4(&val); unsigned int *image = reinterpret_cast<unsigned int **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } } else if (compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; if (!FindZFPCompressionParam(&zfp_compression_param, attributes, num_attributes)) { assert(0); return false; } // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = outBuf.size(); assert(dstLen > 0); tinyexr::DecompressZfp(reinterpret_cast<float *>(&outBuf.at(0)), width, num_lines, num_channels, data_ptr, static_cast<unsigned long>(data_len), zfp_compression_param); // For ZFP_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { assert(channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const float *line_ptr = reinterpret_cast<float *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { float val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); float *image = reinterpret_cast<float **>(out_images)[c]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } *image = val; } } } else { assert(0); return false; } } #else (void)attributes; (void)num_attributes; (void)num_channels; assert(0); return false; #endif } else if (compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { for (size_t c = 0; c < num_channels; c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + c * static_cast<size_t>(width) * sizeof(unsigned short)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; hf.u = line_ptr[u]; tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); outLine[u] = hf.u; } } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; hf.u = line_ptr[u]; tinyexr::swap2(reinterpret_cast<unsigned short *>(&hf.u)); tinyexr::FP32 f32 = half_to_float(hf); outLine[u] = f32.f; } } else { assert(0); return false; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { const float *line_ptr = reinterpret_cast<const float *>( data_ptr + c * static_cast<size_t>(width) * sizeof(float)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { float val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { const unsigned int *line_ptr = reinterpret_cast<const unsigned int *>( data_ptr + c * static_cast<size_t>(width) * sizeof(unsigned int)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { unsigned int val = line_ptr[u]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); outLine[u] = val; } } } } return true; } static void DecodeTiledPixelData( unsigned char **out_images, int *width, int *height, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int data_width, int data_height, int tile_offset_x, int tile_offset_y, int tile_size_x, int tile_size_y, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { assert(tile_offset_x * tile_size_x < data_width); assert(tile_offset_y * tile_size_y < data_height); // Compute actual image size in a tile. if ((tile_offset_x + 1) * tile_size_x >= data_width) { (*width) = data_width - (tile_offset_x * tile_size_x); } else { (*width) = tile_size_x; } if ((tile_offset_y + 1) * tile_size_y >= data_height) { (*height) = data_height - (tile_offset_y * tile_size_y); } else { (*height) = tile_size_y; } // Image size = tile size. DecodePixelData(out_images, requested_pixel_types, data_ptr, data_len, compression_type, line_order, (*width), tile_size_y, /* stride */ tile_size_x, /* y */ 0, /* line_no */ 0, (*height), pixel_data_size, num_attributes, attributes, num_channels, channels, channel_offset_list); } static void ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { assert(0); } } } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) = "Failed to parse channel info."; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) = "# of channels is zero."; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_ATTRIBUTES) { EXRAttribute attrib; #ifdef _MSC_VER strncpy_s(attrib.name, attr_name.c_str(), 255); strncpy_s(attrib.type, attr_type.c_str(), 255); #else strncpy(attrib.name, attr_name.c_str(), 255); strncpy(attrib.type, attr_type.c_str(), 255); #endif attrib.name[255] = '\0'; attrib.type[255] = '\0'; attrib.size = static_cast<int>(data.size()); attrib.value = static_cast<unsigned char *>(malloc(data.size())); memcpy(reinterpret_cast<char *>(attrib.value), &data.at(0), data.size()); info->attributes.push_back(attrib); } } } // Check if required attributes exist { std::stringstream ss_err; if (!has_compression) { ss_err << "\"compression\" attribute not found in the header." << std::endl; } if (!has_channels) { ss_err << "\"channels\" attribute not found in the header." << std::endl; } if (!has_line_order) { ss_err << "\"lineOrder\" attribute not found in the header." << std::endl; } if (!has_display_window) { ss_err << "\"displayWindow\" attribute not found in the header." << std::endl; } if (!has_data_window) { ss_err << "\"dataWindow\" attribute not found in the header or invalid." << std::endl; } if (!has_pixel_aspect_ratio) { ss_err << "\"pixelAspectRatio\" attribute not found in the header." << std::endl; } if (!has_screen_window_width) { ss_err << "\"screenWindowWidth\" attribute not found in the header." << std::endl; } if (!has_screen_window_center) { ss_err << "\"screenWindowCenter\" attribute not found in the header." << std::endl; } if (!(ss_err.str().empty())) { if (err) { (*err) += ss_err.str(); } return TINYEXR_ERROR_INVALID_HEADER; } } info->header_len = static_cast<unsigned int>(orig_size - size); return TINYEXR_SUCCESS; } // C++ HeaderInfo to C EXRHeader conversion. static void ConvertHeader(EXRHeader *exr_header, const HeaderInfo &info) { exr_header->pixel_aspect_ratio = info.pixel_aspect_ratio; exr_header->screen_window_center[0] = info.screen_window_center[0]; exr_header->screen_window_center[1] = info.screen_window_center[1]; exr_header->screen_window_width = info.screen_window_width; exr_header->chunk_count = info.chunk_count; exr_header->display_window[0] = info.display_window[0]; exr_header->display_window[1] = info.display_window[1]; exr_header->display_window[2] = info.display_window[2]; exr_header->display_window[3] = info.display_window[3]; exr_header->data_window[0] = info.data_window[0]; exr_header->data_window[1] = info.data_window[1]; exr_header->data_window[2] = info.data_window[2]; exr_header->data_window[3] = info.data_window[3]; exr_header->line_order = info.line_order; exr_header->compression_type = info.compression_type; exr_header->tile_size_x = info.tile_size_x; exr_header->tile_size_y = info.tile_size_y; exr_header->tile_level_mode = info.tile_level_mode; exr_header->tile_rounding_mode = info.tile_rounding_mode; exr_header->num_channels = static_cast<int>(info.channels.size()); exr_header->channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { #ifdef _MSC_VER strncpy_s(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #else strncpy(exr_header->channels[c].name, info.channels[c].name.c_str(), 255); #endif // manually add '\0' for safety. exr_header->channels[c].name[255] = '\0'; exr_header->channels[c].pixel_type = info.channels[c].pixel_type; exr_header->channels[c].p_linear = info.channels[c].p_linear; exr_header->channels[c].x_sampling = info.channels[c].x_sampling; exr_header->channels[c].y_sampling = info.channels[c].y_sampling; } exr_header->pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->pixel_types[c] = info.channels[c].pixel_type; } // Initially fill with values of `pixel_types` exr_header->requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(exr_header->num_channels))); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { exr_header->requested_pixel_types[c] = info.channels[c].pixel_type; } assert(info.attributes.size() < TINYEXR_MAX_ATTRIBUTES); exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); for (size_t i = 0; i < info.attributes.size(); i++) { memcpy(exr_header->custom_attributes[i].name, info.attributes[i].name, 256); memcpy(exr_header->custom_attributes[i].type, info.attributes[i].type, 256); exr_header->custom_attributes[i].size = info.attributes[i].size; // Just copy poiner exr_header->custom_attributes[i].value = info.attributes[i].value; } exr_header->header_len = info.header_len; } static int DecodeChunk(EXRImage *exr_image, const EXRHeader *exr_header, const std::vector<tinyexr::tinyexr_uint64> &offsets, const unsigned char *head, const size_t size) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels); bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { return TINYEXR_ERROR_INVALID_DATA; } size_t data_size = size - (offsets[tile_idx] + sizeof(int) * 5); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[tile_idx]); int tile_coordinates[4]; memcpy(tile_coordinates, data_ptr, sizeof(int) * 4); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&tile_coordinates[3])); // @todo{ LoD } if (tile_coordinates[2] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } if (tile_coordinates[3] != 0) { return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } int data_len; memcpy(&data_len, data_ptr + 16, sizeof(int)); // 16 = sizeof(tile_coordinates) tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (data_len < 4 || size_t(data_len) > data_size) { return TINYEXR_ERROR_INVALID_DATA; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; exr_image->num_tiles = static_cast<int>(num_tiles); } } else { // scanline format exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #ifdef _OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size - (offsets[y_idx] + sizeof(int) * 2); const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y_idx]); int line_no; memcpy(&line_no, data_ptr, sizeof(int)); int data_len; memcpy(&data_len, data_ptr + 4, sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); if (size_t(data_len) > data_size) { invalid_data = true; } else { int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; //assert(num_lines > 0); if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y line_no -= exr_header->data_window[1]; if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } } // omp parallel } if (invalid_data) { return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0]; if (data_width >= std::numeric_limits<int>::max()) { // Issue 63 if (err) { (*err) = "Invalid data window value."; } return TINYEXR_ERROR_INVALID_DATA; } data_width++; int data_height = exr_header->data_window[3] - exr_header->data_window[1]; if (data_height >= std::numeric_limits<int>::max()) { if (err) { (*err) = "Invalid data height value."; } return TINYEXR_ERROR_INVALID_DATA; } if ((data_width < 0) || (data_height < 0)) { if (err) { (*err) = "Invalid data window value."; } return TINYEXR_ERROR_INVALID_DATA; } // Read offset tables. size_t num_blocks = 0; if (exr_header->chunk_count > 0) { // Use `chunkCount` attribute. num_blocks = static_cast<size_t>(exr_header->chunk_count); } else if (exr_header->tiled) { // @todo { LoD } size_t num_x_tiles = static_cast<size_t>(data_width) / static_cast<size_t>(exr_header->tile_size_x); if (num_x_tiles * static_cast<size_t>(exr_header->tile_size_x) < static_cast<size_t>(data_width)) { num_x_tiles++; } size_t num_y_tiles = static_cast<size_t>(data_height) / static_cast<size_t>(exr_header->tile_size_y); if (num_y_tiles * static_cast<size_t>(exr_header->tile_size_y) < static_cast<size_t>(data_height)) { num_y_tiles++; } num_blocks = num_x_tiles * num_y_tiles; } else { num_blocks = static_cast<size_t>(data_height) / static_cast<size_t>(num_scanline_blocks); if (num_blocks * static_cast<size_t>(num_scanline_blocks) < static_cast<size_t>(data_height)) { num_blocks++; } } std::vector<tinyexr::tinyexr_uint64> offsets(num_blocks); for (size_t y = 0; y < num_blocks; y++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { if (err) { (*err) = "Invalid offset value."; } return TINYEXR_ERROR_INVALID_DATA; } marker += sizeof(tinyexr::tinyexr_uint64); // = 8 offsets[y] = offset; } // If line offsets are invalid, we try to reconstruct it. // See OpenEXR/IlmImf/ImfScanLineInputFile.cpp::readLineOffsets() for details. for (size_t y = 0; y < num_blocks; y++) { if (offsets[y] <= 0) { // TODO(syoyo) Report as warning? // if (err) { // stringstream ss; // ss << "Incomplete lineOffsets." << std::endl; // (*err) += ss.str(); //} bool ret = ReconstructLineOffsets(&offsets, num_blocks, head, marker, size); if (ret) { // OK break; } else { if (err) { (*err) = "Cannot reconstruct lineOffset table."; } return TINYEXR_ERROR_INVALID_DATA; } } } return DecodeChunk(exr_image, exr_header, offsets, head, size); } } // namespace tinyexr int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { if (out_rgba == NULL) { if (err) { (*err) = "Invalid argument.\n"; } return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); InitEXRImage(&exr_image); { int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return ret; } if (exr_version.multipart || exr_version.non_image) { if (err) { (*err) = "Loading multipart or DeepImage is not supported yet.\n"; } return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { return ret; } } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } { int ret = LoadEXRImageFromFile(&exr_image, &exr_header, filename, err); if (ret != TINYEXR_SUCCESS) { return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if ((idxA == 0) && (idxR == -1) && (idxG == -1) && (idxB == -1)) { // Alpha channel only. (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } else { // Assume RGB(A) if (idxR == -1) { if (err) { (*err) = "R channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { if (err) { (*err) = "G channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { if (err) { (*err) = "B channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int ParseEXRHeaderFromMemory(EXRHeader *exr_header, const EXRVersion *version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_header == NULL) { if (err) { (*err) = "Invalid argument.\n"; } // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; tinyexr::HeaderInfo info; info.clear(); std::string err_str; int ret = ParseEXRHeader(&info, NULL, version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err && !err_str.empty()) { #ifdef _WIN32 (*err) = _strdup(err_str.c_str()); // May leak #else (*err) = strdup(err_str.c_str()); // May leak #endif } } ConvertHeader(exr_header, info); // transfoer `tiled` from version. exr_header->tiled = version->tiled; return ret; } int LoadEXRFromMemory(float **out_rgba, int *width, int *height, const unsigned char *memory, size_t size, const char **err) { if (out_rgba == NULL || memory == NULL) { if (err) { (*err) = "Invalid argument.\n"; } return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRVersion exr_version; EXRImage exr_image; EXRHeader exr_header; InitEXRHeader(&exr_header); int ret = ParseEXRVersionFromMemory(&exr_version, memory, size); if (ret != TINYEXR_SUCCESS) { return ret; } ret = ParseEXRHeaderFromMemory(&exr_header, &exr_version, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // Read HALF channel as FLOAT. for (int i = 0; i < exr_header.num_channels; i++) { if (exr_header.pixel_types[i] == TINYEXR_PIXELTYPE_HALF) { exr_header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; } } InitEXRImage(&exr_image); ret = LoadEXRImageFromMemory(&exr_image, &exr_header, memory, size, err); if (ret != TINYEXR_SUCCESS) { return ret; } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if (idxR == -1) { if (err) { (*err) = "R channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { if (err) { (*err) = "G channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { if (err) { (*err) = "B channel not found\n"; } // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); for (int i = 0; i < exr_image.width * exr_image.height; i++) { (*out_rgba)[4 * i + 0] = reinterpret_cast<float **>(exr_image.images)[idxR][i]; (*out_rgba)[4 * i + 1] = reinterpret_cast<float **>(exr_image.images)[idxG][i]; (*out_rgba)[4 * i + 2] = reinterpret_cast<float **>(exr_image.images)[idxB][i]; if (idxA != -1) { (*out_rgba)[4 * i + 3] = reinterpret_cast<float **>(exr_image.images)[idxA][i]; } else { (*out_rgba)[4 * i + 3] = 1.0; } } (*width) = exr_image.width; (*height) = exr_image.height; FreeEXRHeader(&exr_header); FreeEXRImage(&exr_image); return TINYEXR_SUCCESS; } int LoadEXRImageFromFile(EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRImageFromMemory(exr_image, exr_header, &buf.at(0), filesize, err); } int LoadEXRImageFromMemory(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *memory, const size_t size, const char **err) { if (exr_image == NULL || memory == NULL || (size < tinyexr::kEXRVersionSize)) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { if (err) { (*err) = "EXRHeader is not initialized."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } const unsigned char *head = memory; const unsigned char *marker = reinterpret_cast<const unsigned char *>( memory + exr_header->header_len + 8); // +8 for magic number + version header. return tinyexr::DecodeEXRImage(exr_image, exr_header, head, marker, size, err); } size_t SaveEXRImageToMemory(const EXRImage *exr_image, const EXRHeader *exr_header, unsigned char **memory_out, const char **err) { if (exr_image == NULL || memory_out == NULL || exr_header->compression_type < 0) { if (err) { (*err) = "Invalid argument."; } return 0; // @fixme } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { if (err) { (*err) = "PIZ compression is not supported in this build."; } return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { if (err) { (*err) = "ZFP compression is not supported in this build."; } return 0; } #endif #if TINYEXR_USE_ZFP for (size_t i = 0; i < static_cast<size_t>(exr_header->num_channels); i++) { if (exr_header->requested_pixel_types[i] != TINYEXR_PIXELTYPE_FLOAT) { if (err) { (*err) = "Pixel type must be FLOAT for ZFP compression."; } return 0; } } #endif std::vector<unsigned char> memory; // Header { const char header[] = {0x76, 0x2f, 0x31, 0x01}; memory.insert(memory.end(), header, header + 4); } // Version, scanline. { char marker[] = {2, 0, 0, 0}; /* @todo if (exr_header->tiled) { marker[1] |= 0x2; } if (exr_header->long_name) { marker[1] |= 0x4; } if (exr_header->non_image) { marker[1] |= 0x8; } if (exr_header->multipart) { marker[1] |= 0x10; } */ memory.insert(memory.end(), marker, marker + 4); } int num_scanlines = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanlines = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanlines = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanlines = 16; } // Write attributes. std::vector<tinyexr::ChannelInfo> channels; { std::vector<unsigned char> data; for (int c = 0; c < exr_header->num_channels; c++) { tinyexr::ChannelInfo info; info.p_linear = 0; info.pixel_type = exr_header->requested_pixel_types[c]; info.x_sampling = 1; info.y_sampling = 1; info.name = std::string(exr_header->channels[c].name); channels.push_back(info); } tinyexr::WriteChannelInfo(data, channels); tinyexr::WriteAttributeToMemory(&memory, "channels", "chlist", &data.at(0), static_cast<int>(data.size())); } { int comp = exr_header->compression_type; tinyexr::swap4(reinterpret_cast<unsigned int *>(&comp)); tinyexr::WriteAttributeToMemory( &memory, "compression", "compression", reinterpret_cast<const unsigned char *>(&comp), 1); } { int data[4] = {0, 0, exr_image->width - 1, exr_image->height - 1}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data[3])); tinyexr::WriteAttributeToMemory( &memory, "dataWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); tinyexr::WriteAttributeToMemory( &memory, "displayWindow", "box2i", reinterpret_cast<const unsigned char *>(data), sizeof(int) * 4); } { unsigned char line_order = 0; // @fixme { read line_order from EXRHeader } tinyexr::WriteAttributeToMemory(&memory, "lineOrder", "lineOrder", &line_order, 1); } { float aspectRatio = 1.0f; tinyexr::swap4(reinterpret_cast<unsigned int *>(&aspectRatio)); tinyexr::WriteAttributeToMemory( &memory, "pixelAspectRatio", "float", reinterpret_cast<const unsigned char *>(&aspectRatio), sizeof(float)); } { float center[2] = {0.0f, 0.0f}; tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&center[1])); tinyexr::WriteAttributeToMemory( &memory, "screenWindowCenter", "v2f", reinterpret_cast<const unsigned char *>(center), 2 * sizeof(float)); } { float w = static_cast<float>(exr_image->width); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::WriteAttributeToMemory(&memory, "screenWindowWidth", "float", reinterpret_cast<const unsigned char *>(&w), sizeof(float)); } // Custom attributes if (exr_header->num_custom_attributes > 0) { for (int i = 0; i < exr_header->num_custom_attributes; i++) { tinyexr::WriteAttributeToMemory( &memory, exr_header->custom_attributes[i].name, exr_header->custom_attributes[i].type, reinterpret_cast<const unsigned char *>( exr_header->custom_attributes[i].value), exr_header->custom_attributes[i].size); } } { // end of header unsigned char e = 0; memory.push_back(e); } int num_blocks = exr_image->height / num_scanlines; if (num_blocks * num_scanlines < exr_image->height) { num_blocks++; } std::vector<tinyexr::tinyexr_uint64> offsets(static_cast<size_t>(num_blocks)); size_t headerSize = memory.size(); tinyexr::tinyexr_uint64 offset = headerSize + static_cast<size_t>(num_blocks) * sizeof( tinyexr::tinyexr_int64); // sizeof(header) + sizeof(offsetTable) std::vector<unsigned char> data; std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { for (int x = 0; x < exr_image->width; x++) { tinyexr::FP16 h16; h16.u = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP32 f32 = half_to_float(h16); tinyexr::swap4(reinterpret_cast<unsigned int *>(&f32.f)); // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); line_ptr[x] = f32.f; } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { for (int x = 0; x < exr_image->width; x++) { unsigned short val = reinterpret_cast<unsigned short **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap2(&val); // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); line_ptr[x] = val; } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { for (int x = 0; x < exr_image->width; x++) { tinyexr::FP32 f32; f32.f = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::FP16 h16; h16 = float_to_half_full(f32); tinyexr::swap2(reinterpret_cast<unsigned short *>(&h16.u)); // Assume increasing Y unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &buf.at(static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); line_ptr[x] = h16.u; } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { for (int x = 0; x < exr_image->width; x++) { float val = reinterpret_cast<float **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(reinterpret_cast<unsigned int *>(&val)); // Assume increasing Y float *line_ptr = reinterpret_cast<float *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); line_ptr[x] = val; } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { for (int x = 0; x < exr_image->width; x++) { unsigned int val = reinterpret_cast<unsigned int **>( exr_image->images)[c][(y + start_y) * exr_image->width + x]; tinyexr::swap4(&val); // Assume increasing Y unsigned int *line_ptr = reinterpret_cast<unsigned int *>(&buf.at( static_cast<size_t>(pixel_data_size * y * exr_image->width) + channel_offset_list[c] * static_cast<size_t>(exr_image->width))); line_ptr[x] = val; } } } } if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_NONE) { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(buf.size()); memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), buf.begin(), buf.begin() + data_len); } else if ((exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #if TINYEXR_USE_MINIZ std::vector<unsigned char> block(tinyexr::miniz::mz_compressBound( static_cast<unsigned long>(buf.size()))); #else std::vector<unsigned char> block( compressBound(static_cast<uLong>(buf.size()))); #endif tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressZip(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_RLE) { // (buf.size() * 3) / 2 would be enough. std::vector<unsigned char> block((buf.size() * 3) / 2); tinyexr::tinyexr_uint64 outSize = block.size(); tinyexr::CompressRle(&block.at(0), outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), static_cast<unsigned long>(buf.size())); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = static_cast<unsigned int>(outSize); // truncate memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ unsigned int bufLen = 1024 + static_cast<unsigned int>( 1.2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { data.insert(data.end(), data_list[i].begin(), data_list[i].end()); offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } { memory.insert(memory.end(), data.begin(), data.end()); } assert(memory.size() > 0); (*memory_out) = static_cast<unsigned char *>(malloc(memory.size())); memcpy((*memory_out), &memory.at(0), memory.size()); return memory.size(); // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { if (err) { (*err) = "PIZ compression is not supported in this build."; } return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { if (err) { (*err) = "ZFP compression is not supported in this build."; } return 0; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { if (err) { (*err) = "Cannot write a file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if ((mem_size > 0) && mem) { fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((!errcode) || (!fp)) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } #endif size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (filesize == 0) { fclose(fp); if (err) { (*err) = "File size is zero."; } return TINYEXR_ERROR_INVALID_FILE; } std::vector<char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); (void)ret; } fclose(fp); const char *head = &buf[0]; const char *marker = &buf[0]; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { if (err) { (*err) = "Invalid magic number."; } return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } // Version, scanline. { // ver 2.0, scanline, deep bit on(0x800) // must be [2, 0, 0, 0] if (marker[0] != 2 || marker[1] != 8 || marker[2] != 0 || marker[3] != 0) { if (err) { (*err) = "Unsupported version or scanline."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } marker += 4; } int dx = -1; int dy = -1; int dw = -1; int dh = -1; int num_scanline_blocks = 1; // 16 for ZIP compression. int compression_type = -1; int num_channels = -1; std::vector<tinyexr::ChannelInfo> channels; // Read attributes size_t size = filesize - tinyexr::kEXRVersionSize; for (;;) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { marker++; size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (attr_name.compare("compression") == 0) { compression_type = data[0]; if (compression_type > TINYEXR_COMPRESSIONTYPE_PIZ) { if (err) { (*err) = "Unsupported compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } if (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!tinyexr::ReadChannelInfo(channels, data)) { if (err) { (*err) = "Failed to parse channel info."; } return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { if (err) { (*err) = "Invalid channels format."; } return TINYEXR_ERROR_INVALID_DATA; } } else if (attr_name.compare("dataWindow") == 0) { memcpy(&dx, &data.at(0), sizeof(int)); memcpy(&dy, &data.at(4), sizeof(int)); memcpy(&dw, &data.at(8), sizeof(int)); memcpy(&dh, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dx)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dy)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dw)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&dh)); } else if (attr_name.compare("displayWindow") == 0) { int x; int y; int w; int h; memcpy(&x, &data.at(0), sizeof(int)); memcpy(&y, &data.at(4), sizeof(int)); memcpy(&w, &data.at(8), sizeof(int)); memcpy(&h, &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&x)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&w)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&h)); } } assert(dx >= 0); assert(dy >= 0); assert(dw >= 0); assert(dh >= 0); assert(num_channels >= 1); int data_width = dw - dx + 1; int data_height = dh - dy + 1; std::vector<float> image( static_cast<size_t>(data_width * data_height * 4)); // 4 = RGBA // Read offset tables. int num_blocks = data_height / num_scanline_blocks; if (num_blocks * num_scanline_blocks < data_height) { num_blocks++; } std::vector<tinyexr::tinyexr_int64> offsets(static_cast<size_t>(num_blocks)); for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { tinyexr::tinyexr_int64 offset; memcpy(&offset, marker, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offset)); marker += sizeof(tinyexr::tinyexr_int64); // = 8 offsets[y] = offset; } #if TINYEXR_USE_PIZ if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) || (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ)) { #else if ((compression_type == TINYEXR_COMPRESSIONTYPE_NONE) || (compression_type == TINYEXR_COMPRESSIONTYPE_RLE) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIPS) || (compression_type == TINYEXR_COMPRESSIONTYPE_ZIP)) { #endif // OK } else { if (err) { (*err) = "Unsupported format."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } deep_image->image = static_cast<float ***>( malloc(sizeof(float **) * static_cast<size_t>(num_channels))); for (int c = 0; c < num_channels; c++) { deep_image->image[c] = static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { } } deep_image->offset_table = static_cast<int **>( malloc(sizeof(int *) * static_cast<size_t>(data_height))); for (int y = 0; y < data_height; y++) { deep_image->offset_table[y] = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(data_width))); } for (size_t y = 0; y < static_cast<size_t>(num_blocks); y++) { const unsigned char *data_ptr = reinterpret_cast<const unsigned char *>(head + offsets[y]); // int: y coordinate // int64: packed size of pixel offset table // int64: packed size of sample data // int64: unpacked size of sample data // compressed pixel offset table // compressed sample data int line_no; tinyexr::tinyexr_int64 packedOffsetTableSize; tinyexr::tinyexr_int64 packedSampleDataSize; tinyexr::tinyexr_int64 unpackedSampleDataSize; memcpy(&line_no, data_ptr, sizeof(int)); memcpy(&packedOffsetTableSize, data_ptr + 4, sizeof(tinyexr::tinyexr_int64)); memcpy(&packedSampleDataSize, data_ptr + 12, sizeof(tinyexr::tinyexr_int64)); memcpy(&unpackedSampleDataSize, data_ptr + 20, sizeof(tinyexr::tinyexr_int64)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&line_no)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedOffsetTableSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&packedSampleDataSize)); tinyexr::swap8( reinterpret_cast<tinyexr::tinyexr_uint64 *>(&unpackedSampleDataSize)); std::vector<int> pixelOffsetTable(static_cast<size_t>(data_width)); // decode pixel offset table. { unsigned long dstLen = static_cast<unsigned long>(pixelOffsetTable.size() * sizeof(int)); if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&pixelOffsetTable.at(0)), &dstLen, data_ptr + 28, static_cast<unsigned long>(packedOffsetTableSize))) { return false; } assert(dstLen == pixelOffsetTable.size() * sizeof(int)); for (size_t i = 0; i < static_cast<size_t>(data_width); i++) { deep_image->offset_table[y][i] = pixelOffsetTable[i]; } } std::vector<unsigned char> sample_data( static_cast<size_t>(unpackedSampleDataSize)); // decode sample data. { unsigned long dstLen = static_cast<unsigned long>(unpackedSampleDataSize); if (dstLen) { if (!tinyexr::DecompressZip( reinterpret_cast<unsigned char *>(&sample_data.at(0)), &dstLen, data_ptr + 28 + packedOffsetTableSize, static_cast<unsigned long>(packedSampleDataSize))) { return false; } assert(dstLen == static_cast<unsigned long>(unpackedSampleDataSize)); } } // decode sample int sampleSize = -1; std::vector<int> channel_offset_list(static_cast<size_t>(num_channels)); { int channel_offset = 0; for (size_t i = 0; i < static_cast<size_t>(num_channels); i++) { channel_offset_list[i] = channel_offset; if (channels[i].pixel_type == TINYEXR_PIXELTYPE_UINT) { // UINT channel_offset += 4; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_HALF) { // half channel_offset += 2; } else if (channels[i].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // float channel_offset += 4; } else { assert(0); } } sampleSize = channel_offset; } assert(sampleSize >= 2); assert(static_cast<size_t>( pixelOffsetTable[static_cast<size_t>(data_width - 1)] * sampleSize) == sample_data.size()); int samples_per_line = static_cast<int>(sample_data.size()) / sampleSize; // // Alloc memory // // // pixel data is stored as image[channels][pixel_samples] // { tinyexr::tinyexr_uint64 data_offset = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { deep_image->image[c][y] = static_cast<float *>( malloc(sizeof(float) * static_cast<size_t>(samples_per_line))); if (channels[c].pixel_type == 0) { // UINT for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { unsigned int ui = *reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); deep_image->image[c][y][x] = static_cast<float>(ui); // @fixme } data_offset += sizeof(unsigned int) * static_cast<size_t>(samples_per_line); } else if (channels[c].pixel_type == 1) { // half for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { tinyexr::FP16 f16; f16.u = *reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::FP32 f32 = half_to_float(f16); deep_image->image[c][y][x] = f32.f; } data_offset += sizeof(short) * static_cast<size_t>(samples_per_line); } else { // float for (size_t x = 0; x < static_cast<size_t>(samples_per_line); x++) { float f = *reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); deep_image->image[c][y][x] = f; } data_offset += sizeof(float) * static_cast<size_t>(samples_per_line); } } } } // y deep_image->width = data_width; deep_image->height = data_height; deep_image->channel_names = static_cast<const char **>( malloc(sizeof(const char *) * static_cast<size_t>(num_channels))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { #ifdef _WIN32 deep_image->channel_names[c] = _strdup(channels[c].name.c_str()); #else deep_image->channel_names[c] = strdup(channels[c].name.c_str()); #endif } deep_image->num_channels = num_channels; return TINYEXR_SUCCESS; } void InitEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return; } exr_image->width = 0; exr_image->height = 0; exr_image->num_channels = 0; exr_image->images = NULL; exr_image->tiles = NULL; exr_image->num_tiles = 0; } void InitEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return; } memset(exr_header, 0, sizeof(EXRHeader)); } int FreeEXRHeader(EXRHeader *exr_header) { if (exr_header == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->channels) { free(exr_header->channels); } if (exr_header->pixel_types) { free(exr_header->pixel_types); } if (exr_header->requested_pixel_types) { free(exr_header->requested_pixel_types); } for (int i = 0; i < exr_header->num_custom_attributes; i++) { if (exr_header->custom_attributes[i].value) { free(exr_header->custom_attributes[i].value); } } return TINYEXR_SUCCESS; } int FreeEXRImage(EXRImage *exr_image) { if (exr_image == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->images && exr_image->images[i]) { free(exr_image->images[i]); } } if (exr_image->images) { free(exr_image->images); } if (exr_image->tiles) { for (int tid = 0; tid < exr_image->num_tiles; tid++) { for (int i = 0; i < exr_image->num_channels; i++) { if (exr_image->tiles[tid].images && exr_image->tiles[tid].images[i]) { free(exr_image->tiles[tid].images[i]); } } if (exr_image->tiles[tid].images) { free(exr_image->tiles[tid].images); } } } return TINYEXR_SUCCESS; } int ParseEXRHeaderFromFile(EXRHeader *exr_header, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_header == NULL || exr_version == NULL || filename == NULL) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { if (err) { (*err) = "fread error."; } return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRHeaderFromMemory(exr_header, exr_version, &buf.at(0), filesize, err); } int ParseEXRMultipartHeaderFromMemory(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const unsigned char *memory, size_t size, const char **err) { if (memory == NULL || exr_headers == NULL || num_headers == NULL || exr_version == NULL) { // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory + tinyexr::kEXRVersionSize; size_t marker_size = size - tinyexr::kEXRVersionSize; std::vector<tinyexr::HeaderInfo> infos; for (;;) { tinyexr::HeaderInfo info; info.clear(); std::string err_str; bool empty_header = false; int ret = ParseEXRHeader(&info, &empty_header, exr_version, &err_str, marker, marker_size); if (ret != TINYEXR_SUCCESS) { if (err) { #ifdef _WIN32 (*err) = _strdup(err_str.c_str()); // may leak #else (*err) = strdup(err_str.c_str()); // may leak #endif } return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { if (err) { (*err) = "`chunkCount' attribute is not found in the header."; } return TINYEXR_ERROR_INVALID_DATA; } infos.push_back(info); // move to next header. marker += info.header_len; size -= info.header_len; } // allocate memory for EXRHeader and create array of EXRHeader pointers. (*exr_headers) = static_cast<EXRHeader **>(malloc(sizeof(EXRHeader *) * infos.size())); for (size_t i = 0; i < infos.size(); i++) { EXRHeader *exr_header = static_cast<EXRHeader *>(malloc(sizeof(EXRHeader))); ConvertHeader(exr_header, infos[i]); // transfoer `tiled` from version. exr_header->tiled = exr_version->tiled; (*exr_headers)[i] = exr_header; } (*num_headers) = static_cast<int>(infos.size()); return TINYEXR_SUCCESS; } int ParseEXRMultipartHeaderFromFile(EXRHeader ***exr_headers, int *num_headers, const EXRVersion *exr_version, const char *filename, const char **err) { if (exr_headers == NULL || num_headers == NULL || exr_version == NULL || filename == NULL) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); if (ret != filesize) { if (err) { (*err) = "fread error."; } return TINYEXR_ERROR_INVALID_FILE; } } return ParseEXRMultipartHeaderFromMemory( exr_headers, num_headers, exr_version, &buf.at(0), filesize, err); } int ParseEXRVersionFromMemory(EXRVersion *version, const unsigned char *memory, size_t size) { if (version == NULL || memory == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_DATA; } const unsigned char *marker = memory; // Header check. { const char header[] = {0x76, 0x2f, 0x31, 0x01}; if (memcmp(marker, header, 4) != 0) { return TINYEXR_ERROR_INVALID_MAGIC_NUMBER; } marker += 4; } version->tiled = false; version->long_name = false; version->non_image = false; version->multipart = false; // Parse version header. { // must be 2 if (marker[0] != 2) { return TINYEXR_ERROR_INVALID_EXR_VERSION; } if (version == NULL) { return TINYEXR_SUCCESS; // May OK } version->version = 2; if (marker[1] & 0x2) { // 9th bit version->tiled = true; } if (marker[1] & 0x4) { // 10th bit version->long_name = true; } if (marker[1] & 0x8) { // 11th bit version->non_image = true; // (deep image) } if (marker[1] & 0x10) { // 12th bit version->multipart = true; } } return TINYEXR_SUCCESS; } int ParseEXRVersionFromFile(EXRVersion *version, const char *filename) { if (filename == NULL) { return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t file_size; // Compute size fseek(fp, 0, SEEK_END); file_size = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); if (file_size < tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } unsigned char buf[tinyexr::kEXRVersionSize]; size_t ret = fread(&buf[0], 1, tinyexr::kEXRVersionSize, fp); fclose(fp); if (ret != tinyexr::kEXRVersionSize) { return TINYEXR_ERROR_INVALID_FILE; } return ParseEXRVersionFromMemory(version, buf, tinyexr::kEXRVersionSize); } int LoadEXRMultipartImageFromMemory(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const unsigned char *memory, const size_t size, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0 || memory == NULL || (size <= tinyexr::kEXRVersionSize)) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } // compute total header size. size_t total_header_size = 0; for (unsigned int i = 0; i < num_parts; i++) { if (exr_headers[i]->header_len == 0) { if (err) { (*err) = "EXRHeader is not initialized."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } total_header_size += exr_headers[i]->header_len; } const char *marker = reinterpret_cast<const char *>( memory + total_header_size + 4 + 4); // +8 for magic number and version header. marker += 1; // Skip empty header. // NOTE 1: // In multipart image, There is 'part number' before chunk data. // 4 byte : part number // 4+ : chunk // // NOTE 2: // EXR spec says 'part number' is 'unsigned long' but actually this is // 'unsigned int(4 bytes)' in OpenEXR implementation... // http://www.openexr.com/openexrfilelayout.pdf // Load chunk offset table. std::vector<std::vector<tinyexr::tinyexr_uint64> > chunk_offset_table_list; for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> offset_table( static_cast<size_t>(exr_headers[i]->chunk_count)); for (size_t c = 0; c < offset_table.size(); c++) { tinyexr::tinyexr_uint64 offset; memcpy(&offset, marker, 8); tinyexr::swap8(&offset); if (offset >= size) { if (err) { (*err) = "Invalid offset size."; } return TINYEXR_ERROR_INVALID_DATA; } offset_table[c] = offset + 4; // +4 to skip 'part number' marker += 8; } chunk_offset_table_list.push_back(offset_table); } // Decode image. for (size_t i = 0; i < static_cast<size_t>(num_parts); i++) { std::vector<tinyexr::tinyexr_uint64> &offset_table = chunk_offset_table_list[i]; // First check 'part number' is identitical to 'i' for (size_t c = 0; c < offset_table.size(); c++) { const unsigned char *part_number_addr = memory + offset_table[c] - 4; // -4 to move to 'part number' field. unsigned int part_no; memcpy(&part_no, part_number_addr, sizeof(unsigned int)); // 4 tinyexr::swap4(&part_no); if (part_no != i) { assert(0); return TINYEXR_ERROR_INVALID_DATA; } } int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size); if (ret != TINYEXR_SUCCESS) { return ret; } } return TINYEXR_SUCCESS; } int LoadEXRMultipartImageFromFile(EXRImage *exr_images, const EXRHeader **exr_headers, unsigned int num_parts, const char *filename, const char **err) { if (exr_images == NULL || exr_headers == NULL || num_parts == 0) { if (err) { (*err) = "Invalid argument."; } return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { if (err) { (*err) = "Cannot read file."; } return TINYEXR_ERROR_CANT_OPEN_FILE; } size_t filesize; // Compute size fseek(fp, 0, SEEK_END); filesize = static_cast<size_t>(ftell(fp)); fseek(fp, 0, SEEK_SET); std::vector<unsigned char> buf(filesize); // @todo { use mmap } { size_t ret; ret = fread(&buf[0], 1, filesize, fp); assert(ret == filesize); fclose(fp); (void)ret; } return LoadEXRMultipartImageFromMemory(exr_images, exr_headers, num_parts, &buf.at(0), filesize, err); } int SaveEXR(const float *data, int width, int height, int components, const int save_as_fp16, const char *outfilename) { if ((components == 1) || components == 3 || components == 4) { // OK } else { return TINYEXR_ERROR_INVALID_ARGUMENT; } // Assume at least 16x16 pixels. if (width < 16) return TINYEXR_ERROR_INVALID_ARGUMENT; if (height < 16) return TINYEXR_ERROR_INVALID_ARGUMENT; EXRHeader header; InitEXRHeader(&header); EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } const char *err; int ret = SaveEXRImageToFile(&image, &header, outfilename, &err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
1.norace8.c
// RUN: clang %loadLLOV %s -o /dev/null 2>&1 | FileCheck %s #include <omp.h> #define N 20 int main() { int A[N][N]; #pragma omp parallel for schedule(static, 4) for (int i = 1; i < N; i++) for (int j = 1; j < N; j++) A[i][j] = A[i][j - 1]; } // CHECK: Region is Data Race Free. // END
DRB011-minusminus-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. 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 disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL 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 LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY 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. */ /* The -- operation on numNodes2 is not protected, causing data race. Data race pair: numNodes2@74:7 vs. numNodes2@74:7 */ #include <stdlib.h> #include <stdio.h> int main(int argc, char* argv[]) { int i; int len=100; int numNodes=len, numNodes2=0; int x[100]; // initialize x[] #pragma omp parallel for for (i=0; i< len; i++) { if (i%2==0) x[i]=5; else x[i]= -5; } #pragma omp parallel for reduction(-:numNodes2) for (i=numNodes-1 ; i>-1 ; --i) { if (x[i]<=0) { numNodes2-- ; } } printf ("numNodes2 = %d\n", numNodes2); return 0; }
GaussianProcess.h
/** * @file GaussianProcess.h * @author Jan Nguyen * @date 17.05.19 */ #pragma once #include <Eigen/Dense> #include "autopas/options/AcquisitionFunctionOption.h" #include "autopas/utils/ExceptionHandler.h" #include "autopas/utils/Math.h" #include "autopas/utils/NumberSet.h" #include "autopas/utils/Random.h" #include "autopas/utils/WrapOpenMP.h" namespace autopas { /** * Gaussian process is a stochastical model. It predicts the * output of a blackbox function f(x) for given input x. To do so, some sample * input-output pairs (x,f(x)) should be provided as evidence. * * Currently the squared exponential kernel is used. * TODO: maybe offer some options. * @tparam Vector class should be subtractable and convertible to Eigen::VectorXd */ template <class Vector> class GaussianProcess { // number of samples to find optimal hyperparameters static constexpr size_t hp_sample_size = 10000; // number of hyperparameters static constexpr size_t hp_size = 100; /** * Hyperparameters and derived matrices used for prediction */ struct Hyperparameters { /** * score used to weight hyperparameters */ double score; /** * prior mean */ double mean; /** * prior variance */ double theta; /** * Scale for each input dimension */ Eigen::VectorXd dimScales; /** * Covariance Matrix Inverse */ Eigen::MatrixXd covMatInv; /** * Weights used for predictions */ Eigen::VectorXd weights; /** * Default Constructor */ Hyperparameters() : mean(0.), theta(1.), dimScales(Eigen::VectorXd::Ones(1)), covMatInv(Eigen::MatrixXd::Ones(1, 1)), weights(Eigen::VectorXd::Ones(1)) {} /** * Contructor * @param mean prior mean of Gaussian process * @param theta prior variance * @param dimScales scale for each input dimension */ Hyperparameters(double mean, double theta, const Eigen::VectorXd &dimScales) : mean(mean), theta(theta), dimScales(dimScales) {} /** * Precalculate matrices needed for predictions * @param sigma assumed noise * @param inputs evidence input * @param outputs evidence output */ void precalculate(double sigma, const std::vector<Vector> &inputs, const Eigen::VectorXd &outputs) { size_t size = outputs.size(); // mean of output shifted to zero Eigen::VectorXd outputCentered = outputs - mean * Eigen::VectorXd::Ones(size); Eigen::MatrixXd covMat(size, size); // calculate covariance matrix for (size_t i = 0; i < size; ++i) { covMat(i, i) = kernel(inputs[i], inputs[i], theta, dimScales) + sigma; for (size_t j = i + 1; j < size; ++j) { covMat(i, j) = covMat(j, i) = kernel(inputs[i], inputs[j], theta, dimScales); } } // cholesky decomposition Eigen::LLT<Eigen::MatrixXd> llt = covMat.llt(); Eigen::MatrixXd l = llt.matrixL(); // precalculate inverse of covMat and weights for predictions covMatInv = llt.solve(Eigen::MatrixXd::Identity(size, size)); weights = covMatInv * outputCentered; // likelihood of evidence given parameters score = std::exp(-0.5 * outputCentered.dot(weights)) / l.diagonal().prod(); if (std::isnan(score)) { // error score calculation failed utils::ExceptionHandler::exception("GaussianProcess: invalid score ", score); } } }; public: /** * Constructor * @param dims number of input dimensions * @param sigma fixed noise * @param rngRef reference to rng */ GaussianProcess(size_t dims, double sigma, Random &rngRef) : _inputs(), _outputs(), _dims(dims), _sigma(sigma), _hypers(), _rng(rngRef) {} /** * Discard all evidence. */ void clear() { _inputs.clear(); } /** * Get the number of evidence provided. * @return */ size_t numEvidence() const { return _inputs.size(); } /** * Provide a input-output pair as evidence. * Each evidence improve the quality of future predictions. * @param input x * @param output f(x) */ void addEvidence(Vector input, double output) { auto inputVec = static_cast<Eigen::VectorXd>(input); if (static_cast<size_t>(inputVec.size()) != _dims) { utils::ExceptionHandler::exception("GaussianProcess: size of input {} does not match specified dimensions {}", inputVec.size(), _dims); } if (_inputs.empty()) { // first evidence _evidenceMinValue = _evidenceMaxValue = output; _evidenceMinVector = _evidenceMaxVector = input; } else if (output < _evidenceMinValue) { _evidenceMinValue = output; _evidenceMinVector = input; } else if (output > _evidenceMaxValue) { _evidenceMaxValue = output; _evidenceMaxVector = input; } _inputs.push_back(input); long newSize = _inputs.size(); // extend output vector _outputs.conservativeResize(newSize, Eigen::NoChange_t()); _outputs(newSize - 1) = output; updateHyperparameters(); } /** * Get the evidence with the smallest output value * @return input of min */ Vector getEvidenceMin() { if (_inputs.empty()) { utils::ExceptionHandler::exception("GaussianProcess has no evidence"); } return _evidenceMinVector; } /** * Get the evidence with the highest output value * @return input of max */ Vector getEvidenceMax() { if (_inputs.empty()) { utils::ExceptionHandler::exception("GaussianProcess has no evidence"); } return _evidenceMaxVector; } /** * Try to predict f(x) using the evidence * provided so far. * @param input x * @return expected output of f(x) */ double predictMean(const Vector &input) const { auto inputVec = static_cast<Eigen::VectorXd>(input); if (static_cast<size_t>(inputVec.size()) != _dims) { utils::ExceptionHandler::exception("GaussianProcess: size of input {} does not match specified dimensions {}", inputVec.size(), _dims); } // default mean 0. if (_inputs.size() == 0) return 0.; double result = 0.; for (auto &hyper : _hypers) { result += hyper.score * (hyper.mean + kernelVector(input, hyper.theta, hyper.dimScales).dot(hyper.weights)); } return result; } /** * The variance of the predicted f(x) from predictMean(). * @param input x * @return variance */ double predictVar(const Vector &input) const { auto inputVec = static_cast<Eigen::VectorXd>(input); if (static_cast<size_t>(inputVec.size()) != _dims) { utils::ExceptionHandler::exception("GaussianProcess: size of input {} does not match specified dimensions {}", inputVec.size(), _dims); } // default variance 1. if (_inputs.size() == 0) return 1.; double result = 0.; for (auto &hyper : _hypers) { Eigen::VectorXd kVec = kernelVector(input, hyper.theta, hyper.dimScales); result += hyper.score * (kernel(input, input, hyper.theta, hyper.dimScales) - kVec.dot(hyper.covMatInv * kVec)); } return result; } /** * Calculates the acquisition function for given input. * @param af acquisition function a:input->double * @param input i * @return a(i). This value can be compared with values a(x) of other inputs x to weigh which input would give the * most gain if its evidence were provided. */ inline double calcAcquisition(AcquisitionFunctionOption af, const Vector &input) const { switch (af) { case AcquisitionFunctionOption::upperConfidenceBound: { return predictMean(input) + 2 * std::sqrt(predictVar(input)); } case AcquisitionFunctionOption::lowerConfidenceBound: { return predictMean(input) - 2 * std::sqrt(predictVar(input)); } case AcquisitionFunctionOption::mean: { return predictMean(input); } case AcquisitionFunctionOption::variance: { return predictVar(input); } case AcquisitionFunctionOption::probabilityOfDecrease: { return utils::Math::normalCDF((_evidenceMinValue - predictMean(input)) / std::sqrt(predictVar(input))); } case AcquisitionFunctionOption::expectedDecrease: { double mean = predictMean(input); double stddev = std::sqrt(predictVar(input)); double minNormed = (_evidenceMinValue - mean) / stddev; return (_evidenceMinValue - mean) * utils::Math::normalCDF(minNormed) + stddev * utils::Math::normalPDF(minNormed); } } autopas::utils::ExceptionHandler::exception("GaussianProcess.calcAcquisition: Unknown acquisition function {}.", af); return 0; } /** * Find the input in samples which maximizes given aquisition function. * TODO: maybe add parameters for hyperparameters of aquisition functions * @param af function to maximize * @param samples * @return */ Vector sampleAquisitionMax(AcquisitionFunctionOption af, const std::vector<Vector> &samples) const { int maxIdx = -1; double maxVal = 0.; // find maximum from samples for (unsigned i = 0; i < samples.size(); ++i) { double val = calcAcquisition(af, samples[i]); if (maxIdx == -1 || val > maxVal) { maxIdx = i; maxVal = val; } } return samples[maxIdx]; } /** * Find the input in samples which minimizes given aquisition function. * TODO: maybe add parameters for hyperparameters of aquisition functions * @param af function to minimize * @param samples * @return */ Vector sampleAquisitionMin(AcquisitionFunctionOption af, const std::vector<Vector> &samples) const { int minIdx = -1; double minVal = 0.; // find minimum from samples for (unsigned i = 0; i < samples.size(); ++i) { double val = calcAcquisition(af, samples[i]); if (minIdx == -1 || val < minVal) { minIdx = i; minVal = val; } } return samples[minIdx]; } private: /** * Update the hyperparameters: theta, dimScale. * To do so, hyperparameter-samples are randomly generated. * The samples are combined using a weighted average. The weight of a sample * equals to the probability that given evidence and hyperparameter-sample * generates given output. */ inline void updateHyperparameters() { // number of evidence size_t newSize = _inputs.size(); _hypers.clear(); // if no evidence if (newSize == 0) { // use default values return; } if (newSize == 1) { // default values for one evidence _hypers.emplace_back(_outputs[0], _outputs[0] * _outputs[0], Eigen::VectorXd::Ones(_dims)); _hypers[0].precalculate(_sigma, _inputs, _outputs); } else { // range of mean // inside bounds of evidence outputs NumberInterval<double> meanRange(_evidenceMinValue, _evidenceMaxValue); // range of theta // max sample stddev: (max - min) // max stddev from zero: abs(min) & abs(max) double thetaMax = std::pow( std::max({_evidenceMaxValue - _evidenceMinValue, std::abs(_evidenceMinValue), std::abs(_evidenceMaxValue)}), 2); // at least sigma thetaMax = std::max(thetaMax, _sigma); NumberInterval<double> thetaRange(_sigma, thetaMax); // range of dimScale // Assuming most distances are greater equal 1. // For a dimScale d > 5 + ln(thetaMax): theta * exp(-d r) < 1%. So choosing // a greater dimScale may lead to many kernels close to zero. // But if needed the upper bound can be increased. NumberInterval<double> dimScaleRange(0., 5. + std::max(0., std::log(thetaMax))); // generate mean auto sample_means = meanRange.uniformSample(hp_sample_size, _rng); // generate theta auto sample_thetas = thetaRange.uniformSample(hp_sample_size, _rng); // generate dimScale std::vector<std::vector<double>> sample_dimScaleData; for (size_t d = 0; d < _dims; ++d) { sample_dimScaleData.push_back(dimScaleRange.uniformSample(hp_sample_size, _rng)); } // convert dimScales to Vectors std::vector<Eigen::VectorXd> sample_dimScales; for (size_t t = 0; t < hp_sample_size; ++t) { std::vector<double> dimScaleData; for (size_t d = 0; d < _dims; ++d) { dimScaleData.push_back(sample_dimScaleData[d][t]); } Eigen::VectorXd dimScale = Eigen::Map<Eigen::VectorXd>(dimScaleData.data(), dimScaleData.size()); sample_dimScales.push_back(std::move(dimScale)); } // initialize hyperparameter samples _hypers.reserve(hp_sample_size); for (size_t t = 0; t < hp_sample_size; ++t) { _hypers.emplace_back(sample_means[t], sample_thetas[t], sample_dimScales[t]); } // precalculate matrices for all hyperparameters // @TODO find sensible chunkSize #ifdef AUTOPAS_OPENMP const size_t chunkSize = std::max(hp_sample_size / (autopas_get_num_threads() * 10), 1ul); #pragma omp parallel for schedule(dynamic, chunkSize) #endif for (size_t t = 0; t < hp_sample_size; ++t) { _hypers[t].precalculate(_sigma, _inputs, _outputs); } // sort by score std::sort(_hypers.begin(), _hypers.end(), [](const Hyperparameters &h1, const Hyperparameters &h2) { return h1.score > h2.score; }); // only keep top 'hp_size' hyperparameters _hypers.resize(hp_size); } // normalize scores double scoreSum = 0.; for (auto &hyper : _hypers) { scoreSum += hyper.score; } for (auto &hyper : _hypers) { hyper.score /= scoreSum; } } /** * Kernel function to describe similarity between two inputs * using given hyperparameters. * @param input1 * @param input2 * @param theta * @param dimScale * @return */ static inline double kernel(const Vector &input1, const Vector &input2, double theta, const Eigen::VectorXd &dimScale) { double dot = 0; for (int i = 0; i < input1.size(); ++i) { double dist = input1[i] - input2[i]; dist *= dist * dimScale[i]; dot += dist; } return theta * std::exp(-dot); } /** * Calculates the kernel between input and all evidence. * @param input * @return Vector of covariances */ Eigen::VectorXd kernelVector(const Vector &input, double theta, const Eigen::VectorXd &dimScale) const { std::vector<double> k(_inputs.size()); for (size_t i = 0; i < k.size(); ++i) { k[i] = kernel(input, _inputs[i], theta, dimScale); } return Eigen::Map<Eigen::VectorXd>(k.data(), k.size()); } std::vector<Vector> _inputs; Eigen::VectorXd _outputs; /** * Current smallest evidence output */ double _evidenceMinValue; /** * Current smallest evidence input */ Vector _evidenceMinVector; /** * Current greatest evidence output */ double _evidenceMaxValue; /** * Current greatest evidence input */ Vector _evidenceMaxVector; /** * input dimensions */ const size_t _dims; /** * fixed noise assumed */ const double _sigma; /** * hyperparameters */ std::vector<Hyperparameters> _hypers; Random &_rng; }; } // namespace autopas
GB_binop__bshift_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 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__bshift_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__bshift_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__bshift_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__bshift_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bshift_uint32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bshift_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__bshift_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bshift_uint32) // C=scalar+B GB (_bind1st__bshift_uint32) // C=scalar+B' GB (_bind1st_tran__bshift_uint32) // C=A+scalar GB (_bind2nd__bshift_uint32) // C=A'+scalar GB (_bind2nd_tran__bshift_uint32) // C type: uint32_t // A type: uint32_t // B,b type: int8_t // BinaryOp: cij = GB_bitshift_uint32 (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ uint32_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 0 // 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 \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_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_bitshift_uint32 (x, y) ; // 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_BSHIFT || GxB_NO_UINT32 || GxB_NO_BSHIFT_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__bshift_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__bshift_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 { #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__bshift_uint32) ( 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, 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 uint32_t *restrict Cx = (uint32_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, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_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__bshift_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, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__bshift_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_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__bshift_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_04__bshift_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_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__bshift_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__bshift_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 bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t x = (*((uint32_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_bitshift_uint32 (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bshift_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 ; uint32_t *Cx = (uint32_t *) Cx_output ; uint32_t *Ax = (uint32_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 ; uint32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_bitshift_uint32 (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) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_uint32 (x, aij) ; \ } GrB_Info GB (_bind1st_tran__bshift_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 \ int8_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 = GBX (Ax, pA, false) ; \ Cx [pC] = GB_bitshift_uint32 (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__bshift_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 int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_int32_int16.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__identity_int32_int16 // op(A') function: GB_unop_tran__identity_int32_int16 // C type: int32_t // A type: int16_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ int16_t #define GB_CTYPE \ int32_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) \ int32_t z = (int32_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ int16_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ int32_t z = (int32_t) aij ; \ Cx [pC] = z ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__identity_int32_int16 ( int32_t *Cx, // Cx and Ax may be aliased const int16_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++) { int16_t aij = Ax [p] ; int32_t z = (int32_t) 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_int32_int16 ( 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
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_lock.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, ...) { int gtid = __kmp_entry_gtid(); #if (KMP_STATS_ENABLED) int inParallel = __kmpc_in_parallel(loc); if (inParallel) { KMP_COUNT_BLOCK(OMP_NESTED_PARALLEL); } else { KMP_COUNT_BLOCK(OMP_PARALLEL); } #endif // maybe to save thr_state is enough here { va_list ap; va_start( ap, microtask ); #if OMPT_SUPPORT ompt_frame_t* ompt_frame; if (ompt_enabled) { kmp_info_t *master_th = __kmp_threads[ gtid ]; kmp_team_t *parent_team = master_th->th.th_team; ompt_lw_taskteam_t *lwt = parent_team->t.ompt_serialized_team_info; if (lwt) ompt_frame = &(lwt->ompt_task_info.frame); else { int tid = __kmp_tid_from_gtid( gtid ); ompt_frame = &(parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame); } ompt_frame->reenter_runtime_frame = __builtin_frame_address(1); } #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 #if OMPT_SUPPORT , fork_context_intel #endif ); va_end( ap ); } } #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 ); KMP_COUNT_BLOCK(OMP_TEAMS); // 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_enabled) { parent_team->t.t_implicit_task_taskdata[tid]. ompt_task_info.frame.reenter_runtime_frame = __builtin_frame_address(1); } #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 #if OMPT_SUPPORT , fork_context_intel #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_45_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 USE_ITT_BUILD_ARG(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 ( __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 _mm_mfence(); #elif KMP_COMPILER_MSVC MemoryBarrier(); #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); 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 ); } #if OMPT_SUPPORT && OMPT_TRACE ompt_frame_t * ompt_frame; if (ompt_enabled ) { ompt_frame = __ompt_get_task_frame_internal(0); if ( ompt_frame->reenter_runtime_frame == NULL ) ompt_frame->reenter_runtime_frame = __builtin_frame_address(1); } #endif __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 ); #if OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled ) { ompt_frame->reenter_runtime_frame = NULL; } #endif } /* 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) { 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 )) { KMP_COUNT_BLOCK(OMP_MASTER); KMP_PUSH_PARTITIONED_TIMER(OMP_master); status = 1; } #if OMPT_SUPPORT && OMPT_TRACE if (status) { if (ompt_enabled && 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 )); KMP_POP_PARTITIONED_TIMER(); #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_enabled && 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_enabled) { /* 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_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_enabled) { /* 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_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_enabled && 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 void __kmp_init_indirect_csptr(kmp_critical_name * crit, ident_t const * loc, kmp_int32 gtid, kmp_indirect_locktag_t tag) { // Pointer to the allocated indirect lock is written to crit, while indexing is ignored. void *idx; kmp_indirect_lock_t **lck; lck = (kmp_indirect_lock_t **)crit; kmp_indirect_lock_t *ilk = __kmp_allocate_indirect_lock(&idx, gtid, tag); KMP_I_LOCK_FUNC(ilk, init)(ilk->lock); KMP_SET_I_LOCK_LOCATION(ilk, loc); KMP_SET_I_LOCK_FLAGS(ilk, kmp_lf_critical_section); KA_TRACE(20, ("__kmp_init_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 // We don't really need to destroy the unclaimed lock here since it will be cleaned up at program exit. //KMP_D_LOCK_FUNC(&idx, destroy)((kmp_dyna_lock_t *)&idx); } KMP_DEBUG_ASSERT(*lck != NULL); } // Fast-path acquire tas lock #define KMP_ACQUIRE_TAS_LOCK(lock, gtid) { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ if (l->lk.poll != KMP_LOCK_FREE(tas) || \ ! KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), KMP_LOCK_FREE(tas), KMP_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); \ } \ kmp_backoff_t backoff = __kmp_spin_backoff_params; \ while (l->lk.poll != KMP_LOCK_FREE(tas) || \ ! KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), KMP_LOCK_FREE(tas), KMP_LOCK_BUSY(gtid+1, tas))) { \ __kmp_spin_backoff(&backoff); \ 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 KMP_TEST_TAS_LOCK(lock, gtid, rc) { \ kmp_tas_lock_t *l = (kmp_tas_lock_t *)lock; \ rc = l->lk.poll == KMP_LOCK_FREE(tas) && \ KMP_COMPARE_AND_STORE_ACQ32(&(l->lk.poll), KMP_LOCK_FREE(tas), KMP_LOCK_BUSY(gtid+1, tas)); \ } // Fast-path release tas lock #define KMP_RELEASE_TAS_LOCK(lock, gtid) { \ TCW_4(((kmp_tas_lock_t *)lock)->lk.poll, KMP_LOCK_FREE(tas)); \ KMP_MB(); \ } #if KMP_USE_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 KMP_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), KMP_LOCK_FREE(futex), \ KMP_LOCK_BUSY(gtid_code, futex))) != KMP_LOCK_FREE(futex)) { \ kmp_int32 cond = KMP_LOCK_STRIP(poll_val) & 1; \ if (!cond) { \ if (!KMP_COMPARE_AND_STORE_RET32(&(ftx->lk.poll), poll_val, poll_val | KMP_LOCK_BUSY(1, futex))) { \ continue; \ } \ poll_val |= KMP_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 KMP_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), KMP_LOCK_FREE(futex), KMP_LOCK_BUSY(gtid+1 << 1, futex))) { \ KMP_FSYNC_ACQUIRED(ftx); \ rc = TRUE; \ } else { \ rc = FALSE; \ } \ } // Fast-path release futex lock #define KMP_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), KMP_LOCK_FREE(futex)); \ if (KMP_LOCK_STRIP(poll_val) & 1) { \ syscall(__NR_futex, &(ftx->lk.poll), FUTEX_WAKE, KMP_LOCK_BUSY(1, futex), NULL, NULL, 0); \ } \ KMP_MB(); \ KMP_YIELD(TCR_4(__kmp_nth) > (__kmp_avail_proc ? __kmp_avail_proc : __kmp_xproc)); \ } #endif // KMP_USE_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 ) { #if KMP_USE_DYNAMIC_LOCK __kmpc_critical_with_hint(loc, global_tid, crit, omp_lock_hint_none); #else KMP_COUNT_BLOCK(OMP_CRITICAL); KMP_TIME_PARTITIONED_BLOCK(OMP_critical_wait); /* Time spent waiting to enter the critical section */ kmp_user_lock_p lck; KC_TRACE( 10, ("__kmpc_critical: called T#%d\n", global_tid ) ); //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_USE_FUTEX 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 ); #if USE_ITT_BUILD __kmp_itt_critical_acquired( lck ); #endif /* USE_ITT_BUILD */ KMP_START_EXPLICIT_TIMER(OMP_critical); KA_TRACE( 15, ("__kmpc_critical: done T#%d\n", global_tid )); #endif // KMP_USE_DYNAMIC_LOCK } #if KMP_USE_DYNAMIC_LOCK // Converts the given hint to an internal lock implementation static __forceinline kmp_dyna_lockseq_t __kmp_map_hint_to_lock(uintptr_t hint) { #if KMP_USE_TSX # define KMP_TSX_LOCK(seq) lockseq_##seq #else # define KMP_TSX_LOCK(seq) __kmp_user_lock_seq #endif #if KMP_ARCH_X86 || KMP_ARCH_X86_64 # define KMP_CPUINFO_RTM (__kmp_cpuinfo.rtm) #else # define KMP_CPUINFO_RTM 0 #endif // Hints that do not require further logic if (hint & kmp_lock_hint_hle) return KMP_TSX_LOCK(hle); if (hint & kmp_lock_hint_rtm) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(rtm): __kmp_user_lock_seq; if (hint & kmp_lock_hint_adaptive) return KMP_CPUINFO_RTM ? KMP_TSX_LOCK(adaptive): __kmp_user_lock_seq; // Rule out conflicting hints first by returning the default lock if ((hint & omp_lock_hint_contended) && (hint & omp_lock_hint_uncontended)) return __kmp_user_lock_seq; if ((hint & omp_lock_hint_speculative) && (hint & omp_lock_hint_nonspeculative)) return __kmp_user_lock_seq; // Do not even consider speculation when it appears to be contended if (hint & omp_lock_hint_contended) return lockseq_queuing; // Uncontended lock without speculation if ((hint & omp_lock_hint_uncontended) && !(hint & omp_lock_hint_speculative)) return lockseq_tas; // HLE lock for speculation if (hint & omp_lock_hint_speculative) return KMP_TSX_LOCK(hle); return __kmp_user_lock_seq; } /*! @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. @param hint the lock hint. Enter code protected by a `critical` construct with a hint. The hint value is used to suggest a lock implementation. This function blocks until the executing thread can enter the critical section unless the hint suggests use of speculative execution and the hardware supports it. */ void __kmpc_critical_with_hint( ident_t * loc, kmp_int32 global_tid, kmp_critical_name * crit, uintptr_t hint ) { KMP_COUNT_BLOCK(OMP_CRITICAL); kmp_user_lock_p lck; KC_TRACE( 10, ("__kmpc_critical: called T#%d\n", global_tid ) ); kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. if (*lk == 0) { kmp_dyna_lockseq_t lckseq = __kmp_map_hint_to_lock(hint); if (KMP_IS_D_LOCK(lckseq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(lckseq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(lckseq)); } } // Branch for accessing the actual lock object and set operation. This branching is inevitable since // this lock initialization does not follow the normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } # if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); # endif # if KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(lck, global_tid); } else # elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(lck, global_tid); } else # endif { KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_map_hint_to_lock(hint)); } # if USE_ITT_BUILD __kmp_itt_critical_acquiring(lck); # endif KMP_I_LOCK_FUNC(ilk, set)(lck, global_tid); } #if USE_ITT_BUILD __kmp_itt_critical_acquired( lck ); #endif /* USE_ITT_BUILD */ KMP_PUSH_PARTITIONED_TIMER(OMP_critical); KA_TRACE( 15, ("__kmpc_critical: done T#%d\n", global_tid )); } // __kmpc_critical_with_hint #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. 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 (KMP_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 KMP_USE_INLINED_TAS if (__kmp_user_lock_seq == lockseq_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(lck, global_tid); } else # elif KMP_USE_INLINED_FUTEX if (__kmp_user_lock_seq == lockseq_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(lck, global_tid); } else # endif { KMP_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 KMP_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_USE_FUTEX 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_enabled && 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 KMP_POP_PARTITIONED_TIMER(); 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_int32 rc = __kmp_enter_single( global_tid, loc, TRUE ); if (rc) { // We are going to execute the single statement, so we should count it. KMP_COUNT_BLOCK(OMP_SINGLE); KMP_PUSH_PARTITIONED_TIMER(OMP_single); } #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_enabled) { 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 ); KMP_POP_PARTITIONED_TIMER(); #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_enabled && 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 if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_loop_end)) { ompt_team_info_t *team_info = __ompt_get_teaminfo(0, NULL); ompt_task_info_t *task_info = __ompt_get_taskinfo(0); ompt_callbacks.ompt_callback(ompt_event_loop_end)( team_info->parallel_id, 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 ) ); } void kmpc_set_disp_num_buffers( int arg ) { // ignore after initialization because some teams have already // allocated dispatch buffers if( __kmp_init_serial == 0 && arg > 0 ) __kmp_dispatch_num_buffers = arg; } 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 */ #if KMP_USE_DYNAMIC_LOCK // internal lock initializer static __forceinline void __kmp_init_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { if (KMP_IS_D_LOCK(seq)) { KMP_INIT_D_LOCK(lock, seq); #if USE_ITT_BUILD __kmp_itt_lock_creating((kmp_user_lock_p)lock, NULL); #endif } else { KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } } // internal nest lock initializer static __forceinline void __kmp_init_nest_lock_with_hint(ident_t *loc, void **lock, kmp_dyna_lockseq_t seq) { #if KMP_USE_TSX // Don't have nested lock implementation for speculative locks if (seq == lockseq_hle || seq == lockseq_rtm || seq == lockseq_adaptive) seq = __kmp_user_lock_seq; #endif switch (seq) { case lockseq_tas: seq = lockseq_nested_tas; break; #if KMP_USE_FUTEX case lockseq_futex: seq = lockseq_nested_futex; break; #endif case lockseq_ticket: seq = lockseq_nested_ticket; break; case lockseq_queuing: seq = lockseq_nested_queuing; break; case lockseq_drdpa: seq = lockseq_nested_drdpa; break; default: seq = lockseq_nested_queuing; } KMP_INIT_I_LOCK(lock, seq); #if USE_ITT_BUILD kmp_indirect_lock_t *ilk = KMP_LOOKUP_I_LOCK(lock); __kmp_itt_lock_creating(ilk->lock, loc); #endif } /* initialize the lock with a hint */ void __kmpc_init_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_lock_with_hint"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); } /* initialize the lock with a hint */ void __kmpc_init_nest_lock_with_hint(ident_t *loc, kmp_int32 gtid, void **user_lock, uintptr_t hint) { KMP_DEBUG_ASSERT(__kmp_init_serial); if (__kmp_env_consistency_check && user_lock == NULL) { KMP_FATAL(LockIsUninitialized, "omp_init_nest_lock_with_hint"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_map_hint_to_lock(hint)); } #endif // KMP_USE_DYNAMIC_LOCK /* 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"); } __kmp_init_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #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_USE_FUTEX 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 OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_init_lock)) { ompt_callbacks.ompt_callback(ompt_event_init_lock)((uint64_t) lck); } #endif #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"); } __kmp_init_nest_lock_with_hint(loc, user_lock, __kmp_user_lock_seq); #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_USE_FUTEX 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 OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_init_nest_lock)) { ompt_callbacks.ompt_callback(ompt_event_init_nest_lock)((uint64_t) lck); } #endif #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 (KMP_EXTRACT_D_TAG(user_lock) == 0) { lck = ((kmp_indirect_lock_t *)KMP_LOOKUP_I_LOCK(user_lock))->lock; } else { lck = (kmp_user_lock_p)user_lock; } __kmp_itt_lock_destroyed(lck); # endif KMP_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_USE_FUTEX 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 OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_destroy_lock)) { ompt_callbacks.ompt_callback(ompt_event_destroy_lock)((uint64_t) lck); } #endif #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_USE_FUTEX 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 = KMP_LOOKUP_I_LOCK(user_lock); __kmp_itt_lock_destroyed(ilk->lock); # endif KMP_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_USE_FUTEX 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 OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_destroy_nest_lock)) { ompt_callbacks.ompt_callback(ompt_event_destroy_nest_lock)((uint64_t) lck); } #endif #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_USE_FUTEX 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 = KMP_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 KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_ACQUIRE_TAS_LOCK(user_lock, gtid); } else # elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_ACQUIRE_FUTEX_LOCK(user_lock, gtid); } else # endif { __kmp_direct_set[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_USE_FUTEX 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 */ #if OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled && ompt_callbacks.ompt_callback(ompt_event_acquired_lock)) { ompt_callbacks.ompt_callback(ompt_event_acquired_lock)((uint64_t) lck); } #endif #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 KMP_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 #if OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled) { // missing support here: need to know whether acquired first or not } #endif #else // KMP_USE_DYNAMIC_LOCK int acquire_status; 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_USE_FUTEX 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, &acquire_status ); #if USE_ITT_BUILD __kmp_itt_lock_acquired( lck ); #endif /* USE_ITT_BUILD */ #if OMPT_SUPPORT && OMPT_TRACE if (ompt_enabled) { if (acquire_status == KMP_LOCK_ACQUIRED_FIRST) { if(ompt_callbacks.ompt_callback(ompt_event_acquired_nest_lock_first)) ompt_callbacks.ompt_callback(ompt_event_acquired_nest_lock_first)((uint64_t) lck); } else { if(ompt_callbacks.ompt_callback(ompt_event_acquired_nest_lock_next)) ompt_callbacks.ompt_callback(ompt_event_acquired_nest_lock_next)((uint64_t) lck); } } #endif #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 = KMP_EXTRACT_D_TAG(user_lock); # if USE_ITT_BUILD __kmp_itt_lock_releasing((kmp_user_lock_p)user_lock); # endif # if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_RELEASE_TAS_LOCK(user_lock, gtid); } else # elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_RELEASE_FUTEX_LOCK(user_lock, gtid); } else # endif { __kmp_direct_unset[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_USE_FUTEX 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_enabled && 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 KMP_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_USE_FUTEX 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_enabled) { 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); #if KMP_USE_DYNAMIC_LOCK int rc; int tag = KMP_EXTRACT_D_TAG(user_lock); # if USE_ITT_BUILD __kmp_itt_lock_acquiring((kmp_user_lock_p)user_lock); # endif # if KMP_USE_INLINED_TAS if (tag == locktag_tas && !__kmp_env_consistency_check) { KMP_TEST_TAS_LOCK(user_lock, gtid, rc); } else # elif KMP_USE_INLINED_FUTEX if (tag == locktag_futex && !__kmp_env_consistency_check) { KMP_TEST_FUTEX_LOCK(user_lock, gtid, rc); } else # endif { rc = __kmp_direct_test[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_USE_FUTEX 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 = KMP_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_USE_FUTEX 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 threading profile tool 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 kmp_dyna_lock_t *lk = (kmp_dyna_lock_t *)crit; // Check if it is initialized. if (*lk == 0) { if (KMP_IS_D_LOCK(__kmp_user_lock_seq)) { KMP_COMPARE_AND_STORE_ACQ32((volatile kmp_int32 *)crit, 0, KMP_GET_D_TAG(__kmp_user_lock_seq)); } else { __kmp_init_indirect_csptr(crit, loc, global_tid, KMP_GET_I_TAG(__kmp_user_lock_seq)); } } // Branch for accessing the actual lock object and set operation. This branching is inevitable since // this lock initialization does not follow the normal dispatch path (lock table is not used). if (KMP_EXTRACT_D_TAG(lk) != 0) { lck = (kmp_user_lock_p)lk; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_D_LOCK_FUNC(lk, set)(lk, global_tid); } else { kmp_indirect_lock_t *ilk = *((kmp_indirect_lock_t **)lk); lck = ilk->lock; KMP_DEBUG_ASSERT(lck != NULL); if (__kmp_env_consistency_check) { __kmp_push_sync(global_tid, ct_critical, loc, lck, __kmp_user_lock_seq); } KMP_I_LOCK_FUNC(ilk, set)(lck, 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 (KMP_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); KMP_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); KMP_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 threading profile tool // (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 threading profile tool // (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 threading profile tool // (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 nS, int sO, int nC, int cO, int nT) { if ( ! __kmp_init_serial ) { __kmp_serial_initialize(); } __kmp_place_num_sockets = nS; __kmp_place_socket_offset = sO; __kmp_place_num_cores = nC; __kmp_place_core_offset = cO; __kmp_place_num_threads_per_core = nT; } #if OMP_45_ENABLED /*! @ingroup WORK_SHARING @param loc source location information. @param gtid global thread number. @param num_dims number of associated doacross loops. @param dims info on loops bounds. Initialize doacross loop information. Expect compiler send us inclusive bounds, e.g. for(i=2;i<9;i+=2) lo=2, up=8, st=2. */ void __kmpc_doacross_init(ident_t *loc, int gtid, int num_dims, struct kmp_dim * dims) { int j, idx; kmp_int64 last, trace_count; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_uint32 *flags; kmp_disp_t *pr_buf = th->th.th_dispatch; dispatch_shared_info_t *sh_buf; KA_TRACE(20,("__kmpc_doacross_init() enter: called T#%d, num dims %d, active %d\n", gtid, num_dims, !team->t.t_serialized)); KMP_DEBUG_ASSERT(dims != NULL); KMP_DEBUG_ASSERT(num_dims > 0); if( team->t.t_serialized ) { KA_TRACE(20,("__kmpc_doacross_init() exit: serialized team\n")); return; // no dependencies if team is serialized } KMP_DEBUG_ASSERT(team->t.t_nproc > 1); idx = pr_buf->th_doacross_buf_idx++; // Increment index of shared buffer for the next loop sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; // Save bounds info into allocated private buffer KMP_DEBUG_ASSERT(pr_buf->th_doacross_info == NULL); pr_buf->th_doacross_info = (kmp_int64*)__kmp_thread_malloc(th, sizeof(kmp_int64)*(4 * num_dims + 1)); KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); pr_buf->th_doacross_info[0] = (kmp_int64)num_dims; // first element is number of dimensions // Save also address of num_done in order to access it later without knowing the buffer index pr_buf->th_doacross_info[1] = (kmp_int64)&sh_buf->doacross_num_done; pr_buf->th_doacross_info[2] = dims[0].lo; pr_buf->th_doacross_info[3] = dims[0].up; pr_buf->th_doacross_info[4] = dims[0].st; last = 5; for( j = 1; j < num_dims; ++j ) { kmp_int64 range_length; // To keep ranges of all dimensions but the first dims[0] if( dims[j].st == 1 ) { // most common case // AC: should we care of ranges bigger than LLONG_MAX? (not for now) range_length = dims[j].up - dims[j].lo + 1; } else { if( dims[j].st > 0 ) { KMP_DEBUG_ASSERT(dims[j].up > dims[j].lo); range_length = (kmp_uint64)(dims[j].up - dims[j].lo) / dims[j].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[j].lo > dims[j].up); range_length = (kmp_uint64)(dims[j].lo - dims[j].up) / (-dims[j].st) + 1; } } pr_buf->th_doacross_info[last++] = range_length; pr_buf->th_doacross_info[last++] = dims[j].lo; pr_buf->th_doacross_info[last++] = dims[j].up; pr_buf->th_doacross_info[last++] = dims[j].st; } // Compute total trip count. // Start with range of dims[0] which we don't need to keep in the buffer. if( dims[0].st == 1 ) { // most common case trace_count = dims[0].up - dims[0].lo + 1; } else if( dims[0].st > 0 ) { KMP_DEBUG_ASSERT(dims[0].up > dims[0].lo); trace_count = (kmp_uint64)(dims[0].up - dims[0].lo) / dims[0].st + 1; } else { // negative increment KMP_DEBUG_ASSERT(dims[0].lo > dims[0].up); trace_count = (kmp_uint64)(dims[0].lo - dims[0].up) / (-dims[0].st) + 1; } for( j = 1; j < num_dims; ++j ) { trace_count *= pr_buf->th_doacross_info[4 * j + 1]; // use kept ranges } KMP_DEBUG_ASSERT(trace_count > 0); // Check if shared buffer is not occupied by other loop (idx - __kmp_dispatch_num_buffers) if( idx != sh_buf->doacross_buf_idx ) { // Shared buffer is occupied, wait for it to be free __kmp_wait_yield_4( (kmp_uint32*)&sh_buf->doacross_buf_idx, idx, __kmp_eq_4, NULL ); } // Check if we are the first thread. After the CAS the first thread gets 0, // others get 1 if initialization is in progress, allocated pointer otherwise. flags = (kmp_uint32*)KMP_COMPARE_AND_STORE_RET64( (kmp_int64*)&sh_buf->doacross_flags,NULL,(kmp_int64)1); if( flags == NULL ) { // we are the first thread, allocate the array of flags kmp_int64 size = trace_count / 8 + 8; // in bytes, use single bit per iteration sh_buf->doacross_flags = (kmp_uint32*)__kmp_thread_calloc(th, size, 1); } else if( (kmp_int64)flags == 1 ) { // initialization is still in progress, need to wait while( (volatile kmp_int64)sh_buf->doacross_flags == 1 ) { KMP_YIELD(TRUE); } } KMP_DEBUG_ASSERT((kmp_int64)sh_buf->doacross_flags > 1); // check value of pointer pr_buf->th_doacross_flags = sh_buf->doacross_flags; // save private copy in order to not // touch shared buffer on each iteration KA_TRACE(20,("__kmpc_doacross_init() exit: T#%d\n", gtid)); } void __kmpc_doacross_wait(ident_t *loc, int gtid, long long *vec) { kmp_int32 shft, num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, up, st; KA_TRACE(20,("__kmpc_doacross_wait() enter: called T#%d\n", gtid)); if( team->t.t_serialized ) { KA_TRACE(20,("__kmpc_doacross_wait() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number and check out-of-bounds condition pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; up = pr_buf->th_doacross_info[3]; st = pr_buf->th_doacross_info[4]; if( st == 1 ) { // most common case if( vec[0] < lo || vec[0] > up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = vec[0] - lo; } else if( st > 0 ) { if( vec[0] < lo || vec[0] > up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment if( vec[0] > lo || vec[0] < up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[0], lo, up)); return; } iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } for( i = 1; i < num_dims; ++i ) { kmp_int64 iter, ln; kmp_int32 j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; up = pr_buf->th_doacross_info[j + 3]; st = pr_buf->th_doacross_info[j + 4]; if( st == 1 ) { if( vec[i] < lo || vec[i] > up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = vec[i] - lo; } else if( st > 0 ) { if( vec[i] < lo || vec[i] > up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 if( vec[i] > lo || vec[i] < up ) { KA_TRACE(20,( "__kmpc_doacross_wait() exit: T#%d iter %lld is out of bounds [%lld,%lld]\n", gtid, vec[i], lo, up)); return; } iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; } shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; while( (flag & pr_buf->th_doacross_flags[iter_number]) == 0 ) { KMP_YIELD(TRUE); } KA_TRACE(20,("__kmpc_doacross_wait() exit: T#%d wait for iter %lld completed\n", gtid, (iter_number<<5)+shft)); } void __kmpc_doacross_post(ident_t *loc, int gtid, long long *vec) { kmp_int32 shft, num_dims, i; kmp_uint32 flag; kmp_int64 iter_number; // iteration number of "collapsed" loop nest kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf; kmp_int64 lo, st; KA_TRACE(20,("__kmpc_doacross_post() enter: called T#%d\n", gtid)); if( team->t.t_serialized ) { KA_TRACE(20,("__kmpc_doacross_post() exit: serialized team\n")); return; // no dependencies if team is serialized } // calculate sequential iteration number (same as in "wait" but no out-of-bounds checks) pr_buf = th->th.th_dispatch; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info != NULL); num_dims = pr_buf->th_doacross_info[0]; lo = pr_buf->th_doacross_info[2]; st = pr_buf->th_doacross_info[4]; if( st == 1 ) { // most common case iter_number = vec[0] - lo; } else if( st > 0 ) { iter_number = (kmp_uint64)(vec[0] - lo) / st; } else { // negative increment iter_number = (kmp_uint64)(lo - vec[0]) / (-st); } for( i = 1; i < num_dims; ++i ) { kmp_int64 iter, ln; kmp_int32 j = i * 4; ln = pr_buf->th_doacross_info[j + 1]; lo = pr_buf->th_doacross_info[j + 2]; st = pr_buf->th_doacross_info[j + 4]; if( st == 1 ) { iter = vec[i] - lo; } else if( st > 0 ) { iter = (kmp_uint64)(vec[i] - lo) / st; } else { // st < 0 iter = (kmp_uint64)(lo - vec[i]) / (-st); } iter_number = iter + ln * iter_number; } shft = iter_number % 32; // use 32-bit granularity iter_number >>= 5; // divided by 32 flag = 1 << shft; if( (flag & pr_buf->th_doacross_flags[iter_number]) == 0 ) KMP_TEST_THEN_OR32( (kmp_int32*)&pr_buf->th_doacross_flags[iter_number], (kmp_int32)flag ); KA_TRACE(20,("__kmpc_doacross_post() exit: T#%d iter %lld posted\n", gtid, (iter_number<<5)+shft)); } void __kmpc_doacross_fini(ident_t *loc, int gtid) { kmp_int64 num_done; kmp_info_t *th = __kmp_threads[gtid]; kmp_team_t *team = th->th.th_team; kmp_disp_t *pr_buf = th->th.th_dispatch; KA_TRACE(20,("__kmpc_doacross_fini() enter: called T#%d\n", gtid)); if( team->t.t_serialized ) { KA_TRACE(20,("__kmpc_doacross_fini() exit: serialized team %p\n", team)); return; // nothing to do } num_done = KMP_TEST_THEN_INC64((kmp_int64*)pr_buf->th_doacross_info[1]) + 1; if( num_done == th->th.th_team_nproc ) { // we are the last thread, need to free shared resources int idx = pr_buf->th_doacross_buf_idx - 1; dispatch_shared_info_t *sh_buf = &team->t.t_disp_buffer[idx % __kmp_dispatch_num_buffers]; KMP_DEBUG_ASSERT(pr_buf->th_doacross_info[1] == (kmp_int64)&sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(num_done == (kmp_int64)sh_buf->doacross_num_done); KMP_DEBUG_ASSERT(idx == sh_buf->doacross_buf_idx); __kmp_thread_free(th, (void*)sh_buf->doacross_flags); sh_buf->doacross_flags = NULL; sh_buf->doacross_num_done = 0; sh_buf->doacross_buf_idx += __kmp_dispatch_num_buffers; // free buffer for future re-use } // free private resources (need to keep buffer index forever) __kmp_thread_free(th, (void*)pr_buf->th_doacross_info); pr_buf->th_doacross_info = NULL; KA_TRACE(20,("__kmpc_doacross_fini() exit: T#%d\n", gtid)); } #endif // end of file //
sp.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 2.3 OpenMP C versions - SP This benchmark is an OpenMP C version of the NPB SP code. The OpenMP C versions are developed by RWCP and derived from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Author: R. Van der Wijngaart W. Saphir OpenMP C version: S. Satoh --------------------------------------------------------------------*/ #include "npb-C.h" /* global variables */ #include "header.h" /* function declarations */ static void add(void); static void adi(void); static void error_norm(double rms[5]); static void rhs_norm(double rms[5]); static void exact_rhs(void); static void exact_solution(double xi, double eta, double zeta, double dtemp[5]); static void initialize(void); static void lhsinit(void); static void lhsx(void); static void lhsy(void); static void lhsz(void); static void ninvr(void); static void pinvr(void); static void compute_rhs(void); static void set_constants(void); static void txinvr(void); static void tzetar(void); static void verify(int no_time_steps, char *cclass, boolean *verified); static void x_solve(void); static void y_solve(void); static void z_solve(void); /*-------------------------------------------------------------------- program SP c-------------------------------------------------------------------*/ int main(int argc, char **argv) { int niter, step; double mflops, tmax; int nthreads = 1; boolean verified; char cclass; FILE *fp; /*-------------------------------------------------------------------- c Read input file (if it exists), else take c defaults from parameters c-------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version" " - SP Benchmark\n\n"); fp = fopen("inputsp.data", "r"); if (fp != NULL) { printf(" Reading from input file inputsp.data\n"); fscanf(fp, "%d", &niter); while (fgetc(fp) != '\n'); fscanf(fp, "%lf", &dt); while (fgetc(fp) != '\n'); fscanf(fp, "%d%d%d", &grid_points[0], &grid_points[1], &grid_points[2]); fclose(fp); } else { printf(" No input file inputsp.data. Using compiled defaults"); niter = NITER_DEFAULT; dt = DT_DEFAULT; grid_points[0] = PROBLEM_SIZE; grid_points[1] = PROBLEM_SIZE; grid_points[2] = PROBLEM_SIZE; } printf(" Size: %3dx%3dx%3d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Iterations: %3d dt: %10.6f\n", niter, dt); if ( (grid_points[0] > IMAX) || (grid_points[1] > JMAX) || (grid_points[2] > KMAX) ) { printf("%d, %d, %d\n", grid_points[0], grid_points[1], grid_points[2]); printf(" Problem size too big for compiled array sizes\n"); exit(1); } set_constants(); initialize(); lhsinit(); exact_rhs(); /*-------------------------------------------------------------------- c do one time step to touch all code, and reinitialize c-------------------------------------------------------------------*/ #pragma omp parallel { adi(); } initialize(); timer_clear(1); timer_start(1); #pragma omp parallel private(step) { for (step = 1; step <= niter; step++) { if (step % 20 == 0 || step == 1) { #pragma omp master printf(" Time step %4d\n", step); } adi(); } #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif /* _OPENMP */ } /* end parallel */ timer_stop(1); tmax = timer_read(1); verify(niter, &cclass, &verified); if (tmax != 0) { mflops = ( 881.174 * pow((double)PROBLEM_SIZE, 3.0) - 4683.91 * pow2((double)PROBLEM_SIZE) + 11484.5 * (double)PROBLEM_SIZE - 19272.4) * (double)niter / (tmax*1000000.0); } else { mflops = 0.0; } c_print_results("SP", cclass, grid_points[0], grid_points[1], grid_points[2], niter, nthreads, tmax, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, "(none)"); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void add(void) { int i, j, k, m; /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c addition of update to the vector u c-------------------------------------------------------------------*/ #pragma omp for for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { u[m][i][j][k] = u[m][i][j][k] + rhs[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void adi(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ compute_rhs(); txinvr(); x_solve(); y_solve(); z_solve(); add(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void error_norm(double rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function computes the norm of the difference between the c computed solution and the exact solution c-------------------------------------------------------------------*/ int i, j, k, m, d; double xi, eta, zeta, u_exact[5], add; for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, u_exact); for (m = 0; m < 5; m++) { add = u[m][i][j][k] - u_exact[m]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void rhs_norm(double rms[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, d, m; double add; for (m = 0; m < 5; m++) { rms[m] = 0.0; } for (i = 0; i <= grid_points[0]-2; i++) { for (j = 0; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-2; k++) { for (m = 0; m < 5; m++) { add = rhs[m][i][j][k]; rms[m] = rms[m] + add*add; } } } } for (m = 0; m < 5; m++) { for (d = 0; d < 3; d++) { rms[m] = rms[m] / (double)(grid_points[d]-2); } rms[m] = sqrt(rms[m]); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_rhs(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c compute the right hand side based on exact solution c-------------------------------------------------------------------*/ double dtemp[5], xi, eta, zeta, dtpp; int m, i, j, k, ip1, im1, jp1, jm1, km1, kp1; /*-------------------------------------------------------------------- c initialize c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k= 0; k <= grid_points[2]-1; k++) { forcing[m][i][j][k] = 0.0; } } } } /*-------------------------------------------------------------------- c xi-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)k * dnzm1; for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)j * dnym1; for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][i] = dtemp[m]; } dtpp = 1.0 / dtemp[0]; for (m = 1; m < 5; m++) { buf[m][i] = dtpp * dtemp[m]; } cuf[i] = buf[1][i] * buf[1][i]; buf[0][i] = cuf[i] + buf[2][i] * buf[2][i] + buf[3][i] * buf[3][i]; q[i] = 0.5 * (buf[1][i]*ue[1][i] + buf[2][i]*ue[2][i] + buf[3][i]*ue[3][i]); } for (i = 1; i <= grid_points[0]-2; i++) { im1 = i-1; ip1 = i+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tx2*( ue[1][ip1]-ue[1][im1] )+ dx1tx1*(ue[0][ip1]-2.0*ue[0][i]+ue[0][im1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tx2 * ((ue[1][ip1]*buf[1][ip1]+c2*(ue[4][ip1]-q[ip1]))- (ue[1][im1]*buf[1][im1]+c2*(ue[4][im1]-q[im1])))+ xxcon1*(buf[1][ip1]-2.0*buf[1][i]+buf[1][im1])+ dx2tx1*( ue[1][ip1]-2.0* ue[1][i]+ue[1][im1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tx2 * (ue[2][ip1]*buf[1][ip1]-ue[2][im1]*buf[1][im1])+ xxcon2*(buf[2][ip1]-2.0*buf[2][i]+buf[2][im1])+ dx3tx1*( ue[2][ip1]-2.0*ue[2][i] +ue[2][im1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tx2*(ue[3][ip1]*buf[1][ip1]-ue[3][im1]*buf[1][im1])+ xxcon2*(buf[3][ip1]-2.0*buf[3][i]+buf[3][im1])+ dx4tx1*( ue[3][ip1]-2.0* ue[3][i]+ ue[3][im1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tx2*(buf[1][ip1]*(c1*ue[4][ip1]-c2*q[ip1])- buf[1][im1]*(c1*ue[4][im1]-c2*q[im1]))+ 0.5*xxcon3*(buf[0][ip1]-2.0*buf[0][i]+ buf[0][im1])+ xxcon4*(cuf[ip1]-2.0*cuf[i]+cuf[im1])+ xxcon5*(buf[4][ip1]-2.0*buf[4][i]+buf[4][im1])+ dx5tx1*( ue[4][ip1]-2.0* ue[4][i]+ ue[4][im1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { i = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][i] - 4.0*ue[m][i+1] +ue[m][i+2]); i = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1] + ue[m][i+2]); } for (m = 0; m < 5; m++) { for (i = 3; i <= grid_points[0]-4; i++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][i-2] - 4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1] + ue[m][i+2]); } } for (m = 0; m < 5; m++) { i = grid_points[0]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - 4.0*ue[m][i-1] + 6.0*ue[m][i] - 4.0*ue[m][i+1]); i = grid_points[0]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][i-2] - 4.0*ue[m][i-1] + 5.0*ue[m][i]); } } } /*-------------------------------------------------------------------- c eta-direction flux differences c-------------------------------------------------------------------*/ for (k = 1; k <= grid_points[2]-2; k++) { zeta = (double)k * dnzm1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][j] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][j] = dtpp * dtemp[m]; } cuf[j] = buf[2][j] * buf[2][j]; buf[0][j] = cuf[j] + buf[1][j] * buf[1][j] + buf[3][j] * buf[3][j]; q[j] = 0.5*(buf[1][j]*ue[1][j] + buf[2][j]*ue[2][j] + buf[3][j]*ue[3][j]); } for (j = 1; j <= grid_points[1]-2; j++) { jm1 = j-1; jp1 = j+1; forcing[0][i][j][k] = forcing[0][i][j][k] - ty2*( ue[2][jp1]-ue[2][jm1] )+ dy1ty1*(ue[0][jp1]-2.0*ue[0][j]+ue[0][jm1]); forcing[1][i][j][k] = forcing[1][i][j][k] - ty2*(ue[1][jp1]*buf[2][jp1]-ue[1][jm1]*buf[2][jm1])+ yycon2*(buf[1][jp1]-2.0*buf[1][j]+buf[1][jm1])+ dy2ty1*( ue[1][jp1]-2.0* ue[1][j]+ ue[1][jm1]); forcing[2][i][j][k] = forcing[2][i][j][k] - ty2*((ue[2][jp1]*buf[2][jp1]+c2*(ue[4][jp1]-q[jp1]))- (ue[2][jm1]*buf[2][jm1]+c2*(ue[4][jm1]-q[jm1])))+ yycon1*(buf[2][jp1]-2.0*buf[2][j]+buf[2][jm1])+ dy3ty1*( ue[2][jp1]-2.0*ue[2][j] +ue[2][jm1]); forcing[3][i][j][k] = forcing[3][i][j][k] - ty2*(ue[3][jp1]*buf[2][jp1]-ue[3][jm1]*buf[2][jm1])+ yycon2*(buf[3][jp1]-2.0*buf[3][j]+buf[3][jm1])+ dy4ty1*( ue[3][jp1]-2.0*ue[3][j]+ ue[3][jm1]); forcing[4][i][j][k] = forcing[4][i][j][k] - ty2*(buf[2][jp1]*(c1*ue[4][jp1]-c2*q[jp1])- buf[2][jm1]*(c1*ue[4][jm1]-c2*q[jm1]))+ 0.5*yycon3*(buf[0][jp1]-2.0*buf[0][j]+ buf[0][jm1])+ yycon4*(cuf[jp1]-2.0*cuf[j]+cuf[jm1])+ yycon5*(buf[4][jp1]-2.0*buf[4][j]+buf[4][jm1])+ dy5ty1*(ue[4][jp1]-2.0*ue[4][j]+ue[4][jm1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { j = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][j] - 4.0*ue[m][j+1] +ue[m][j+2]); j = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1] + ue[m][j+2]); } for (m = 0; m < 5; m++) { for (j = 3; j <= grid_points[1]-4; j++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][j-2] - 4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1] + ue[m][j+2]); } } for (m = 0; m < 5; m++) { j = grid_points[1]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - 4.0*ue[m][j-1] + 6.0*ue[m][j] - 4.0*ue[m][j+1]); j = grid_points[1]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][j-2] - 4.0*ue[m][j-1] + 5.0*ue[m][j]); } } } /*-------------------------------------------------------------------- c zeta-direction flux differences c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { eta = (double)j * dnym1; for (i = 1; i <= grid_points[0]-2; i++) { xi = (double)i * dnxm1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, dtemp); for (m = 0; m < 5; m++) { ue[m][k] = dtemp[m]; } dtpp = 1.0/dtemp[0]; for (m = 1; m < 5; m++) { buf[m][k] = dtpp * dtemp[m]; } cuf[k] = buf[3][k] * buf[3][k]; buf[0][k] = cuf[k] + buf[1][k] * buf[1][k] + buf[2][k] * buf[2][k]; q[k] = 0.5*(buf[1][k]*ue[1][k] + buf[2][k]*ue[2][k] + buf[3][k]*ue[3][k]); } for (k = 1; k <= grid_points[2]-2; k++) { km1 = k-1; kp1 = k+1; forcing[0][i][j][k] = forcing[0][i][j][k] - tz2*( ue[3][kp1]-ue[3][km1] )+ dz1tz1*(ue[0][kp1]-2.0*ue[0][k]+ue[0][km1]); forcing[1][i][j][k] = forcing[1][i][j][k] - tz2 * (ue[1][kp1]*buf[3][kp1]-ue[1][km1]*buf[3][km1])+ zzcon2*(buf[1][kp1]-2.0*buf[1][k]+buf[1][km1])+ dz2tz1*( ue[1][kp1]-2.0* ue[1][k]+ ue[1][km1]); forcing[2][i][j][k] = forcing[2][i][j][k] - tz2 * (ue[2][kp1]*buf[3][kp1]-ue[2][km1]*buf[3][km1])+ zzcon2*(buf[2][kp1]-2.0*buf[2][k]+buf[2][km1])+ dz3tz1*(ue[2][kp1]-2.0*ue[2][k]+ue[2][km1]); forcing[3][i][j][k] = forcing[3][i][j][k] - tz2 * ((ue[3][kp1]*buf[3][kp1]+c2*(ue[4][kp1]-q[kp1]))- (ue[3][km1]*buf[3][km1]+c2*(ue[4][km1]-q[km1])))+ zzcon1*(buf[3][kp1]-2.0*buf[3][k]+buf[3][km1])+ dz4tz1*( ue[3][kp1]-2.0*ue[3][k] +ue[3][km1]); forcing[4][i][j][k] = forcing[4][i][j][k] - tz2 * (buf[3][kp1]*(c1*ue[4][kp1]-c2*q[kp1])- buf[3][km1]*(c1*ue[4][km1]-c2*q[km1]))+ 0.5*zzcon3*(buf[0][kp1]-2.0*buf[0][k] +buf[0][km1])+ zzcon4*(cuf[kp1]-2.0*cuf[k]+cuf[km1])+ zzcon5*(buf[4][kp1]-2.0*buf[4][k]+buf[4][km1])+ dz5tz1*( ue[4][kp1]-2.0*ue[4][k]+ ue[4][km1]); } /*-------------------------------------------------------------------- c Fourth-order dissipation c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { k = 1; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (5.0*ue[m][k] - 4.0*ue[m][k+1] +ue[m][k+2]); k = 2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (-4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1] + ue[m][k+2]); } for (m = 0; m < 5; m++) { for (k = 3; k <= grid_points[2]-4; k++) { forcing[m][i][j][k] = forcing[m][i][j][k] - dssp* (ue[m][k-2] - 4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1] + ue[m][k+2]); } } for (m = 0; m < 5; m++) { k = grid_points[2]-3; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - 4.0*ue[m][k-1] + 6.0*ue[m][k] - 4.0*ue[m][k+1]); k = grid_points[2]-2; forcing[m][i][j][k] = forcing[m][i][j][k] - dssp * (ue[m][k-2] - 4.0*ue[m][k-1] + 5.0*ue[m][k]); } } } /*-------------------------------------------------------------------- c now change the sign of the forcing function, c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { forcing[m][i][j][k] = -1.0 * forcing[m][i][j][k]; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void exact_solution(double xi, double eta, double zeta, double dtemp[5]) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function returns the exact solution at point xi, eta, zeta c-------------------------------------------------------------------*/ int m; for (m = 0; m < 5; m++) { dtemp[m] = ce[0][m] + xi*(ce[1][m] + xi*(ce[4][m] + xi*(ce[7][m] + xi*ce[10][m]))) + eta*(ce[2][m] + eta*(ce[5][m] + eta*(ce[8][m] + eta*ce[11][m])))+ zeta*(ce[3][m] + zeta*(ce[6][m] + zeta*(ce[9][m] + zeta*ce[12][m]))); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void initialize(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This subroutine initializes the field variable u using c tri-linear transfinite interpolation of the boundary values c-------------------------------------------------------------------*/ int i, j, k, m, ix, iy, iz; double xi, eta, zeta, Pface[2][3][5], Pxi, Peta, Pzeta, temp[5]; /*-------------------------------------------------------------------- c Later (in compute_rhs) we compute 1/u for every element. A few of c the corner elements are not used, but it convenient (and faster) c to compute the whole thing with a simple loop. Make sure those c values are nonzero by initializing the whole thing here. c-------------------------------------------------------------------*/ for (i = 0; i <= IMAX-1; i++) { for (j = 0; j <= IMAX-1; j++) { for (k = 0; k <= IMAX-1; k++) { u[0][i][j][k] = 1.0; u[1][i][j][k] = 0.0; u[2][i][j][k] = 0.0; u[3][i][j][k] = 0.0; u[4][i][j][k] = 1.0; } } } /*-------------------------------------------------------------------- c first store the "interpolated" values everywhere on the grid c-------------------------------------------------------------------*/ for (i = 0; i <= grid_points[0]-1; i++) { xi = (double)i * dnxm1; for (j = 0; j <= grid_points[1]-1; j++) { eta = (double)j * dnym1; for (k = 0; k <= grid_points[2]-1; k++) { zeta = (double)k * dnzm1; for (ix = 0; ix < 2; ix++) { exact_solution((double)ix, eta, zeta, &Pface[ix][0][0]); } for (iy = 0; iy < 2; iy++) { exact_solution(xi, (double)iy , zeta, &Pface[iy][1][0]); } for (iz = 0; iz < 2; iz++) { exact_solution(xi, eta, (double)iz, &Pface[iz][2][0]); } for (m = 0; m < 5; m++) { Pxi = xi * Pface[1][0][m] + (1.0-xi) * Pface[0][0][m]; Peta = eta * Pface[1][1][m] + (1.0-eta) * Pface[0][1][m]; Pzeta = zeta * Pface[1][2][m] + (1.0-zeta) * Pface[0][2][m]; u[m][i][j][k] = Pxi + Peta + Pzeta - Pxi*Peta - Pxi*Pzeta - Peta*Pzeta + Pxi*Peta*Pzeta; } } } } /*-------------------------------------------------------------------- c now store the exact values on the boundaries c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c west face c-------------------------------------------------------------------*/ xi = 0.0; i = 0; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c east face c-------------------------------------------------------------------*/ xi = 1.0; i = grid_points[0]-1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c south face c-------------------------------------------------------------------*/ eta = 0.0; j = 0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c north face c-------------------------------------------------------------------*/ eta = 1.0; j = grid_points[1]-1; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (k = 0; k < grid_points[2]; k++) { zeta = (double)k * dnzm1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c bottom face c-------------------------------------------------------------------*/ zeta = 0.0; k = 0; for (i = 0; i < grid_points[0]; i++) { xi = (double)i *dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } /*-------------------------------------------------------------------- c top face c-------------------------------------------------------------------*/ zeta = 1.0; k = grid_points[2]-1; for (i = 0; i < grid_points[0]; i++) { xi = (double)i * dnxm1; for (j = 0; j < grid_points[1]; j++) { eta = (double)j * dnym1; exact_solution(xi, eta, zeta, temp); for (m = 0; m < 5; m++) { u[m][i][j][k] = temp[m]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsinit(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, n; /*-------------------------------------------------------------------- c zap the whole left hand side for starters c-------------------------------------------------------------------*/ for (n = 0; n < 15; n++) { #pragma omp for nowait for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[n][i][j][k] = 0.0; } } } } #pragma omp barrier /*-------------------------------------------------------------------- c next, set all diagonal values to 1. This is overkill, but c convenient c-------------------------------------------------------------------*/ for (n = 0; n < 3; n++) { #pragma omp for for (i = 0; i < grid_points[0]; i++) { for (j = 0; j < grid_points[1]; j++) { for (k = 0; k < grid_points[2]; k++) { lhs[5*n+2][i][j][k] = 1.0; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsx(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three x-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { ru1 = c3c4*rho_i[i][j][k]; cv[i] = us[i][j][k]; rhon[i] = max(dx2+con43*ru1, max(dx5+c1c5*ru1, max(dxmax+ru1, dx1))); } #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = - dttx2 * cv[i-1] - dttx1 * rhon[i-1]; lhs[2][i][j][k] = 1.0 + c2dttx1 * rhon[i]; lhs[3][i][j][k] = dttx2 * cv[i+1] - dttx1 * rhon[i+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ i = 1; #pragma omp for nowait for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz6; lhs[3][i+1][j][k] = lhs[3][i+1][j][k] - comz4; lhs[4][i+1][j][k] = lhs[4][i+1][j][k] + comz1; } } #pragma omp for nowait for (i = 3; i <= grid_points[0]-4; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } i = grid_points[0]-3; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i+1][j][k] = lhs[0][i+1][j][k] + comz1; lhs[1][i+1][j][k] = lhs[1][i+1][j][k] - comz4; lhs[2][i+1][j][k] = lhs[2][i+1][j][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) by adding to c the first c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttx2 * speed[i-1][j][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttx2 * speed[i+1][j][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttx2 * speed[i-1][j][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttx2 * speed[i+1][j][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsy(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three y-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { #pragma omp for for (j = 0; j <= grid_points[1]-1; j++) { ru1 = c3c4*rho_i[i][j][k]; cv[j] = vs[i][j][k]; rhoq[j] = max(dy3 + con43 * ru1, max(dy5 + c1c5*ru1, max(dymax + ru1, dy1))); } #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = -dtty2 * cv[j-1] - dtty1 * rhoq[j-1]; lhs[2][i][j][k] = 1.0 + c2dtty1 * rhoq[j]; lhs[3][i][j][k] = dtty2 * cv[j+1] - dtty1 * rhoq[j+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ j = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz6; lhs[3][i][j+1][k] = lhs[3][i][j+1][k] - comz4; lhs[4][i][j+1][k] = lhs[4][i][j+1][k] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3; j <= grid_points[1]-4; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } j = grid_points[1]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j+1][k] = lhs[0][i][j+1][k] + comz1; lhs[1][i][j+1][k] = lhs[1][i][j+1][k] - comz4; lhs[2][i][j+1][k] = lhs[2][i][j+1][k] + comz5; } } /*-------------------------------------------------------------------- c subsequently, do the other two factors c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dtty2 * speed[i][j-1][k]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dtty2 * speed[i][j+1][k]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dtty2 * speed[i][j-1][k]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dtty2 * speed[i][j+1][k]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void lhsz(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c This function computes the left hand side for the three z-factors c-------------------------------------------------------------------*/ double ru1; int i, j, k; /*-------------------------------------------------------------------- c first fill the lhs for the u-eigenvalue c-------------------------------------------------------------------*/ for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { #pragma omp for for (k = 0; k <= grid_points[2]-1; k++) { ru1 = c3c4*rho_i[i][j][k]; cv[k] = ws[i][j][k]; rhos[k] = max(dz4 + con43 * ru1, max(dz5 + c1c5 * ru1, max(dzmax + ru1, dz1))); } #pragma omp for for (k = 1; k <= grid_points[2]-2; k++) { lhs[0][i][j][k] = 0.0; lhs[1][i][j][k] = -dttz2 * cv[k-1] - dttz1 * rhos[k-1]; lhs[2][i][j][k] = 1.0 + c2dttz1 * rhos[k]; lhs[3][i][j][k] = dttz2 * cv[k+1] - dttz1 * rhos[k+1]; lhs[4][i][j][k] = 0.0; } } } /*-------------------------------------------------------------------- c add fourth order dissipation c-------------------------------------------------------------------*/ k = 1; #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[2][i][j][k] = lhs[2][i][j][k] + comz5; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz6; lhs[3][i][j][k+1] = lhs[3][i][j][k+1] - comz4; lhs[4][i][j][k+1] = lhs[4][i][j][k+1] + comz1; } } #pragma omp for nowait for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3; k <= grid_points[2]-4; k++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[4][i][j][k] = lhs[4][i][j][k] + comz1; } } } k = grid_points[2]-3; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { lhs[0][i][j][k] = lhs[0][i][j][k] + comz1; lhs[1][i][j][k] = lhs[1][i][j][k] - comz4; lhs[2][i][j][k] = lhs[2][i][j][k] + comz6; lhs[3][i][j][k] = lhs[3][i][j][k] - comz4; lhs[0][i][j][k+1] = lhs[0][i][j][k+1] + comz1; lhs[1][i][j][k+1] = lhs[1][i][j][k+1] - comz4; lhs[2][i][j][k+1] = lhs[2][i][j][k+1] + comz5; } } /*-------------------------------------------------------------------- c subsequently, fill the other factors (u+c), (u-c) c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { lhs[0+5][i][j][k] = lhs[0][i][j][k]; lhs[1+5][i][j][k] = lhs[1][i][j][k] - dttz2 * speed[i][j][k-1]; lhs[2+5][i][j][k] = lhs[2][i][j][k]; lhs[3+5][i][j][k] = lhs[3][i][j][k] + dttz2 * speed[i][j][k+1]; lhs[4+5][i][j][k] = lhs[4][i][j][k]; lhs[0+10][i][j][k] = lhs[0][i][j][k]; lhs[1+10][i][j][k] = lhs[1][i][j][k] + dttz2 * speed[i][j][k-1]; lhs[2+10][i][j][k] = lhs[2][i][j][k]; lhs[3+10][i][j][k] = lhs[3][i][j][k] - dttz2 * speed[i][j][k+1]; lhs[4+10][i][j][k] = lhs[4][i][j][k]; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void ninvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double r1, r2, r3, r4, r5, t1, t2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r3; t2 = 0.5 * ( r4 + r5 ); rhs[0][i][j][k] = -r2; rhs[1][i][j][k] = r1; rhs[2][i][j][k] = bt * ( r4 - r5 ); rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void pinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double r1, r2, r3, r4, r5, t1, t2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = bt * r1; t2 = 0.5 * ( r4 + r5 ); rhs[0][i][j][k] = bt * ( r4 - r5 ); rhs[1][i][j][k] = -r3; rhs[2][i][j][k] = r2; rhs[3][i][j][k] = -t1 + t2; rhs[4][i][j][k] = t1 + t2; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void compute_rhs(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ int i, j, k, m; double aux, rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1; /*-------------------------------------------------------------------- c compute the reciprocal of density, and the kinetic energy, c and the speed of sound. c-------------------------------------------------------------------*/ #pragma omp for nowait for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rho_inv = 1.0/u[0][i][j][k]; rho_i[i][j][k] = rho_inv; us[i][j][k] = u[1][i][j][k] * rho_inv; vs[i][j][k] = u[2][i][j][k] * rho_inv; ws[i][j][k] = u[3][i][j][k] * rho_inv; square[i][j][k] = 0.5* (u[1][i][j][k]*u[1][i][j][k] + u[2][i][j][k]*u[2][i][j][k] + u[3][i][j][k]*u[3][i][j][k] ) * rho_inv; qs[i][j][k] = square[i][j][k] * rho_inv; /*-------------------------------------------------------------------- c (do not need speed and ainx until the lhs computation) c-------------------------------------------------------------------*/ aux = c1c2*rho_inv* (u[4][i][j][k] - square[i][j][k]); aux = sqrt(aux); speed[i][j][k] = aux; ainv[i][j][k] = 1.0/aux; } } } /*-------------------------------------------------------------------- c copy the exact forcing term to the right hand side; because c this forcing term is known, we can store it on the whole grid c including the boundary c-------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { #pragma omp for for (i = 0; i <= grid_points[0]-1; i++) { for (j = 0; j <= grid_points[1]-1; j++) { for (k = 0; k <= grid_points[2]-1; k++) { rhs[m][i][j][k] = forcing[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c compute xi-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { uijk = us[i][j][k]; up1 = us[i+1][j][k]; um1 = us[i-1][j][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dx1tx1 * (u[0][i+1][j][k] - 2.0*u[0][i][j][k] + u[0][i-1][j][k]) - tx2 * (u[1][i+1][j][k] - u[1][i-1][j][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dx2tx1 * (u[1][i+1][j][k] - 2.0*u[1][i][j][k] + u[1][i-1][j][k]) + xxcon2*con43 * (up1 - 2.0*uijk + um1) - tx2 * (u[1][i+1][j][k]*up1 - u[1][i-1][j][k]*um1 + (u[4][i+1][j][k]- square[i+1][j][k]- u[4][i-1][j][k]+ square[i-1][j][k])* c2); rhs[2][i][j][k] = rhs[2][i][j][k] + dx3tx1 * (u[2][i+1][j][k] - 2.0*u[2][i][j][k] + u[2][i-1][j][k]) + xxcon2 * (vs[i+1][j][k] - 2.0*vs[i][j][k] + vs[i-1][j][k]) - tx2 * (u[2][i+1][j][k]*up1 - u[2][i-1][j][k]*um1); rhs[3][i][j][k] = rhs[3][i][j][k] + dx4tx1 * (u[3][i+1][j][k] - 2.0*u[3][i][j][k] + u[3][i-1][j][k]) + xxcon2 * (ws[i+1][j][k] - 2.0*ws[i][j][k] + ws[i-1][j][k]) - tx2 * (u[3][i+1][j][k]*up1 - u[3][i-1][j][k]*um1); rhs[4][i][j][k] = rhs[4][i][j][k] + dx5tx1 * (u[4][i+1][j][k] - 2.0*u[4][i][j][k] + u[4][i-1][j][k]) + xxcon3 * (qs[i+1][j][k] - 2.0*qs[i][j][k] + qs[i-1][j][k]) + xxcon4 * (up1*up1 - 2.0*uijk*uijk + um1*um1) + xxcon5 * (u[4][i+1][j][k]*rho_i[i+1][j][k] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i-1][j][k]*rho_i[i-1][j][k]) - tx2 * ( (c1*u[4][i+1][j][k] - c2*square[i+1][j][k])*up1 - (c1*u[4][i-1][j][k] - c2*square[i-1][j][k])*um1 ); } } } /*-------------------------------------------------------------------- c add fourth order xi-direction dissipation c-------------------------------------------------------------------*/ i = 1; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } i = 2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 3*1; i <= grid_points[0]-3*1-1; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] + u[m][i+2][j][k] ); } } } } i = grid_points[0]-3; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i+1][j][k] ); } } } i = grid_points[0]-2; for (m = 0; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i-2][j][k] - 4.0*u[m][i-1][j][k] + 5.0*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute eta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { vijk = vs[i][j][k]; vp1 = vs[i][j+1][k]; vm1 = vs[i][j-1][k]; rhs[0][i][j][k] = rhs[0][i][j][k] + dy1ty1 * (u[0][i][j+1][k] - 2.0*u[0][i][j][k] + u[0][i][j-1][k]) - ty2 * (u[2][i][j+1][k] - u[2][i][j-1][k]); rhs[1][i][j][k] = rhs[1][i][j][k] + dy2ty1 * (u[1][i][j+1][k] - 2.0*u[1][i][j][k] + u[1][i][j-1][k]) + yycon2 * (us[i][j+1][k] - 2.0*us[i][j][k] + us[i][j-1][k]) - ty2 * (u[1][i][j+1][k]*vp1 - u[1][i][j-1][k]*vm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dy3ty1 * (u[2][i][j+1][k] - 2.0*u[2][i][j][k] + u[2][i][j-1][k]) + yycon2*con43 * (vp1 - 2.0*vijk + vm1) - ty2 * (u[2][i][j+1][k]*vp1 - u[2][i][j-1][k]*vm1 + (u[4][i][j+1][k] - square[i][j+1][k] - u[4][i][j-1][k] + square[i][j-1][k]) *c2); rhs[3][i][j][k] = rhs[3][i][j][k] + dy4ty1 * (u[3][i][j+1][k] - 2.0*u[3][i][j][k] + u[3][i][j-1][k]) + yycon2 * (ws[i][j+1][k] - 2.0*ws[i][j][k] + ws[i][j-1][k]) - ty2 * (u[3][i][j+1][k]*vp1 - u[3][i][j-1][k]*vm1); rhs[4][i][j][k] = rhs[4][i][j][k] + dy5ty1 * (u[4][i][j+1][k] - 2.0*u[4][i][j][k] + u[4][i][j-1][k]) + yycon3 * (qs[i][j+1][k] - 2.0*qs[i][j][k] + qs[i][j-1][k]) + yycon4 * (vp1*vp1 - 2.0*vijk*vijk + vm1*vm1) + yycon5 * (u[4][i][j+1][k]*rho_i[i][j+1][k] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j-1][k]*rho_i[i][j-1][k]) - ty2 * ((c1*u[4][i][j+1][k] - c2*square[i][j+1][k]) * vp1 - (c1*u[4][i][j-1][k] - c2*square[i][j-1][k]) * vm1); } } } /*-------------------------------------------------------------------- c add fourth order eta-direction dissipation c-------------------------------------------------------------------*/ j = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } j = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 3*1; j <= grid_points[1]-3*1-1; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] + u[m][i][j+2][k] ); } } } } j = grid_points[1]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j+1][k] ); } } } j = grid_points[1]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j-2][k] - 4.0*u[m][i][j-1][k] + 5.0*u[m][i][j][k] ); } } } #pragma omp barrier /*-------------------------------------------------------------------- c compute zeta-direction fluxes c-------------------------------------------------------------------*/ #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { wijk = ws[i][j][k]; wp1 = ws[i][j][k+1]; wm1 = ws[i][j][k-1]; rhs[0][i][j][k] = rhs[0][i][j][k] + dz1tz1 * (u[0][i][j][k+1] - 2.0*u[0][i][j][k] + u[0][i][j][k-1]) - tz2 * (u[3][i][j][k+1] - u[3][i][j][k-1]); rhs[1][i][j][k] = rhs[1][i][j][k] + dz2tz1 * (u[1][i][j][k+1] - 2.0*u[1][i][j][k] + u[1][i][j][k-1]) + zzcon2 * (us[i][j][k+1] - 2.0*us[i][j][k] + us[i][j][k-1]) - tz2 * (u[1][i][j][k+1]*wp1 - u[1][i][j][k-1]*wm1); rhs[2][i][j][k] = rhs[2][i][j][k] + dz3tz1 * (u[2][i][j][k+1] - 2.0*u[2][i][j][k] + u[2][i][j][k-1]) + zzcon2 * (vs[i][j][k+1] - 2.0*vs[i][j][k] + vs[i][j][k-1]) - tz2 * (u[2][i][j][k+1]*wp1 - u[2][i][j][k-1]*wm1); rhs[3][i][j][k] = rhs[3][i][j][k] + dz4tz1 * (u[3][i][j][k+1] - 2.0*u[3][i][j][k] + u[3][i][j][k-1]) + zzcon2*con43 * (wp1 - 2.0*wijk + wm1) - tz2 * (u[3][i][j][k+1]*wp1 - u[3][i][j][k-1]*wm1 + (u[4][i][j][k+1] - square[i][j][k+1] - u[4][i][j][k-1] + square[i][j][k-1]) *c2); rhs[4][i][j][k] = rhs[4][i][j][k] + dz5tz1 * (u[4][i][j][k+1] - 2.0*u[4][i][j][k] + u[4][i][j][k-1]) + zzcon3 * (qs[i][j][k+1] - 2.0*qs[i][j][k] + qs[i][j][k-1]) + zzcon4 * (wp1*wp1 - 2.0*wijk*wijk + wm1*wm1) + zzcon5 * (u[4][i][j][k+1]*rho_i[i][j][k+1] - 2.0*u[4][i][j][k]*rho_i[i][j][k] + u[4][i][j][k-1]*rho_i[i][j][k-1]) - tz2 * ( (c1*u[4][i][j][k+1] - c2*square[i][j][k+1])*wp1 - (c1*u[4][i][j][k-1] - c2*square[i][j][k-1])*wm1); } } } /*-------------------------------------------------------------------- c add fourth order zeta-direction dissipation c-------------------------------------------------------------------*/ k = 1; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k]- dssp * ( 5.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } k = 2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * (-4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2]); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 3*1; k <= grid_points[2]-3*1-1; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] + u[m][i][j][k+2] ); } } } } k = grid_points[2]-3; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 6.0*u[m][i][j][k] - 4.0*u[m][i][j][k+1] ); } } } k = grid_points[2]-2; for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - dssp * ( u[m][i][j][k-2] - 4.0*u[m][i][j][k-1] + 5.0*u[m][i][j][k] ); } } } for (m = 0; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] * dt; } } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void set_constants(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ ce[0][0] = 2.0; ce[1][0] = 0.0; ce[2][0] = 0.0; ce[3][0] = 4.0; ce[4][0] = 5.0; ce[5][0] = 3.0; ce[6][0] = 0.5; ce[7][0] = 0.02; ce[8][0] = 0.01; ce[9][0] = 0.03; ce[10][0] = 0.5; ce[11][0] = 0.4; ce[12][0] = 0.3; ce[0][1] = 1.0; ce[1][1] = 0.0; ce[2][1] = 0.0; ce[3][1] = 0.0; ce[4][1] = 1.0; ce[5][1] = 2.0; ce[6][1] = 3.0; ce[7][1] = 0.01; ce[8][1] = 0.03; ce[9][1] = 0.02; ce[10][1] = 0.4; ce[11][1] = 0.3; ce[12][1] = 0.5; ce[0][2] = 2.0; ce[1][2] = 2.0; ce[2][2] = 0.0; ce[3][2] = 0.0; ce[4][2] = 0.0; ce[5][2] = 2.0; ce[6][2] = 3.0; ce[7][2] = 0.04; ce[8][2] = 0.03; ce[9][2] = 0.05; ce[10][2] = 0.3; ce[11][2] = 0.5; ce[12][2] = 0.4; ce[0][3] = 2.0; ce[1][3] = 2.0; ce[2][3] = 0.0; ce[3][3] = 0.0; ce[4][3] = 0.0; ce[5][3] = 2.0; ce[6][3] = 3.0; ce[7][3] = 0.03; ce[8][3] = 0.05; ce[9][3] = 0.04; ce[10][3] = 0.2; ce[11][3] = 0.1; ce[12][3] = 0.3; ce[0][4] = 5.0; ce[1][4] = 4.0; ce[2][4] = 3.0; ce[3][4] = 2.0; ce[4][4] = 0.1; ce[5][4] = 0.4; ce[6][4] = 0.3; ce[7][4] = 0.05; ce[8][4] = 0.04; ce[9][4] = 0.03; ce[10][4] = 0.1; ce[11][4] = 0.3; ce[12][4] = 0.2; c1 = 1.4; c2 = 0.4; c3 = 0.1; c4 = 1.0; c5 = 1.4; bt = sqrt(0.5); dnxm1 = 1.0 / (double)(grid_points[0]-1); dnym1 = 1.0 / (double)(grid_points[1]-1); dnzm1 = 1.0 / (double)(grid_points[2]-1); c1c2 = c1 * c2; c1c5 = c1 * c5; c3c4 = c3 * c4; c1345 = c1c5 * c3c4; conz1 = (1.0-c1c5); tx1 = 1.0 / (dnxm1 * dnxm1); tx2 = 1.0 / (2.0 * dnxm1); tx3 = 1.0 / dnxm1; ty1 = 1.0 / (dnym1 * dnym1); ty2 = 1.0 / (2.0 * dnym1); ty3 = 1.0 / dnym1; tz1 = 1.0 / (dnzm1 * dnzm1); tz2 = 1.0 / (2.0 * dnzm1); tz3 = 1.0 / dnzm1; dx1 = 0.75; dx2 = 0.75; dx3 = 0.75; dx4 = 0.75; dx5 = 0.75; dy1 = 0.75; dy2 = 0.75; dy3 = 0.75; dy4 = 0.75; dy5 = 0.75; dz1 = 1.0; dz2 = 1.0; dz3 = 1.0; dz4 = 1.0; dz5 = 1.0; dxmax = max(dx3, dx4); dymax = max(dy2, dy4); dzmax = max(dz2, dz3); dssp = 0.25 * max(dx1, max(dy1, dz1) ); c4dssp = 4.0 * dssp; c5dssp = 5.0 * dssp; dttx1 = dt*tx1; dttx2 = dt*tx2; dtty1 = dt*ty1; dtty2 = dt*ty2; dttz1 = dt*tz1; dttz2 = dt*tz2; c2dttx1 = 2.0*dttx1; c2dtty1 = 2.0*dtty1; c2dttz1 = 2.0*dttz1; dtdssp = dt*dssp; comz1 = dtdssp; comz4 = 4.0*dtdssp; comz5 = 5.0*dtdssp; comz6 = 6.0*dtdssp; c3c4tx3 = c3c4*tx3; c3c4ty3 = c3c4*ty3; c3c4tz3 = c3c4*tz3; dx1tx1 = dx1*tx1; dx2tx1 = dx2*tx1; dx3tx1 = dx3*tx1; dx4tx1 = dx4*tx1; dx5tx1 = dx5*tx1; dy1ty1 = dy1*ty1; dy2ty1 = dy2*ty1; dy3ty1 = dy3*ty1; dy4ty1 = dy4*ty1; dy5ty1 = dy5*ty1; dz1tz1 = dz1*tz1; dz2tz1 = dz2*tz1; dz3tz1 = dz3*tz1; dz4tz1 = dz4*tz1; dz5tz1 = dz5*tz1; c2iv = 2.5; con43 = 4.0/3.0; con16 = 1.0/6.0; xxcon1 = c3c4tx3*con43*tx3; xxcon2 = c3c4tx3*tx3; xxcon3 = c3c4tx3*conz1*tx3; xxcon4 = c3c4tx3*con16*tx3; xxcon5 = c3c4tx3*c1c5*tx3; yycon1 = c3c4ty3*con43*ty3; yycon2 = c3c4ty3*ty3; yycon3 = c3c4ty3*conz1*ty3; yycon4 = c3c4ty3*con16*ty3; yycon5 = c3c4ty3*c1c5*ty3; zzcon1 = c3c4tz3*con43*tz3; zzcon2 = c3c4tz3*tz3; zzcon3 = c3c4tz3*conz1*tz3; zzcon4 = c3c4tz3*con16*tz3; zzcon5 = c3c4tz3*c1c5*tz3; } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void txinvr(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication --------------------------------------------------------------------*/ int i, j, k; double t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3, r4, r5, ac2inv; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { ru1 = rho_i[i][j][k]; uu = us[i][j][k]; vv = vs[i][j][k]; ww = ws[i][j][k]; ac = speed[i][j][k]; ac2inv = ainv[i][j][k]*ainv[i][j][k]; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; t1 = c2 * ac2inv * ( qs[i][j][k]*r1 - uu*r2 - vv*r3 - ww*r4 + r5 ); t2 = bt * ru1 * ( uu * r1 - r2 ); t3 = ( bt * ru1 * ac ) * t1; rhs[0][i][j][k] = r1 - t1; rhs[1][i][j][k] = - ru1 * ( ww*r1 - r4 ); rhs[2][i][j][k] = ru1 * ( vv*r1 - r3 ); rhs[3][i][j][k] = - t2 + t3; rhs[4][i][j][k] = t2 + t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void tzetar(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c block-diagonal matrix-vector multiplication c-------------------------------------------------------------------*/ int i, j, k; double t1, t2, t3, ac, xvel, yvel, zvel, r1, r2, r3, r4, r5, btuz, acinv, ac2u, uzik1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { xvel = us[i][j][k]; yvel = vs[i][j][k]; zvel = ws[i][j][k]; ac = speed[i][j][k]; acinv = ainv[i][j][k]; ac2u = ac*ac; r1 = rhs[0][i][j][k]; r2 = rhs[1][i][j][k]; r3 = rhs[2][i][j][k]; r4 = rhs[3][i][j][k]; r5 = rhs[4][i][j][k]; uzik1 = u[0][i][j][k]; btuz = bt * uzik1; t1 = btuz*acinv * (r4 + r5); t2 = r3 + t1; t3 = btuz * (r4 - r5); rhs[0][i][j][k] = t2; rhs[1][i][j][k] = -uzik1*r2 + xvel*t2; rhs[2][i][j][k] = uzik1*r1 + yvel*t2; rhs[3][i][j][k] = zvel*t2 + t3; rhs[4][i][j][k] = uzik1*(-xvel*r2 + yvel*r1) + qs[i][j][k]*t2 + c2iv*ac2u*t1 + zvel*t3; } } } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void verify(int no_time_steps, char *cclass, boolean *verified) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c verification routine --------------------------------------------------------------------*/ double xcrref[5],xceref[5],xcrdif[5],xcedif[5], epsilon, xce[5], xcr[5], dtref; int m; /*-------------------------------------------------------------------- c tolerance level --------------------------------------------------------------------*/ epsilon = 1.0e-08; /*-------------------------------------------------------------------- c compute the error norm and the residual norm, and exit if not printing --------------------------------------------------------------------*/ error_norm(xce); compute_rhs(); rhs_norm(xcr); for (m = 0; m < 5; m++) { xcr[m] = xcr[m] / dt; } *cclass = 'U'; *verified = TRUE; for (m = 0; m < 5; m++) { xcrref[m] = 1.0; xceref[m] = 1.0; } /*-------------------------------------------------------------------- c reference data for 12X12X12 grids after 100 time steps, with DT = 1.50d-02 --------------------------------------------------------------------*/ if ( grid_points[0] == 12 && grid_points[1] == 12 && grid_points[2] == 12 && no_time_steps == 100) { *cclass = 'S'; dtref = 1.5e-2; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 2.7470315451339479e-02; xcrref[1] = 1.0360746705285417e-02; xcrref[2] = 1.6235745065095532e-02; xcrref[3] = 1.5840557224455615e-02; xcrref[4] = 3.4849040609362460e-02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 2.7289258557377227e-05; xceref[1] = 1.0364446640837285e-05; xceref[2] = 1.6154798287166471e-05; xceref[3] = 1.5750704994480102e-05; xceref[4] = 3.4177666183390531e-05; /*-------------------------------------------------------------------- c reference data for 36X36X36 grids after 400 time steps, with DT = 1.5d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 36 && grid_points[1] == 36 && grid_points[2] == 36 && no_time_steps == 400) { *cclass = 'W'; dtref = 1.5e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.1893253733584e-02; xcrref[1] = 0.1717075447775e-03; xcrref[2] = 0.2778153350936e-03; xcrref[3] = 0.2887475409984e-03; xcrref[4] = 0.3143611161242e-02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.7542088599534e-04; xceref[1] = 0.6512852253086e-05; xceref[2] = 0.1049092285688e-04; xceref[3] = 0.1128838671535e-04; xceref[4] = 0.1212845639773e-03; /*-------------------------------------------------------------------- c reference data for 64X64X64 grids after 400 time steps, with DT = 1.5d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 64 && grid_points[1] == 64 && grid_points[2] == 64 && no_time_steps == 400 ) { *cclass = 'A'; dtref = 1.5e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 2.4799822399300195; xcrref[1] = 1.1276337964368832; xcrref[2] = 1.5028977888770491; xcrref[3] = 1.4217816211695179; xcrref[4] = 2.1292113035138280; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 1.0900140297820550e-04; xceref[1] = 3.7343951769282091e-05; xceref[2] = 5.0092785406541633e-05; xceref[3] = 4.7671093939528255e-05; xceref[4] = 1.3621613399213001e-04; /*-------------------------------------------------------------------- c reference data for 102X102X102 grids after 400 time steps, c with DT = 1.0d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 102 && grid_points[1] == 102 && grid_points[2] == 102 && no_time_steps == 400) { *cclass = 'B'; dtref = 1.0e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.6903293579998e+02; xcrref[1] = 0.3095134488084e+02; xcrref[2] = 0.4103336647017e+02; xcrref[3] = 0.3864769009604e+02; xcrref[4] = 0.5643482272596e+02; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.9810006190188e-02; xceref[1] = 0.1022827905670e-02; xceref[2] = 0.1720597911692e-02; xceref[3] = 0.1694479428231e-02; xceref[4] = 0.1847456263981e-01; /*-------------------------------------------------------------------- c reference data for 162X162X162 grids after 400 time steps, c with DT = 0.67d-03 --------------------------------------------------------------------*/ } else if (grid_points[0] == 162 && grid_points[1] == 162 && grid_points[2] == 162 && no_time_steps == 400) { *cclass = 'C'; dtref = 0.67e-3; /*-------------------------------------------------------------------- c Reference values of RMS-norms of residual. --------------------------------------------------------------------*/ xcrref[0] = 0.5881691581829e+03; xcrref[1] = 0.2454417603569e+03; xcrref[2] = 0.3293829191851e+03; xcrref[3] = 0.3081924971891e+03; xcrref[4] = 0.4597223799176e+03; /*-------------------------------------------------------------------- c Reference values of RMS-norms of solution error. --------------------------------------------------------------------*/ xceref[0] = 0.2598120500183e+00; xceref[1] = 0.2590888922315e-01; xceref[2] = 0.5132886416320e-01; xceref[3] = 0.4806073419454e-01; xceref[4] = 0.5483377491301e+00; } else { *verified = FALSE; } /*-------------------------------------------------------------------- c verification test for residuals if gridsize is either 12X12X12 or c 64X64X64 or 102X102X102 or 162X162X162 --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c Compute the difference of solution values and the known reference values. --------------------------------------------------------------------*/ for (m = 0; m < 5; m++) { xcrdif[m] = fabs((xcr[m]-xcrref[m])/xcrref[m]) ; xcedif[m] = fabs((xce[m]-xceref[m])/xceref[m]); } /*-------------------------------------------------------------------- c Output the comparison of computed results to known cases. --------------------------------------------------------------------*/ if (*cclass != 'U') { printf(" Verification being performed for cclass %1c\n", *cclass); printf(" accuracy setting for epsilon = %20.13e\n", epsilon); if (fabs(dt-dtref) > epsilon) { *verified = FALSE; *cclass = 'U'; printf(" DT does not match the reference value of %15.8e\n", dtref); } } else { printf(" Unknown cclass\n"); } if (*cclass != 'U') { printf(" Comparison of RMS-norms of residual\n"); } else { printf(" RMS-norms of residual\n"); } for (m = 0; m < 5; m++) { if (*cclass == 'U') { printf(" %2d%20.13e\n", m, xcr[m]); } else if (xcrdif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m,xcr[m],xcrref[m],xcrdif[m]); } } if (*cclass != 'U') { printf(" Comparison of RMS-norms of solution error\n"); } else { printf(" RMS-norms of solution error\n"); } for (m = 0; m < 5; m++) { if (*cclass == 'U') { printf(" %2d%20.13e\n", m, xce[m]); } else if (xcedif[m] > epsilon) { *verified = FALSE; printf(" FAILURE: %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } else { printf(" %2d%20.13e%20.13e%20.13e\n", m,xce[m],xceref[m],xcedif[m]); } } if (*cclass == 'U') { printf(" No reference values provided\n"); printf(" No verification performed\n"); } else if (*verified) { printf(" Verification Successful\n"); } else { printf(" Verification failed\n"); } } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void x_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the x-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the x-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, i1, i2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsx(); /*-------------------------------------------------------------------- c perform the Thomas algorithm; first, FORWARD ELIMINATION --------------------------------------------------------------------*/ n = 0; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1.0/lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i1][j][k]; for (m = 0; m < 3; m++) { rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = 0; i <= grid_points[0]-3; i++) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; lhs[n+1][i2][j][k] = lhs[n+1][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+3][i][j][k]; lhs[n+2][i2][j][k] = lhs[n+2][i2][j][k] - lhs[n+0][i2][j][k]*lhs[n+4][i][j][k]; rhs[m][i2][j][k] = rhs[m][i2][j][k] - lhs[n+0][i2][j][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i1][j][k] = lhs[n+2][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+3][i][j][k]; lhs[n+3][i1][j][k] = lhs[n+3][i1][j][k] - lhs[n+1][i1][j][k]*lhs[n+4][i][j][k]; rhs[m][i1][j][k] = rhs[m][i1][j][k] - lhs[n+1][i1][j][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i1][j][k]; rhs[m][i1][j][k] = fac2*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ i = grid_points[0]-2; i1 = grid_points[0]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (m = 0; m < 3; m++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (i = grid_points[0]-3; i >= 0; i--) { i1 = i + 1; i2 = i + 2; #pragma omp for for (j = 1; j <= grid_points[1]-2; j++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i1][j][k] - lhs[n+4][i][j][k]*rhs[m][i2][j][k]; } } } } /*-------------------------------------------------------------------- c Do the block-diagonal inversion --------------------------------------------------------------------*/ ninvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void y_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the y-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the y-lines. Boundary conditions are non-periodic --------------------------------------------------------------------*/ int i, j, k, n, j1, j2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION --------------------------------------------------------------------*/ lhsy(); n = 0; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j1][k]; for (m = 0; m < 3; m++) { rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = 0; j <= grid_points[1]-3; j++) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; lhs[n+1][i][j2][k] = lhs[n+1][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+3][i][j][k]; lhs[n+2][i][j2][k] = lhs[n+2][i][j2][k] - lhs[n+0][i][j2][k]*lhs[n+4][i][j][k]; rhs[m][i][j2][k] = rhs[m][i][j2][k] - lhs[n+0][i][j2][k]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j1][k] = lhs[n+2][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+3][i][j][k]; lhs[n+3][i][j1][k] = lhs[n+3][i][j1][k] - lhs[n+1][i][j1][k]*lhs[n+4][i][j][k]; rhs[m][i][j1][k] = rhs[m][i][j1][k] - lhs[n+1][i][j1][k]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately --------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j1][k]; rhs[m][i][j1][k] = fac2*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION --------------------------------------------------------------------*/ j = grid_points[1]-2; j1 = grid_points[1]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } for (m = 3; m < 5; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { n = (m-3+1)*5; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k]; } } } /*-------------------------------------------------------------------- c The first three factors --------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j + 2; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } /*-------------------------------------------------------------------- c And the remaining two --------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; for (j = grid_points[1]-3; j >= 0; j--) { j1 = j + 1; j2 = j1 + 1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (k = 1; k <= grid_points[2]-2; k++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j1][k] - lhs[n+4][i][j][k]*rhs[m][i][j2][k]; } } } } pinvr(); } /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ static void z_solve(void) { /*-------------------------------------------------------------------- --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c this function performs the solution of the approximate factorization c step in the z-direction for all five matrix components c simultaneously. The Thomas algorithm is employed to solve the c systems for the z-lines. Boundary conditions are non-periodic c-------------------------------------------------------------------*/ int i, j, k, n, k1, k2, m; double fac1, fac2; /*-------------------------------------------------------------------- c FORWARD ELIMINATION c-------------------------------------------------------------------*/ lhsz(); n = 0; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } } /*-------------------------------------------------------------------- c The last two rows in this grid block are a bit different, c since they do not have two more rows available for the c elimination of off-diagonal entries c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; } lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; } /*-------------------------------------------------------------------- c scale the last row immediately c-------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j][k1]; for (m = 0; m < 3; m++) { rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c do the u+c and the u-c factors c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = 0; k <= grid_points[2]-3; k++) { k1 = k + 1; k2 = k + 2; fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; lhs[n+1][i][j][k2] = lhs[n+1][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+3][i][j][k]; lhs[n+2][i][j][k2] = lhs[n+2][i][j][k2] - lhs[n+0][i][j][k2]*lhs[n+4][i][j][k]; rhs[m][i][j][k2] = rhs[m][i][j][k2] - lhs[n+0][i][j][k2]*rhs[m][i][j][k]; } } } /*-------------------------------------------------------------------- c And again the last two rows separately c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { fac1 = 1./lhs[n+2][i][j][k]; lhs[n+3][i][j][k] = fac1*lhs[n+3][i][j][k]; lhs[n+4][i][j][k] = fac1*lhs[n+4][i][j][k]; rhs[m][i][j][k] = fac1*rhs[m][i][j][k]; lhs[n+2][i][j][k1] = lhs[n+2][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+3][i][j][k]; lhs[n+3][i][j][k1] = lhs[n+3][i][j][k1] - lhs[n+1][i][j][k1]*lhs[n+4][i][j][k]; rhs[m][i][j][k1] = rhs[m][i][j][k1] - lhs[n+1][i][j][k1]*rhs[m][i][j][k]; /*-------------------------------------------------------------------- c Scale the last row immediately (some of this is overkill c if this is the last cell) c-------------------------------------------------------------------*/ fac2 = 1./lhs[n+2][i][j][k1]; rhs[m][i][j][k1] = fac2*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c BACKSUBSTITUTION c-------------------------------------------------------------------*/ k = grid_points[2]-2; k1 = grid_points[2]-1; n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1]; } } } /*-------------------------------------------------------------------- c Whether or not this is the last processor, we always have c to complete the back-substitution c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c The first three factors c-------------------------------------------------------------------*/ n = 0; for (m = 0; m < 3; m++) { #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } /*-------------------------------------------------------------------- c And the remaining two c-------------------------------------------------------------------*/ for (m = 3; m < 5; m++) { n = (m-3+1)*5; #pragma omp for for (i = 1; i <= grid_points[0]-2; i++) { for (j = 1; j <= grid_points[1]-2; j++) { for (k = grid_points[2]-3; k >= 0; k--) { k1 = k + 1; k2 = k + 2; rhs[m][i][j][k] = rhs[m][i][j][k] - lhs[n+3][i][j][k]*rhs[m][i][j][k1] - lhs[n+4][i][j][k]*rhs[m][i][j][k2]; } } } } tzetar(); }
libperf.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2019. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015-2016. ALL RIGHTS RESERVED. * Copyright (C) ARM Ltd. 2017-2020. ALL RIGHTS RESERVED. * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <ucs/debug/log.h> #include <ucs/arch/bitops.h> #include <ucs/sys/module.h> #include <ucs/sys/string.h> #include <string.h> #include <tools/perf/lib/libperf_int.h> #include <unistd.h> #if _OPENMP #include <omp.h> #endif /* _OPENMP */ #define ATOMIC_OP_CONFIG(_size, _op32, _op64, _op, _msg, _params, _status) \ _status = __get_atomic_flag((_size), (_op32), (_op64), (_op)); \ if (_status != UCS_OK) { \ ucs_error(UCT_PERF_TEST_PARAMS_FMT" does not support atomic %s for " \ "message size %zu bytes", UCT_PERF_TEST_PARAMS_ARG(_params), \ (_msg)[_op], (_size)); \ return _status; \ } #define ATOMIC_OP_CHECK(_size, _attr, _required, _params, _msg) \ if (!ucs_test_all_flags(_attr, _required)) { \ if ((_params)->flags & UCX_PERF_TEST_FLAG_VERBOSE) { \ ucs_error(UCT_PERF_TEST_PARAMS_FMT" does not support required " \ #_size"-bit atomic: %s", UCT_PERF_TEST_PARAMS_ARG(_params), \ (_msg)[ucs_ffs64(~(_attr) & (_required))]); \ } \ return UCS_ERR_UNSUPPORTED; \ } typedef struct { union { struct { size_t dev_addr_len; size_t iface_addr_len; size_t ep_addr_len; } uct; struct { size_t worker_addr_len; size_t total_wireup_len; } ucp; }; size_t rkey_size; unsigned long recv_buffer; } ucx_perf_ep_info_t; const ucx_perf_allocator_t* ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_LAST]; static const char *perf_iface_ops[] = { [ucs_ilog2(UCT_IFACE_FLAG_AM_SHORT)] = "am short", [ucs_ilog2(UCT_IFACE_FLAG_AM_BCOPY)] = "am bcopy", [ucs_ilog2(UCT_IFACE_FLAG_AM_ZCOPY)] = "am zcopy", [ucs_ilog2(UCT_IFACE_FLAG_PUT_SHORT)] = "put short", [ucs_ilog2(UCT_IFACE_FLAG_PUT_BCOPY)] = "put bcopy", [ucs_ilog2(UCT_IFACE_FLAG_PUT_ZCOPY)] = "put zcopy", [ucs_ilog2(UCT_IFACE_FLAG_GET_SHORT)] = "get short", [ucs_ilog2(UCT_IFACE_FLAG_GET_BCOPY)] = "get bcopy", [ucs_ilog2(UCT_IFACE_FLAG_GET_ZCOPY)] = "get zcopy", [ucs_ilog2(UCT_IFACE_FLAG_ERRHANDLE_PEER_FAILURE)] = "peer failure handler", [ucs_ilog2(UCT_IFACE_FLAG_CONNECT_TO_IFACE)] = "connect to iface", [ucs_ilog2(UCT_IFACE_FLAG_CONNECT_TO_EP)] = "connect to ep", [ucs_ilog2(UCT_IFACE_FLAG_AM_DUP)] = "full reliability", [ucs_ilog2(UCT_IFACE_FLAG_CB_SYNC)] = "sync callback", [ucs_ilog2(UCT_IFACE_FLAG_CB_ASYNC)] = "async callback", [ucs_ilog2(UCT_IFACE_FLAG_PENDING)] = "pending", [ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_SHORT)] = "tag eager short", [ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_BCOPY)] = "tag eager bcopy", [ucs_ilog2(UCT_IFACE_FLAG_TAG_EAGER_ZCOPY)] = "tag eager zcopy", [ucs_ilog2(UCT_IFACE_FLAG_TAG_RNDV_ZCOPY)] = "tag rndv zcopy", [ucs_ilog2(UCT_IFACE_FLAG_EP_CHECK)] = "ep check", [ucs_ilog2(UCT_IFACE_FLAG_EP_KEEPALIVE)] = "ep keepalive" }; static const char *perf_atomic_op[] = { [UCT_ATOMIC_OP_ADD] = "add", [UCT_ATOMIC_OP_AND] = "and", [UCT_ATOMIC_OP_OR] = "or" , [UCT_ATOMIC_OP_XOR] = "xor" }; static const char *perf_atomic_fop[] = { [UCT_ATOMIC_OP_ADD] = "fetch-add", [UCT_ATOMIC_OP_AND] = "fetch-and", [UCT_ATOMIC_OP_OR] = "fetch-or", [UCT_ATOMIC_OP_XOR] = "fetch-xor", [UCT_ATOMIC_OP_SWAP] = "swap", [UCT_ATOMIC_OP_CSWAP] = "cswap" }; /* * This Quickselect routine is based on the algorithm described in * "Numerical recipes in C", Second Edition, * Cambridge University Press, 1992, Section 8.5, ISBN 0-521-43108-5 * This code by Nicolas Devillard - 1998. Public domain. */ static ucs_time_t __find_median_quick_select(ucs_time_t arr[], int n) { int low, high ; int median; int middle, ll, hh; #define ELEM_SWAP(a,b) { register ucs_time_t t=(a);(a)=(b);(b)=t; } low = 0 ; high = n-1 ; median = (low + high) / 2; for (;;) { if (high <= low) /* One element only */ return arr[median] ; if (high == low + 1) { /* Two elements only */ if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ; return arr[median] ; } /* Find median of low, middle and high items; swap into position low */ middle = (low + high) / 2; if (arr[middle] > arr[high]) ELEM_SWAP(arr[middle], arr[high]) ; if (arr[low] > arr[high]) ELEM_SWAP(arr[low], arr[high]) ; if (arr[middle] > arr[low]) ELEM_SWAP(arr[middle], arr[low]) ; /* Swap low item (now in position middle) into position (low+1) */ ELEM_SWAP(arr[middle], arr[low+1]) ; /* Nibble from each end towards middle, swapping items when stuck */ ll = low + 1; hh = high; for (;;) { do ll++; while (arr[low] > arr[ll]) ; do hh--; while (arr[hh] > arr[low]) ; if (hh < ll) break; ELEM_SWAP(arr[ll], arr[hh]) ; } /* Swap middle item (in position low) back into correct position */ ELEM_SWAP(arr[low], arr[hh]) ; /* Re-set active partition */ if (hh <= median) low = ll; if (hh >= median) high = hh - 1; } } static ucs_status_t uct_perf_test_alloc_host(const ucx_perf_context_t *perf, size_t length, unsigned flags, uct_allocated_memory_t *alloc_mem) { ucs_status_t status; status = uct_iface_mem_alloc(perf->uct.iface, length, flags, "perftest", alloc_mem); if (status != UCS_OK) { ucs_free(alloc_mem); ucs_error("failed to allocate memory: %s", ucs_status_string(status)); return status; } ucs_assert(alloc_mem->md == perf->uct.md); return UCS_OK; } static void uct_perf_test_free_host(const ucx_perf_context_t *perf, uct_allocated_memory_t *alloc_mem) { uct_iface_mem_free(alloc_mem); } static void ucx_perf_test_memcpy_host(void *dst, ucs_memory_type_t dst_mem_type, const void *src, ucs_memory_type_t src_mem_type, size_t count) { if ((dst_mem_type != UCS_MEMORY_TYPE_HOST) || (src_mem_type != UCS_MEMORY_TYPE_HOST)) { ucs_error("wrong memory type passed src - %d, dst - %d", src_mem_type, dst_mem_type); } else { memcpy(dst, src, count); } } static ucs_status_t uct_perf_test_alloc_mem(ucx_perf_context_t *perf) { ucx_perf_params_t *params = &perf->params; ucs_status_t status; unsigned flags; size_t buffer_size; if ((UCT_PERF_DATA_LAYOUT_ZCOPY == params->uct.data_layout) && params->iov_stride) { buffer_size = params->msg_size_cnt * params->iov_stride; } else { buffer_size = ucx_perf_get_message_size(params); } /* TODO use params->alignment */ flags = (params->flags & UCX_PERF_TEST_FLAG_MAP_NONBLOCK) ? UCT_MD_MEM_FLAG_NONBLOCK : 0; flags |= UCT_MD_MEM_ACCESS_ALL; /* Allocate send buffer memory */ status = perf->allocator->uct_alloc(perf, buffer_size * params->thread_count, flags, &perf->uct.send_mem); if (status != UCS_OK) { goto err; } perf->send_buffer = perf->uct.send_mem.address; /* Allocate receive buffer memory */ status = perf->allocator->uct_alloc(perf, buffer_size * params->thread_count, flags, &perf->uct.recv_mem); if (status != UCS_OK) { goto err_free_send; } perf->recv_buffer = perf->uct.recv_mem.address; /* Allocate IOV datatype memory */ perf->params.msg_size_cnt = params->msg_size_cnt; perf->uct.iov = malloc(sizeof(*perf->uct.iov) * perf->params.msg_size_cnt * params->thread_count); if (NULL == perf->uct.iov) { status = UCS_ERR_NO_MEMORY; ucs_error("Failed allocate send IOV(%lu) buffer: %s", perf->params.msg_size_cnt, ucs_status_string(status)); goto err_free_recv; } ucs_debug("allocated memory. Send buffer %p, Recv buffer %p", perf->send_buffer, perf->recv_buffer); return UCS_OK; err_free_recv: perf->allocator->uct_free(perf, &perf->uct.recv_mem); err_free_send: perf->allocator->uct_free(perf, &perf->uct.send_mem); err: return status; } static void uct_perf_test_free_mem(ucx_perf_context_t *perf) { perf->allocator->uct_free(perf, &perf->uct.send_mem); perf->allocator->uct_free(perf, &perf->uct.recv_mem); free(perf->uct.iov); } void ucx_perf_test_start_clock(ucx_perf_context_t *perf) { ucs_time_t start_time = ucs_get_time(); perf->start_time_acc = ucs_get_accurate_time(); perf->end_time = (perf->params.max_time == 0.0) ? UINT64_MAX : ucs_time_from_sec(perf->params.max_time) + start_time; perf->prev_time = start_time; perf->prev.time = start_time; perf->prev.time_acc = perf->start_time_acc; perf->current.time_acc = perf->start_time_acc; } /* Initialize/reset all parameters that could be modified by the warm-up run */ static void ucx_perf_test_prepare_new_run(ucx_perf_context_t *perf, const ucx_perf_params_t *params) { unsigned i; perf->max_iter = (perf->params.max_iter == 0) ? UINT64_MAX : perf->params.max_iter; perf->report_interval = ucs_time_from_sec(perf->params.report_interval); perf->current.time = 0; perf->current.msgs = 0; perf->current.bytes = 0; perf->current.iters = 0; perf->prev.msgs = 0; perf->prev.bytes = 0; perf->prev.iters = 0; perf->timing_queue_head = 0; for (i = 0; i < TIMING_QUEUE_SIZE; ++i) { perf->timing_queue[i] = 0; } ucx_perf_test_start_clock(perf); } static void ucx_perf_test_init(ucx_perf_context_t *perf, const ucx_perf_params_t *params) { unsigned group_index; perf->params = *params; group_index = rte_call(perf, group_index); if (0 == group_index) { perf->allocator = ucx_perf_mem_type_allocators[params->send_mem_type]; } else { perf->allocator = ucx_perf_mem_type_allocators[params->recv_mem_type]; } ucx_perf_test_prepare_new_run(perf, params); } void ucx_perf_calc_result(ucx_perf_context_t *perf, ucx_perf_result_t *result) { ucs_time_t median; double factor; if ((perf->params.test_type == UCX_PERF_TEST_TYPE_PINGPONG) || (perf->params.test_type == UCX_PERF_TEST_TYPE_PINGPONG_WAIT_MEM)) { factor = 2.0; } else { factor = 1.0; } result->iters = perf->current.iters; result->bytes = perf->current.bytes; result->elapsed_time = perf->current.time_acc - perf->start_time_acc; /* Latency */ median = __find_median_quick_select(perf->timing_queue, TIMING_QUEUE_SIZE); result->latency.typical = ucs_time_to_sec(median) / factor; result->latency.moment_average = (perf->current.time_acc - perf->prev.time_acc) / (perf->current.iters - perf->prev.iters) / factor; result->latency.total_average = (perf->current.time_acc - perf->start_time_acc) / perf->current.iters / factor; /* Bandwidth */ result->bandwidth.typical = 0.0; // Undefined result->bandwidth.moment_average = (perf->current.bytes - perf->prev.bytes) / (perf->current.time_acc - perf->prev.time_acc) * factor; result->bandwidth.total_average = perf->current.bytes / (perf->current.time_acc - perf->start_time_acc) * factor; /* Packet rate */ result->msgrate.typical = 0.0; // Undefined result->msgrate.moment_average = (perf->current.msgs - perf->prev.msgs) / (perf->current.time_acc - perf->prev.time_acc) * factor; result->msgrate.total_average = perf->current.msgs / (perf->current.time_acc - perf->start_time_acc) * factor; } static ucs_status_t ucx_perf_test_check_params(ucx_perf_params_t *params) { size_t it; /* check if zero-size messages are requested and supported */ if ((/* they are not supported by: */ /* - UCT tests, except UCT AM Short/Bcopy */ (params->api == UCX_PERF_API_UCT) || (/* - UCP RMA and AMO tests */ (params->api == UCX_PERF_API_UCP) && (params->command != UCX_PERF_CMD_AM) && (params->command != UCX_PERF_CMD_TAG) && (params->command != UCX_PERF_CMD_TAG_SYNC) && (params->command != UCX_PERF_CMD_STREAM))) && ucx_perf_get_message_size(params) < 1) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Message size too small, need to be at least 1"); } return UCS_ERR_INVALID_PARAM; } if ((params->api == UCX_PERF_API_UCP) && ((params->send_mem_type != UCS_MEMORY_TYPE_HOST) || (params->recv_mem_type != UCS_MEMORY_TYPE_HOST)) && ((params->command == UCX_PERF_CMD_PUT) || (params->command == UCX_PERF_CMD_GET) || (params->command == UCX_PERF_CMD_ADD) || (params->command == UCX_PERF_CMD_FADD) || (params->command == UCX_PERF_CMD_SWAP) || (params->command == UCX_PERF_CMD_CSWAP))) { /* TODO: remove when support for non-HOST memory types will be added */ if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("UCP doesn't support RMA/AMO for \"%s\"<->\"%s\" memory types", ucs_memory_type_names[params->send_mem_type], ucs_memory_type_names[params->recv_mem_type]); } return UCS_ERR_INVALID_PARAM; } if (params->max_outstanding < 1) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("max_outstanding, need to be at least 1"); } return UCS_ERR_INVALID_PARAM; } /* check if particular message size fit into stride size */ if (params->iov_stride) { for (it = 0; it < params->msg_size_cnt; ++it) { if (params->msg_size_list[it] > params->iov_stride) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Buffer size %lu bigger than stride %lu", params->msg_size_list[it], params->iov_stride); } return UCS_ERR_INVALID_PARAM; } } } return UCS_OK; } void uct_perf_ep_flush_b(ucx_perf_context_t *perf, int peer_index) { uct_ep_h ep = perf->uct.peers[peer_index].ep; uct_completion_t comp; ucs_status_t status; int started; started = 0; comp.func = NULL; comp.count = 2; do { if (!started) { status = uct_ep_flush(ep, 0, &comp); if (status == UCS_OK) { --comp.count; } else if (status == UCS_INPROGRESS) { started = 1; } else if (status != UCS_ERR_NO_RESOURCE) { ucs_error("uct_ep_flush() failed: %s", ucs_status_string(status)); return; } } uct_worker_progress(perf->uct.worker); } while (comp.count > 1); } void uct_perf_iface_flush_b(ucx_perf_context_t *perf) { ucs_status_t status; do { status = uct_iface_flush(perf->uct.iface, 0, NULL); uct_worker_progress(perf->uct.worker); } while (status == UCS_INPROGRESS); if (status != UCS_OK) { ucs_error("uct_iface_flush() failed: %s", ucs_status_string(status)); } } static inline uint64_t __get_flag(uct_perf_data_layout_t layout, uint64_t short_f, uint64_t bcopy_f, uint64_t zcopy_f) { return ((layout == UCT_PERF_DATA_LAYOUT_SHORT) || (layout == UCT_PERF_DATA_LAYOUT_SHORT_IOV)) ? short_f : (layout == UCT_PERF_DATA_LAYOUT_BCOPY) ? bcopy_f : (layout == UCT_PERF_DATA_LAYOUT_ZCOPY) ? zcopy_f : 0; } static inline ucs_status_t __get_atomic_flag(size_t size, uint64_t *op32, uint64_t *op64, uint64_t op) { if (size == sizeof(uint32_t)) { *op32 = UCS_BIT(op); return UCS_OK; } else if (size == sizeof(uint64_t)) { *op64 = UCS_BIT(op); return UCS_OK; } return UCS_ERR_UNSUPPORTED; } static inline size_t __get_max_size(uct_perf_data_layout_t layout, size_t short_m, size_t bcopy_m, uint64_t zcopy_m) { return ((layout == UCT_PERF_DATA_LAYOUT_SHORT) || (layout == UCT_PERF_DATA_LAYOUT_SHORT_IOV)) ? short_m : (layout == UCT_PERF_DATA_LAYOUT_BCOPY) ? bcopy_m : (layout == UCT_PERF_DATA_LAYOUT_ZCOPY) ? zcopy_m : 0; } static ucs_status_t uct_perf_test_check_md_support(ucx_perf_params_t *params, ucs_memory_type_t mem_type, uct_md_attr_t *md_attr) { if (!(md_attr->cap.access_mem_types & UCS_BIT(mem_type)) && !(md_attr->cap.reg_mem_types & UCS_BIT(mem_type))) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Unsupported memory type %s by "UCT_PERF_TEST_PARAMS_FMT, ucs_memory_type_names[mem_type], UCT_PERF_TEST_PARAMS_ARG(params)); return UCS_ERR_INVALID_PARAM; } } return UCS_OK; } static ucs_status_t uct_perf_test_check_capabilities(ucx_perf_params_t *params, uct_iface_h iface, uct_md_h md) { uint64_t required_flags = 0; uint64_t atomic_op32 = 0; uint64_t atomic_op64 = 0; uint64_t atomic_fop32 = 0; uint64_t atomic_fop64 = 0; uct_md_attr_t md_attr; uct_iface_attr_t attr; ucs_status_t status; size_t min_size, max_size, max_iov, message_size; status = uct_md_query(md, &md_attr); if (status != UCS_OK) { ucs_error("uct_md_query(%s) failed: %s", params->uct.md_name, ucs_status_string(status)); return status; } status = uct_iface_query(iface, &attr); if (status != UCS_OK) { ucs_error("uct_iface_query("UCT_PERF_TEST_PARAMS_FMT") failed: %s", UCT_PERF_TEST_PARAMS_ARG(params), ucs_status_string(status)); return status; } min_size = 0; max_iov = 1; message_size = ucx_perf_get_message_size(params); switch (params->command) { case UCX_PERF_CMD_AM: required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_AM_SHORT, UCT_IFACE_FLAG_AM_BCOPY, UCT_IFACE_FLAG_AM_ZCOPY); required_flags |= UCT_IFACE_FLAG_CB_SYNC; min_size = __get_max_size(params->uct.data_layout, 0, 0, attr.cap.am.min_zcopy); max_size = __get_max_size(params->uct.data_layout, attr.cap.am.max_short, attr.cap.am.max_bcopy, attr.cap.am.max_zcopy); max_iov = attr.cap.am.max_iov; break; case UCX_PERF_CMD_PUT: required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_PUT_SHORT, UCT_IFACE_FLAG_PUT_BCOPY, UCT_IFACE_FLAG_PUT_ZCOPY); min_size = __get_max_size(params->uct.data_layout, 0, 0, attr.cap.put.min_zcopy); max_size = __get_max_size(params->uct.data_layout, attr.cap.put.max_short, attr.cap.put.max_bcopy, attr.cap.put.max_zcopy); max_iov = attr.cap.put.max_iov; break; case UCX_PERF_CMD_GET: required_flags = __get_flag(params->uct.data_layout, UCT_IFACE_FLAG_GET_SHORT, UCT_IFACE_FLAG_GET_BCOPY, UCT_IFACE_FLAG_GET_ZCOPY); min_size = __get_max_size(params->uct.data_layout, 0, 0, attr.cap.get.min_zcopy); max_size = __get_max_size(params->uct.data_layout, attr.cap.get.max_short, attr.cap.get.max_bcopy, attr.cap.get.max_zcopy); max_iov = attr.cap.get.max_iov; break; case UCX_PERF_CMD_ADD: ATOMIC_OP_CONFIG(message_size, &atomic_op32, &atomic_op64, UCT_ATOMIC_OP_ADD, perf_atomic_op, params, status); max_size = 8; break; case UCX_PERF_CMD_FADD: ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_ADD, perf_atomic_fop, params, status); max_size = 8; break; case UCX_PERF_CMD_SWAP: ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_SWAP, perf_atomic_fop, params, status); max_size = 8; break; case UCX_PERF_CMD_CSWAP: ATOMIC_OP_CONFIG(message_size, &atomic_fop32, &atomic_fop64, UCT_ATOMIC_OP_CSWAP, perf_atomic_fop, params, status); max_size = 8; break; default: if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Invalid test command"); } return UCS_ERR_INVALID_PARAM; } status = ucx_perf_test_check_params(params); if (status != UCS_OK) { return status; } /* check atomics first */ ATOMIC_OP_CHECK(32, attr.cap.atomic32.op_flags, atomic_op32, params, perf_atomic_op); ATOMIC_OP_CHECK(64, attr.cap.atomic64.op_flags, atomic_op64, params, perf_atomic_op); ATOMIC_OP_CHECK(32, attr.cap.atomic32.fop_flags, atomic_fop32, params, perf_atomic_fop); ATOMIC_OP_CHECK(64, attr.cap.atomic64.fop_flags, atomic_fop64, params, perf_atomic_fop); /* check iface flags */ if (!(atomic_op32 | atomic_op64 | atomic_fop32 | atomic_fop64) && (!ucs_test_all_flags(attr.cap.flags, required_flags) || !required_flags)) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error(UCT_PERF_TEST_PARAMS_FMT" does not support operation %s", UCT_PERF_TEST_PARAMS_ARG(params), perf_iface_ops[ucs_ffs64(~attr.cap.flags & required_flags)]); } return UCS_ERR_UNSUPPORTED; } if (message_size < min_size) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Message size (%zu) is smaller than min supported (%zu)", message_size, min_size); } return UCS_ERR_UNSUPPORTED; } if (message_size > max_size) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Message size (%zu) is larger than max supported (%zu)", message_size, max_size); } return UCS_ERR_UNSUPPORTED; } if (params->command == UCX_PERF_CMD_AM) { if ((params->uct.data_layout == UCT_PERF_DATA_LAYOUT_SHORT) && (params->uct.am_hdr_size != sizeof(uint64_t))) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Short AM header size must be 8 bytes"); } return UCS_ERR_INVALID_PARAM; } if ((params->uct.data_layout == UCT_PERF_DATA_LAYOUT_ZCOPY) && (params->uct.am_hdr_size > attr.cap.am.max_hdr)) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("AM header size (%zu) is larger than max supported " "(%zu)", params->uct.am_hdr_size, attr.cap.am.max_hdr); } return UCS_ERR_UNSUPPORTED; } if (params->uct.am_hdr_size > message_size) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("AM header size (%zu) is larger than message size " "(%zu)", params->uct.am_hdr_size, message_size); } return UCS_ERR_INVALID_PARAM; } if (params->uct.fc_window > UCT_PERF_TEST_MAX_FC_WINDOW) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("AM flow-control window (%d) too large (should be <= %d)", params->uct.fc_window, UCT_PERF_TEST_MAX_FC_WINDOW); } return UCS_ERR_INVALID_PARAM; } if ((params->flags & UCX_PERF_TEST_FLAG_ONE_SIDED) && (params->flags & UCX_PERF_TEST_FLAG_VERBOSE)) { ucs_warn("Running active-message test with on-sided progress"); } } if ((UCT_PERF_DATA_LAYOUT_ZCOPY == params->uct.data_layout) || (UCT_PERF_DATA_LAYOUT_SHORT_IOV == params->uct.data_layout)) { if (params->msg_size_cnt > max_iov) { if ((params->flags & UCX_PERF_TEST_FLAG_VERBOSE) || !params->msg_size_cnt) { ucs_error("Wrong number of IOV entries. Requested is %lu, " "should be in the range 1...%lu", params->msg_size_cnt, max_iov); } return UCS_ERR_UNSUPPORTED; } /* if msg_size_cnt == 1 the message size checked above */ if ((UCT_PERF_DATA_LAYOUT_ZCOPY == params->uct.data_layout) && (UCX_PERF_CMD_AM == params->command) && (params->msg_size_cnt > 1)) { if (params->uct.am_hdr_size > params->msg_size_list[0]) { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("AM header size (%lu) larger than the first IOV " "message size (%lu)", params->uct.am_hdr_size, params->msg_size_list[0]); } return UCS_ERR_INVALID_PARAM; } } } status = uct_perf_test_check_md_support(params, params->send_mem_type, &md_attr); if (status != UCS_OK) { return status; } status = uct_perf_test_check_md_support(params, params->recv_mem_type, &md_attr); if (status != UCS_OK) { return status; } return UCS_OK; } static ucs_status_t uct_perf_test_setup_endpoints(ucx_perf_context_t *perf) { const size_t buffer_size = ADDR_BUF_SIZE; ucx_perf_ep_info_t info, *remote_info; unsigned group_size, i, group_index; uct_device_addr_t *dev_addr; uct_iface_addr_t *iface_addr; uct_ep_addr_t *ep_addr; uct_iface_attr_t iface_attr; uct_md_attr_t md_attr; uct_ep_params_t ep_params; void *rkey_buffer; ucs_status_t status; struct iovec vec[5]; void *buffer; void *req; buffer = malloc(buffer_size); if (buffer == NULL) { ucs_error("Failed to allocate RTE buffer"); status = UCS_ERR_NO_MEMORY; goto err; } status = uct_iface_query(perf->uct.iface, &iface_attr); if (status != UCS_OK) { ucs_error("Failed to uct_iface_query: %s", ucs_status_string(status)); goto err_free; } status = uct_md_query(perf->uct.md, &md_attr); if (status != UCS_OK) { ucs_error("Failed to uct_md_query: %s", ucs_status_string(status)); goto err_free; } if (md_attr.cap.flags & (UCT_MD_FLAG_ALLOC|UCT_MD_FLAG_REG)) { info.rkey_size = md_attr.rkey_packed_size; } else { info.rkey_size = 0; } info.uct.dev_addr_len = iface_attr.device_addr_len; info.uct.iface_addr_len = iface_attr.iface_addr_len; info.uct.ep_addr_len = iface_attr.ep_addr_len; info.recv_buffer = (uintptr_t)perf->recv_buffer; rkey_buffer = buffer; dev_addr = UCS_PTR_BYTE_OFFSET(rkey_buffer, info.rkey_size); iface_addr = UCS_PTR_BYTE_OFFSET(dev_addr, info.uct.dev_addr_len); ep_addr = UCS_PTR_BYTE_OFFSET(iface_addr, info.uct.iface_addr_len); ucs_assert_always(UCS_PTR_BYTE_OFFSET(ep_addr, info.uct.ep_addr_len) <= UCS_PTR_BYTE_OFFSET(buffer, buffer_size)); status = uct_iface_get_device_address(perf->uct.iface, dev_addr); if (status != UCS_OK) { ucs_error("Failed to uct_iface_get_device_address: %s", ucs_status_string(status)); goto err_free; } status = uct_iface_get_address(perf->uct.iface, iface_addr); if (status != UCS_OK) { ucs_error("Failed to uct_iface_get_address: %s", ucs_status_string(status)); goto err_free; } if (info.rkey_size > 0) { memset(rkey_buffer, 0, info.rkey_size); status = uct_md_mkey_pack(perf->uct.md, perf->uct.recv_mem.memh, rkey_buffer); if (status != UCS_OK) { ucs_error("Failed to uct_rkey_pack: %s", ucs_status_string(status)); goto err_free; } } group_size = rte_call(perf, group_size); group_index = rte_call(perf, group_index); perf->uct.peers = calloc(group_size, sizeof(*perf->uct.peers)); if (perf->uct.peers == NULL) { goto err_free; } ep_params.field_mask = UCT_EP_PARAM_FIELD_IFACE; ep_params.iface = perf->uct.iface; if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) { for (i = 0; i < group_size; ++i) { if (i == group_index) { continue; } status = uct_ep_create(&ep_params, &perf->uct.peers[i].ep); if (status != UCS_OK) { ucs_error("Failed to uct_ep_create: %s", ucs_status_string(status)); goto err_destroy_eps; } status = uct_ep_get_address(perf->uct.peers[i].ep, ep_addr); if (status != UCS_OK) { ucs_error("Failed to uct_ep_get_address: %s", ucs_status_string(status)); goto err_destroy_eps; } } } else if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) { ep_params.field_mask |= UCT_EP_PARAM_FIELD_DEV_ADDR | UCT_EP_PARAM_FIELD_IFACE_ADDR; } vec[0].iov_base = &info; vec[0].iov_len = sizeof(info); vec[1].iov_base = buffer; vec[1].iov_len = info.rkey_size + info.uct.dev_addr_len + info.uct.iface_addr_len + info.uct.ep_addr_len; rte_call(perf, post_vec, vec, 2, &req); rte_call(perf, exchange_vec, req); for (i = 0; i < group_size; ++i) { if (i == group_index) { continue; } rte_call(perf, recv, i, buffer, buffer_size, req); remote_info = buffer; rkey_buffer = remote_info + 1; dev_addr = UCS_PTR_BYTE_OFFSET(rkey_buffer, remote_info->rkey_size); iface_addr = UCS_PTR_BYTE_OFFSET(dev_addr, remote_info->uct.dev_addr_len); ep_addr = UCS_PTR_BYTE_OFFSET(iface_addr, remote_info->uct.iface_addr_len); perf->uct.peers[i].remote_addr = remote_info->recv_buffer; if (!uct_iface_is_reachable(perf->uct.iface, dev_addr, remote_info->uct.iface_addr_len ? iface_addr : NULL)) { ucs_error("Destination is unreachable"); status = UCS_ERR_UNREACHABLE; goto err_destroy_eps; } if (remote_info->rkey_size > 0) { status = uct_rkey_unpack(perf->uct.cmpt, rkey_buffer, &perf->uct.peers[i].rkey); if (status != UCS_OK) { ucs_error("Failed to uct_rkey_unpack: %s", ucs_status_string(status)); goto err_destroy_eps; } } else { perf->uct.peers[i].rkey.handle = NULL; perf->uct.peers[i].rkey.rkey = UCT_INVALID_RKEY; } if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_EP) { status = uct_ep_connect_to_ep(perf->uct.peers[i].ep, dev_addr, ep_addr); } else if (iface_attr.cap.flags & UCT_IFACE_FLAG_CONNECT_TO_IFACE) { ep_params.dev_addr = dev_addr; ep_params.iface_addr = iface_addr; status = uct_ep_create(&ep_params, &perf->uct.peers[i].ep); } else { status = UCS_ERR_UNSUPPORTED; } if (status != UCS_OK) { ucs_error("Failed to connect endpoint: %s", ucs_status_string(status)); goto err_destroy_eps; } } uct_perf_iface_flush_b(perf); free(buffer); uct_perf_barrier(perf); return UCS_OK; err_destroy_eps: for (i = 0; i < group_size; ++i) { if (perf->uct.peers[i].rkey.rkey != UCT_INVALID_RKEY) { uct_rkey_release(perf->uct.cmpt, &perf->uct.peers[i].rkey); } if (perf->uct.peers[i].ep != NULL) { uct_ep_destroy(perf->uct.peers[i].ep); } } free(perf->uct.peers); err_free: free(buffer); err: return status; } static void uct_perf_test_cleanup_endpoints(ucx_perf_context_t *perf) { unsigned group_size, group_index, i; uct_perf_barrier(perf); uct_iface_set_am_handler(perf->uct.iface, UCT_PERF_TEST_AM_ID, NULL, NULL, 0); group_size = rte_call(perf, group_size); group_index = rte_call(perf, group_index); for (i = 0; i < group_size; ++i) { if (i != group_index) { if (perf->uct.peers[i].rkey.rkey != UCT_INVALID_RKEY) { uct_rkey_release(perf->uct.cmpt, &perf->uct.peers[i].rkey); } if (perf->uct.peers[i].ep) { uct_ep_destroy(perf->uct.peers[i].ep); } } } free(perf->uct.peers); } static ucs_status_t ucp_perf_test_fill_params(ucx_perf_params_t *params, ucp_params_t *ucp_params) { ucs_status_t status; size_t message_size; message_size = ucx_perf_get_message_size(params); switch (params->command) { case UCX_PERF_CMD_PUT: case UCX_PERF_CMD_GET: ucp_params->features |= UCP_FEATURE_RMA; break; case UCX_PERF_CMD_ADD: case UCX_PERF_CMD_FADD: case UCX_PERF_CMD_SWAP: case UCX_PERF_CMD_CSWAP: if (message_size == sizeof(uint32_t)) { ucp_params->features |= UCP_FEATURE_AMO32; } else if (message_size == sizeof(uint64_t)) { ucp_params->features |= UCP_FEATURE_AMO64; } else { if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Atomic size should be either 32 or 64 bit"); } return UCS_ERR_INVALID_PARAM; } break; case UCX_PERF_CMD_TAG: case UCX_PERF_CMD_TAG_SYNC: ucp_params->features |= UCP_FEATURE_TAG; break; case UCX_PERF_CMD_STREAM: ucp_params->features |= UCP_FEATURE_STREAM; break; case UCX_PERF_CMD_AM: ucp_params->features |= UCP_FEATURE_AM; break; default: if (params->flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Invalid test command"); } return UCS_ERR_INVALID_PARAM; } if ((params->flags & UCX_PERF_TEST_FLAG_WAKEUP) || (params->wait_mode == UCX_PERF_WAIT_MODE_SLEEP)) { ucp_params->features |= UCP_FEATURE_WAKEUP; } status = ucx_perf_test_check_params(params); if (status != UCS_OK) { return status; } return UCS_OK; } static ucs_status_t ucp_perf_test_alloc_iov_mem(ucp_perf_datatype_t datatype, size_t iovcnt, unsigned thread_count, ucp_dt_iov_t **iov_p) { ucp_dt_iov_t *iov; if (UCP_PERF_DATATYPE_IOV == datatype) { iov = malloc(sizeof(*iov) * iovcnt * thread_count); if (NULL == iov) { ucs_error("Failed allocate IOV buffer with iovcnt=%lu", iovcnt); return UCS_ERR_NO_MEMORY; } *iov_p = iov; } return UCS_OK; } static ucs_status_t ucp_perf_test_alloc_host(const ucx_perf_context_t *perf, size_t length, void **address_p, ucp_mem_h *memh, int non_blk_flag) { ucp_mem_map_params_t mem_map_params; ucp_mem_attr_t mem_attr; ucs_status_t status; mem_map_params.field_mask = UCP_MEM_MAP_PARAM_FIELD_ADDRESS | UCP_MEM_MAP_PARAM_FIELD_LENGTH | UCP_MEM_MAP_PARAM_FIELD_FLAGS; mem_map_params.address = *address_p; mem_map_params.length = length; mem_map_params.flags = UCP_MEM_MAP_ALLOCATE; if (perf->params.flags & UCX_PERF_TEST_FLAG_MAP_NONBLOCK) { mem_map_params.flags |= non_blk_flag; } status = ucp_mem_map(perf->ucp.context, &mem_map_params, memh); if (status != UCS_OK) { goto err; } mem_attr.field_mask = UCP_MEM_ATTR_FIELD_ADDRESS; status = ucp_mem_query(*memh, &mem_attr); if (status != UCS_OK) { goto err; } *address_p = mem_attr.address; return UCS_OK; err: return status; } static void ucp_perf_test_free_host(const ucx_perf_context_t *perf, void *address, ucp_mem_h memh) { ucs_status_t status; status = ucp_mem_unmap(perf->ucp.context, memh); if (status != UCS_OK) { ucs_warn("ucp_mem_unmap() failed: %s", ucs_status_string(status)); } } static ucs_status_t ucp_perf_test_alloc_mem(ucx_perf_context_t *perf) { ucx_perf_params_t *params = &perf->params; ucs_status_t status; size_t buffer_size; if (params->iov_stride) { buffer_size = params->msg_size_cnt * params->iov_stride; } else { buffer_size = ucx_perf_get_message_size(params); } /* Allocate send buffer memory */ perf->send_buffer = NULL; status = perf->allocator->ucp_alloc(perf, buffer_size * params->thread_count, &perf->send_buffer, &perf->ucp.send_memh, UCP_MEM_MAP_NONBLOCK); if (status != UCS_OK) { goto err; } /* Allocate receive buffer memory */ perf->recv_buffer = NULL; status = perf->allocator->ucp_alloc(perf, buffer_size * params->thread_count, &perf->recv_buffer, &perf->ucp.recv_memh, 0); if (status != UCS_OK) { goto err_free_send_buffer; } /* Allocate AM header */ if (params->ucp.am_hdr_size != 0) { perf->ucp.am_hdr = malloc(params->ucp.am_hdr_size); if (perf->ucp.am_hdr == NULL) { goto err_free_buffers; } } else { perf->ucp.am_hdr = NULL; } /* Allocate IOV datatype memory */ perf->ucp.send_iov = NULL; status = ucp_perf_test_alloc_iov_mem(params->ucp.send_datatype, perf->params.msg_size_cnt, params->thread_count, &perf->ucp.send_iov); if (UCS_OK != status) { goto err_free_am_hdr; } perf->ucp.recv_iov = NULL; status = ucp_perf_test_alloc_iov_mem(params->ucp.recv_datatype, perf->params.msg_size_cnt, params->thread_count, &perf->ucp.recv_iov); if (UCS_OK != status) { goto err_free_send_iov_buffers; } return UCS_OK; err_free_send_iov_buffers: free(perf->ucp.send_iov); err_free_am_hdr: free(perf->ucp.am_hdr); err_free_buffers: perf->allocator->ucp_free(perf, perf->recv_buffer, perf->ucp.recv_memh); err_free_send_buffer: perf->allocator->ucp_free(perf, perf->send_buffer, perf->ucp.send_memh); err: return UCS_ERR_NO_MEMORY; } static void ucp_perf_test_free_mem(ucx_perf_context_t *perf) { free(perf->ucp.recv_iov); free(perf->ucp.send_iov); free(perf->ucp.am_hdr); perf->allocator->ucp_free(perf, perf->recv_buffer, perf->ucp.recv_memh); perf->allocator->ucp_free(perf, perf->send_buffer, perf->ucp.send_memh); } static void ucp_perf_test_destroy_eps(ucx_perf_context_t* perf) { unsigned i, thread_count = perf->params.thread_count; ucs_status_ptr_t *req; ucs_status_t status; for (i = 0; i < thread_count; ++i) { if (perf->ucp.tctx[i].perf.ucp.rkey != NULL) { ucp_rkey_destroy(perf->ucp.tctx[i].perf.ucp.rkey); } if (perf->ucp.tctx[i].perf.ucp.ep != NULL) { req = ucp_ep_close_nb(perf->ucp.tctx[i].perf.ucp.ep, UCP_EP_CLOSE_MODE_FLUSH); if (UCS_PTR_IS_PTR(req)) { do { ucp_worker_progress(perf->ucp.tctx[i].perf.ucp.worker); status = ucp_request_check_status(req); } while (status == UCS_INPROGRESS); ucp_request_release(req); } else if (UCS_PTR_STATUS(req) != UCS_OK) { ucs_warn("failed to close ep %p on thread %d: %s\n", perf->ucp.tctx[i].perf.ucp.ep, i, ucs_status_string(UCS_PTR_STATUS(req))); } } } } static ucs_status_t ucp_perf_test_exchange_status(ucx_perf_context_t *perf, ucs_status_t status) { unsigned group_size = rte_call(perf, group_size); ucs_status_t collective_status = status; struct iovec vec; void *req = NULL; unsigned i; vec.iov_base = &status; vec.iov_len = sizeof(status); rte_call(perf, post_vec, &vec, 1, &req); rte_call(perf, exchange_vec, req); for (i = 0; i < group_size; ++i) { rte_call(perf, recv, i, &status, sizeof(status), req); if (status != UCS_OK) { collective_status = status; } } return collective_status; } static ucs_status_t ucp_perf_test_receive_remote_data(ucx_perf_context_t *perf) { unsigned thread_count = perf->params.thread_count; void *rkey_buffer = NULL; void *req = NULL; unsigned group_size, group_index, i; ucx_perf_ep_info_t *remote_info; ucp_ep_params_t ep_params; ucp_address_t *address; ucs_status_t status; size_t buffer_size; void *buffer; group_size = rte_call(perf, group_size); group_index = rte_call(perf, group_index); if (group_size != 2) { ucs_error("perftest requires group size to be exactly 2 " "(actual group size: %u)", group_size); return UCS_ERR_UNSUPPORTED; } buffer_size = ADDR_BUF_SIZE * thread_count; buffer = malloc(buffer_size); if (buffer == NULL) { ucs_error("failed to allocate RTE receive buffer"); status = UCS_ERR_NO_MEMORY; goto err; } /* Initialize all endpoints and rkeys to NULL to handle error flow */ for (i = 0; i < thread_count; i++) { perf->ucp.tctx[i].perf.ucp.ep = NULL; perf->ucp.tctx[i].perf.ucp.rkey = NULL; } /* receive the data from the remote peer, extract the address from it * (along with additional wireup info) and create an endpoint to the peer */ rte_call(perf, recv, 1 - group_index, buffer, buffer_size, req); remote_info = buffer; for (i = 0; i < thread_count; i++) { address = (ucp_address_t*)(remote_info + 1); rkey_buffer = UCS_PTR_BYTE_OFFSET(address, remote_info->ucp.worker_addr_len); perf->ucp.tctx[i].perf.ucp.remote_addr = remote_info->recv_buffer; ep_params.field_mask = UCP_EP_PARAM_FIELD_REMOTE_ADDRESS; ep_params.address = address; status = ucp_ep_create(perf->ucp.tctx[i].perf.ucp.worker, &ep_params, &perf->ucp.tctx[i].perf.ucp.ep); if (status != UCS_OK) { if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("ucp_ep_create() failed: %s", ucs_status_string(status)); } goto err_free_eps_buffer; } if (remote_info->rkey_size > 0) { status = ucp_ep_rkey_unpack(perf->ucp.tctx[i].perf.ucp.ep, rkey_buffer, &perf->ucp.tctx[i].perf.ucp.rkey); if (status != UCS_OK) { if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_fatal("ucp_rkey_unpack() failed: %s", ucs_status_string(status)); } goto err_free_eps_buffer; } } else { perf->ucp.tctx[i].perf.ucp.rkey = NULL; } remote_info = UCS_PTR_BYTE_OFFSET(remote_info, remote_info->ucp.total_wireup_len); } free(buffer); return UCS_OK; err_free_eps_buffer: ucp_perf_test_destroy_eps(perf); free(buffer); err: return status; } static ucs_status_t ucp_perf_test_send_local_data(ucx_perf_context_t *perf, uint64_t features) { unsigned i, j, thread_count = perf->params.thread_count; size_t address_length = 0; void *rkey_buffer = NULL; void *req = NULL; ucx_perf_ep_info_t *info; ucp_address_t *address; ucs_status_t status; struct iovec *vec; size_t rkey_size; if (features & (UCP_FEATURE_RMA|UCP_FEATURE_AMO32|UCP_FEATURE_AMO64)) { status = ucp_rkey_pack(perf->ucp.context, perf->ucp.recv_memh, &rkey_buffer, &rkey_size); if (status != UCS_OK) { if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("ucp_rkey_pack() failed: %s", ucs_status_string(status)); } goto err; } } else { rkey_size = 0; } /* each thread has an iovec with 3 entries to send to the remote peer: * ep_info, worker_address and rkey buffer */ vec = calloc(3 * thread_count, sizeof(struct iovec)); if (vec == NULL) { ucs_error("failed to allocate iovec"); status = UCS_ERR_NO_MEMORY; goto err_rkey_release; } /* get the worker address created for every thread and send it to the remote * peer */ for (i = 0; i < thread_count; i++) { status = ucp_worker_get_address(perf->ucp.tctx[i].perf.ucp.worker, &address, &address_length); if (status != UCS_OK) { if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("ucp_worker_get_address() failed: %s", ucs_status_string(status)); } goto err_free_workers_vec; } vec[i * 3].iov_base = malloc(sizeof(*info)); if (vec[i * 3].iov_base == NULL) { ucs_error("failed to allocate vec entry for info"); status = UCS_ERR_NO_MEMORY; ucp_worker_destroy(perf->ucp.tctx[i].perf.ucp.worker); goto err_free_workers_vec; } info = vec[i * 3].iov_base; info->ucp.worker_addr_len = address_length; info->ucp.total_wireup_len = sizeof(*info) + address_length + rkey_size; info->rkey_size = rkey_size; info->recv_buffer = (uintptr_t)perf->ucp.tctx[i].perf.recv_buffer; vec[(i * 3) + 0].iov_len = sizeof(*info); vec[(i * 3) + 1].iov_base = address; vec[(i * 3) + 1].iov_len = address_length; vec[(i * 3) + 2].iov_base = rkey_buffer; vec[(i * 3) + 2].iov_len = info->rkey_size; address_length = 0; } /* send to the remote peer */ rte_call(perf, post_vec, vec, 3 * thread_count, &req); rte_call(perf, exchange_vec, req); if (features & (UCP_FEATURE_RMA|UCP_FEATURE_AMO32|UCP_FEATURE_AMO64)) { ucp_rkey_buffer_release(rkey_buffer); } for (i = 0; i < thread_count; i++) { free(vec[i * 3].iov_base); ucp_worker_release_address(perf->ucp.tctx[i].perf.ucp.worker, vec[(i * 3) + 1].iov_base); } free(vec); return UCS_OK; err_free_workers_vec: for (j = 0; j < i; j++) { ucp_worker_destroy(perf->ucp.tctx[i].perf.ucp.worker); } free(vec); err_rkey_release: if (features & (UCP_FEATURE_RMA|UCP_FEATURE_AMO32|UCP_FEATURE_AMO64)) { ucp_rkey_buffer_release(rkey_buffer); } err: return status; } static ucs_status_t ucp_perf_test_setup_endpoints(ucx_perf_context_t *perf, uint64_t features) { ucs_status_t status; unsigned i; /* pack the local endpoints data and send to the remote peer */ status = ucp_perf_test_send_local_data(perf, features); if (status != UCS_OK) { goto err; } /* receive remote peer's endpoints' data and connect to them */ status = ucp_perf_test_receive_remote_data(perf); if (status != UCS_OK) { goto err; } /* sync status across all processes */ status = ucp_perf_test_exchange_status(perf, UCS_OK); if (status != UCS_OK) { goto err_destroy_eps; } /* force wireup completion */ for (i = 0; i < perf->params.thread_count; i++) { status = ucp_worker_flush(perf->ucp.tctx[i].perf.ucp.worker); if (status != UCS_OK) { ucs_warn("ucp_worker_flush() failed on theread %d: %s", i, ucs_status_string(status)); } } return status; err_destroy_eps: ucp_perf_test_destroy_eps(perf); err: (void)ucp_perf_test_exchange_status(perf, status); return status; } static void ucp_perf_test_cleanup_endpoints(ucx_perf_context_t *perf) { ucp_perf_barrier(perf); ucp_perf_test_destroy_eps(perf); } static void ucp_perf_test_destroy_workers(ucx_perf_context_t *perf) { unsigned i; for (i = 0; i < perf->params.thread_count; i++) { if (perf->ucp.tctx[i].perf.ucp.worker != NULL) { ucp_worker_destroy(perf->ucp.tctx[i].perf.ucp.worker); } } } static void ucx_perf_set_warmup(ucx_perf_context_t* perf, const ucx_perf_params_t* params) { perf->max_iter = ucs_min(params->warmup_iter, ucs_div_round_up(params->max_iter, 10)); perf->report_interval = ULONG_MAX; } static ucs_status_t uct_perf_create_md(ucx_perf_context_t *perf) { uct_component_h *uct_components; uct_component_attr_t component_attr; uct_tl_resource_desc_t *tl_resources; unsigned md_index, num_components; unsigned tl_index, num_tl_resources; unsigned cmpt_index; ucs_status_t status; uct_md_h md; uct_md_config_t *md_config; status = uct_query_components(&uct_components, &num_components); if (status != UCS_OK) { goto out; } for (cmpt_index = 0; cmpt_index < num_components; ++cmpt_index) { component_attr.field_mask = UCT_COMPONENT_ATTR_FIELD_MD_RESOURCE_COUNT; status = uct_component_query(uct_components[cmpt_index], &component_attr); if (status != UCS_OK) { goto out_release_components_list; } component_attr.field_mask = UCT_COMPONENT_ATTR_FIELD_MD_RESOURCES; component_attr.md_resources = alloca(sizeof(*component_attr.md_resources) * component_attr.md_resource_count); status = uct_component_query(uct_components[cmpt_index], &component_attr); if (status != UCS_OK) { goto out_release_components_list; } for (md_index = 0; md_index < component_attr.md_resource_count; ++md_index) { status = uct_md_config_read(uct_components[cmpt_index], NULL, NULL, &md_config); if (status != UCS_OK) { goto out_release_components_list; } ucs_strncpy_zero(perf->params.uct.md_name, component_attr.md_resources[md_index].md_name, UCT_MD_NAME_MAX); status = uct_md_open(uct_components[cmpt_index], component_attr.md_resources[md_index].md_name, md_config, &md); uct_config_release(md_config); if (status != UCS_OK) { goto out_release_components_list; } status = uct_md_query_tl_resources(md, &tl_resources, &num_tl_resources); if (status != UCS_OK) { uct_md_close(md); goto out_release_components_list; } for (tl_index = 0; tl_index < num_tl_resources; ++tl_index) { if (!strcmp(perf->params.uct.tl_name, tl_resources[tl_index].tl_name) && !strcmp(perf->params.uct.dev_name, tl_resources[tl_index].dev_name)) { uct_release_tl_resource_list(tl_resources); perf->uct.cmpt = uct_components[cmpt_index]; perf->uct.md = md; status = UCS_OK; goto out_release_components_list; } } uct_md_close(md); uct_release_tl_resource_list(tl_resources); } } ucs_error("Cannot use "UCT_PERF_TEST_PARAMS_FMT, UCT_PERF_TEST_PARAMS_ARG(&perf->params)); status = UCS_ERR_NO_DEVICE; out_release_components_list: uct_release_component_list(uct_components); out: return status; } void uct_perf_barrier(ucx_perf_context_t *perf) { rte_call(perf, barrier, (void(*)(void*))uct_worker_progress, (void*)perf->uct.worker); } void ucp_perf_barrier(ucx_perf_context_t *perf) { rte_call(perf, barrier, (void(*)(void*))ucp_worker_progress, #if _OPENMP (void*)perf->ucp.tctx[omp_get_thread_num()].perf.ucp.worker); #else (void*)perf->ucp.tctx[0].perf.ucp.worker); #endif } static ucs_status_t uct_perf_setup(ucx_perf_context_t *perf) { ucx_perf_params_t *params = &perf->params; uct_iface_config_t *iface_config; ucs_status_t status; uct_iface_params_t iface_params = { .field_mask = UCT_IFACE_PARAM_FIELD_OPEN_MODE | UCT_IFACE_PARAM_FIELD_STATS_ROOT | UCT_IFACE_PARAM_FIELD_RX_HEADROOM | UCT_IFACE_PARAM_FIELD_CPU_MASK, .open_mode = UCT_IFACE_OPEN_MODE_DEVICE, .mode.device.tl_name = params->uct.tl_name, .mode.device.dev_name = params->uct.dev_name, .stats_root = ucs_stats_get_root(), .rx_headroom = 0 }; UCS_CPU_ZERO(&iface_params.cpu_mask); status = ucs_async_context_init(&perf->uct.async, params->async_mode); if (status != UCS_OK) { goto out; } status = uct_worker_create(&perf->uct.async, params->thread_mode, &perf->uct.worker); if (status != UCS_OK) { goto out_cleanup_async; } status = uct_perf_create_md(perf); if (status != UCS_OK) { goto out_destroy_worker; } status = uct_md_iface_config_read(perf->uct.md, params->uct.tl_name, NULL, NULL, &iface_config); if (status != UCS_OK) { goto out_destroy_md; } status = uct_iface_open(perf->uct.md, perf->uct.worker, &iface_params, iface_config, &perf->uct.iface); uct_config_release(iface_config); if (status != UCS_OK) { ucs_error("Failed to open iface: %s", ucs_status_string(status)); goto out_destroy_md; } status = uct_perf_test_check_capabilities(params, perf->uct.iface, perf->uct.md); /* sync status across all processes */ status = ucp_perf_test_exchange_status(perf, status); if (status != UCS_OK) { goto out_iface_close; } status = uct_perf_test_alloc_mem(perf); if (status != UCS_OK) { goto out_iface_close; } /* Enable progress before `uct_iface_flush` and `uct_worker_progress` called * to give a chance to finish connection for some tranports (ib/ud, tcp). * They may return UCS_INPROGRESS from `uct_iface_flush` when connections are * in progress */ uct_iface_progress_enable(perf->uct.iface, UCT_PROGRESS_SEND | UCT_PROGRESS_RECV); status = uct_perf_test_setup_endpoints(perf); if (status != UCS_OK) { ucs_error("Failed to setup endpoints: %s", ucs_status_string(status)); goto out_free_mem; } return UCS_OK; out_free_mem: uct_perf_test_free_mem(perf); out_iface_close: uct_iface_close(perf->uct.iface); out_destroy_md: uct_md_close(perf->uct.md); out_destroy_worker: uct_worker_destroy(perf->uct.worker); out_cleanup_async: ucs_async_context_cleanup(&perf->uct.async); out: return status; } static void uct_perf_cleanup(ucx_perf_context_t *perf) { uct_perf_test_cleanup_endpoints(perf); uct_perf_test_free_mem(perf); uct_iface_close(perf->uct.iface); uct_md_close(perf->uct.md); uct_worker_destroy(perf->uct.worker); ucs_async_context_cleanup(&perf->uct.async); } static void ucp_perf_request_init(void *req) { ucp_perf_request_t *request = req; request->context = NULL; } static ucs_status_t ucp_perf_setup(ucx_perf_context_t *perf) { ucp_params_t ucp_params; ucp_worker_params_t worker_params; ucp_worker_attr_t worker_attr; ucp_config_t *config; ucs_status_t status; unsigned i, thread_count; size_t message_size; ucp_params.field_mask = UCP_PARAM_FIELD_FEATURES | UCP_PARAM_FIELD_REQUEST_SIZE | UCP_PARAM_FIELD_REQUEST_INIT; ucp_params.features = 0; ucp_params.request_size = sizeof(ucp_perf_request_t); ucp_params.request_init = ucp_perf_request_init; if (perf->params.thread_count > 1) { /* when there is more than one thread, a ucp_worker would be created for * each. all of them will share the same ucp_context */ ucp_params.features |= UCP_PARAM_FIELD_MT_WORKERS_SHARED; ucp_params.mt_workers_shared = 1; } status = ucp_perf_test_fill_params(&perf->params, &ucp_params); if (status != UCS_OK) { goto err; } status = ucp_config_read(NULL, NULL, &config); if (status != UCS_OK) { goto err; } status = ucp_init(&ucp_params, config, &perf->ucp.context); ucp_config_release(config); if (status != UCS_OK) { goto err; } thread_count = perf->params.thread_count; message_size = ucx_perf_get_message_size(&perf->params); status = ucp_perf_test_alloc_mem(perf); if (status != UCS_OK) { ucs_warn("ucp test failed to allocate memory"); goto err_cleanup; } perf->ucp.tctx = calloc(thread_count, sizeof(ucx_perf_thread_context_t)); if (perf->ucp.tctx == NULL) { ucs_warn("ucp test failed to allocate memory for thread contexts"); goto err_free_mem; } worker_params.field_mask = UCP_WORKER_PARAM_FIELD_THREAD_MODE; worker_params.thread_mode = perf->params.thread_mode; for (i = 0; i < thread_count; i++) { perf->ucp.tctx[i].tid = i; perf->ucp.tctx[i].perf = *perf; /* Doctor the src and dst buffers to make them thread specific */ perf->ucp.tctx[i].perf.send_buffer = UCS_PTR_BYTE_OFFSET(perf->send_buffer, i * message_size); perf->ucp.tctx[i].perf.recv_buffer = UCS_PTR_BYTE_OFFSET(perf->recv_buffer, i * message_size); status = ucp_worker_create(perf->ucp.context, &worker_params, &perf->ucp.tctx[i].perf.ucp.worker); if (status != UCS_OK) { goto err_free_tctx_destroy_workers; } } if (perf->params.command == UCX_PERF_CMD_AM) { /* Check that requested AM header size is not larger than max supported. */ worker_attr.field_mask = UCP_WORKER_ATTR_FIELD_MAX_AM_HEADER; status = ucp_worker_query(perf->ucp.tctx[0].perf.ucp.worker, &worker_attr); if (status != UCS_OK) { goto err_free_tctx_destroy_workers; } if (worker_attr.max_am_header < perf->params.ucp.am_hdr_size) { ucs_error("AM header size (%zu) is larger than max supported (%zu)", perf->params.ucp.am_hdr_size, worker_attr.max_am_header); status = UCS_ERR_INVALID_PARAM; goto err_free_tctx_destroy_workers; } } status = ucp_perf_test_setup_endpoints(perf, ucp_params.features); if (status != UCS_OK) { if (perf->params.flags & UCX_PERF_TEST_FLAG_VERBOSE) { ucs_error("Failed to setup endpoints: %s", ucs_status_string(status)); } goto err_free_tctx_destroy_workers; } return UCS_OK; err_free_tctx_destroy_workers: ucp_perf_test_destroy_workers(perf); free(perf->ucp.tctx); err_free_mem: ucp_perf_test_free_mem(perf); err_cleanup: ucp_cleanup(perf->ucp.context); err: return status; } static void ucp_perf_cleanup(ucx_perf_context_t *perf) { ucp_perf_test_cleanup_endpoints(perf); ucp_perf_barrier(perf); ucp_perf_test_free_mem(perf); ucp_perf_test_destroy_workers(perf); free(perf->ucp.tctx); ucp_cleanup(perf->ucp.context); } static struct { ucs_status_t (*setup)(ucx_perf_context_t *perf); void (*cleanup)(ucx_perf_context_t *perf); ucs_status_t (*run)(ucx_perf_context_t *perf); void (*barrier)(ucx_perf_context_t *perf); } ucx_perf_funcs[] = { [UCX_PERF_API_UCT] = {uct_perf_setup, uct_perf_cleanup, uct_perf_test_dispatch, uct_perf_barrier}, [UCX_PERF_API_UCP] = {ucp_perf_setup, ucp_perf_cleanup, ucp_perf_test_dispatch, ucp_perf_barrier} }; static ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result); ucs_status_t ucx_perf_run(const ucx_perf_params_t *params, ucx_perf_result_t *result) { ucx_perf_context_t *perf; ucs_status_t status; ucx_perf_global_init(); if (params->command == UCX_PERF_CMD_LAST) { ucs_error("Test is not selected"); status = UCS_ERR_INVALID_PARAM; goto out; } if ((params->api != UCX_PERF_API_UCT) && (params->api != UCX_PERF_API_UCP)) { ucs_error("Invalid test API parameter (should be UCT or UCP)"); status = UCS_ERR_INVALID_PARAM; goto out; } perf = malloc(sizeof(*perf)); if (perf == NULL) { status = UCS_ERR_NO_MEMORY; goto out; } ucx_perf_test_init(perf, params); if (perf->allocator == NULL) { ucs_error("Unsupported memory types %s<->%s", ucs_memory_type_names[params->send_mem_type], ucs_memory_type_names[params->recv_mem_type]); status = UCS_ERR_UNSUPPORTED; goto out_free; } if ((params->api == UCX_PERF_API_UCT) && (perf->allocator->mem_type != UCS_MEMORY_TYPE_HOST)) { ucs_warn("UCT tests also copy 2-byte values from %s memory to " "%s memory, which may impact performance results", ucs_memory_type_names[perf->allocator->mem_type], ucs_memory_type_names[UCS_MEMORY_TYPE_HOST]); } status = perf->allocator->init(perf); if (status != UCS_OK) { goto out_free; } status = ucx_perf_funcs[params->api].setup(perf); if (status != UCS_OK) { goto out_free; } if (params->thread_count == 1) { if (params->api == UCX_PERF_API_UCP) { perf->ucp.worker = perf->ucp.tctx[0].perf.ucp.worker; perf->ucp.ep = perf->ucp.tctx[0].perf.ucp.ep; perf->ucp.remote_addr = perf->ucp.tctx[0].perf.ucp.remote_addr; perf->ucp.rkey = perf->ucp.tctx[0].perf.ucp.rkey; } if (params->warmup_iter > 0) { ucx_perf_set_warmup(perf, params); status = ucx_perf_funcs[params->api].run(perf); if (status != UCS_OK) { goto out_cleanup; } ucx_perf_funcs[params->api].barrier(perf); ucx_perf_test_prepare_new_run(perf, params); } /* Run test */ status = ucx_perf_funcs[params->api].run(perf); ucx_perf_funcs[params->api].barrier(perf); if (status == UCS_OK) { ucx_perf_calc_result(perf, result); rte_call(perf, report, result, perf->params.report_arg, 1, 0); } } else { status = ucx_perf_thread_spawn(perf, result); } out_cleanup: ucx_perf_funcs[params->api].cleanup(perf); out_free: free(perf); out: return status; } #if _OPENMP static ucs_status_t ucx_perf_thread_run_test(void* arg) { ucx_perf_thread_context_t* tctx = (ucx_perf_thread_context_t*) arg; /* a single thread context */ ucx_perf_result_t* result = &tctx->result; ucx_perf_context_t* perf = &tctx->perf; ucx_perf_params_t* params = &perf->params; ucs_status_t status; /* new threads need explicit device association */ status = perf->allocator->init(perf); if (status != UCS_OK) { goto out; } if (params->warmup_iter > 0) { ucx_perf_set_warmup(perf, params); status = ucx_perf_funcs[params->api].run(perf); ucx_perf_funcs[params->api].barrier(perf); if (UCS_OK != status) { goto out; } ucx_perf_test_prepare_new_run(perf, params); } /* Run test */ #pragma omp barrier status = ucx_perf_funcs[params->api].run(perf); ucx_perf_funcs[params->api].barrier(perf); if (UCS_OK != status) { goto out; } ucx_perf_calc_result(perf, result); out: return status; } static void ucx_perf_thread_report_aggregated_results(ucx_perf_context_t *perf) { ucx_perf_thread_context_t* tctx = perf->ucp.tctx; /* all the thread contexts on perf */ unsigned i, thread_count = perf->params.thread_count; double lat_sum_total_avegare = 0.0; ucx_perf_result_t agg_result; agg_result.iters = tctx[0].result.iters; agg_result.bytes = tctx[0].result.bytes; agg_result.elapsed_time = tctx[0].result.elapsed_time; agg_result.bandwidth.total_average = 0.0; agg_result.bandwidth.typical = 0.0; /* Undefined since used only for latency calculations */ agg_result.latency.total_average = 0.0; agg_result.msgrate.total_average = 0.0; agg_result.msgrate.typical = 0.0; /* Undefined since used only for latency calculations */ /* when running with multiple threads, the moment average value is * undefined since we don't capture the values of the last iteration */ agg_result.msgrate.moment_average = 0.0; agg_result.bandwidth.moment_average = 0.0; agg_result.latency.moment_average = 0.0; agg_result.latency.typical = 0.0; /* in case of multiple threads, we have to aggregate the results so that the * final output of the result would show the performance numbers that were * collected from all the threads. * BW and message rate values will be the sum of their values from all * the threads, while the latency value is the average latency from the * threads. */ for (i = 0; i < thread_count; i++) { agg_result.bandwidth.total_average += tctx[i].result.bandwidth.total_average; agg_result.msgrate.total_average += tctx[i].result.msgrate.total_average; lat_sum_total_avegare += tctx[i].result.latency.total_average; } agg_result.latency.total_average = lat_sum_total_avegare / thread_count; rte_call(perf, report, &agg_result, perf->params.report_arg, 1, 1); } static ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result) { ucx_perf_thread_context_t* tctx = perf->ucp.tctx; /* all the thread contexts on perf */ int ti, thread_count = perf->params.thread_count; ucs_status_t* statuses; ucs_status_t status; omp_set_num_threads(thread_count); statuses = calloc(thread_count, sizeof(ucs_status_t)); if (statuses == NULL) { status = UCS_ERR_NO_MEMORY; goto out; } #pragma omp parallel private(ti) { ti = omp_get_thread_num(); tctx[ti].status = ucx_perf_thread_run_test((void*)&tctx[ti]); } status = UCS_OK; for (ti = 0; ti < thread_count; ti++) { if (UCS_OK != tctx[ti].status) { ucs_error("Thread %d failed to run test: %s", tctx[ti].tid, ucs_status_string(tctx[ti].status)); status = tctx[ti].status; } } ucx_perf_thread_report_aggregated_results(perf); free(statuses); out: return status; } #else static ucs_status_t ucx_perf_thread_spawn(ucx_perf_context_t *perf, ucx_perf_result_t* result) { ucs_error("Invalid test parameter (thread mode requested without OpenMP capabilities)"); return UCS_ERR_INVALID_PARAM; } #endif /* _OPENMP */ void ucx_perf_global_init() { static ucx_perf_allocator_t host_allocator = { .mem_type = UCS_MEMORY_TYPE_HOST, .init = ucs_empty_function_return_success, .ucp_alloc = ucp_perf_test_alloc_host, .ucp_free = ucp_perf_test_free_host, .uct_alloc = uct_perf_test_alloc_host, .uct_free = uct_perf_test_free_host, .memcpy = ucx_perf_test_memcpy_host, .memset = memset }; UCS_MODULE_FRAMEWORK_DECLARE(ucx_perftest); ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_HOST] = &host_allocator; /* FIXME Memtype allocator modules must be loaded to global scope, otherwise * alloc hooks, which are using dlsym() to get pointer to original function, * do not work. Need to use bistro for memtype hooks to fix it. */ UCS_MODULE_FRAMEWORK_LOAD(ucx_perftest, UCS_MODULE_LOAD_FLAG_GLOBAL); }
median.c
/* * median.c * * Code generation for function 'median' * */ /* Include files */ #include "rt_nonfinite.h" #include "yaapt.h" #include "median.h" #include "yaapt_emxutil.h" #include "eml_int_forloop_overflow_check.h" #include "isequal.h" #include "yaapt_data.h" #include "blas.h" #include "lapacke.h" /* Variable Definitions */ static emlrtRSInfo lk_emlrtRSI = { 78, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRSInfo mk_emlrtRSI = { 79, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRSInfo nk_emlrtRSI = { 140, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRSInfo ok_emlrtRSI = { 101, "sortIdx", "F:\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\sortIdx.m" }; static emlrtRSInfo pk_emlrtRSI = { 239, "sortIdx", "F:\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\sortIdx.m" }; static emlrtRSInfo qk_emlrtRSI = { 292, "sortIdx", "F:\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\sortIdx.m" }; static emlrtRTEInfo fd_emlrtRTEI = { 1, 14, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRTEInfo gd_emlrtRTEI = { 234, 9, "sortIdx", "F:\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\sortIdx.m" }; static emlrtRTEInfo hd_emlrtRTEI = { 140, 1, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRTEInfo id_emlrtRTEI = { 234, 1, "sortIdx", "F:\\MATLAB\\R2016a\\toolbox\\eml\\eml\\+coder\\+internal\\sortIdx.m" }; static emlrtRTEInfo ig_emlrtRTEI = { 20, 19, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; static emlrtRTEInfo jg_emlrtRTEI = { 17, 19, "median", "F:\\MATLAB\\R2016a\\toolbox\\eml\\lib\\matlab\\datafun\\median.m" }; /* Function Definitions */ void median(const emlrtStack *sp, const emxArray_real_T *x, emxArray_real_T *y) { boolean_T overflow; int32_T ub_loop; int32_T loop_ub; int32_T i; emxArray_int32_T *iwork; emxArray_int32_T *idx; int32_T b_i; int32_T midm1; int32_T i33; int32_T c_i; real_T m; boolean_T p; int32_T i2; int32_T j; int32_T pEnd; int32_T b_p; int32_T q; int32_T qEnd; int32_T kEnd; jmp_buf * volatile emlrtJBStack; emlrtStack st; emlrtStack b_st; emlrtStack c_st; jmp_buf b_emlrtJBEnviron; emlrtStack d_st; emlrtStack e_st; emlrtStack f_st; emlrtStack g_st; emlrtStack h_st; boolean_T emlrtHadParallelError = false; st.prev = sp; st.tls = sp->tls; b_st.prev = &st; b_st.tls = st.tls; emlrtHeapReferenceStackEnterFcnR2012b(sp); overflow = !b_isequal(x); if (overflow) { } else { emlrtErrorWithMessageIdR2012b(sp, &jg_emlrtRTEI, "Coder:toolbox:median_specialEmpty", 0); } if (((x->size[0] == 1) && (x->size[1] == 1)) || (x->size[0] != 1)) { overflow = true; } else { overflow = false; } if (overflow) { } else { emlrtErrorWithMessageIdR2012b(sp, &ig_emlrtRTEI, "Coder:toolbox:autoDimIncompatibility", 0); } ub_loop = y->size[0] * y->size[1]; y->size[0] = 1; y->size[1] = x->size[1]; emxEnsureCapacity(sp, (emxArray__common *)y, ub_loop, (int32_T)sizeof(real_T), &fd_emlrtRTEI); if ((x->size[0] == 0) || (x->size[1] == 0)) { ub_loop = y->size[0] * y->size[1]; y->size[0] = 1; emxEnsureCapacity(sp, (emxArray__common *)y, ub_loop, (int32_T)sizeof(real_T), &fd_emlrtRTEI); loop_ub = y->size[1]; for (ub_loop = 0; ub_loop < loop_ub; ub_loop++) { y->data[y->size[0] * ub_loop] = rtNaN; } } else { ub_loop = x->size[1]; st.site = &lk_emlrtRSI; overflow = (x->size[1] > 2147483646); if (overflow) { b_st.site = &ab_emlrtRSI; check_forloop_overflow_error(&b_st); } emlrtEnterParallelRegion(sp, omp_in_parallel()); emlrtPushJmpBuf(sp, &emlrtJBStack); #pragma omp parallel \ num_threads(emlrtAllocRegionTLSs(sp->tls, omp_in_parallel(), omp_get_max_threads(), omp_get_num_procs())) \ private(iwork,idx,b_i,midm1,i33,c_i,m,p,i2,j,pEnd,b_p,q,qEnd,kEnd,b_emlrtJBEnviron) \ firstprivate(c_st,d_st,e_st,f_st,g_st,h_st,emlrtHadParallelError) { if (setjmp(b_emlrtJBEnviron) == 0) { c_st.prev = sp; c_st.tls = emlrtAllocTLS(sp, omp_get_thread_num()); c_st.site = NULL; emlrtSetJmpBuf(&c_st, &b_emlrtJBEnviron); d_st.prev = &c_st; d_st.tls = c_st.tls; e_st.prev = &d_st; e_st.tls = d_st.tls; f_st.prev = &e_st; f_st.tls = e_st.tls; g_st.prev = &f_st; g_st.tls = f_st.tls; h_st.prev = &g_st; h_st.tls = g_st.tls; emxInit_int32_T1(&c_st, &iwork, 1, &id_emlrtRTEI, true); emxInit_int32_T1(&c_st, &idx, 1, &hd_emlrtRTEI, true); } else { emlrtHadParallelError = true; } #pragma omp for nowait for (i = 1; i <= ub_loop; i++) { if (emlrtHadParallelError) continue; if (setjmp(b_emlrtJBEnviron) == 0) { b_i = i; d_st.site = &mk_emlrtRSI; e_st.site = &nk_emlrtRSI; midm1 = x->size[0]; i33 = idx->size[0]; idx->size[0] = midm1; emxEnsureCapacity(&e_st, (emxArray__common *)idx, i33, (int32_T)sizeof (int32_T), &fd_emlrtRTEI); for (i33 = 0; i33 < midm1; i33++) { idx->data[i33] = 0; } f_st.site = &ok_emlrtRSI; i33 = x->size[0] + 1; c_i = iwork->size[0]; iwork->size[0] = midm1; emxEnsureCapacity(&f_st, (emxArray__common *)iwork, c_i, (int32_T) sizeof(int32_T), &gd_emlrtRTEI); g_st.site = &pk_emlrtRSI; if ((!(1 > i33 - 2)) && (i33 - 2 > 2147483645)) { h_st.site = &ab_emlrtRSI; check_forloop_overflow_error(&h_st); } for (midm1 = 1; midm1 <= i33 - 2; midm1 += 2) { m = x->data[midm1 + x->size[0] * (b_i - 1)]; if ((x->data[(midm1 + x->size[0] * (b_i - 1)) - 1] <= m) || muDoubleScalarIsNaN(m)) { p = true; } else { p = false; } if (p) { idx->data[midm1 - 1] = midm1; idx->data[midm1] = midm1 + 1; } else { idx->data[midm1 - 1] = midm1 + 1; idx->data[midm1] = midm1; } } c_i = x->size[0]; if ((c_i & 1) != 0) { c_i = x->size[0] - 1; midm1 = x->size[0]; idx->data[c_i] = midm1; } c_i = 2; while (c_i < i33 - 1) { i2 = c_i << 1; j = 1; for (pEnd = 1 + c_i; pEnd < i33; pEnd = qEnd + c_i) { b_p = j; q = pEnd; qEnd = j + i2; if (qEnd > i33) { qEnd = i33; } midm1 = 0; kEnd = qEnd - j; while (midm1 + 1 <= kEnd) { m = x->data[(idx->data[q - 1] + x->size[0] * (b_i - 1)) - 1]; if ((x->data[(idx->data[b_p - 1] + x->size[0] * (b_i - 1)) - 1] <= m) || muDoubleScalarIsNaN(m)) { p = true; } else { p = false; } if (p) { iwork->data[midm1] = idx->data[b_p - 1]; b_p++; if (b_p == pEnd) { while (q < qEnd) { midm1++; iwork->data[midm1] = idx->data[q - 1]; q++; } } } else { iwork->data[midm1] = idx->data[q - 1]; q++; if (q == qEnd) { while (b_p < pEnd) { midm1++; iwork->data[midm1] = idx->data[b_p - 1]; b_p++; } } } midm1++; } g_st.site = &qk_emlrtRSI; for (midm1 = 0; midm1 + 1 <= kEnd; midm1++) { idx->data[(j + midm1) - 1] = iwork->data[midm1]; } j = qEnd; } c_i = i2; } i33 = x->size[0]; midm1 = i33 >> 1; i33 = x->size[0]; if (muDoubleScalarIsNaN(x->data[(idx->data[i33 - 1] + x->size[0] * (b_i - 1)) - 1])) { m = rtNaN; } else { i33 = x->size[0]; if ((i33 & 1) == 0) { if (((x->data[(idx->data[midm1 - 1] + x->size[0] * (b_i - 1)) - 1] < 0.0) && (x->data[(idx->data[midm1] + x->size[0] * (b_i - 1)) - 1] >= 0.0)) || muDoubleScalarIsInf(x->data [(idx->data[midm1 - 1] + x->size[0] * (b_i - 1)) - 1]) || muDoubleScalarIsInf(x->data[(idx->data[midm1] + x->size[0] * (b_i - 1)) - 1])) { m = (x->data[(idx->data[midm1 - 1] + x->size[0] * (b_i - 1)) - 1] + x->data[(idx->data[midm1] + x->size[0] * (b_i - 1)) - 1]) / 2.0; } else { m = x->data[(idx->data[midm1 - 1] + x->size[0] * (b_i - 1)) - 1] + (x->data[(idx->data[midm1] + x->size[0] * (b_i - 1)) - 1] - x->data[(idx->data[midm1 - 1] + x->size[0] * (b_i - 1)) - 1]) / 2.0; } } else { m = x->data[(idx->data[midm1] + x->size[0] * (b_i - 1)) - 1]; } } y->data[b_i - 1] = m; } else { emlrtHadParallelError = true; } } if (!emlrtHadParallelError) { emlrtHeapReferenceStackLeaveScope(&c_st, 2); emxFree_int32_T(&idx); emxFree_int32_T(&iwork); } } emlrtPopJmpBuf(sp, &emlrtJBStack); emlrtExitParallelRegion(sp, omp_in_parallel()); } emlrtHeapReferenceStackLeaveFcnR2012b(sp); } /* End of code generation (median.c) */