source
stringlengths
3
92
c
stringlengths
26
2.25M
matrix_mul_OMP_seq.c
//usage, $ ./exec < matrix.csv > matrix_out.csv #include<omp.h> #include<stdio.h> #include<stdlib.h> #include<time.h> const int CHUNK = 10; void print_matrix(float *mat, int rows, int cols) { int i, j; printf("%d, %d\n", rows, cols); for (i = 0; i < rows; i++) { for (j = 0; j < cols; j++) printf("%f, ", mat[i * cols + j]); printf("\n"); } } void multiply_matrix(float *mat1, int r1, int c1, float *mat2, int r2, int c2, float *res) { int pos_matrix1, pos_matrix2; int i, j, k, tid, acc; for (i = 0; i < r1 * c2; i++) res[i] = 0; time_t t_init = time(NULL); double init_t = omp_get_wtime( ); #pragma omp shared(mat1, r1, c1, mat2, r2, c2, res) private(i, j, k, acc, tid) { #pragma omp for schedule(dynamic, CHUNK) for (i = 0; i < r1; i++) { for (j = 0; j < c2; j++) { for (k = 0; k < c1; k++) { res[i * c2 + j] += mat1[i * c1 + k] * mat2[c2 * k + j]; } } } } time_t t_end = time(NULL); double end_t = omp_get_wtime( ); printf("{\n"); printf("\"Normal time\": %ld\n", (t_end - t_init)); printf("\"OMP time\" : %lf\n", (end_t - init_t)); printf("}\n"); } int main() { float *mat1, *mat2, *it, *res; int sr1, sr2, sc1, sc2, i, j; while (scanf("%d, %d", &sr1, &sc1) == 2) { mat1 = (float *)malloc(sizeof (float) * sr1 * sc1); for (i = 0, it = mat1; i < sr1 * sc1; i++) scanf("%f,", it++); scanf("%d, %d", &sr2, &sc2); mat2 = (float *)malloc(sizeof (float) * sr2 * sc2); for (i = 0, it = mat2; i < sr2 * sc2; i++) scanf("%f,", it++); if (sc1 != sr2) { printf("invalid matrices\n"); break; } res = (float *)malloc(sizeof (float) * sr1 * sc2); multiply_matrix(mat1, sr1, sc1, mat2, sr2, sc2, res); // print_matrix(res, sr1, sc2); // printf("\n"); // print_matrix(mat1, sr1, sc1); } return 0; }
solver_main.c
/** * \file * \brief the generic main file for all CPU solvers * * \author Nicholas Curtis * \date 03/09/2015 * * Contains main function, setup, initialization, logging, timing and driver functions */ /** Include common code. */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdbool.h> #include <complex.h> #include <sys/types.h> #include <sys/stat.h> #ifdef DEBUG #include <fenv.h> #endif //our code #include "header.h" #include "solver.h" #include "timer.h" #include "read_initial_conditions.h" #ifdef GENERATE_DOCS namespace generic { #endif /** * \brief Writes state vectors to file * \param[in] NUM the number of state vectors to write * \param[in] t the current system time * \param[in] y_host the current state vectors * \param[in] pFile the opened binary file object * * The resulting file is updated as: * system time\n * temperature, mass fractions (State #1)\n * temperature, mass fractions (State #2)... */ void write_log(int NUM, double t, const double* y_host, FILE* pFile) { fwrite(&t, sizeof(double), 1, pFile); double buffer[NN]; for (int j = 0; j < NUM; j++) { double Y_N = 1.0; buffer[0] = y_host[j]; for (int i = 1; i < NSP; ++i) { buffer[i] = y_host[NUM * i + j]; Y_N -= buffer[i]; } #if NN == NSP + 1 //pyjac buffer[NSP] = Y_N; #endif apply_reverse_mask(&buffer[1]); fwrite(buffer, sizeof(double), NN, pFile); } } ////////////////////////////////////////////////////////////////////////////// /** Main function * * \param[in] argc command line argument count * \param[in] argv command line argument vector * * This allows running the integrators from the command line. The syntax is as follows:\n * `./solver-name [num_threads] [num_IVPs]`\n * * num_threads [Optional, Default:1] * * The number OpenMP threads to utilize * * The number of threads cannot be greater than recognized by OpenMP via `omp_get_max_threads()` * * num_IVPs [Optional, Default:1] * * The number of initial value problems to solve. * * This must be less than the number of conditions in the data file if #SAME_IC is not defined. * * If #SAME_IC is defined, then the initial conditions in the mechanism files will be used. * */ int main (int argc, char *argv[]) { //enable signaling NAN and other bad numerics tracking for easier debugging #ifdef DEBUG feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW); #endif int NUM = 1; int num_threads = 1; ///////////////////////////////////////////////////////////////////// // OpenMP ///////////////////////////////////////////////////////////////////// // set & initialize OpenMP threads via command line argument (if any) #ifdef _OPENMP int max_threads = omp_get_max_threads (); if (argc == 1) { // set to max threads (environment variable) omp_set_num_threads (max_threads); } else { if (argc > 1) { num_threads = max_threads; // first check if is number if (sscanf(argv[1], "%i", &num_threads) !=1 || (num_threads <= 0) || (num_threads > max_threads)) { printf("Error: Number of threads not in correct range\n"); printf("Provide number between 1 and %i\n", max_threads); exit(1); } omp_set_num_threads (num_threads); } if (argc > 2) { //check for problem size int problemsize = NUM; if (sscanf(argv[2], "%i", &problemsize) !=1 || (problemsize <= 0)) { printf("Error: Problem size not in correct range\n"); printf("Provide number greater than 0\n"); exit(1); } NUM = problemsize; } } //get max number of threads from OMP num_threads = 0; #pragma omp parallel reduction(+:num_threads) num_threads += 1; #endif // print number of independent ODEs printf ("# ODEs: %d\n", NUM); printf ("# threads: %d\n", num_threads); initialize_solver(num_threads); ///////////////////////////////////////////////// // arrays ///////////////////////////////////////////////// #ifdef SHUFFLE const char* filename = "shuffled_data.bin"; #elif !defined(SAME_IC) const char* filename = "ign_data.bin"; #endif double* y_host; double* var_host; #ifdef SAME_IC set_same_initial_conditions(NUM, &y_host, &var_host); #else read_initial_conditions(filename, NUM, &y_host, &var_host); #endif // flag for ignition #ifdef IGN bool ign_flag = false; // ignition delay time, units [s] double t_ign = 0.0; double T0 = y_host[0]; #endif #ifdef LOG_OUTPUT // file for data FILE *pFile; const char* f_name = solver_name(); int len = strlen(f_name); char out_name[len + 13]; struct stat info; if (stat("./log/", &info) != 0) { printf("Expecting 'log' subdirectory in current working directory. Please run" " mkdir log (or the equivalent) and run again.\n"); exit(-1); } sprintf(out_name, "log/%s-log.bin", f_name); pFile = fopen(out_name, "wb"); write_log(NUM, 0, y_host, pFile); init_solver_log(); #endif ////////////////////////////// // start timer StartTimer(); ////////////////////////////// // set initial time double t = 0; double t_next = fmin(end_time, t_step); int numSteps = 0; // time integration loop while (t + EPS < end_time) { numSteps++; intDriver(NUM, t, t_next, var_host, y_host); t = t_next; t_next = fmin(end_time, (numSteps + 1) * t_step); #if defined(PRINT) printf("%.15le\t%.15le\n", t, y_host[0]); #endif #ifdef DEBUG // check if within bounds if ((y_host[0] < 0.0) || (y_host[0] > 10000.0)) { printf("Error, out of bounds.\n"); printf("Time: %e, ind %d val %e\n", t, 0, y_host[0]); return 1; } #endif #ifdef LOG_OUTPUT #if !defined(LOG_END_ONLY) write_log(NUM, t, y_host, pFile); solver_log(); #endif #endif #ifdef IGN // determine if ignition has occurred if ((y_host[0] >= (T0 + 400.0)) && !(ign_flag)) { ign_flag = true; t_ign = t; } #endif } #ifdef LOG_END_ONLY write_log(NUM, t, y_host, pFile); solver_log(); #endif ///////////////////////////////// // end timer double runtime = GetTimer(); ///////////////////////////////// runtime /= 1000.0; printf ("Time: %.15e sec\n", runtime); runtime = runtime / ((double)(numSteps)); printf ("Time per step: %e (s)\t%.15e (s/thread)\n", runtime, runtime / NUM); #ifdef IGN printf ("Ig. Delay (s): %e\n", t_ign); #endif printf("TFinal: %e\n", y_host[0]); #ifdef LOG_OUTPUT fclose (pFile); #endif free (y_host); free(var_host); cleanup_solver(num_threads); return 0; } #ifdef GENERATE_DOCS } #endif
simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized void xxx(int argc) { int x; // expected-note {{initialize the variable 'x' to silence this warning}} #pragma omp simd for (int i = 0; i < 10; ++i) argc = x; // expected-warning {{variable 'x' is uninitialized when used here}} } // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd foo // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd safelen(4) void test_no_clause() { int i; #pragma omp simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp simd' must be a for loop}} #pragma omp simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd; for (i = 0; i < 16; ++i) ; // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd firstprivate(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd safelen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd safelen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, ) for (i = 0; i < 16; ++i) ; // xxpected-error@+1 {{expected expression}} #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd simdlen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd simdlen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_safelen_simdlen() { int i; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd simdlen(6) safelen(5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // xxpected-error@+1 {{expected expression}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} #pragma omp simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expression is not an integer constant expression}} #pragma omp simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-note@+2 2 {{defined as reduction}} #pragma omp parallel #pragma omp simd collapse(2) reduction(+ : i) for (i = 0; i < 16; ++i) // expected-error {{loop iteration variable in the associated loop of 'omp simd' directive may not be reduction, predetermined as lastprivate}} // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}} for (int j = 0; j < 16; ++j) // expected-error@+2 2 {{reduction variable must be shared}} // expected-error@+1 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; #pragma omp parallel #pragma omp for for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp simd reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd linear(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd linear(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp simd linear(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be linear}} #pragma omp simd linear(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as private}} // expected-error@+1 {{private variable cannot be linear}} #pragma omp simd private(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be private}} #pragma omp simd linear(x) private(x) for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{zero linear step (x and other variables in clause should probably be const)}} #pragma omp simd linear(x, y : 0) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be lastprivate}} #pragma omp simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp simd lastprivate(x) linear(x) for (i = 0; i < 16; ++i) ; } void test_aligned() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as aligned}} // expected-error@+1 {{a variable cannot appear in more than one aligned clause}} #pragma omp simd aligned(x) aligned(z, x) for (i = 0; i < 16; ++i) ; // expected-note@+3 {{defined as aligned}} // expected-error@+2 {{a variable cannot appear in more than one aligned clause}} // expected-error@+1 2 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_firstprivate() { int i; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-error@+1 {{expected expression}} #pragma omp simd firstprivate( for (i = 0; i < 16; ++i) ; } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_reduction() { int i, x, y; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction() for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction( : x) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(, for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(+ for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+: for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ : x, + : y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction(% : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(+ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(* : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(- : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(^ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(&& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(|| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(max : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(min : x) for (i = 0; i < 16; ++i) ; struct X { int x; }; struct X X; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : X.x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : x + x) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void linear_modifiers(int argc) { int f; #pragma omp simd linear(f) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(val(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(foo(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; } void test_nontemporal() { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 2 {{expected expression}} #pragma omp simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} #pragma omp simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} #pragma omp simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} omp50-error@+1 {{expected variable name}} #pragma omp simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd nontemporal(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd nontemporal(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd nontemporal(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp simd nontemporal(x :, ) for (i = 0; i < 16; ++i) ; // omp50-note@+2 {{defined as nontemporal}} // omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; #pragma omp simd order // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected '(' after 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order( // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(none // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(concurrent // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(concurrent) // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} for (int i = 0; i < 10; ++i) ; }
amask_hybrid.c
/* Program hybrid_affinity reports the mask for each OMP thread for each MPI process, and works for nsec seconds (10). This allows one to inspect occupation through utilities like top (e.g. execute top, then hit the 1 key). Uses maskeraid utilities github.com/TACC/maskeraid amask_mpi(): in pure MPI region to report MPI process masks amask_hybrid(): in OpenMP parallel region to report thread masks map_to_procid( procid ): sets thread affinity to cpu_id (see /proc/cpuinfo, or hwloc) load_cpu_nsec(nsec): loads the cpu for nsec (default 10) hybrid_affinity.c is a driver for: 1.) Get line arguments (optional): help or number of seconds for load 2.) Start MPI Affinity for MPI processes can be reset here. amask_mpi() reports MPI process masks 3.) Start OpenMP parallel region amask_hybrid() reports masks for each thread of each MPI process. 4.) Set a work load on each thread 5.) Finish parallel region 6.) Stop MPI Kent Milfeld 12/16/15 Update to separate require a single call for OpenMP hybrid. Uses multi-threaded MPI initialization Kent Milfeld 2015/07/13 */ #include <stdio.h> #include <omp.h> #include <mpi.h> #include <unistd.h> #include <stdlib.h> #include "opts.h" void load_cpu_nsec(int nsec); void amask_hybrid(void); int map_to_procid( int icore); void amask_mpi(void); int main(int argc, char **argv){ int rank, nranks; // MPI variables. int nthrds, thrd, procid; //Thread info int requested=MPI_THREAD_MULTIPLE, provided; int nsec = 10; // Load, default time int ierr; // Error number // cmdln_get_nsec_or_help( &nsec, argc, argv); //optional, get nsec from cmd line Maskopts opts(argc,argv); // thread safe init replaces MPI_Init(&argc, &argv); MPI_Init_thread(&argc, &argv, requested, &provided); MPI_Comm_size(MPI_COMM_WORLD, &nranks); MPI_Comm_rank(MPI_COMM_WORLD, &rank); amask_mpi(); // Report JUST MPI process masks #pragma omp parallel private(thrd,nthrds,ierr) { thrd = omp_get_thread_num(); nthrds = omp_get_num_threads(); // procid = thrd; // set procid to thread number (thrd) // ierr = map_to_procid( procid ); // set your own affinity here amask_hybrid(); // Call mask reporter load_cpu_nsec( nsec ); // Load up rank process so user can watch top. } MPI_Finalize(); }
GB_binop__isle_int16.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__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_08__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_02__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_04__isle_int16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isle_int16) // A*D function (colscale): GB (_AxD__isle_int16) // D*A function (rowscale): GB (_DxB__isle_int16) // C+=B function (dense accum): GB (_Cdense_accumB__isle_int16) // C+=b function (dense accum): GB (_Cdense_accumb__isle_int16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isle_int16) // C=scalar+B GB (_bind1st__isle_int16) // C=scalar+B' GB (_bind1st_tran__isle_int16) // C=A+scalar GB (_bind2nd__isle_int16) // C=A'+scalar GB (_bind2nd_tran__isle_int16) // C type: int16_t // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij <= bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ int16_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) \ int16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int16_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_ISLE || GxB_NO_INT16 || GxB_NO_ISLE_INT16) //------------------------------------------------------------------------------ // 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__isle_int16) ( 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__isle_int16) ( 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__isle_int16) ( 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 int16_t int16_t bwork = (*((int16_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__isle_int16) ( 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 int16_t *restrict Cx = (int16_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__isle_int16) ( 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 int16_t *restrict Cx = (int16_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__isle_int16) ( 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__isle_int16) ( 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__isle_int16) ( 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__isle_int16) ( 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__isle_int16) ( 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__isle_int16) ( 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 int16_t *Cx = (int16_t *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_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 ; int16_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__isle_int16) ( 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 ; int16_t *Cx = (int16_t *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x <= aij) ; \ } GrB_Info GB (_bind1st_tran__isle_int16) ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_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) \ { \ int16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij <= y) ; \ } GrB_Info GB (_bind2nd_tran__isle_int16) ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
max_SSE.c
/* * File: max_SSE.c * Author: Malcolm Davis * Course: Computer Architecture II * Created on Apr 20, 2018 * 16 bit values vector max * * Usage: * ./max for default parameters and random vectors or; * ./max v1.1 v1.2 v1.3 v1.4 v1.5 v1.6 v1.7 v1.8 v2.1 v2.2 v2.3 v2.4 v2.5 v2.6 v2.7 v2.8 [ v3.1 ...] */ #include <emmintrin.h>//v3 #include <smmintrin.h>//v4 #include <stdio.h> #include <stdlib.h> #include <time.h> void usage(){ printf("Usage:\n ./max for default parameters and random vectors or;\n\ ./max v1.1 v1.2 v1.3 v1.4 v1.5 v1.6 v1.7 v1.8 v2.1 v2.2 v2.3 v2.4 v2.5 v2.6 v2.7 v2.8 [ vn.1 ...]\n"); } /* * Prints a __m128i vector on console * @param v the vector to print */ void printVector(__m128i* v){ int16_t * pointer = (int16_t*)v; for (int i = 0; i < 8; ++i) { printf("%d\t", *pointer); pointer++; } printf("\n"); } /* * Main method, retrive command line options, and loops comparing vectors */ int main(int argc, char ** argv){ //If the count of the input is not a multiple of 8 greater than 2, then exit if (((argc-1)%8)!=0 || (int)((argc-1)/8) == 1){ usage(); return -1; } __m128i *vector1,* vector2, result; static int16_t v1[8], v2[8]; if(argc == 1){ srand (time(NULL)); //If no arguments then generate random vectors #pragma omp parallel for for (int i = 0; i < 8; ++i) { v1[i] = rand()%32767; v2[i] = rand()%32767; } } else{ //If arguments then set the values into a vector #pragma omp parallel for for (int i = 0; i < 8; ++i) { v1[i]=atoi(argv[i+1]); v2[i]=atoi(argv[i+9]); } } vector1 = (__m128i*)v1; vector2 = (__m128i*)v2; printf("Vector 1: "); printVector(vector1); printf("Vector 2: "); printVector(vector2); result = _mm_max_epi16(*vector1, *vector2); //If there are more than 2 vectors, loop and compare if((int)((argc-1)/8) >2){ for (int i = 2; i < (argc-1)/8; ++i) { for (int j = 0; j < 8; ++j) { v1[j]=*((int16_t*)(&result)+j); v2[j]=atoi(argv[i*8+j+1]); } vector1 = (__m128i*)v1; vector2 = (__m128i*)v2; printf("Vector %d: ", i+1); printVector(vector2); result = _mm_max_epi16(*vector1, *vector2); } } printf("Result *********************** \n"); printf("Result: "); printVector(&result); }
HDF5SubdomainDumper.h
// // HDF5SubdomainDumper.h // Cubism // // Created by Fabian Wermelinger 2018-08-03 // Copyright 2018 ETH Zurich. All rights reserved. // #ifndef HDF5SUBDOMAINDUMPER_H_3C2DKYV4 #define HDF5SUBDOMAINDUMPER_H_3C2DKYV4 #include <cassert> #include <iostream> #include <vector> #include <string> #include <sstream> #include "HDF5Dumper.h" CUBISM_NAMESPACE_BEGIN /////////////////////////////////////////////////////////////////////////////// // helpers namespace SubdomainTypes { template <typename TGrid> class Subdomain { public: template <typename TSubdomain> static std::vector<TSubdomain> getEntities(ArgumentParser& parser, TGrid& grid) { typedef typename TGrid::BlockType B; // Concept: // 1.) Extract bounding box data from parser input subdomains // 2.) Compute global bounding box for each subdomain // defines the number of subdomains in the config file: // nsubdomains 1 # defines one subdomain const size_t nSubdomains = parser("nsubdomains").asInt(0); std::vector<TSubdomain> subdomains; for (size_t i = 0; i < nSubdomains; ++i) { // 1.) const size_t id = i+1; std::ostringstream identifier; identifier << "subdomain" << id; parser.set_strict_mode(); // each defined subdomain requires an origin and an extent: // subdomain1_origin 0 1.0 2 # requires 3 coordinates, separated by white space (no newlines!) // subdomain1_extent 1 1 1 # if subdomain exceeds simulation domain, it will be clipped. const std::string input_origin = parser(identifier.str()+"_origin").asString(); const std::string input_extent = parser(identifier.str()+"_extent").asString(); parser.unset_strict_mode(); std::vector<double> new_origin(0); { std::istringstream iss(input_origin); for (int coord = 0; coord < 3; ++coord) { assert(!iss.eof()); double val; iss >> val; new_origin.push_back(val); } } std::vector<double> new_extent(0); { std::istringstream iss(input_extent); for (int coord = 0; coord < 3; ++coord) { assert(!iss.eof()); double val; iss >> val; new_extent.push_back(val); } } // 2.) int idx_start[3]; int idx_end[3]; const double* h[3]; double sub_start[3]; double sub_end[3]; for (int coord = 0; coord < 3; ++coord) { const MeshMap<B>& mmap = grid.getMeshMap(coord); const double c_start = mmap.start(); const double c_end = mmap.end(); // check and reset if domain violation. assert(new_origin[coord] < c_end); assert(new_extent[coord] > 0); if (new_origin[coord] < c_start) new_origin[coord] = c_start; // set to domain start if (new_origin[coord]+new_extent[coord] > c_end) new_extent[coord] = c_end - new_origin[coord]; // clip to domain end // compute bounding box const unsigned int ncells = mmap.ncells(); const double lower_bound = new_origin[coord]; double c_vertex = c_start; for (unsigned int cell = 0; cell < ncells; ++cell) { c_vertex += mmap.cell_width(cell); if (lower_bound < c_vertex) { idx_start[coord] = cell; h[coord] = mmap.data_grid_spacing() + cell; sub_start[coord] = c_vertex - mmap.cell_width(cell); break; } } const double upper_bound = lower_bound + new_extent[coord]; c_vertex = c_end; for (int cell = ncells-1; cell >= 0; --cell) { c_vertex -= mmap.cell_width(cell); if (upper_bound > c_vertex) { idx_end[coord] = cell; sub_end[coord] = c_vertex + mmap.cell_width(cell); break; } } } subdomains.emplace_back(&grid, id, sub_start, sub_end, h, idx_start, idx_end); } return subdomains; } public: typedef TGrid GridType; // bb_start: cell index within which the bounding box start (lower left) lies // bb_end: cell index within which the bounding box end (upper right) lies Subdomain(TGrid* grid, const int id, const double start[3], const double end[3], const double* h[3], const int bb_start[3]=0, const int bb_end[3]=0) : m_grid(grid), m_id(id), m_bbox_start{bb_start[0], bb_start[1], bb_start[2]}, m_bbox_end{bb_end[0], bb_end[1], bb_end[2]}, m_subcount{0}, m_subdim{bb_end[0]-bb_start[0]+1, bb_end[1]-bb_start[1]+1, bb_end[2]-bb_start[2]+1}, m_valid(false), m_grid_spacing{h[0], h[1], h[2]}, m_start{start[0], start[1], start[2]}, m_end{end[0], end[1], end[2]} { assert(m_grid != NULL); typedef typename TGrid::BlockType TBlock; // process span std::vector<BlockInfo> infos_all = grid->getBlocksInfo(); const BlockInfo info_first = infos_all.front(); const BlockInfo info_last = infos_all.back(); const int process_start[3] = { static_cast<int>(info_first.index[0] * TBlock::sizeX), static_cast<int>(info_first.index[1] * TBlock::sizeY), static_cast<int>(info_first.index[2] * TBlock::sizeZ) }; const int process_end[3] = { static_cast<int>((info_last.index[0] + 1) * TBlock::sizeX - 1), static_cast<int>((info_last.index[1] + 1) * TBlock::sizeY - 1), static_cast<int>((info_last.index[2] + 1) * TBlock::sizeZ - 1) }; bool b_intersect[3] = { false, false, false }; for (size_t i = 0; i < 3; ++i) { // case 1: subdomain is fully contained in this process // dimension if (process_start[i] <= m_bbox_start[i] && m_bbox_end[i] <= process_end[i]) { b_intersect[i] = true; continue; } // case 2: subdomain is partially contained in this process // dimension (distributed) if (process_start[i] <= m_bbox_start[i] && m_bbox_start[i] <= process_end[i] && m_bbox_end[i] > process_end[i]) { m_bbox_end[i] = process_end[i]; b_intersect[i] = true; } else if (m_bbox_start[i] < process_start[i] && process_end[i] < m_bbox_end[i]) { m_bbox_start[i] = process_start[i]; m_bbox_end[i] = process_end[i]; b_intersect[i] = true; } else if (m_bbox_start[i] < process_start[i] && process_start[i] <= m_bbox_end[i] && m_bbox_end[i] <= process_end[i]) { m_bbox_start[i] = process_start[i]; b_intersect[i] = true; } } m_valid = true; m_max_size = 1; for (size_t i = 0; i < 3; ++i) { m_subcount[i] = m_bbox_end[i] - m_bbox_start[i] + 1; m_max_size *= static_cast<unsigned long>(m_subcount[i]); m_valid = m_valid && b_intersect[i]; } // see which blocks are needed if (m_valid) { for (size_t i = 0; i < infos_all.size(); ++i) { const BlockInfo info = infos_all[i]; const int block_start[3] = { static_cast<int>(info.index[0] * TBlock::sizeX), static_cast<int>(info.index[1] * TBlock::sizeY), static_cast<int>(info.index[2] * TBlock::sizeZ) }; const int block_end[3] = { static_cast<int>(block_start[0] + TBlock::sizeX - 1), static_cast<int>(block_start[1] + TBlock::sizeY - 1), static_cast<int>(block_start[2] + TBlock::sizeZ - 1) }; const bool b_need_X = ((block_start[0] <= m_bbox_end[0]) && (block_end[0] >= m_bbox_start[0])); const bool b_need_Y = ((block_start[1] <= m_bbox_end[1]) && (block_end[1] >= m_bbox_start[1])); const bool b_need_Z = ((block_start[2] <= m_bbox_end[2]) && (block_end[2] >= m_bbox_start[2])); if (b_need_X && b_need_Y && b_need_Z) m_intersecting_blocks.push_back( info ); } } } Subdomain(const Subdomain& c) = default; inline int id() const { return m_id; } inline const int (&bbox_start() const)[3] { return m_bbox_start; } inline const int (&bbox_end() const)[3] { return m_bbox_end; } inline const int (&count() const)[3] { return m_subcount; } inline const int (&dim() const)[3] { return m_subdim; } inline int dim(const size_t i) const { assert(i<3); return m_subdim[i]; } inline const double (&start() const)[3] { return m_start; } inline double start(const size_t i) const { assert(i<3); return m_start[i]; } inline const double (&end() const)[3] { return m_end; } inline double end(const size_t i) const { assert(i<3); return m_end[i]; } inline const double* grid_spacing(const size_t i) const { assert(i<3); return m_grid_spacing[i]; } inline unsigned long max_size() const { return m_max_size; } inline bool valid() const { return m_valid; } inline const std::vector<BlockInfo>& getBlocksInfo() const { return m_intersecting_blocks; } inline TGrid* getGrid() const { return m_grid; } inline std::string name() const { std::ostringstream out; out << "subdomain" << m_id; return out.str(); } virtual void show(const std::string prefix="") const { std::cout << prefix << "subdomain" << m_id << ":" << std::endl; std::cout << prefix << "ID = " << m_id << std::endl; std::cout << prefix << "START = (" << m_start[0] << ", " << m_start[1] << ", " << m_start[2] << ")" << std::endl; std::cout << prefix << "END = (" << m_end[0] << ", " << m_end[1] << ", " << m_end[2] << ")" << std::endl; std::cout << prefix << "BBOX_START = (" << m_bbox_start[0] << ", " << m_bbox_start[1] << ", " << m_bbox_start[2] << ")" << std::endl; std::cout << prefix << "BBOX_END = (" << m_bbox_end[0] << ", " << m_bbox_end[1] << ", " << m_bbox_end[2] << ")" << std::endl; std::cout << prefix << "DIM = (" << m_subdim[0] << ", " << m_subdim[1] << ", " << m_subdim[2] << ")" << std::endl; std::cout << prefix << "SUBDIM = (" << m_subcount[0] << ", " << m_subcount[1] << ", " << m_subcount[2] << ")" << std::endl; std::cout << prefix << "MAXSIZE = " << m_max_size << std::endl; std::cout << prefix << "VALID = " << m_valid << std::endl; std::cout << prefix << "NUMBER OF BLOCKS = " << m_intersecting_blocks.size() << std::endl; } protected: TGrid * m_grid; const int m_id; int m_bbox_start[3]; // local start indices of bounding box int m_bbox_end[3]; // local end indices of bounding box int m_subcount[3]; // number of elements in local subdomain int m_subdim[3]; // number of elements in global subdomain unsigned long m_max_size; bool m_valid; const double* m_grid_spacing[3]; double m_start[3]; // lower left coordinates of smallest subdomain that contains the specified origin in config file double m_end[3]; // upper right coordinates of smallest subdomain that contains the specified extent in config file std::vector<BlockInfo> m_intersecting_blocks; }; } /////////////////////////////////////////////////////////////////////////////// // Dumpers // // The following requirements for the data TStreamer are required: // TStreamer::NCHANNELS : Number of data elements (1=Scalar, 3=Vector, 9=Tensor) // TStreamer::operate : Data access methods for read and write // TStreamer::getAttributeName : Attribute name of the date ("Scalar", "Vector", "Tensor") template<typename TStreamer, typename hdf5Real, typename TSubdomain> void DumpSubdomainHDF5(const TSubdomain& subdomain, const int stepID, const typename TSubdomain::GridType::Real t, const std::string &fname, const std::string &dpath = ".", const bool bXMF = true) { #ifdef CUBISM_USE_HDF typedef typename TSubdomain::GridType::BlockType B; // fname is the base filepath tail without file type extension and // additional identifiers std::ostringstream filename; std::ostringstream fullpath; filename << fname << "_subdomain" << subdomain.id(); fullpath << dpath << "/" << filename.str(); herr_t status; hid_t file_id, dataset_id, fspace_id, fapl_id, mspace_id; /////////////////////////////////////////////////////////////////////////// // startup file H5open(); fapl_id = H5Pcreate(H5P_FILE_ACCESS); file_id = H5Fcreate((fullpath.str()+".h5").c_str(), H5F_ACC_TRUNC, H5P_DEFAULT, fapl_id); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); /////////////////////////////////////////////////////////////////////////// // write mesh std::vector<int> mesh_dims; std::vector<std::string> dset_name; dset_name.push_back("/vx"); dset_name.push_back("/vy"); dset_name.push_back("/vz"); for (size_t i = 0; i < 3; ++i) { const int nCells = subdomain.dim(i); const double* const h = subdomain.grid_spacing(i); std::vector<double> vertices(nCells+1, subdomain.start(i)); mesh_dims.push_back(vertices.size()); for (int j = 0; j < nCells; ++j) vertices[j+1] = vertices[j] + h[j];; hsize_t dim[1] = {vertices.size()}; fspace_id = H5Screate_simple(1, dim, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, dset_name[i].c_str(), H5T_NATIVE_DOUBLE, fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif status = H5Dwrite(dataset_id, H5T_NATIVE_DOUBLE, H5S_ALL, H5S_ALL, H5P_DEFAULT, vertices.data()); status = H5Sclose(fspace_id); status = H5Dclose(dataset_id); } /////////////////////////////////////////////////////////////////////////// // write data std::vector<BlockInfo> infos_sub = subdomain.getBlocksInfo(); static const unsigned int NCHANNELS = TStreamer::NCHANNELS; const unsigned int NX = subdomain.count()[0]; const unsigned int NY = subdomain.count()[1]; const unsigned int NZ = subdomain.count()[2]; std::cout << "Allocating " << (subdomain.max_size() * NCHANNELS * sizeof(hdf5Real))/(1024.*1024.) << " MB of HDF5 subdomain data" << std::endl; hdf5Real * array_all = NULL; hsize_t count[4] = { NZ, NY, NX, NCHANNELS }; hsize_t dims[4] = { NZ, NY, NX, NCHANNELS }; hsize_t offset[4] = {0, 0, 0, 0}; if (subdomain.valid()) { array_all = new hdf5Real[NX * NY * NZ * NCHANNELS]; const int bbox_start[3] = { subdomain.bbox_start()[0], subdomain.bbox_start()[1], subdomain.bbox_start()[2] }; const int bbox_end[3] = { subdomain.bbox_end()[0], subdomain.bbox_end()[1], subdomain.bbox_end()[2] }; #pragma omp parallel for for(int i=0; i<(int)infos_sub.size(); i++) { BlockInfo& info = infos_sub[i]; const B& b = *(B*)info.ptrBlock; const int idx[3] = { info.index[0], info.index[1], info.index[2] }; for(int iz=0; iz<static_cast<int>(B::sizeZ); iz++) for(int iy=0; iy<static_cast<int>(B::sizeY); iy++) for(int ix=0; ix<static_cast<int>(B::sizeX); ix++) { int gx = idx[0]*B::sizeX + ix; int gy = idx[1]*B::sizeY + iy; int gz = idx[2]*B::sizeZ + iz; const bool b_containedX = (bbox_start[0] <= gx) && (gx <= bbox_end[0]); const bool b_containedY = (bbox_start[1] <= gy) && (gy <= bbox_end[1]); const bool b_containedZ = (bbox_start[2] <= gz) && (gz <= bbox_end[2]); if (!(b_containedX && b_containedY && b_containedZ)) continue; hdf5Real output[NCHANNELS]; for(unsigned int j=0; j<NCHANNELS; ++j) output[j] = 0; TStreamer::operate(b, ix, iy, iz, (hdf5Real*)output); gx -= bbox_start[0]; // shift to process local gy -= bbox_start[1]; // shift to process local gz -= bbox_start[2]; // shift to process local hdf5Real * const ptr = array_all + NCHANNELS*(gx + NX * (gy + NY * gz)); for(unsigned int j=0; j<NCHANNELS; ++j) ptr[j] = output[j]; } } } fapl_id = H5Pcreate(H5P_DATASET_XFER); fspace_id = H5Screate_simple(4, dims, NULL); #ifndef CUBISM_ON_FERMI dataset_id = H5Dcreate(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #else dataset_id = H5Dcreate2(file_id, "data", get_hdf5_type<hdf5Real>(), fspace_id, H5P_DEFAULT, H5P_DEFAULT, H5P_DEFAULT); #endif fspace_id = H5Dget_space(dataset_id); H5Sselect_hyperslab(fspace_id, H5S_SELECT_SET, offset, NULL, count, NULL); mspace_id = H5Screate_simple(4, count, NULL); if (!subdomain.valid()) { H5Sselect_none(fspace_id); H5Sselect_none(mspace_id); } status = H5Dwrite(dataset_id, get_hdf5_type<hdf5Real>(), mspace_id, fspace_id, fapl_id, array_all); if (status < 0) H5Eprint1(stdout); status = H5Sclose(mspace_id); if(status<0) H5Eprint1(stdout); status = H5Sclose(fspace_id); if(status<0) H5Eprint1(stdout); status = H5Dclose(dataset_id); if(status<0) H5Eprint1(stdout); status = H5Pclose(fapl_id); if(status<0) H5Eprint1(stdout); status = H5Fclose(file_id); if(status<0) H5Eprint1(stdout); H5close(); if (subdomain.valid()) delete [] array_all; if (bXMF) { FILE *xmf = 0; xmf = fopen((fullpath.str()+".xmf").c_str(), "w"); fprintf(xmf, "<?xml version=\"1.0\" ?>\n"); fprintf(xmf, "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\" []>\n"); fprintf(xmf, "<Xdmf Version=\"2.0\">\n"); fprintf(xmf, " <Domain>\n"); fprintf(xmf, " <Grid GridType=\"Uniform\">\n"); fprintf(xmf, " <Time Value=\"%e\"/>\n\n", t); fprintf(xmf, " <Topology TopologyType=\"3DRectMesh\" Dimensions=\"%d %d %d\"/>\n\n", mesh_dims[2], mesh_dims[1], mesh_dims[0]); fprintf(xmf, " <Geometry GeometryType=\"VxVyVz\">\n"); fprintf(xmf, " <DataItem Name=\"mesh_vx\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[0]); fprintf(xmf, " %s:/vx\n",(filename.str()+".h5").c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vy\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[1]); fprintf(xmf, " %s:/vy\n",(filename.str()+".h5").c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " <DataItem Name=\"mesh_vz\" Dimensions=\"%d\" NumberType=\"Float\" Precision=\"8\" Format=\"HDF\">\n", mesh_dims[2]); fprintf(xmf, " %s:/vz\n",(filename.str()+".h5").c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Geometry>\n\n"); fprintf(xmf, " <Attribute Name=\"data\" AttributeType=\"%s\" Center=\"Cell\">\n", TStreamer::getAttributeName()); fprintf(xmf, " <DataItem Dimensions=\"%d %d %d %d\" NumberType=\"Float\" Precision=\"%d\" Format=\"HDF\">\n", (int)dims[0], (int)dims[1], (int)dims[2], (int)dims[3], (int)sizeof(hdf5Real)); fprintf(xmf, " %s:/data\n",(filename.str()+".h5").c_str()); fprintf(xmf, " </DataItem>\n"); fprintf(xmf, " </Attribute>\n"); fprintf(xmf, " </Grid>\n"); fprintf(xmf, " </Domain>\n"); fprintf(xmf, "</Xdmf>\n"); fclose(xmf); } #else #warning USE OF HDF WAS DISABLED AT COMPILE TIME #endif } CUBISM_NAMESPACE_END #endif /* HDF5SUBDOMAINDUMPER_H_3C2DKYV4 */
composite.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % John Cristy % % July 1992 % % % % % % Copyright 1999-2013 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 % % % % http://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 "magick/studio.h" #include "magick/artifact.h" #include "magick/cache-view.h" #include "magick/channel.h" #include "magick/client.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/composite.h" #include "magick/composite-private.h" #include "magick/constitute.h" #include "magick/draw.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/memory_.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/property.h" #include "magick/quantum.h" #include "magick/resample.h" #include "magick/resource_.h" #include "magick/string_.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImageChannel() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImageChannel method is: % % MagickBooleanType CompositeImage(Image *image, % const CompositeOperator compose,Image *composite_image, % const ssize_t x_offset,const ssize_t y_offset) % MagickBooleanType CompositeImageChannel(Image *image, % const ChannelType channel,const CompositeOperator compose, % Image *composite_image,const ssize_t x_offset,const ssize_t y_offset) % % A description of each parameter follows: % % o image: the destination image, modified by he composition % % o channel: the channel. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o composite_image: the composite (source) image. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'composite_image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o "compose:outside-overlay" % Modify how the composition is to effect areas not directly covered % by the 'composite_image' at the offset given. Normally this is % dependant on the 'compose' method, especially Duff-Porter methods. % % If set to "false" then disable all normal handling of pixels not % covered by the composite_image. Typically used for repeated tiling % of the composite_image by the calling API. % % Previous to IM v6.5.3-3 this was called "modify-outside-overlay" % */ static inline double MagickMin(const double x,const double y) { if (x < y) return(x); return(y); } static inline double MagickMax(const double x,const double y) { if (x > y) return(x); return(y); } /* ** Programmers notes on SVG specification. ** ** A Composition is defined by... ** Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors ** Blending areas : X = 1 for area of overlap ie: f(Sc,Dc) ** Y = 1 for source preserved ** Z = 1 for destination preserved ** ** Conversion to transparency (then optimized) ** Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) ** Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) ** ** Where... ** Sca = Sc*Sa normalized Source color divided by Source alpha ** Dca = Dc*Da normalized Dest color divided by Dest alpha ** Dc' = Dca'/Da' the desired color value for this channel. ** ** Da' in in the follow formula as 'gamma' The resulting alpla value. ** ** ** Most functions use a blending mode of over (X=1,Y=1,Z=1) ** this results in the following optimizations... ** gamma = Sa+Da-Sa*Da; ** gamma = 1 - QuantiumScale*alpha * QuantiumScale*beta; ** opacity = QuantiumScale*alpha*beta; // over blend, optimized 1-Gamma ** ** The above SVG definitions also definate that Mathematical Composition ** methods should use a 'Over' blending mode for Alpha Channel. ** It however was not applied for composition modes of 'Plus', 'Minus', ** the modulus versions of 'Add' and 'Subtract'. ** ** ** Mathematical operator changes to be applied from IM v6.7... ** ** 1/ Modulus modes 'Add' and 'Subtract' are obsoleted and renamed ** 'ModulusAdd' and 'ModulusSubtract' for clarity. ** ** 2/ All mathematical compositions work as per the SVG specification ** with regard to blending. This now includes 'ModulusAdd' and ** 'ModulusSubtract'. ** ** 3/ When the special channel flag 'sync' (syncronize channel updates) ** is turned off (enabled by default) then mathematical compositions are ** only performed on the channels specified, and are applied ** independantally of each other. In other words the mathematics is ** performed as 'pure' mathematical operations, rather than as image ** operations. */ static inline MagickRealType Atop(const MagickRealType p, const MagickRealType Sa,const MagickRealType q, const MagickRealType magick_unused(Da)) { return(p*Sa+q*(1.0-Sa)); /* Da optimized out, Da/gamma => 1.0 */ } static inline void CompositeAtop(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ composite->opacity=q->opacity; /* optimized Da = 1.0-Gamma */ composite->red=Atop(p->red,Sa,q->red,1.0); composite->green=Atop(p->green,Sa,q->green,1.0); composite->blue=Atop(p->blue,Sa,q->blue,1.0); if (q->colorspace == CMYKColorspace) composite->index=Atop(p->index,Sa,q->index,1.0); } /* What is this Composition method for? Can't find any specification! WARNING this is not doing correct 'over' blend handling (Anthony Thyssen). */ static inline void CompositeBumpmap(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType intensity; intensity=MagickPixelIntensity(p); composite->red=QuantumScale*intensity*q->red; composite->green=QuantumScale*intensity*q->green; composite->blue=QuantumScale*intensity*q->blue; composite->opacity=(MagickRealType) QuantumScale*intensity* p->opacity; if (q->colorspace == CMYKColorspace) composite->index=QuantumScale*intensity*q->index; } static inline void CompositeClear(const MagickPixelPacket *q, MagickPixelPacket *composite) { composite->opacity=(MagickRealType) TransparentOpacity; composite->red=0.0; composite->green=0.0; composite->blue=0.0; if (q->colorspace == CMYKColorspace) composite->index=0.0; } static MagickRealType ColorBurn(const MagickRealType Sca, const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da) { #if 0 /* Oct 2004 SVG specification. */ if (Sca*Da + Dca*Sa <= Sa*Da) return(Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Sa*(Sca*Da+Dca*Sa-Sa*Da)/Sca + Sca*(1.0-Da) + Dca*(1.0-Sa)); #else /* March 2009 SVG specification. */ if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca-Da) < MagickEpsilon)) return(Sa*Da+Dca*(1.0-Sa)); if (Sca < MagickEpsilon) return(Dca*(1.0-Sa)); return(Sa*Da-Sa*MagickMin(Da,(Da-Dca)*Sa/Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); #endif } static inline void CompositeColorBurn(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*ColorBurn(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*ColorBurn(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*ColorBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*ColorBurn(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static MagickRealType ColorDodge(const MagickRealType Sca, const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da) { #if 0 /* Oct 2004 SVG specification. */ if ((Sca*Da+Dca*Sa) >= Sa*Da) return( Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) ); return( Dca*Sa*Sa/(Sa-Sca) + Sca*(1.0-Da) + Dca*(1.0-Sa) ); #endif #if 0 /* New specification, March 2009 SVG specification. This specification was also wrong of non-overlap cases. */ if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon)) return(Sca*(1.0-Da)); if (fabs(Sca-Sa) < MagickEpsilon) return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Sa*MagickMin(Da,Dca*Sa/(Sa-Sca))); #endif /* Working from first principles using the original formula: f(Sc,Dc) = Dc/(1-Sc) This works correctly! Looks like the 2004 model was right but just required a extra condition for correct handling. */ if ((fabs(Sca-Sa) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon)) return(Sca*(1.0-Da)+Dca*(1.0-Sa)); if (fabs(Sca-Sa) < MagickEpsilon) return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Dca*Sa*Sa/(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeColorDodge(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*ColorDodge(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*ColorDodge(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*ColorDodge(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*ColorDodge(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static inline MagickRealType Darken(const MagickRealType p, const MagickRealType alpha,const MagickRealType q,const MagickRealType beta) { if (p < q) return(MagickOver_(p,alpha,q,beta)); /* src-over */ return(MagickOver_(q,beta,p,alpha)); /* dst-over */ } static inline void CompositeDarken(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ double gamma; if ( (channel & SyncChannels) != 0 ) { composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */ gamma=1.0-QuantumScale*composite->opacity; gamma=PerceptibleReciprocal(gamma); composite->red=gamma*Darken(p->red,p->opacity,q->red,q->opacity); composite->green=gamma*Darken(p->green,p->opacity,q->green,q->opacity); composite->blue=gamma*Darken(p->blue,p->opacity,q->blue,q->opacity); if (q->colorspace == CMYKColorspace) composite->index=gamma*Darken(p->index,p->opacity,q->index,q->opacity); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=MagickMax(p->opacity,q->opacity); if ( (channel & RedChannel) != 0 ) composite->red=MagickMin(p->red,q->red); if ( (channel & GreenChannel) != 0 ) composite->green=MagickMin(p->green,q->green); if ( (channel & BlueChannel) != 0 ) composite->blue=MagickMin(p->blue,q->blue); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=MagickMin(p->index,q->index); } } static inline void CompositeDarkenIntensity(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { /* Select the pixel based on the intensity level. If 'Sync' flag select whole pixel based on alpha weighted intensity. Otherwise use intensity only, but restrict copy according to channel. */ if ( (channel & SyncChannels) != 0 ) { MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; Da=1.0-QuantumScale*q->opacity; *composite = (Sa*MagickPixelIntensity(p) < Da*MagickPixelIntensity(q)) ? *p : *q; } else { int from_p = (MagickPixelIntensity(p) < MagickPixelIntensity(q)); if ( (channel & AlphaChannel) != 0 ) composite->opacity = from_p ? p->opacity : q->opacity; if ( (channel & RedChannel) != 0 ) composite->red = from_p ? p->red : q->red; if ( (channel & GreenChannel) != 0 ) composite->green = from_p ? p->green : q->green; if ( (channel & BlueChannel) != 0 ) composite->blue = from_p ? p->blue : q->blue; if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index = from_p ? p->index : q->index; } } static inline MagickRealType Difference(const MagickRealType p, const MagickRealType Sa,const MagickRealType q,const MagickRealType Da) { /* Optimized by Multipling by QuantumRange (taken from gamma). */ return(Sa*p+Da*q-Sa*Da*2.0*MagickMin(p,q)); } static inline void CompositeDifference(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); /* Values are not normalized as an optimization. */ composite->red=gamma*Difference(p->red,Sa,q->red,Da); composite->green=gamma*Difference(p->green,Sa,q->green,Da); composite->blue=gamma*Difference(p->blue,Sa,q->blue,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Difference(p->index,Sa,q->index,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange-fabs(p->opacity - q->opacity); if ( (channel & RedChannel) != 0 ) composite->red=fabs(p->red - q->red); if ( (channel & GreenChannel) != 0 ) composite->green=fabs(p->green - q->green); if ( (channel & BlueChannel) != 0 ) composite->blue=fabs(p->blue - q->blue); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=fabs(p->index - q->index); } } static MagickRealType Divide(const MagickRealType Sca,const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da) { /* Divide Source by Destination f(Sc,Dc) = Sc / Dc But with appropriate handling for special case of Dc == 0 specifically so that f(Black,Black)=Black and f(non-Black,Black)=White. It is however also important to correctly do 'over' alpha blending which is why the formula becomes so complex. */ if ((fabs(Sca) < MagickEpsilon) && (fabs(Dca) < MagickEpsilon)) return(Sca*(1.0-Da)+Dca*(1.0-Sa)); if (fabs(Dca) < MagickEpsilon) return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeDivide(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*Divide(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*Divide(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*Divide(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Divide(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-Divide(Sa,1.0,Da,1.0)); if ( (channel & RedChannel) != 0 ) composite->red=QuantumRange* Divide(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0); if ( (channel & GreenChannel) != 0 ) composite->green=QuantumRange* Divide(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0); if ( (channel & BlueChannel) != 0 ) composite->blue=QuantumRange* Divide(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=QuantumRange* Divide(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0); } } static MagickRealType Exclusion(const MagickRealType Sca, const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da) { return(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeExclusion(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { MagickRealType gamma, Sa, Da; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*Exclusion(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*Exclusion(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*Exclusion(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Exclusion(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-Exclusion(Sa,1.0,Da,1.0)); if ( (channel & RedChannel) != 0 ) composite->red=QuantumRange* Exclusion(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0); if ( (channel & GreenChannel) != 0 ) composite->green=QuantumRange* Exclusion(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0); if ( (channel & BlueChannel) != 0 ) composite->blue=QuantumRange* Exclusion(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=QuantumRange* Exclusion(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0); } } static MagickRealType HardLight(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { if ((2.0*Sca) < Sa) return(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeHardLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*HardLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*HardLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*HardLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*HardLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static inline MagickRealType ConvertHueToRGB(MagickRealType m1, MagickRealType m2,MagickRealType hue) { if (hue < 0.0) hue+=1.0; if (hue > 1.0) hue-=1.0; if ((6.0*hue) < 1.0) return(m1+6.0*(m2-m1)*hue); if ((2.0*hue) < 1.0) return(m2); if ((3.0*hue) < 2.0) return(m1+6.0*(m2-m1)*(2.0/3.0-hue)); return(m1); } static void HCLComposite(const double hue,const double chroma,const double luma, MagickRealType *red,MagickRealType *green,MagickRealType *blue) { double b, c, g, h, m, r, x, z; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); z=1.0; if (m < 0.0) { z=luma/(luma-m); m=0.0; } else if (m+c > 1.0) { z=(1.0-luma)/(m+c-luma); m=1.0-z*c; } *red=QuantumRange*(z*r+m); *green=QuantumRange*(z*g+m); *blue=QuantumRange*(z*b+m); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,double *hue,double *chroma,double *luma) { double b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (double *) NULL); assert(chroma != (double *) NULL); assert(luma != (double *) NULL); r=(double) red; g=(double) green; b=(double) blue; max=MagickMax(r,MagickMax(g,b)); c=max-(double) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == (MagickRealType) max) h=fmod((g-b)/c+6.0,6.0); else if (green == (MagickRealType) max) h=((b-r)/c)+2.0; else if (blue == (MagickRealType) max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static inline MagickRealType In(const MagickRealType p,const MagickRealType Sa, const MagickRealType magick_unused(q),const MagickRealType Da) { return(Sa*p*Da); } static inline void CompositeIn(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { double gamma; MagickRealType Sa, Da; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=Sa*Da; composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=gamma*In(p->red,Sa,q->red,Da); composite->green=gamma*In(p->green,Sa,q->green,Da); composite->blue=gamma*In(p->blue,Sa,q->blue,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*In(p->index,Sa,q->index,Da); } static inline MagickRealType Lighten(const MagickRealType p, const MagickRealType alpha,const MagickRealType q,const MagickRealType beta) { if (p > q) return(MagickOver_(p,alpha,q,beta)); /* src-over */ return(MagickOver_(q,beta,p,alpha)); /* dst-over */ } static inline void CompositeLighten(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { /* Lighten is also equvalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ double gamma; if ( (channel & SyncChannels) != 0 ) { composite->opacity=QuantumScale*p->opacity*q->opacity; /* Over Blend */ gamma=1.0-QuantumScale*composite->opacity; gamma=PerceptibleReciprocal(gamma); composite->red=gamma*Lighten(p->red,p->opacity,q->red,q->opacity); composite->green=gamma*Lighten(p->green,p->opacity,q->green,q->opacity); composite->blue=gamma*Lighten(p->blue,p->opacity,q->blue,q->opacity); if (q->colorspace == CMYKColorspace) composite->index=gamma*Lighten(p->index,p->opacity,q->index,q->opacity); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=MagickMin(p->opacity,q->opacity); if ( (channel & RedChannel) != 0 ) composite->red=MagickMax(p->red,q->red); if ( (channel & GreenChannel) != 0 ) composite->green=MagickMax(p->green,q->green); if ( (channel & BlueChannel) != 0 ) composite->blue=MagickMax(p->blue,q->blue); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=MagickMax(p->index,q->index); } } static inline void CompositeLightenIntensity(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { /* Select the pixel based on the intensity level. If 'Sync' flag select whole pixel based on alpha weighted intensity. Otherwise use Intenisty only, but restrict copy according to channel. */ if ( (channel & SyncChannels) != 0 ) { MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; Da=1.0-QuantumScale*q->opacity; *composite = (Sa*MagickPixelIntensity(p) > Da*MagickPixelIntensity(q)) ? *p : *q; } else { int from_p = (MagickPixelIntensity(p) > MagickPixelIntensity(q)); if ( (channel & AlphaChannel) != 0 ) composite->opacity = from_p ? p->opacity : q->opacity; if ( (channel & RedChannel) != 0 ) composite->red = from_p ? p->red : q->red; if ( (channel & GreenChannel) != 0 ) composite->green = from_p ? p->green : q->green; if ( (channel & BlueChannel) != 0 ) composite->blue = from_p ? p->blue : q->blue; if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index = from_p ? p->index : q->index; } } #if 0 static inline MagickRealType LinearDodge(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { /* LinearDodge: simplifies to a trivial formula f(Sc,Dc) = Sc + Dc Dca' = Sca + Dca */ return(Sca+Dca); } #endif static inline void CompositeLinearDodge(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=gamma*(p->red*Sa+q->red*Da); composite->green=gamma*(p->green*Sa+q->green*Da); composite->blue=gamma*(p->blue*Sa+q->blue*Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*(p->index*Sa+q->index*Da); } static inline MagickRealType LinearBurn(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ return(Sca+Dca-Sa*Da); } static inline void CompositeLinearBurn(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*LinearBurn(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*LinearBurn(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*LinearBurn(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*LinearBurn(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static inline MagickRealType LinearLight(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { #if 0 /* Previous formula, was only valid for fully-opaque images. */ return(Dca+2*Sca-1.0); #else /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ return((Sca-Sa)*Da+Sca+Dca); #endif } static inline void CompositeLinearLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*LinearLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*LinearLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*LinearLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*LinearLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static inline MagickRealType Mathematics(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da, const GeometryInfo *geometry_info) { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ return(geometry_info->rho*Sca*Dca+geometry_info->sigma*Sca*Da+ geometry_info->xi*Dca*Sa+geometry_info->psi*Sa*Da+Sca*(1.0-Da)+ Dca*(1.0-Sa)); } static inline void CompositeMathematics(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, const GeometryInfo *args, MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* ??? - AT */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*Mathematics(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da,args); composite->green=gamma*Mathematics(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da,args); composite->blue=gamma*Mathematics(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da,args); if (q->colorspace == CMYKColorspace) composite->index=gamma*Mathematics(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da,args); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-Mathematics(Sa,1.0,Da,1.0,args)); if ( (channel & RedChannel) != 0 ) composite->red=QuantumRange* Mathematics(QuantumScale*p->red,1.0,QuantumScale*q->red,1.0,args); if ( (channel & GreenChannel) != 0 ) composite->green=QuantumRange* Mathematics(QuantumScale*p->green,1.0,QuantumScale*q->green,1.0,args); if ( (channel & BlueChannel) != 0 ) composite->blue=QuantumRange* Mathematics(QuantumScale*p->blue,1.0,QuantumScale*q->blue,1.0,args); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=QuantumRange* Mathematics(QuantumScale*p->index,1.0,QuantumScale*q->index,1.0,args); } } static inline void CompositePlus(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { if ( (channel & SyncChannels) != 0 ) { /* NOTE: "Plus" does not use 'over' alpha-blending but uses a special 'plus' form of alph-blending. It is the ONLY mathematical operator to do this. this is what makes it different to the otherwise equivalent "LinearDodge" composition method. Note however that color channels are still effected by the alpha channel as a result of the blending, making it just as useless for independant channel maths, just like all other mathematical composition methods. As such the removal of the 'sync' flag, is still a usful convention. The MagickPixelCompositePlus() function is defined in "composite-private.h" so it can also be used for Image Blending. */ MagickPixelCompositePlus(p,p->opacity,q,q->opacity,composite); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=p->opacity+q->opacity-QuantumRange; if ( (channel & RedChannel) != 0 ) composite->red=p->red+q->red; if ( (channel & GreenChannel) != 0 ) composite->green=p->green+q->green; if ( (channel & BlueChannel) != 0 ) composite->blue=p->blue+q->blue; if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=p->index+q->index; } } static inline MagickRealType Minus(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca, const MagickRealType magick_unused(Da)) { /* Minus Source from Destination f(Sc,Dc) = Sc - Dc */ return(Sca + Dca - 2*Dca*Sa); } static inline void CompositeMinus(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=gamma*Minus(p->red*Sa,Sa,q->red*Da,Da); composite->green=gamma*Minus(p->green*Sa,Sa,q->green*Da,Da); composite->blue=gamma*Minus(p->blue*Sa,Sa,q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Minus(p->index*Sa,Sa,q->index*Da,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-(Sa-Da)); if ( (channel & RedChannel) != 0 ) composite->red=p->red-q->red; if ( (channel & GreenChannel) != 0 ) composite->green=p->green-q->green; if ( (channel & BlueChannel) != 0 ) composite->blue=p->blue-q->blue; if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=p->index-q->index; } } static inline MagickRealType ModulusAdd(const MagickRealType p, const MagickRealType Sa, const MagickRealType q, const MagickRealType Da) { MagickRealType pixel; pixel=p+q; if (pixel > QuantumRange) pixel-=(QuantumRange+1.0); return(pixel*Sa*Da + p*Sa*(1-Da) + q*Da*(1-Sa)); } static inline void CompositeModulusAdd(const MagickPixelPacket *p, const MagickPixelPacket *q, const ChannelType channel, MagickPixelPacket *composite) { if ( (channel & SyncChannels) != 0 ) { double gamma; MagickRealType Sa, Da; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=ModulusAdd(p->red,Sa,q->red,Da); composite->green=ModulusAdd(p->green,Sa,q->green,Da); composite->blue=ModulusAdd(p->blue,Sa,q->blue,Da); if (q->colorspace == CMYKColorspace) composite->index=ModulusAdd(p->index,Sa,q->index,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange-ModulusAdd(QuantumRange-p->opacity, 1.0,QuantumRange-q->opacity,1.0); if ( (channel & RedChannel) != 0 ) composite->red=ModulusAdd(p->red,1.0,q->red,1.0); if ( (channel & GreenChannel) != 0 ) composite->green=ModulusAdd(p->green,1.0,q->green,1.0); if ( (channel & BlueChannel) != 0 ) composite->blue=ModulusAdd(p->blue,1.0,q->blue,1.0); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=ModulusAdd(p->index,1.0,q->index,1.0); } } static inline MagickRealType ModulusSubtract(const MagickRealType p, const MagickRealType Sa, const MagickRealType q, const MagickRealType Da) { MagickRealType pixel; pixel=p-q; if (pixel < 0.0) pixel+=(QuantumRange+1.0); return(pixel*Sa*Da + p*Sa*(1-Da) + q*Da*(1-Sa)); } static inline void CompositeModulusSubtract(const MagickPixelPacket *p, const MagickPixelPacket *q, const ChannelType channel, MagickPixelPacket *composite) { if ( (channel & SyncChannels) != 0 ) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma = RoundToUnity(Sa+Da-Sa*Da); composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=ModulusSubtract(p->red,Sa,q->red,Da); composite->green=ModulusSubtract(p->green,Sa,q->green,Da); composite->blue=ModulusSubtract(p->blue,Sa,q->blue,Da); if (q->colorspace == CMYKColorspace) composite->index=ModulusSubtract(p->index,Sa,q->index,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange-ModulusSubtract(QuantumRange-p->opacity, 1.0,QuantumRange-q->opacity,1.0); if ( (channel & RedChannel) != 0 ) composite->red=ModulusSubtract(p->red,1.0,q->red,1.0); if ( (channel & GreenChannel) != 0 ) composite->green=ModulusSubtract(p->green,1.0,q->green,1.0); if ( (channel & BlueChannel) != 0 ) composite->blue=ModulusSubtract(p->blue,1.0,q->blue,1.0); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=ModulusSubtract(p->index,1.0,q->index,1.0); } } static inline MagickRealType Multiply(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { return(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeMultiply(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*Multiply(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*Multiply(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*Multiply(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Multiply(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-Sa*Da); if ( (channel & RedChannel) != 0 ) composite->red=QuantumScale*p->red*q->red; if ( (channel & GreenChannel) != 0 ) composite->green=QuantumScale*p->green*q->green; if ( (channel & BlueChannel) != 0 ) composite->blue=QuantumScale*p->blue*q->blue; if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=QuantumScale*p->index*q->index; } } static inline MagickRealType Out(const MagickRealType p, const MagickRealType Sa,const MagickRealType magick_unused(q), const MagickRealType Da) { return(Sa*p*(1.0-Da)); } static inline void CompositeOut(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=Sa*(1.0-Da); composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=gamma*Out(p->red,Sa,q->red,Da); composite->green=gamma*Out(p->green,Sa,q->green,Da); composite->blue=gamma*Out(p->blue,Sa,q->blue,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Out(p->index,Sa,q->index,Da); } static MagickRealType PegtopLight(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc See http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs(Da) < MagickEpsilon) return(Sca); return(Dca*Dca*(Sa-2*Sca)/Da+Sca*(2*Dca+1-Da)+Dca*(1-Sa)); } static inline void CompositePegtopLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*PegtopLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*PegtopLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*PegtopLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*PegtopLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static MagickRealType PinLight(const MagickRealType Sca, const MagickRealType Sa,const MagickRealType Dca,const MagickRealType Da) { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if (Dca*Sa < Da*(2*Sca-Sa)) return(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); if ((Dca*Sa) > (2*Sca*Da)) return(Sca*Da+Sca+Dca*(1.0-Sa)); return(Sca*(1.0-Da)+Dca); } static inline void CompositePinLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*PinLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*PinLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*PinLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*PinLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static inline MagickRealType Screen(const MagickRealType Sca, const MagickRealType Dca) { /* Screen: A negated multiply f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ return(Sca+Dca-Sca*Dca); } static inline void CompositeScreen(const MagickPixelPacket *p, const MagickPixelPacket *q,const ChannelType channel, MagickPixelPacket *composite) { double gamma; MagickRealType Da, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; if ( (channel & SyncChannels) != 0 ) { gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); Sa*=(MagickRealType) QuantumScale; Da*=(MagickRealType) QuantumScale; /* optimization */ gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*Screen(p->red*Sa,q->red*Da); composite->green=gamma*Screen(p->green*Sa,q->green*Da); composite->blue=gamma*Screen(p->blue*Sa,q->blue*Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Screen(p->index*Sa,q->index*Da); } else { /* handle channels as separate grayscale channels */ if ( (channel & AlphaChannel) != 0 ) composite->opacity=QuantumRange*(1.0-Screen(Sa,Da)); if ( (channel & RedChannel) != 0 ) composite->red=QuantumRange*Screen(QuantumScale*p->red, QuantumScale*q->red); if ( (channel & GreenChannel) != 0 ) composite->green=QuantumRange*Screen(QuantumScale*p->green, QuantumScale*q->green); if ( (channel & BlueChannel) != 0 ) composite->blue=QuantumRange*Screen(QuantumScale*p->blue, QuantumScale*q->blue); if ( (channel & IndexChannel) != 0 && q->colorspace == CMYKColorspace) composite->index=QuantumRange*Screen(QuantumScale*p->index, QuantumScale*q->index); } } static MagickRealType SoftLight(const MagickRealType Sca, const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da) { #if 0 /* Oct 2004 SVG specification -- was found to be incorrect See http://lists.w3.org/Archives/Public/www-svg/2009Feb/0014.html. */ if (2.0*Sca < Sa) return(Dca*(Sa-(1.0-Dca/Da)*(2.0*Sca-Sa))+Sca*(1.0-Da)+Dca*(1.0-Sa)); if (8.0*Dca <= Da) return(Dca*(Sa-(1.0-Dca/Da)*(2.0*Sca-Sa)*(3.0-8.0*Dca/Da))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); return((Dca*Sa+(pow(Dca/Da,0.5)*Da-Dca)*(2.0*Sca-Sa))+Sca*(1.0-Da)+ Dca*(1.0-Sa)); #else MagickRealType alpha, beta; /* New specification: March 2009 SVG specification. */ alpha=Dca/Da; if ((2.0*Sca) < Sa) return(Dca*(Sa+(2.0*Sca-Sa)*(1.0-alpha))+Sca*(1.0-Da)+Dca*(1.0-Sa)); if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { beta=Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*alpha*(4.0*alpha+1.0)*(alpha-1.0)+7.0* alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa); return(beta); } beta=Dca*Sa+Da*(2.0*Sca-Sa)*(pow(alpha,0.5)-alpha)+Sca*(1.0-Da)+Dca*(1.0-Sa); return(beta); #endif } static inline void CompositeSoftLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*SoftLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*SoftLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*SoftLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*SoftLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } /* Depreciated Multiply difference by amount, if differance larger than threshold??? What use this is is completely unknown The Opacity calculation appears to be inverted -- Anthony Thyssen */ static inline MagickRealType Threshold(const MagickRealType p, const MagickRealType q,const MagickRealType threshold, const MagickRealType amount) { MagickRealType delta; delta=p-q; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) return(q); return(q+delta*amount); } static inline void CompositeThreshold(const MagickPixelPacket *p, const MagickPixelPacket *q,const MagickRealType threshold, const MagickRealType amount,MagickPixelPacket *composite) { composite->red=Threshold(p->red,q->red,threshold,amount); composite->green=Threshold(p->green,q->green,threshold,amount); composite->blue=Threshold(p->blue,q->blue,threshold,amount); composite->opacity=QuantumRange-Threshold(p->opacity,q->opacity, threshold,amount); if (q->colorspace == CMYKColorspace) composite->index=Threshold(p->index,q->index,threshold,amount); } static MagickRealType VividLight(const MagickRealType Sca, const MagickRealType Sa, const MagickRealType Dca, const MagickRealType Da) { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs(Sa) < MagickEpsilon) || (fabs(Sca-Sa) < MagickEpsilon)) return(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); if ((2*Sca) <= Sa) return(Sa*(Da+Sa*(Dca-Da)/(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); return(Dca*Sa*Sa/(2.0*(Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); } static inline void CompositeVividLight(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=RoundToUnity(Sa+Da-Sa*Da); /* over blend, as per SVG doc */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=QuantumRange/(fabs(gamma) < MagickEpsilon ? MagickEpsilon : gamma); composite->red=gamma*VividLight(QuantumScale*p->red*Sa,Sa,QuantumScale* q->red*Da,Da); composite->green=gamma*VividLight(QuantumScale*p->green*Sa,Sa,QuantumScale* q->green*Da,Da); composite->blue=gamma*VividLight(QuantumScale*p->blue*Sa,Sa,QuantumScale* q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*VividLight(QuantumScale*p->index*Sa,Sa,QuantumScale* q->index*Da,Da); } static MagickRealType Xor(const MagickRealType Sca,const MagickRealType Sa, const MagickRealType Dca,const MagickRealType Da) { return(Sca*(1-Da)+Dca*(1-Sa)); } static inline void CompositeXor(const MagickPixelPacket *p, const MagickPixelPacket *q,MagickPixelPacket *composite) { MagickRealType Da, gamma, Sa; Sa=1.0-QuantumScale*p->opacity; /* simplify and speed up equations */ Da=1.0-QuantumScale*q->opacity; gamma=Sa+Da-2*Sa*Da; /* Xor blend mode X=0,Y=1,Z=1 */ composite->opacity=(MagickRealType) QuantumRange*(1.0-gamma); gamma=PerceptibleReciprocal(gamma); composite->red=gamma*Xor(p->red*Sa,Sa,q->red*Da,Da); composite->green=gamma*Xor(p->green*Sa,Sa,q->green*Da,Da); composite->blue=gamma*Xor(p->blue*Sa,Sa,q->blue*Da,Da); if (q->colorspace == CMYKColorspace) composite->index=gamma*Xor(p->index*Sa,Sa,q->index*Da,Da); } MagickExport MagickBooleanType CompositeImage(Image *image, const CompositeOperator compose,const Image *composite_image, const ssize_t x_offset,const ssize_t y_offset) { MagickBooleanType status; status=CompositeImageChannel(image,DefaultChannels,compose,composite_image, x_offset,y_offset); return(status); } MagickExport MagickBooleanType CompositeImageChannel(Image *image, const ChannelType channel,const CompositeOperator compose, const Image *composite,const ssize_t x_offset,const ssize_t y_offset) { #define CompositeImageTag "Composite/Image" CacheView *composite_view, *image_view; const char *value; ExceptionInfo *exception; GeometryInfo geometry_info; Image *composite_image, *destination_image; MagickBooleanType clip_to_self, status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType amount, destination_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; /* Prepare composite image. */ assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickSignature); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); exception=(&image->exception); composite_image=CloneImage(composite,0,0,MagickTrue,exception); if (composite_image == (const Image *) NULL) return(MagickFalse); if (IsGrayColorspace(image->colorspace) != MagickFalse) (void) SetImageColorspace(image,sRGBColorspace); (void) SetImageColorspace(composite_image,image->colorspace); GetMagickPixelPacket(image,&zero); destination_image=(Image *) NULL; amount=0.5; destination_dissolve=1.0; clip_to_self=MagickTrue; percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case ClearCompositeOp: case SrcCompositeOp: case InCompositeOp: case SrcInCompositeOp: case OutCompositeOp: case SrcOutCompositeOp: case DstInCompositeOp: case DstAtopCompositeOp: { /* Modify destination outside the overlaid region. */ clip_to_self=MagickFalse; break; } case OverCompositeOp: { if (image->matte != MagickFalse) break; if (composite_image->matte != MagickFalse) break; } case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) composite_image->columns) >= (ssize_t) image->columns) break; if ((y_offset+(ssize_t) composite_image->rows) >= (ssize_t) image->rows) break; status=MagickTrue; composite_view=AcquireVirtualCacheView(composite_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(composite_image,image,composite_image->rows,1) #endif for (y=0; y < (ssize_t) composite_image->rows; y++) { MagickBooleanType sync; register const IndexPacket *composite_indexes; register const PixelPacket *p; register IndexPacket *indexes; register PixelPacket *q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns, 1,exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, composite_image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } composite_indexes=GetCacheViewVirtualIndexQueue(composite_view); indexes=GetCacheViewAuthenticIndexQueue(image_view); (void) CopyMagickMemory(q,p,composite_image->columns*sizeof(*p)); if ((indexes != (IndexPacket *) NULL) && (composite_indexes != (const IndexPacket *) NULL)) (void) CopyMagickMemory(indexes,composite_indexes, composite_image->columns*sizeof(*indexes)); sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImage) #endif proceed=SetImageProgress(image,CompositeImageTag, (MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } composite_view=DestroyCacheView(composite_view); image_view=DestroyCacheView(image_view); composite_image=DestroyImage(composite_image); return(status); } case CopyOpacityCompositeOp: case ChangeMaskCompositeOp: { /* Modify destination outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->matte == MagickFalse) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel); clip_to_self=MagickFalse; break; } case BlurCompositeOp: { CacheView *composite_view, *destination_view; MagickPixelPacket pixel; MagickRealType angle_range, angle_start, height, width; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling. Blur Image dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ destination_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (destination_image == (Image *) NULL) { composite_image=DestroyImage(composite_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(), OptionWarning,"InvalidGeometry","'%s' '%s'", "compose:args",value); composite_image=DestroyImage(composite_image); destination_image=DestroyImage(destination_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=height=geometry_info.rho*2.0; if ((flags & HeightValue) != 0 ) height=geometry_info.sigma*2.0; /* default the unrotated ellipse width and height axis vectors */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; /* rotate vectors if a rotation angle is given */ if ((flags & XValue) != 0 ) { MagickRealType angle; angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } /* Otherwise lets set a angle range and calculate in the loop */ angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, then restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter,1.0); /* do the variable blurring of each pixel in image */ pixel=zero; composite_view=AcquireVirtualCacheView(composite_image,exception); destination_view=AcquireAuthenticCacheView(destination_image,exception); for (y=0; y < (ssize_t) composite_image->rows; y++) { MagickBooleanType sync; register const PixelPacket *restrict p; register PixelPacket *restrict r; register IndexPacket *restrict destination_indexes; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns, 1,exception); r=QueueCacheViewAuthenticPixels(destination_view,0,y, destination_image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL)) break; destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p++; continue; } if (fabs(angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } #if 0 if ( x == 10 && y == 60 ) { fprintf(stderr, "blur.x=%lf,%lf, blur.y=%lf,%lf\n", blur.x1, blur.x2, blur.y1, blur.y2); fprintf(stderr, "scaled by=%lf,%lf\n", QuantumScale*GetPixelRed(p), QuantumScale*GetPixelGreen(p)); } #endif ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(p), blur.y1*QuantumScale*GetPixelGreen(p), blur.x2*QuantumScale*GetPixelRed(p), blur.y2*QuantumScale*GetPixelGreen(p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel); SetPixelPacket(destination_image,&pixel,r,destination_indexes+x); p++; r++; } sync=SyncCacheViewAuthenticPixels(destination_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); composite_view=DestroyCacheView(composite_view); destination_view=DestroyCacheView(destination_view); composite_image=DestroyImage(composite_image); composite_image=destination_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *composite_view, *destination_view, *image_view; MagickPixelPacket pixel; MagickRealType horizontal_scale, vertical_scale; PointInfo center, offset; register IndexPacket *restrict destination_indexes; register PixelPacket *restrict r; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ destination_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (destination_image == (Image *) NULL) { composite_image=DestroyImage(composite_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue|HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (composite_image->columns-1.0)/ 2.0; vertical_scale=(MagickRealType) (composite_image->rows-1.0)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1.0)/2.0; vertical_scale=(MagickRealType) (image->rows-1.0)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(composite_image->columns-1.0)/200.0; vertical_scale*=(composite_image->rows-1.0)/200.0; } else { horizontal_scale*=(image->columns-1.0)/200.0; vertical_scale*=(image->rows-1.0)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) == 0) center.x=(MagickRealType) (x_offset+(composite_image->columns-1)/ 2.0); else center.x=((MagickRealType) image->columns-1)/2.0; else if ((flags & AspectValue) == 0) center.x=(MagickRealType) (x_offset+geometry_info.xi); else center.x=geometry_info.xi; if ((flags & YValue) == 0) if ((flags & AspectValue) == 0) center.y=(MagickRealType) (y_offset+(composite_image->rows-1)/2.0); else center.y=((MagickRealType) image->rows-1)/2.0; else if ((flags & AspectValue) == 0) center.y=(MagickRealType) (y_offset+geometry_info.psi); else center.y=geometry_info.psi; } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ pixel=zero; image_view=AcquireVirtualCacheView(image,exception); composite_view=AcquireVirtualCacheView(composite_image,exception); destination_view=AcquireAuthenticCacheView(destination_image,exception); for (y=0; y < (ssize_t) composite_image->rows; y++) { MagickBooleanType sync; register const PixelPacket *restrict p; register ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(composite_view,0,y,composite_image->columns, 1,exception); r=QueueCacheViewAuthenticPixels(destination_view,0,y, destination_image->columns,1,exception); if ((p == (const PixelPacket *) NULL) || (r == (PixelPacket *) NULL)) break; destination_indexes=GetCacheViewAuthenticIndexQueue(destination_view); for (x=0; x < (ssize_t) composite_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p++; continue; } /* Displace the offset. */ offset.x=(double) ((horizontal_scale*(GetPixelRed(p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0)); offset.y=(double) ((vertical_scale*(GetPixelGreen(p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0)); (void) InterpolateMagickPixelPacket(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.opacity=(MagickRealType) QuantumRange*(1.0-(1.0-QuantumScale* pixel.opacity)*(1.0-QuantumScale*GetPixelOpacity(p))); SetPixelPacket(destination_image,&pixel,r,destination_indexes+x); p++; r++; } sync=SyncCacheViewAuthenticPixels(destination_view,exception); if (sync == MagickFalse) break; } destination_view=DestroyCacheView(destination_view); composite_view=DestroyCacheView(composite_view); image_view=DestroyCacheView(image_view); composite_image=DestroyImage(composite_image); composite_image=destination_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; destination_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { destination_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) destination_dissolve=geometry_info.sigma/100.0; if ((destination_dissolve-MagickEpsilon) < 0.0) destination_dissolve=0.0; clip_to_self=MagickFalse; if ((destination_dissolve+MagickEpsilon) > 1.0 ) { destination_dissolve=1.0; clip_to_self=MagickTrue; } } break; } case BlendCompositeOp: { value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; destination_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) destination_dissolve=geometry_info.sigma/100.0; clip_to_self=MagickFalse; if ((destination_dissolve+MagickEpsilon) > 1.0) clip_to_self=MagickTrue; } break; } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) (void) ParseGeometry(value,&geometry_info); break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. This Composition method is depreciated */ value=GetImageArtifact(composite_image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } value=GetImageArtifact(composite_image,"compose:outside-overlay"); if (value != (const char *) NULL) clip_to_self=IsMagickTrue(value) == MagickFalse ? MagickTrue : MagickFalse; /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; GetMagickPixelPacket(composite_image,&zero); composite_view=AcquireVirtualCacheView(composite_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(composite_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const PixelPacket *pixels; double luma, hue, chroma, sans; MagickPixelPacket composite, destination, source; register const IndexPacket *restrict composite_indexes; register const PixelPacket *restrict p; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) composite_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(PixelPacket *) NULL; p=(PixelPacket *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) composite_image->rows)) { p=GetCacheViewVirtualPixels(composite_view,0,y-y_offset, composite_image->columns,1,exception); if (p == (const PixelPacket *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset; } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); composite_indexes=GetCacheViewVirtualIndexQueue(composite_view); GetMagickPixelPacket(composite_image,&source); GetMagickPixelPacket(image,&destination); hue=0.0; chroma=0.0; luma=0.0; for (x=0; x < (ssize_t) image->columns; x++) { if (clip_to_self != MagickFalse) { if (x < x_offset) { q++; continue; } if ((x-x_offset) >= (ssize_t) composite_image->columns) break; } destination.red=(MagickRealType) GetPixelRed(q); destination.green=(MagickRealType) GetPixelGreen(q); destination.blue=(MagickRealType) GetPixelBlue(q); if (image->matte != MagickFalse) destination.opacity=(MagickRealType) GetPixelOpacity(q); if (image->colorspace == CMYKColorspace) destination.index=(MagickRealType) GetPixelIndex(indexes+x); if (image->colorspace == CMYKColorspace) { destination.red=(MagickRealType) QuantumRange-destination.red; destination.green=(MagickRealType) QuantumRange-destination.green; destination.blue=(MagickRealType) QuantumRange-destination.blue; destination.index=(MagickRealType) QuantumRange-destination.index; } /* Handle destination modifications outside overlaid region. */ composite=destination; if ((pixels == (PixelPacket *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) composite_image->columns)) { switch (compose) { case DissolveCompositeOp: case BlendCompositeOp: { composite.opacity=(MagickRealType) (QuantumRange- destination_dissolve*(QuantumRange-composite.opacity)); break; } case ClearCompositeOp: case SrcCompositeOp: { CompositeClear(&destination,&composite); break; } case InCompositeOp: case SrcInCompositeOp: case OutCompositeOp: case SrcOutCompositeOp: case DstInCompositeOp: case DstAtopCompositeOp: case CopyOpacityCompositeOp: case ChangeMaskCompositeOp: { composite.opacity=(MagickRealType) TransparentOpacity; break; } default: { (void) GetOneVirtualMagickPixel(composite_image,x-x_offset, y-y_offset,&composite,exception); break; } } if (image->colorspace == CMYKColorspace) { composite.red=(MagickRealType) QuantumRange-composite.red; composite.green=(MagickRealType) QuantumRange-composite.green; composite.blue=(MagickRealType) QuantumRange-composite.blue; composite.index=(MagickRealType) QuantumRange-composite.index; } SetPixelRed(q,ClampToQuantum(composite.red)); SetPixelGreen(q,ClampToQuantum(composite.green)); SetPixelBlue(q,ClampToQuantum(composite.blue)); if (image->matte != MagickFalse) SetPixelOpacity(q,ClampToQuantum(composite.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,ClampToQuantum(composite.index)); q++; continue; } /* Handle normal overlay of source onto destination. */ source.red=(MagickRealType) GetPixelRed(p); source.green=(MagickRealType) GetPixelGreen(p); source.blue=(MagickRealType) GetPixelBlue(p); if (composite_image->matte != MagickFalse) source.opacity=(MagickRealType) GetPixelOpacity(p); if (composite_image->colorspace == CMYKColorspace) source.index=(MagickRealType) GetPixelIndex(composite_indexes+ x-x_offset); if (composite_image->colorspace == CMYKColorspace) { source.red=(MagickRealType) QuantumRange-source.red; source.green=(MagickRealType) QuantumRange-source.green; source.blue=(MagickRealType) QuantumRange-source.blue; source.index=(MagickRealType) QuantumRange-source.index; } switch (compose) { /* Duff-Porter Compositions */ case ClearCompositeOp: { CompositeClear(&destination,&composite); break; } case SrcCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: { composite=source; break; } case NoCompositeOp: case DstCompositeOp: break; case OverCompositeOp: case SrcOverCompositeOp: { MagickPixelCompositeOver(&source,source.opacity,&destination, destination.opacity,&composite); break; } case DstOverCompositeOp: { MagickPixelCompositeOver(&destination,destination.opacity,&source, source.opacity,&composite); break; } case SrcInCompositeOp: case InCompositeOp: { CompositeIn(&source,&destination,&composite); break; } case DstInCompositeOp: { CompositeIn(&destination,&source,&composite); break; } case OutCompositeOp: case SrcOutCompositeOp: { CompositeOut(&source,&destination,&composite); break; } case DstOutCompositeOp: { CompositeOut(&destination,&source,&composite); break; } case AtopCompositeOp: case SrcAtopCompositeOp: { CompositeAtop(&source,&destination,&composite); break; } case DstAtopCompositeOp: { CompositeAtop(&destination,&source,&composite); break; } case XorCompositeOp: { CompositeXor(&source,&destination,&composite); break; } /* Mathematical Compositions */ case PlusCompositeOp: { CompositePlus(&source,&destination,channel,&composite); break; } case MinusDstCompositeOp: { CompositeMinus(&source,&destination,channel,&composite); break; } case MinusSrcCompositeOp: { CompositeMinus(&destination,&source,channel,&composite); break; } case ModulusAddCompositeOp: { CompositeModulusAdd(&source,&destination,channel,&composite); break; } case ModulusSubtractCompositeOp: { CompositeModulusSubtract(&source,&destination,channel,&composite); break; } case DifferenceCompositeOp: { CompositeDifference(&source,&destination,channel,&composite); break; } case ExclusionCompositeOp: { CompositeExclusion(&source,&destination,channel,&composite); break; } case MultiplyCompositeOp: { CompositeMultiply(&source,&destination,channel,&composite); break; } case ScreenCompositeOp: { CompositeScreen(&source,&destination,channel,&composite); break; } case DivideDstCompositeOp: { CompositeDivide(&source,&destination,channel,&composite); break; } case DivideSrcCompositeOp: { CompositeDivide(&destination,&source,channel,&composite); break; } case DarkenCompositeOp: { CompositeDarken(&source,&destination,channel,&composite); break; } case LightenCompositeOp: { CompositeLighten(&source,&destination,channel,&composite); break; } case DarkenIntensityCompositeOp: { CompositeDarkenIntensity(&source,&destination,channel,&composite); break; } case LightenIntensityCompositeOp: { CompositeLightenIntensity(&source,&destination,channel,&composite); break; } case MathematicsCompositeOp: { CompositeMathematics(&source,&destination,channel,&geometry_info, &composite); break; } /* Lighting Compositions */ case ColorDodgeCompositeOp: { CompositeColorDodge(&source,&destination,&composite); break; } case ColorBurnCompositeOp: { CompositeColorBurn(&source,&destination,&composite); break; } case LinearDodgeCompositeOp: { CompositeLinearDodge(&source,&destination,&composite); break; } case LinearBurnCompositeOp: { CompositeLinearBurn(&source,&destination,&composite); break; } case HardLightCompositeOp: { CompositeHardLight(&source,&destination,&composite); break; } case OverlayCompositeOp: { /* Overlay = Reversed HardLight. */ CompositeHardLight(&destination,&source,&composite); break; } case SoftLightCompositeOp: { CompositeSoftLight(&source,&destination,&composite); break; } case LinearLightCompositeOp: { CompositeLinearLight(&source,&destination,&composite); break; } case PegtopLightCompositeOp: { CompositePegtopLight(&source,&destination,&composite); break; } case VividLightCompositeOp: { CompositeVividLight(&source,&destination,&composite); break; } case PinLightCompositeOp: { CompositePinLight(&source,&destination,&composite); break; } /* Other Composition */ case ChangeMaskCompositeOp: { if ((composite.opacity > ((MagickRealType) QuantumRange/2.0)) || (IsMagickColorSimilar(&source,&destination) != MagickFalse)) composite.opacity=(MagickRealType) TransparentOpacity; else composite.opacity=(MagickRealType) OpaqueOpacity; break; } case BumpmapCompositeOp: { if (source.opacity == TransparentOpacity) break; CompositeBumpmap(&source,&destination,&composite); break; } case DissolveCompositeOp: { MagickPixelCompositeOver(&source,(MagickRealType) (QuantumRange- source_dissolve*(QuantumRange-source.opacity)),&destination, (MagickRealType) (QuantumRange-destination_dissolve*(QuantumRange- destination.opacity)),&composite); break; } case BlendCompositeOp: { MagickPixelCompositeBlend(&source,source_dissolve,&destination, destination_dissolve,&composite); break; } case ThresholdCompositeOp: { CompositeThreshold(&source,&destination,threshold,amount,&composite); break; } case ModulateCompositeOp: { ssize_t offset; if (source.opacity == TransparentOpacity) break; offset=(ssize_t) (MagickPixelIntensityToQuantum(&source)-midpoint); if (offset == 0) break; CompositeHCL(destination.red,destination.green,destination.blue,&hue, &chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&composite.red, &composite.green,&composite.blue); break; } case HueCompositeOp: { if (source.opacity == TransparentOpacity) break; if (destination.opacity == TransparentOpacity) { composite=source; break; } CompositeHCL(destination.red,destination.green,destination.blue,&hue, &chroma,&luma); CompositeHCL(source.red,source.green,source.blue,&hue,&sans,&sans); HCLComposite(hue,chroma,luma,&composite.red, &composite.green,&composite.blue); if (source.opacity < destination.opacity) composite.opacity=source.opacity; break; } case SaturateCompositeOp: { if (source.opacity == TransparentOpacity) break; if (destination.opacity == TransparentOpacity) { composite=source; break; } CompositeHCL(destination.red,destination.green,destination.blue,&hue, &chroma,&luma); CompositeHCL(source.red,source.green,source.blue,&sans,&chroma, &sans); HCLComposite(hue,chroma,luma,&composite.red, &composite.green,&composite.blue); if (source.opacity < destination.opacity) composite.opacity=source.opacity; break; } case LuminizeCompositeOp: { if (source.opacity == TransparentOpacity) break; if (destination.opacity == TransparentOpacity) { composite=source; break; } CompositeHCL(destination.red,destination.green,destination.blue,&hue, &chroma,&luma); CompositeHCL(source.red,source.green,source.blue,&sans,&sans, &luma); HCLComposite(hue,chroma,luma,&composite.red, &composite.green,&composite.blue); if (source.opacity < destination.opacity) composite.opacity=source.opacity; break; } case ColorizeCompositeOp: { if (source.opacity == TransparentOpacity) break; if (destination.opacity == TransparentOpacity) { composite=source; break; } CompositeHCL(destination.red,destination.green,destination.blue,&sans, &sans,&luma); CompositeHCL(source.red,source.green,source.blue,&hue,&chroma, &sans); HCLComposite(hue,chroma,luma,&composite.red, &composite.green,&composite.blue); if (source.opacity < destination.opacity) composite.opacity=source.opacity; break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { composite.red=source.red; break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { composite.green=source.green; break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { composite.blue=source.blue; break; } case CopyOpacityCompositeOp: { if (source.matte == MagickFalse) { composite.opacity=(MagickRealType) (QuantumRange- MagickPixelIntensityToQuantum(&source)); break; } composite.opacity=source.opacity; break; } case CopyBlackCompositeOp: { if (source.colorspace != CMYKColorspace) ConvertRGBToCMYK(&source); composite.index=source.index; break; } /* compose methods that are already handled */ case BlurCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: { composite=source; break; } default: break; } if (image->colorspace == CMYKColorspace) { composite.red=(MagickRealType) QuantumRange-composite.red; composite.green=(MagickRealType) QuantumRange-composite.green; composite.blue=(MagickRealType) QuantumRange-composite.blue; composite.index=(MagickRealType) QuantumRange-composite.index; } SetPixelRed(q,ClampToQuantum(composite.red)); SetPixelGreen(q,ClampToQuantum(composite.green)); SetPixelBlue(q,ClampToQuantum(composite.blue)); SetPixelOpacity(q,ClampToQuantum(composite.opacity)); if (image->colorspace == CMYKColorspace) SetPixelIndex(indexes+x,ClampToQuantum(composite.index)); p++; if (p >= (pixels+composite_image->columns)) p=pixels; q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_CompositeImageChannel) #endif proceed=SetImageProgress(image,CompositeImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } composite_view=DestroyCacheView(composite_view); image_view=DestroyCacheView(image_view); if (destination_image != (Image * ) NULL) destination_image=DestroyImage(destination_image); else composite_image=DestroyImage(composite_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture) % % A description of each parameter follows: % % o image: the image. % % o texture: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; ExceptionInfo *exception; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); exception=(&image->exception); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->matte != MagickFalse) || (texture_image->matte != MagickFalse))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { register ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,image->compose,texture_image,x+ texture_image->tile_offset.x,y+texture_image->tile_offset.y); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,texture_image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *texture_indexes; register const PixelPacket *p; register IndexPacket *indexes; register ssize_t x; register PixelPacket *q; size_t width; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x,(y+ texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } texture_indexes=GetCacheViewVirtualIndexQueue(texture_view); indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; (void) CopyMagickMemory(q,p,width*sizeof(*p)); if ((image->colorspace == CMYKColorspace) && (texture_image->colorspace == CMYKColorspace)) { (void) CopyMagickMemory(indexes,texture_indexes,width* sizeof(*indexes)); indexes+=width; } q+=width; } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_TextureImage) #endif proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
test_utils.h
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <limits> #include <utility> #include <cstdint> #include <cstdlib> #include <map> extern "C" { #include "mmio.h" } #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #include <library_types.h> #include <thrust/host_vector.h> #include <thrust/adjacent_difference.h> #include <thrust/reduce.h> #include <thrust/functional.h> #include <thrust/device_vector.h> #include <thrust/sequence.h> #include <rmm_utils.h> #include <rmm/rmm.h> #include "cugraph.h" #include "utilities/error_utils.h" #ifndef CUDA_RT_CALL #define CUDA_RT_CALL( call ) \ { \ cudaError_t cudaStatus = call; \ if ( cudaSuccess != cudaStatus ) { \ fprintf(stderr, "ERROR: CUDA RT call \"%s\" in line %d of file %s failed with %s (%d).\n", \ #call, __LINE__, __FILE__, cudaGetErrorString(cudaStatus), cudaStatus); \ } \ } #endif std::function<void(gdf_column*)> gdf_col_deleter = [](gdf_column* col){ if (col) { col->size = 0; if(col->data){ cudaStream_t stream{nullptr}; ALLOC_FREE_TRY(col->data, stream); } delete col; } }; using gdf_column_ptr = typename std::unique_ptr<gdf_column, decltype(gdf_col_deleter)>; std::function<void(cugraph::Graph*)> Graph_deleter = [](cugraph::Graph* G){delete G;}; using Graph_ptr = typename std::unique_ptr<cugraph::Graph,decltype(Graph_deleter)>; std::string getFileName(const std::string& s) { char sep = '/'; #ifdef _WIN32 sep = '\\'; #endif size_t i = s.rfind(sep, s.length()); if (i != std::string::npos) { return(s.substr(i+1, s.length() - i)); } return(""); } template <typename T> void verbose_diff(std::vector<T> & v1, std::vector<T> & v2) { for (unsigned int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { std::cout << "[" << i <<"] : " << v1[i] << " vs. "<< v2[i]<<std::endl; } } } template <typename T> int eq(std::vector<T> & v1, std::vector<T> & v2) { if (v1 == v2) return 0; else { verbose_diff(v1,v2); return 1; } } template <typename T> void printv(size_t n, T* vec, int offset) { thrust::device_ptr<T> dev_ptr(vec); std::cout.precision(15); std::cout << "sample size = "<< n << ", offset = "<< offset << std::endl; thrust::copy(dev_ptr+offset,dev_ptr+offset+n, std::ostream_iterator<T>(std::cout, " "));//Assume no RMM dependency; TODO: check / test (potential BUG !!!!!) std::cout << std::endl; } template <typename T> void random_vals(std::vector<T> & v) { srand(42); for (auto i = size_t{0}; i < v.size(); i++) v[i]=static_cast<T>(std::rand()%10); } template <typename T_ELEM> void ref_csr2csc (int m, int n, int nnz, const T_ELEM *csrVals, const int *csrRowptr, const int *csrColInd, T_ELEM *cscVals, int *cscRowind, int *cscColptr, int base=0){ int i,j, row, col, index; int * counters; T_ELEM val; /* early return */ if ((m <= 0) || (n <= 0) || (nnz <= 0)){ return; } /* build compressed column pointers */ memset(cscColptr, 0, (n+1)*sizeof(cscColptr[0])); cscColptr[0]=base; for (i=0; i<nnz; i++){ cscColptr[1+csrColInd[i]-base]++; } for(i=0; i<n; i++){ cscColptr[i+1]+=cscColptr[i]; } /* expand row indecis and copy them and values into csc arrays according to permutation */ counters = (int *)malloc(n*sizeof(counters[0])); memset(counters, 0, n*sizeof(counters[0])); for (i=0; i<m; i++){ for (j=csrRowptr[i]; j<csrRowptr[i+1]; j++){ row = i+base; col = csrColInd[j-base]; index=cscColptr[col-base]-base+counters[col-base]; counters[col-base]++; cscRowind[index]=row; if(csrVals!=NULL || cscVals!=NULL){ val = csrVals[j-base]; cscVals[index] = val; } } } free(counters); } template <typename T> int transition_matrix_cpu(int n, int e, int *csrRowPtrA, int *csrColIndA, T *weight, T* is_leaf) //omp_set_num_threads(4); //#pragma omp parallel { int j,row, row_size; //#pragma omp for for (row=0; row<n; row++) { row_size = csrRowPtrA[row+1] - csrRowPtrA[row]; if (row_size == 0) is_leaf[row]=1.0; else { is_leaf[row]=0.0; for (j=csrRowPtrA[row]; j<csrRowPtrA[row+1]; j++) weight[j] = 1.0/row_size; } } return 0; } template <typename T> void printCsrMatI(int m, int n, int nnz,std::vector<int> & csrRowPtr, std::vector<uint16_t> & csrColInd, std::vector<T> & csrVal) { std::vector<T> v(n); std::stringstream ss; ss.str(std::string()); ss << std::fixed; ss << std::setprecision(2); for (int i = 0; i < m; i++) { std::fill(v.begin(),v.end(),0); for (int j = csrRowPtr[i]; j < csrRowPtr[i+1]; j++) v[csrColInd[j]] = csrVal[j]; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); ss << "\n"; } ss << "\n"; std::cout<<ss.str(); } /// Read matrix properties from Matrix Market file /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param t (Output) MM_typecode with matrix properties. * @param m (Output) Number of matrix rows. * @param n (Output) Number of matrix columns. * @param nnz (Output) Number of non-zero matrix entries. * @return Zero if properties were read successfully. Otherwise * non-zero. */ template <typename IndexType_> int mm_properties(FILE * f, int tg, MM_typecode * t, IndexType_ * m, IndexType_ * n, IndexType_ * nnz) { // Read matrix properties from file int mint, nint, nnzint; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(*t) || !mm_is_coordinate(*t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&mint,&nint,&nnzint)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(*t) && !mm_is_real(*t) && !mm_is_integer(*t) && !mm_is_complex(*t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } *m = mint; *n = nint; *nnz = nnzint; // Find total number of non-zero entries if(tg && !mm_is_general(*t)) { // Non-diagonal entries should be counted twice IndexType_ nnzOld = *nnz; *nnz *= 2; // Diagonal entries should not be double-counted int i; int st; for(i=0; i<nnzOld; ++i) { // Read matrix entry IndexType_ row, col; double rval, ival; if (mm_is_pattern(*t)) st = fscanf(f, "%d %d\n", &row, &col); else if (mm_is_real(*t) || mm_is_integer(*t)) st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Check if entry is diagonal if(row == col) --(*nnz); } } return 0; } /// Read Matrix Market file and convert to COO format matrix /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param nnz Number of non-zero matrix entries. * @param cooRowInd (Output) Row indices for COO matrix. Should have * at least nnz entries. * @param cooColInd (Output) Column indices for COO matrix. Should * have at least nnz entries. * @param cooRVal (Output) Real component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @param cooIVal (Output) Imaginary component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @return Zero if matrix was read successfully. Otherwise non-zero. */ template <typename IndexType_, typename ValueType_> int mm_to_coo(FILE *f, int tg, IndexType_ nnz, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal , ValueType_ * cooIVal) { // Read matrix properties from file MM_typecode t; int m, n, nnzOld; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,&t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(t) || !mm_is_coordinate(t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&m,&n,&nnzOld)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(t) && !mm_is_real(t) && !mm_is_integer(t) && !mm_is_complex(t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } // Add each matrix entry in file to COO format matrix IndexType_ i; // Entry index in Matrix Market file IndexType_ j = 0; // Entry index in COO format matrix for(i=0;i<nnzOld;++i) { // Read entry from file int row, col; double rval, ival; int st; if (mm_is_pattern(t)) { st = fscanf(f, "%d %d\n", &row, &col); rval = 1.0; ival = 0.0; } else if (mm_is_real(t) || mm_is_integer(t)) { st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); ival = 0.0; } else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Switch to 0-based indexing --row; --col; // Record entry cooRowInd[j] = row; cooColInd[j] = col; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; // Add symmetric complement of non-diagonal entries if(tg && !mm_is_general(t) && (row!=col)) { // Modify entry value if matrix is skew symmetric or Hermitian if(mm_is_skew(t)) { rval = -rval; ival = -ival; } else if(mm_is_hermitian(t)) { ival = -ival; } // Record entry cooRowInd[j] = col; cooColInd[j] = row; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; } } return 0; } /// Compare two tuples based on the element indexed by i class lesser_tuple { const int i; public: lesser_tuple(int _i) : i(_i) {} template<typename Tuple1, typename Tuple2> __host__ __device__ bool operator()(const Tuple1 t1, const Tuple2 t2) { switch(i) { case 0: return (thrust::get<0>(t1) == thrust::get<0>(t2) ? thrust::get<1>(t1) < thrust::get<1>(t2) : thrust::get<0>(t1) < thrust::get<0>(t2)); case 1: return (thrust::get<1>(t1) == thrust::get<1>(t2) ? thrust::get<0>(t1) < thrust::get<0>(t2) : thrust::get<1>(t1) < thrust::get<1>(t2)); default: return (thrust::get<0>(t1) == thrust::get<0>(t2) ? thrust::get<1>(t1) < thrust::get<1>(t2) : thrust::get<0>(t1) < thrust::get<0>(t2)); } } }; /// Sort entries in COO format matrix /** Sort is stable. * * @param nnz Number of non-zero matrix entries. * @param sort_by_row Boolean indicating whether matrix entries * will be sorted by row index or by column index. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component for COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component COO matrix entries. Ignored if * null pointer. */ template <typename IndexType_, typename ValueType_> void coo_sort(IndexType_ nnz, int sort_by_row, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal, ValueType_ * cooIVal) { // Determine whether to sort by row or by column int i; if(sort_by_row == 0) i = 1; else i = 0; // Apply stable sort using namespace thrust; if((cooRVal==NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz)), lesser_tuple(i)); else if((cooRVal==NULL) && (cooIVal!=NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooIVal+nnz)), lesser_tuple(i)); else if((cooRVal!=NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooRVal+nnz)), lesser_tuple(i)); else stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz, cooRVal+nnz,cooIVal+nnz)), lesser_tuple(i)); } template <typename IndexT> void coo2csr(std::vector<IndexT>& cooRowInd, //in: I[] (overwrite) const std::vector<IndexT>& cooColInd, //in: J[] std::vector<IndexT>& csrRowPtr, //out std::vector<IndexT>& csrColInd) //out { std::vector<std::pair<IndexT,IndexT> > items; for (auto i = size_t{0}; i < cooRowInd.size(); ++i) items.push_back(std::make_pair( cooRowInd[i], cooColInd[i])); //sort pairs std::sort(items.begin(), items.end(),[](const std::pair<IndexT,IndexT> &left, const std::pair<IndexT,IndexT> &right) {return left.first < right.first; }); for (auto i = size_t{0}; i < cooRowInd.size(); ++i) { cooRowInd[i]=items[i].first; // save the sorted rows to compress them later csrColInd[i]=items[i].second; // save the col idx, not sure if they are sorted for each row } // Count number of elements per row for(auto i=size_t{0}; i<cooRowInd.size(); ++i) ++(csrRowPtr[cooRowInd[i]+1]); // Compute cumulative sum to obtain row offsets/pointers for(auto i=size_t{0}; i<csrRowPtr.size()-1; ++i) csrRowPtr[i+1] += csrRowPtr[i]; } /// Compress sorted list of indices /** For use in converting COO format matrix to CSR or CSC format. * * @param n Maximum index. * @param nnz Number of non-zero matrix entries. * @param sortedIndices Sorted list of indices (COO format). * @param compressedIndices (Output) Compressed list of indices (CSR * or CSC format). Should have at least n+1 entries. */ template <typename IndexType_> void coo_compress(IndexType_ m, IndexType_ n, IndexType_ nnz, const IndexType_ * __restrict__ sortedIndices, IndexType_ * __restrict__ compressedIndices) { IndexType_ i; // Initialize everything to zero memset(compressedIndices, 0, (m+1)*sizeof(IndexType_)); // Count number of elements per row for(i=0; i<nnz; ++i) ++(compressedIndices[sortedIndices[i]+1]); // Compute cumulative sum to obtain row offsets/pointers for(i=0; i<m; ++i) compressedIndices[i+1] += compressedIndices[i]; } /// Convert COO format matrix to CSR format /** On output, matrix entries in COO format matrix will be sorted * (primarily by row index, secondarily by column index). * * @param m Number of matrix rows. * @param n Number of matrix columns. * @param nnz Number of non-zero matrix entries. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component of COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component of COO matrix entries. Ignored * if null pointer. * @param csrRowPtr Row pointers for CSR matrix. Should have at least * n+1 entries. * @param csrColInd Column indices for CSR matrix (identical to * output of cooColInd). Should have at least nnz entries. Ignored if * null pointer. * @param csrRVal Real component of CSR matrix entries (identical to * output of cooRVal). Should have at least nnz entries. Ignored if * null pointer. * @param csrIVal Imaginary component of CSR matrix entries * (identical to output of cooIVal). Should have at least nnz * entries. Ignored if null pointer. * @return Zero if matrix was converted successfully. Otherwise * non-zero. */ template <typename IndexType_, typename ValueType_> int coo_to_csr(IndexType_ m, IndexType_ n, IndexType_ nnz, IndexType_ * __restrict__ cooRowInd, IndexType_ * __restrict__ cooColInd, ValueType_ * __restrict__ cooRVal, ValueType_ * __restrict__ cooIVal, IndexType_ * __restrict__ csrRowPtr, IndexType_ * __restrict__ csrColInd, ValueType_ * __restrict__ csrRVal, ValueType_ * __restrict__ csrIVal) { // Convert COO to CSR matrix coo_sort(nnz, 0, cooRowInd, cooColInd, cooRVal, cooIVal); coo_sort(nnz, 1, cooRowInd, cooColInd, cooRVal, cooIVal); //coo_sort2<int,float>(m, nnz, cooRowInd, cooColInd); coo_compress(m, n, nnz, cooRowInd, csrRowPtr); // Copy arrays if(csrColInd!=NULL) memcpy(csrColInd, cooColInd, nnz*sizeof(IndexType_)); if((cooRVal!=NULL) && (csrRVal!=NULL)) memcpy(csrRVal, cooRVal, nnz*sizeof(ValueType_)); if((cooIVal!=NULL) && (csrIVal!=NULL)) memcpy(csrIVal, cooIVal, nnz*sizeof(ValueType_)); return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<float>& val ) { size_t is_read1; double* t_storage = new double[n]; is_read1 = fread(t_storage, sizeof(double), n, fpin); for (int i = 0; i < n; i++) { if (t_storage[i] == DBL_MAX) val[i] = FLT_MAX; else if (t_storage[i] == -DBL_MAX) val[i] = -FLT_MAX; else val[i] = static_cast<float>(t_storage[i]); } delete[] t_storage; if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<double>& val ) { size_t is_read1; is_read1 = fread(&val[0], sizeof(double), n, fpin); if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } // Creates a gdf_column from a std::vector template <typename col_type> gdf_column_ptr create_gdf_column(std::vector<col_type> const & host_vector) { // Create a new instance of a gdf_column with a custom deleter that will free // the associated device memory when it eventually goes out of scope gdf_column_ptr the_column{new gdf_column, gdf_col_deleter}; // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaStream_t stream{nullptr}; ALLOC_TRY((void**)&(the_column->data), input_size_bytes, stream); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; return the_column; } // Creates a gdf_column from a std::vector template <typename col_type> void create_gdf_column(std::vector<col_type> const & host_vector, gdf_column * the_column) { // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaStream_t stream{nullptr}; ALLOC_TRY((void**)&(the_column->data), input_size_bytes, stream); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; } void gdf_col_delete(gdf_column* col) { if (col) { col->size = 0; cudaStream_t stream{nullptr}; if(col->data) ALLOC_FREE_TRY(col->data, stream); #if 1 // If delete col is executed, the memory pointed by col is no longer valid and // can be used in another memory allocation, so executing col->data = nullptr // after delete col is dangerous, also, col = nullptr has no effect here (the // address is passed by value, for col = nullptr should work, the input // parameter should be gdf_column*& col (or alternatively, gdf_column** col and // *col = nullptr also work) col->data = nullptr; delete col; #else delete col; col->data = nullptr; col = nullptr; #endif } } template <typename col_type> bool gdf_column_equal(gdf_column* a, gdf_column* b) { if (a == nullptr || b == nullptr){ std::cout << "A given column is null!\n"; return false; } if (a->dtype != b->dtype){ std::cout << "Mismatched dtypes\n"; return false; } if (a->size != b->size){ std::cout << "Mismatched sizes: a=" << a->size << " b=" << b->size << "\n"; return false; } std::vector<col_type>a_h(a->size); std::vector<col_type>b_h(b->size); cudaMemcpy(&a_h[0], a->data, sizeof(col_type) * a->size, cudaMemcpyDefault); cudaMemcpy(&b_h[0], b->data, sizeof(col_type) * b->size, cudaMemcpyDefault); for (size_t i = 0; i < a_h.size(); i++) { if (a_h[i] != b_h[i]){ std::cout << "Elements at " << i << " differ: a=" << a_h[i] << " b=" << b_h[i] << "\n"; return false; } } return true; } template<typename idx_t> bool gdf_csr_equal(gdf_column* a_off, gdf_column* a_ind, gdf_column* b_off, gdf_column* b_ind) { if (a_off == nullptr || a_ind == nullptr || b_off == nullptr || b_ind == nullptr) { std::cout << "A given column is null!\n"; return false; } auto type = a_off->dtype; if (a_ind->dtype != type || b_off->dtype != type || b_ind->dtype != type) { std::cout << "Mismatched dtypes\n"; return false; } if (!gdf_column_equal<idx_t>(a_off, b_off)) { std::cout << "Offsets arrays do not match!\n"; return false; } if (a_ind->size != b_ind->size) { std::cout << "Size of indices arrays do not match\n"; return false; } // Compare the elements of each section of the indices, regardless of order std::vector<idx_t> a_off_h(a_off->size); std::vector<idx_t> a_ind_h(a_ind->size); std::vector<idx_t> b_ind_h(b_ind->size); cudaMemcpy(&a_off_h[0], a_off->data, a_off->size * sizeof(idx_t), cudaMemcpyDefault); cudaMemcpy(&a_ind_h[0], a_ind->data, a_ind->size * sizeof(idx_t), cudaMemcpyDefault); cudaMemcpy(&b_ind_h[0], b_ind->data, b_ind->size * sizeof(idx_t), cudaMemcpyDefault); auto numVerts = a_off_h.size() - 1; for (size_t vert = 0; vert < numVerts; vert++){ auto start = a_off_h[vert]; auto end = a_off_h[vert + 1]; std::set<idx_t> a_set; std::set<idx_t> b_set; for (int i = start; i < end; i++){ a_set.insert(a_ind_h[i]); b_set.insert(b_ind_h[i]); } if (a_set.size() != b_set.size()) { std::cout << "Vertex " << vert << " set sizes do not match!\n"; std::cout << "A Set: {"; for (auto it = a_set.begin(); it != a_set.end(); it++) std::cout << " " << *it; std::cout << "}\nB Set: {"; for (auto it = b_set.begin(); it != b_set.end(); it++) std::cout << " " << *it; std::cout << "}\n"; std::cout << "A list: {"; for (int i = start; i < end; i++) { std::cout << " " << a_ind_h[i]; } std::cout << "}\nB List: {"; for (int i = start; i < end; i++) { std::cout << " " << b_ind_h[i]; } std::cout << "}\n"; return false; } for (auto it = a_set.begin(); it != a_set.end(); it++) { if (b_set.count(*it) != 1) { std::cout << "A set contains " << *it << " B set does not!\n"; return false; } } } return true; } //////////////////////////////////////////////////////////////////////////////// // TODO: move this code to rapids-core //////////////////////////////////////////////////////////////////////////////// // Define RAPIDS_DATASET_ROOT_DIR using a preprocessor variable to // allow for a build to override the default. This is useful for // having different builds for specific default dataset locations. #ifndef RAPIDS_DATASET_ROOT_DIR #define RAPIDS_DATASET_ROOT_DIR "/datasets" #endif static const std::string& get_rapids_dataset_root_dir() { static std::string rdrd(""); // Env var always overrides the value of RAPIDS_DATASET_ROOT_DIR if (rdrd == "") { const char* envVar = std::getenv("RAPIDS_DATASET_ROOT_DIR"); rdrd = (envVar != NULL) ? envVar : RAPIDS_DATASET_ROOT_DIR; } return rdrd; }
parallel_fann.c
/* * parallel_FANN.c * Author: Alessandro Pietro Bardelli */ #ifndef DISABLE_PARALLEL_FANN #include <omp.h> #include "parallel_fann.h" #include "config.h" #include "fann.h" FANN_EXTERNAL float FANN_API fann_train_epoch_batch_parallel(struct fann *ann, struct fann_train_data *data, const unsigned int threadnumb) { /*vector<struct fann *> ann_vect(threadnumb);*/ struct fann** ann_vect= (struct fann**) malloc(threadnumb * sizeof(struct fann*)); int i=0,j=0; fann_reset_MSE(ann); //generate copies of the ann omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(j) { #pragma omp for schedule(static) for(i=0; i<(int)threadnumb; i++) { ann_vect[i]=fann_copy(ann); } //parallel computing of the updates #pragma omp for schedule(static) for(i = 0; i < (int)data->num_data; i++) { j=omp_get_thread_num(); fann_run(ann_vect[j], data->input[i]); fann_compute_MSE(ann_vect[j], data->output[i]); fann_backpropagate_MSE(ann_vect[j]); fann_update_slopes_batch(ann_vect[j], ann_vect[j]->first_layer + 1, ann_vect[j]->last_layer - 1); } } //parallel update of the weights { const unsigned int num_data=data->num_data; const unsigned int first_weight=0; const unsigned int past_end=ann->total_connections; fann_type *weights = ann->weights; const fann_type epsilon = ann->learning_rate / num_data; omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel { #pragma omp for schedule(static) for(i=first_weight; i < (int)past_end; i++) { fann_type temp_slopes=0.0; unsigned int k; fann_type *train_slopes; for(k=0;k<threadnumb;++k) { train_slopes=ann_vect[k]->train_slopes; temp_slopes+= train_slopes[i]; train_slopes[i]=0.0; } weights[i] += temp_slopes*epsilon; } } } //merge of MSEs for(i=0;i<(int)threadnumb;++i) { ann->MSE_value+= ann_vect[i]->MSE_value; ann->num_MSE+=ann_vect[i]->num_MSE; fann_destroy(ann_vect[i]); } free(ann_vect); return fann_get_MSE(ann); } FANN_EXTERNAL float FANN_API fann_train_epoch_irpropm_parallel(struct fann *ann, struct fann_train_data *data, const unsigned int threadnumb) { struct fann** ann_vect= (struct fann**) malloc(threadnumb * sizeof(struct fann*)); int i=0,j=0; if(ann->prev_train_slopes == NULL) { fann_clear_train_arrays(ann); } //#define THREADNUM 1 fann_reset_MSE(ann); /*vector<struct fann *> ann_vect(threadnumb);*/ //generate copies of the ann omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(j) { #pragma omp for schedule(static) for(i=0; i<(int)threadnumb; i++) { ann_vect[i]=fann_copy(ann); } //parallel computing of the updates #pragma omp for schedule(static) for(i = 0; i < (int)data->num_data; i++) { j=omp_get_thread_num(); fann_run(ann_vect[j], data->input[i]); fann_compute_MSE(ann_vect[j], data->output[i]); fann_backpropagate_MSE(ann_vect[j]); fann_update_slopes_batch(ann_vect[j], ann_vect[j]->first_layer + 1, ann_vect[j]->last_layer - 1); } } { fann_type *weights = ann->weights; fann_type *prev_steps = ann->prev_steps; fann_type *prev_train_slopes = ann->prev_train_slopes; fann_type next_step; const float increase_factor = ann->rprop_increase_factor; //1.2; const float decrease_factor = ann->rprop_decrease_factor; //0.5; const float delta_min = ann->rprop_delta_min; //0.0; const float delta_max = ann->rprop_delta_max; //50.0; const unsigned int first_weight=0; const unsigned int past_end=ann->total_connections; omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(next_step) { #pragma omp for schedule(static) for(i=first_weight; i < (int)past_end; i++) { fann_type prev_slope, same_sign; const fann_type prev_step = fann_max(prev_steps[i], (fann_type) 0.0001); // prev_step may not be zero because then the training will stop fann_type temp_slopes=0.0; unsigned int k; fann_type *train_slopes; for(k=0;k<threadnumb;++k) { train_slopes=ann_vect[k]->train_slopes; temp_slopes+= train_slopes[i]; train_slopes[i]=0.0; } prev_slope = prev_train_slopes[i]; same_sign = prev_slope * temp_slopes; if(same_sign >= 0.0) next_step = fann_min(prev_step * increase_factor, delta_max); else { next_step = fann_max(prev_step * decrease_factor, delta_min); temp_slopes = 0; } if(temp_slopes < 0) { weights[i] -= next_step; if(weights[i] < -1500) weights[i] = -1500; } else { weights[i] += next_step; if(weights[i] > 1500) weights[i] = 1500; } // update global data arrays prev_steps[i] = next_step; prev_train_slopes[i] = temp_slopes; } } } //merge of MSEs for(i=0;i<(int)threadnumb;++i) { ann->MSE_value+= ann_vect[i]->MSE_value; ann->num_MSE+=ann_vect[i]->num_MSE; fann_destroy(ann_vect[i]); } free(ann_vect); return fann_get_MSE(ann); } FANN_EXTERNAL float FANN_API fann_train_epoch_quickprop_parallel(struct fann *ann, struct fann_train_data *data, const unsigned int threadnumb) { struct fann** ann_vect= (struct fann**) malloc(threadnumb * sizeof(struct fann*)); int i=0,j=0; if(ann->prev_train_slopes == NULL) { fann_clear_train_arrays(ann); } //#define THREADNUM 1 fann_reset_MSE(ann); /*vector<struct fann *> ann_vect(threadnumb);*/ //generate copies of the ann omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(j) { #pragma omp for schedule(static) for(i=0; i<(int)threadnumb; i++) { ann_vect[i]=fann_copy(ann); } //parallel computing of the updates #pragma omp for schedule(static) for(i = 0; i < (int)data->num_data; i++) { j=omp_get_thread_num(); fann_run(ann_vect[j], data->input[i]); fann_compute_MSE(ann_vect[j], data->output[i]); fann_backpropagate_MSE(ann_vect[j]); fann_update_slopes_batch(ann_vect[j], ann_vect[j]->first_layer + 1, ann_vect[j]->last_layer - 1); } } { fann_type *weights = ann->weights; fann_type *prev_steps = ann->prev_steps; fann_type *prev_train_slopes = ann->prev_train_slopes; const unsigned int first_weight=0; const unsigned int past_end=ann->total_connections; fann_type w=0.0, next_step; const float epsilon = ann->learning_rate / data->num_data; const float decay = ann->quickprop_decay; /*-0.0001;*/ const float mu = ann->quickprop_mu; /*1.75; */ const float shrink_factor = (float) (mu / (1.0 + mu)); omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(w, next_step) { #pragma omp for schedule(static) for(i=first_weight; i < (int)past_end; i++) { fann_type temp_slopes=0.0; unsigned int k; fann_type *train_slopes; fann_type prev_step, prev_slope; w = weights[i]; for(k=0;k<threadnumb;++k) { train_slopes=ann_vect[k]->train_slopes; temp_slopes+= train_slopes[i]; train_slopes[i]=0.0; } temp_slopes+= decay * w; prev_step = prev_steps[i]; prev_slope = prev_train_slopes[i]; next_step = 0.0; /* The step must always be in direction opposite to the slope. */ if(prev_step > 0.001) { /* If last step was positive... */ if(temp_slopes > 0.0) /* Add in linear term if current slope is still positive. */ next_step += epsilon * temp_slopes; /*If current slope is close to or larger than prev slope... */ if(temp_slopes > (shrink_factor * prev_slope)) next_step += mu * prev_step; /* Take maximum size negative step. */ else next_step += prev_step * temp_slopes / (prev_slope - temp_slopes); /* Else, use quadratic estimate. */ } else if(prev_step < -0.001) { /* If last step was negative... */ if(temp_slopes < 0.0) /* Add in linear term if current slope is still negative. */ next_step += epsilon * temp_slopes; /* If current slope is close to or more neg than prev slope... */ if(temp_slopes < (shrink_factor * prev_slope)) next_step += mu * prev_step; /* Take maximum size negative step. */ else next_step += prev_step * temp_slopes / (prev_slope - temp_slopes); /* Else, use quadratic estimate. */ } else /* Last step was zero, so use only linear term. */ next_step += epsilon * temp_slopes; /* update global data arrays */ prev_steps[i] = next_step; prev_train_slopes[i] = temp_slopes; w += next_step; if(w > 1500) weights[i] = 1500; else if(w < -1500) weights[i] = -1500; else weights[i] = w; } } } //merge of MSEs for(i=0;i<(int)threadnumb;++i) { ann->MSE_value+= ann_vect[i]->MSE_value; ann->num_MSE+=ann_vect[i]->num_MSE; fann_destroy(ann_vect[i]); } free(ann_vect); return fann_get_MSE(ann); } FANN_EXTERNAL float FANN_API fann_train_epoch_sarprop_parallel(struct fann *ann, struct fann_train_data *data, const unsigned int threadnumb) { struct fann** ann_vect= (struct fann**) malloc(threadnumb * sizeof(struct fann*)); int i=0,j=0; if(ann->prev_train_slopes == NULL) { fann_clear_train_arrays(ann); } //#define THREADNUM 1 fann_reset_MSE(ann); /*vector<struct fann *> ann_vect(threadnumb);*/ //generate copies of the ann omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(j) { #pragma omp for schedule(static) for(i=0; i<(int)threadnumb; i++) { ann_vect[i]=fann_copy(ann); } //parallel computing of the updates #pragma omp for schedule(static) for(i = 0; i < (int)data->num_data; i++) { j=omp_get_thread_num(); fann_run(ann_vect[j], data->input[i]); fann_compute_MSE(ann_vect[j], data->output[i]); fann_backpropagate_MSE(ann_vect[j]); fann_update_slopes_batch(ann_vect[j], ann_vect[j]->first_layer + 1, ann_vect[j]->last_layer - 1); } } { fann_type *weights = ann->weights; fann_type *prev_steps = ann->prev_steps; fann_type *prev_train_slopes = ann->prev_train_slopes; const unsigned int first_weight=0; const unsigned int past_end=ann->total_connections; const unsigned int epoch=ann->sarprop_epoch; fann_type next_step; /* These should be set from variables */ const float increase_factor = ann->rprop_increase_factor; /*1.2; */ const float decrease_factor = ann->rprop_decrease_factor; /*0.5; */ /* TODO: why is delta_min 0.0 in iRprop? SARPROP uses 1x10^-6 (Braun and Riedmiller, 1993) */ const float delta_min = 0.000001f; const float delta_max = ann->rprop_delta_max; /*50.0; */ const float weight_decay_shift = ann->sarprop_weight_decay_shift; /* ld 0.01 = -6.644 */ const float step_error_threshold_factor = ann->sarprop_step_error_threshold_factor; /* 0.1 */ const float step_error_shift = ann->sarprop_step_error_shift; /* ld 3 = 1.585 */ const float T = ann->sarprop_temperature; float MSE, RMSE; //merge of MSEs for(i=0;i<(int)threadnumb;++i) { ann->MSE_value+= ann_vect[i]->MSE_value; ann->num_MSE+=ann_vect[i]->num_MSE; } MSE = fann_get_MSE(ann); RMSE = sqrtf(MSE); /* for all weights; TODO: are biases included? */ omp_set_dynamic(0); omp_set_num_threads(threadnumb); #pragma omp parallel private(next_step) { #pragma omp for schedule(static) for(i=first_weight; i < (int)past_end; i++) { /* TODO: confirm whether 1x10^-6 == delta_min is really better */ const fann_type prev_step = fann_max(prev_steps[i], (fann_type) 0.000001); /* prev_step may not be zero because then the training will stop */ /* calculate SARPROP slope; TODO: better as new error function? (see SARPROP paper)*/ fann_type prev_slope, same_sign; fann_type temp_slopes=0.0; unsigned int k; fann_type *train_slopes; for(k=0;k<threadnumb;++k) { train_slopes=ann_vect[k]->train_slopes; temp_slopes+= train_slopes[i]; train_slopes[i]=0.0; } temp_slopes= -temp_slopes - weights[i] * (fann_type)fann_exp2(-T * epoch + weight_decay_shift); next_step=0.0; /* TODO: is prev_train_slopes[i] 0.0 in the beginning? */ prev_slope = prev_train_slopes[i]; same_sign = prev_slope * temp_slopes; if(same_sign > 0.0) { next_step = fann_min(prev_step * increase_factor, delta_max); /* TODO: are the signs inverted? see differences between SARPROP paper and iRprop */ if (temp_slopes < 0.0) weights[i] += next_step; else weights[i] -= next_step; } else if(same_sign < 0.0) { #ifndef RAND_MAX #define RAND_MAX 0x7fffffff #endif if(prev_step < step_error_threshold_factor * MSE) next_step = prev_step * decrease_factor + (float)rand() / RAND_MAX * RMSE * (fann_type)fann_exp2(-T * epoch + step_error_shift); else next_step = fann_max(prev_step * decrease_factor, delta_min); temp_slopes = 0.0; } else { if(temp_slopes < 0.0) weights[i] += prev_step; else weights[i] -= prev_step; } /* update global data arrays */ prev_steps[i] = next_step; prev_train_slopes[i] = temp_slopes; } } } ++(ann->sarprop_epoch); //already computed before /*//merge of MSEs for(i=0;i<threadnumb;++i) { ann->MSE_value+= ann_vect[i]->MSE_value; ann->num_MSE+=ann_vect[i]->num_MSE; }*/ //destroy the copies of the ann for(i=0; i<(int)threadnumb; i++) { fann_destroy(ann_vect[i]); } free(ann_vect); return fann_get_MSE(ann); } FANN_EXTERNAL float FANN_API fann_train_epoch_incremental_mod(struct fann *ann, struct fann_train_data *data) { unsigned int i; fann_reset_MSE(ann); for(i = 0; i != data->num_data; i++) { fann_train(ann, data->input[i], data->output[i]); } return fann_get_MSE(ann); } #endif /* DISABLE_PARALLEL_FANN */
graph.h
// Copyright 2021 The Google Research 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 GRAPH_HPP #define GRAPH_HPP #include <chrono> // NOLINT #include <type_traits> #include <vector> #include "common.h" // NOLINT #include "mmapped_vector.h" // NOLINT #include "pkxsort.h" // NOLINT enum class GraphFormat { kNDE, kBinary, kBinaryStreamed }; enum class GraphPermutation { kNone, kDegreeOrder, kDegeneracyOrder }; GraphFormat ParseGraphFormat(const std::string &fmt) { if (fmt == "nde") return GraphFormat::kNDE; if (fmt == "bin") return GraphFormat::kBinary; if (fmt == "sbin") return GraphFormat::kBinaryStreamed; fprintf(stderr, "Invalid graph format.\n"); abort(); } template <typename node_t, typename edge_t> struct GraphT { static_assert(std::is_unsigned<node_t>::value, "node_t must be an unsigned type"); static_assert(std::is_unsigned<edge_t>::value, "edge_t must be an unsigned type"); // Graph fingerprints encode the size of edge and node types, which are // integral types of up to 8 bytes each. static constexpr size_t kFingerprint = (sizeof(edge_t) << 4) | sizeof(node_t); static constexpr size_t kFingerprintStreamed = kFingerprint | 1; mmapped_vector<edge_t> adj_start; mmapped_vector<node_t> adj; size_t N() const { return adj_start.size() - 1; } // Reads a graph from `filename` in the format specified by `format`. If // `permutation` is not `kNone`, the graph is permuted accordingly. If // `forward_only` is true, only edges {a, b} with a < b will be returned. // Otherwise, both pairs {a, b} and {b, a} will be present in the graph. Note // that `kDegeneracyOrder` is only valid if `forward_only == false`. void Read( const std::string &filename, GraphFormat format, GraphPermutation permutation, bool forward_only, std::chrono::high_resolution_clock::time_point *reading_done = nullptr, std::chrono::high_resolution_clock::time_point *permutation_computed = nullptr) { FILE *f = filename.empty() ? stdin : fopen(filename.c_str(), "r"); mmapped_vector<std::pair<node_t, node_t>> adj_pairs; // Temporarily deallocate adj. std::string backing_file = adj.BackingFile(); adj.clear(); // Read the graph. size_t N; switch (format) { case GraphFormat::kNDE: N = ReadNDEGraph(f, forward_only, backing_file, &adj_pairs); break; case GraphFormat::kBinary: N = ReadBinaryGraph(f, forward_only, backing_file, &adj_pairs); break; case GraphFormat::kBinaryStreamed: N = ReadBinaryStreamedGraph(f, forward_only, backing_file, &adj_pairs); break; default: fprintf(stderr, "Invalid graph format enum.\n"); abort(); } if (!filename.empty()) fclose(f); // Clean up duplicate edges. // TODO: external memory version fprintf(stderr, "Sorting...\n"); kx::radix_sort(adj_pairs.data(), adj_pairs.data() + adj_pairs.size(), EdgeRadixTraits()); fprintf(stderr, "Cleaning...\n"); adj_pairs.resize( std::unique(adj_pairs.data(), adj_pairs.data() + adj_pairs.size()) - adj_pairs.data()); fprintf(stderr, "Reading done\n"); if (reading_done) *reading_done = std::chrono::high_resolution_clock::now(); // Compute permutation and permute the graph. if (permutation != GraphPermutation::kNone) { CHECK(!forward_only || permutation == GraphPermutation::kDegreeOrder); std::vector<node_t> perm = permutation == GraphPermutation::kDegreeOrder ? ComputeDegreeOrder(N, &adj_pairs) : ComputeDegeneracyOrder(N, &adj_pairs); fprintf(stderr, "Permutation computed\n"); if (permutation_computed) { *permutation_computed = std::chrono::high_resolution_clock::now(); } std::vector<node_t> reverse_permutation(N); #pragma omp parallel for for (node_t i = 0; i < N; i++) { reverse_permutation[perm[i]] = i; } perm.clear(); #pragma omp parallel for for (size_t i = 0; i < adj.size(); i++) { std::pair<node_t, node_t> &e = adj_pairs[i]; e.first = reverse_permutation[e.first]; e.second = reverse_permutation[e.second]; if (forward_only && e.first > e.second) std::swap(e.first, e.second); } fprintf(stderr, "Sorting again...\n"); kx::radix_sort(adj_pairs.begin(), adj_pairs.end(), EdgeRadixTraits()); fprintf(stderr, "Permuting done\n"); } // Compute degrees, final adjacency lists and their start position. adj_start.resize(N + 1); std::fill(adj_start.begin(), adj_start.end(), 0); for (size_t i = 0; i < adj_pairs.size(); i++) { adj_start[adj_pairs[i].first + 1]++; } for (size_t i = 0; i < N; i++) { adj_start[i + 1] += adj_start[i]; } adj.reinterpret(std::move(adj_pairs)); // TODO: parallel for (edge_t i = 0; 2 * i + 1 < adj.size(); i += 1) { adj[i] = adj[2 * i + 1]; } adj.resize(adj.size() / 2); adj.shrink(); } private: struct EdgeRadixTraits { static const int nBytes = 2 * sizeof(node_t); size_t Value(const std::pair<node_t, node_t> &x) { return ((size_t)x.first << 32) | x.second; } int kth_byte(const std::pair<node_t, node_t> &x, int k) { return (Value(x) >> (8 * k)) & 0xff; } bool compare(const std::pair<node_t, node_t> &x, const std::pair<node_t, node_t> &y) { return Value(x) < Value(y); } }; size_t ReadNDEGraph(FILE *f, bool forward_only, const std::string &backing_file, mmapped_vector<std::pair<node_t, node_t>> *adj_pairs) { // Number of nodes (first line). size_t N = ReadBase10Fast<node_t>(f); // Degrees (N lines). node_t a, b; size_t expected_edges = 0; for (node_t i = 0; i < N; i++) { a = ReadBase10Fast<node_t>(f); b = ReadBase10Fast<node_t>(f); expected_edges += b; } adj_pairs->init(backing_file, expected_edges, /*reserve_only = */ true); // Edges (all other lines). while (true) { a = ReadBase10Fast<node_t>(f); b = ReadBase10Fast<node_t>(f); if (a == (node_t)EOF || b == (node_t)EOF) break; if (a == b) continue; if (forward_only && b < a) std::swap(a, b); adj_pairs->push_back({a, b}); if (!forward_only) adj_pairs->push_back({b, a}); } return N; } size_t ReadBinaryGraph(FILE *f, bool forward_only, const std::string &backing_file, mmapped_vector<std::pair<node_t, node_t>> *adj_pairs) { // Fingerprint. unsigned long long_t fingerprint = ReadBinaryOrDie<unsigned long long_t>(f); CHECK(fingerprint == kFingerprint); // Number of nodes. size_t N = ReadBinaryOrDie<node_t>(f); // Offsets of each adjacency list. adj_start.resize(N + 1); ReadBinaryOrDie(f, adj_start.data(), N + 1); std::vector<node_t> current_adj; adj_pairs->init(backing_file, adj_start.back(), /*reserve_only = */ true); // Edges. for (node_t i = 0; i < N; i++) { size_t degree = adj_start[i + 1] - adj_start[i]; current_adj.reserve(degree); ReadBinaryOrDie(f, current_adj.data(), degree); for (node_t j = 0; j < adj_start.size(); j++) { node_t a = i; node_t b = current_adj[j]; if (a == b) continue; if (forward_only && b < a) std::swap(a, b); adj_pairs->push_back({a, b}); if (!forward_only) adj_pairs->push_back({b, a}); } } return N; } size_t ReadBinaryStreamedGraph( FILE *f, bool forward_only, const std::string &backing_file, mmapped_vector<std::pair<node_t, node_t>> *adj_pairs) { // Fingerprint. unsigned long long_t fingerprint = ReadBinaryOrDie<unsigned long long_t>(f); CHECK(fingerprint == kFingerprintStreamed); // Number of nodes. size_t N = ReadBinaryOrDie<node_t>(f); adj_start.resize(N + 1); std::vector<node_t> current_adj; // Size is unknown at this point - we guess at least N. adj_pairs->init(backing_file, N, /*reserve_only = */ true); // Edges. for (node_t i = 0; i < N; i++) { // Degree. size_t degree = ReadBinaryOrDie<node_t>(f); current_adj.reserve(degree); ReadBinaryOrDie(f, current_adj.data(), degree); for (node_t j = 0; j < adj_start.size(); j++) { node_t a = i; node_t b = current_adj[j]; if (a == b) continue; if (forward_only && b < a) std::swap(a, b); adj_pairs->push_back({a, b}); if (!forward_only) adj_pairs->push_back({b, a}); } } return N; } struct DegreeRadixTraits { static const int nBytes = sizeof(node_t); int kth_byte(const node_t &x, int k) { return (degree[x] >> (8 * k)) & 0xff; } bool compare(const node_t &x, const node_t &y) { return degree[x] < degree[y]; } const std::vector<node_t> &degree; }; // Sort node by increasing order. std::vector<node_t> ComputeDegreeOrder( size_t N, mmapped_vector<std::pair<node_t, node_t>> *adj_pairs) { std::vector<node_t> permutation(N); std::vector<node_t> degree(N); #pragma omp parallel for for (node_t i = 0; i < N; i++) permutation[i] = i; #pragma omp parallel for for (size_t i = 0; i < adj.size(); i++) { degree[(*adj_pairs)[i].first]++; degree[(*adj_pairs)[i].second]++; } // TODO: external memory version kx::radix_sort(permutation.begin(), permutation.end(), DegreeRadixTraits{degree}); return permutation; } // Sort nodes in degeneracy order // (https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)) by iteratively // removing lowest-degree nodes. // Here, we assume that the graph is sufficiently small that // O(number_of_edges) fits in main memory. // TODO: avoid the extra copy of the edges. std::vector<node_t> ComputeDegeneracyOrder( size_t N, mmapped_vector<std::pair<node_t, node_t>> *adj_pairs) { std::vector<std::vector<node_t>> graph(N); for (auto edg : *adj_pairs) { graph[edg.first].push_back(edg.second); } std::vector<node_t> permutation; std::vector<std::vector<node_t>> nodes_by_degree(N); std::vector<node_t> degrees(N); std::vector<node_t> positions(N); std::vector<bool> used(N); std::vector<edge_t> adj_starts; for (node_t i = 0; i < N; i++) { nodes_by_degree[graph[i].size()].push_back(i); degrees[i] = graph[i].size(); positions[i] = nodes_by_degree[degrees[i]].size() - 1; } node_t j = 0; for (node_t i = 0; i < N; i++) { while (nodes_by_degree[j].empty()) j++; node_t v = nodes_by_degree[j].back(); nodes_by_degree[j].pop_back(); permutation.push_back(v); used[v] = true; for (auto g : graph[v]) { if (used[g]) continue; node_t &to_swap = nodes_by_degree[degrees[g]][positions[g]]; std::swap(to_swap, nodes_by_degree[degrees[g]].back()); positions[to_swap] = positions[g]; nodes_by_degree[degrees[g]].pop_back(); degrees[g]--; nodes_by_degree[degrees[g]].push_back(g); positions[g] = nodes_by_degree[degrees[g]].size() - 1; } if (j > 0) j--; } return permutation; } }; #endif
segment.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS EEEEE GGGG M M EEEEE N N TTTTT % % SS E G MM MM E NN N T % % SSS EEE G GGG M M M EEE N N N T % % SS E G G M M E N NN T % % SSSSS EEEEE GGGG M M EEEEE N N T % % % % % % MagickCore Methods to Segment an Image with Thresholding Fuzzy c-Means % % % % Software Design % % Cristy % % April 1993 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Segment segments an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % c-means technique. The scale-space filter analyzes the histograms of % the three color components of the image and identifies a set of % classes. The extents of each class is used to coarsely segment the % image with thresholding. The color associated with each class is % determined by the mean color of all pixels within the extents of a % particular class. Finally, any unclassified pixels are assigned to % the closest class with the fuzzy c-means technique. % % The fuzzy c-Means algorithm can be summarized as follows: % % o Build a histogram, one for each color component of the image. % % o For each histogram, successively apply the scale-space filter and % build an interval tree of zero crossings in the second derivative % at each scale. Analyze this scale-space ``fingerprint'' to % determine which peaks and valleys in the histogram are most % predominant. % % o The fingerprint defines intervals on the axis of the histogram. % Each interval contains either a minima or a maxima in the original % signal. If each color component lies within the maxima interval, % that pixel is considered ``classified'' and is assigned an unique % class number. % % o Any pixel that fails to be classified in the above thresholding % pass is classified using the fuzzy c-Means technique. It is % assigned to one of the classes discovered in the histogram analysis % phase. % % The fuzzy c-Means technique attempts to cluster a pixel by finding % the local minima of the generalized within group sum of squared error % objective function. A pixel is assigned to the closest class of % which the fuzzy membership has a maximum value. % % Segment is strongly based on software written by Andy Gallo, % University of Delaware. % % The following reference was used in creating this program: % % Young Won Lim, Sang Uk Lee, "On The Color Image Segmentation % Algorithm Based on the Thresholding and the Fuzzy c-Means % Techniques", Pattern Recognition, Volume 23, Number 9, pages % 935-952, 1990. % % */ #include "magick/studio.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/memory_.h" #include "magick/memory-private.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/string_.h" #include "magick/thread-private.h" /* Define declarations. */ #define MaxDimension 3 #define DeltaTau 0.5f #if defined(FastClassify) #define WeightingExponent 2.0 #define SegmentPower(ratio) (ratio) #else #define WeightingExponent 2.5 #define SegmentPower(ratio) pow(ratio,(double) (1.0/(weighting_exponent-1.0))); #endif #define Tau 5.2f /* Typedef declarations. */ typedef struct _ExtentPacket { MagickRealType center; ssize_t index, left, right; } ExtentPacket; typedef struct _Cluster { struct _Cluster *next; ExtentPacket red, green, blue; ssize_t count, id; } Cluster; typedef struct _IntervalTree { MagickRealType tau; ssize_t left, right; MagickRealType mean_stability, stability; struct _IntervalTree *sibling, *child; } IntervalTree; typedef struct _ZeroCrossing { MagickRealType tau, histogram[256]; short crossings[256]; } ZeroCrossing; /* Constant declarations. */ static const int Blue = 2, Green = 1, Red = 0, SafeMargin = 3, TreeLength = 600; /* Method prototypes. */ static MagickRealType OptimalTau(const ssize_t *,const double,const double,const double, const double,short *); static ssize_t DefineRegion(const short *,ExtentPacket *); static void FreeNodes(IntervalTree *), InitializeHistogram(const Image *,ssize_t **,ExceptionInfo *), ScaleSpace(const ssize_t *,const MagickRealType,MagickRealType *), ZeroCrossHistogram(MagickRealType *,const MagickRealType,short *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l a s s i f y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % Classify() defines one or more classes. Each pixel is thresholded to % determine which class it belongs to. If the class is not identified it is % assigned to the closest class based on the fuzzy c-Means technique. % % The format of the Classify method is: % % MagickBooleanType Classify(Image *image,short **extrema, % const MagickRealType cluster_threshold, % const MagickRealType weighting_exponent, % const MagickBooleanType verbose) % % A description of each parameter follows. % % o image: the image. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o cluster_threshold: This MagickRealType represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o weighting_exponent: Specifies the membership weighting exponent. % % o verbose: A value greater than zero prints detailed information about % the identified classes. % */ static MagickBooleanType Classify(Image *image,short **extrema, const MagickRealType cluster_threshold, const MagickRealType weighting_exponent,const MagickBooleanType verbose) { #define SegmentImageTag "Segment/Image" CacheView *image_view; Cluster *cluster, *head, *last_cluster, *next_cluster; ExceptionInfo *exception; ExtentPacket blue, green, red; MagickOffsetType progress; MagickRealType *free_squares; MagickStatusType status; register ssize_t i; register MagickRealType *squares; size_t number_clusters; ssize_t count, y; /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ status=MagickTrue; count=0; progress=0; exception=(&image->exception); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetPixelRed(p)); cluster->green.center+=(MagickRealType) ScaleQuantumToChar(GetPixelGreen(p)); cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetPixelBlue(p)); cluster->count++; break; } p++; } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_Classify) #endif proceed=SetImageProgress(image,SegmentImageTag,progress++, 2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } number_clusters=(size_t) count; if (verbose != MagickFalse) { /* Print cluster statistics. */ (void) FormatLocaleFile(stdout,"Fuzzy C-means Statistics\n"); (void) FormatLocaleFile(stdout,"===================\n\n"); (void) FormatLocaleFile(stdout,"\tCluster Threshold = %g\n",(double) cluster_threshold); (void) FormatLocaleFile(stdout,"\tWeighting Exponent = %g\n",(double) weighting_exponent); (void) FormatLocaleFile(stdout,"\tTotal Number of Clusters = %.20g\n\n", (double) number_clusters); /* Print the total number of points per cluster. */ (void) FormatLocaleFile(stdout,"\n\nNumber of Vectors Per Cluster\n"); (void) FormatLocaleFile(stdout,"=============================\n\n"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) (void) FormatLocaleFile(stdout,"Cluster #%.20g = %.20g\n",(double) cluster->id,(double) cluster->count); /* Print the cluster extents. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Extents: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"================"); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout, "%.20g-%.20g %.20g-%.20g %.20g-%.20g\n",(double) cluster->red.left,(double) cluster->red.right,(double) cluster->green.left,(double) cluster->green.right,(double) cluster->blue.left,(double) cluster->blue.right); } /* Print the cluster center values. */ (void) FormatLocaleFile(stdout, "\n\n\nCluster Center Values: (Vector Size: %d)\n",MaxDimension); (void) FormatLocaleFile(stdout,"====================="); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { (void) FormatLocaleFile(stdout,"\n\nCluster #%.20g\n\n",(double) cluster->id); (void) FormatLocaleFile(stdout,"%g %g %g\n",(double) cluster->red.center,(double) cluster->green.center,(double) cluster->blue.center); } (void) FormatLocaleFile(stdout,"\n"); } if (number_clusters > 256) ThrowBinaryException(ImageError,"TooManyClusters",image->filename); /* Speed up distance calculations. */ squares=(MagickRealType *) AcquireQuantumMemory(513UL,sizeof(*squares)); if (squares == (MagickRealType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); squares+=255; for (i=(-255); i <= 255; i++) squares[i]=(MagickRealType) i*(MagickRealType) i; /* Allocate image colormap. */ if (AcquireImageColormap(image,number_clusters) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); i=0; for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { image->colormap[i].red=ScaleCharToQuantum((unsigned char) (cluster->red.center+0.5)); image->colormap[i].green=ScaleCharToQuantum((unsigned char) (cluster->green.center+0.5)); image->colormap[i].blue=ScaleCharToQuantum((unsigned char) (cluster->blue.center+0.5)); i++; } /* Do course grain classes. */ exception=(&image->exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Cluster *cluster; register const PixelPacket *magick_restrict p; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(image_view); for (x=0; x < (ssize_t) image->columns; x++) { SetPixelIndex(indexes+x,0); for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) { if (((ssize_t) ScaleQuantumToChar(q->red) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->red) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->green) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->green) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->blue) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(q->blue) <= (cluster->blue.right+SafeMargin))) { /* Classify this pixel. */ SetPixelIndex(indexes+x,cluster->id); break; } } if (cluster == (Cluster *) NULL) { MagickRealType distance_squared, local_minima, numerator, ratio, sum; register ssize_t j, k; /* Compute fuzzy membership. */ local_minima=0.0; for (j=0; j < (ssize_t) image->colors; j++) { sum=0.0; p=image->colormap+j; distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)- (ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->green)- (ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->blue)- (ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]; numerator=distance_squared; for (k=0; k < (ssize_t) image->colors; k++) { p=image->colormap+k; distance_squared=squares[(ssize_t) ScaleQuantumToChar(q->red)- (ssize_t) ScaleQuantumToChar(GetPixelRed(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->green)- (ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]+ squares[(ssize_t) ScaleQuantumToChar(q->blue)- (ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]; ratio=numerator/distance_squared; sum+=SegmentPower(ratio); } if ((sum != 0.0) && ((1.0/sum) > local_minima)) { /* Classify this pixel. */ local_minima=1.0/sum; SetPixelIndex(indexes+x,j); } } } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_Classify) #endif proceed=SetImageProgress(image,SegmentImageTag,progress++, 2*image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); status&=SyncImage(image); /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } squares-=255; free_squares=squares; free_squares=(MagickRealType *) RelinquishMagickMemory(free_squares); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n s o l i d a t e C r o s s i n g s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConsolidateCrossings() guarantees that an even number of zero crossings % always lie between two crossings. % % The format of the ConsolidateCrossings method is: % % ConsolidateCrossings(ZeroCrossing *zero_crossing, % const size_t number_crossings) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void ConsolidateCrossings(ZeroCrossing *zero_crossing, const size_t number_crossings) { register ssize_t i, j, k, l; ssize_t center, correct, count, left, right; /* Consolidate zero crossings. */ for (i=(ssize_t) number_crossings-1; i >= 0; i--) for (j=0; j <= 255; j++) { if (zero_crossing[i].crossings[j] == 0) continue; /* Find the entry that is closest to j and still preserves the property that there are an even number of crossings between intervals. */ for (k=j-1; k > 0; k--) if (zero_crossing[i+1].crossings[k] != 0) break; left=MagickMax(k,0); center=j; for (k=j+1; k < 255; k++) if (zero_crossing[i+1].crossings[k] != 0) break; right=MagickMin(k,255); /* K is the zero crossing just left of j. */ for (k=j-1; k > 0; k--) if (zero_crossing[i].crossings[k] != 0) break; if (k < 0) k=0; /* Check center for an even number of crossings between k and j. */ correct=(-1); if (zero_crossing[i+1].crossings[j] != 0) { count=0; for (l=k+1; l < center; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (center != k)) correct=center; } /* Check left for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < left; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (left != k)) correct=left; } /* Check right for an even number of crossings between k and j. */ if (correct == -1) { count=0; for (l=k+1; l < right; l++) if (zero_crossing[i+1].crossings[l] != 0) count++; if (((count % 2) == 0) && (right != k)) correct=right; } l=(ssize_t) zero_crossing[i].crossings[j]; zero_crossing[i].crossings[j]=0; if (correct != -1) zero_crossing[i].crossings[correct]=(short) l; } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e f i n e R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DefineRegion() defines the left and right boundaries of a peak region. % % The format of the DefineRegion method is: % % ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) % % A description of each parameter follows. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % % o extents: This pointer to an ExtentPacket represent the extends % of a particular peak or valley of a color component. % */ static ssize_t DefineRegion(const short *extrema,ExtentPacket *extents) { /* Initialize to default values. */ extents->left=0; extents->center=0.0; extents->right=255; /* Find the left side (maxima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] > 0) break; if (extents->index > 255) return(MagickFalse); /* no left side - no region exists */ extents->left=extents->index; /* Find the right side (minima). */ for ( ; extents->index <= 255; extents->index++) if (extrema[extents->index] < 0) break; extents->right=extents->index-1; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e r i v a t i v e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DerivativeHistogram() determines the derivative of the histogram using % central differencing. % % The format of the DerivativeHistogram method is: % % DerivativeHistogram(const MagickRealType *histogram, % MagickRealType *derivative) % % A description of each parameter follows. % % o histogram: Specifies an array of MagickRealTypes representing the number % of pixels for each intensity of a particular color component. % % o derivative: This array of MagickRealTypes is initialized by % DerivativeHistogram to the derivative of the histogram using central % differencing. % */ static void DerivativeHistogram(const MagickRealType *histogram, MagickRealType *derivative) { register ssize_t i, n; /* Compute endpoints using second order polynomial interpolation. */ n=255; derivative[0]=(-1.5*histogram[0]+2.0*histogram[1]-0.5*histogram[2]); derivative[n]=(0.5*histogram[n-2]-2.0*histogram[n-1]+1.5*histogram[n]); /* Compute derivative using central differencing. */ for (i=1; i < n; i++) derivative[i]=(histogram[i+1]-histogram[i-1])/2.0; return; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e D y n a m i c T h r e s h o l d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageDynamicThreshold() returns the dynamic threshold for an image. % % The format of the GetImageDynamicThreshold method is: % % MagickBooleanType GetImageDynamicThreshold(const Image *image, % const double cluster_threshold,const double smooth_threshold, % MagickPixelPacket *pixel,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o cluster_threshold: This MagickRealType represents the minimum number of % pixels contained in a hexahedra before it can be considered valid % (expressed as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % % o pixel: return the dynamic threshold here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageDynamicThreshold(const Image *image, const double cluster_threshold,const double smooth_threshold, MagickPixelPacket *pixel,ExceptionInfo *exception) { Cluster *background, *cluster, *object, *head, *last_cluster, *next_cluster; ExtentPacket blue, green, red; MagickBooleanType proceed; MagickRealType threshold; register const PixelPacket *p; register ssize_t i, x; short *extrema[MaxDimension]; ssize_t count, *histogram[MaxDimension], y; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); GetMagickPixelPacket(image,pixel); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256UL,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256UL,sizeof(**histogram)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } } /* Initialize histogram. */ InitializeHistogram(image,histogram,exception); (void) OptimalTau(histogram[Red],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2f,DeltaTau, (smooth_threshold == 0.0f ? 1.0f : smooth_threshold),extrema[Blue]); /* Form clusters. */ cluster=(Cluster *) NULL; head=(Cluster *) NULL; (void) memset(&red,0,sizeof(red)); (void) memset(&green,0,sizeof(green)); (void) memset(&blue,0,sizeof(blue)); while (DefineRegion(extrema[Red],&red) != 0) { green.index=0; while (DefineRegion(extrema[Green],&green) != 0) { blue.index=0; while (DefineRegion(extrema[Blue],&blue) != 0) { /* Allocate a new class. */ if (head != (Cluster *) NULL) { cluster->next=(Cluster *) AcquireMagickMemory( sizeof(*cluster->next)); cluster=cluster->next; } else { cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); head=cluster; } if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; } } } if (head == (Cluster *) NULL) { /* No classes were identified-- create one. */ cluster=(Cluster *) AcquireMagickMemory(sizeof(*cluster)); if (cluster == (Cluster *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } /* Initialize a new class. */ cluster->count=0; cluster->red=red; cluster->green=green; cluster->blue=blue; cluster->next=(Cluster *) NULL; head=cluster; } /* Count the pixels for each cluster. */ count=0; for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { for (cluster=head; cluster != (Cluster *) NULL; cluster=cluster->next) if (((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) >= (cluster->red.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelRed(p)) <= (cluster->red.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) >= (cluster->green.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelGreen(p)) <= (cluster->green.right+SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) >= (cluster->blue.left-SafeMargin)) && ((ssize_t) ScaleQuantumToChar(GetPixelBlue(p)) <= (cluster->blue.right+SafeMargin))) { /* Count this pixel. */ count++; cluster->red.center+=(MagickRealType) ScaleQuantumToChar(GetPixelRed(p)); cluster->green.center+=(MagickRealType) ScaleQuantumToChar(GetPixelGreen(p)); cluster->blue.center+=(MagickRealType) ScaleQuantumToChar(GetPixelBlue(p)); cluster->count++; break; } p++; } proceed=SetImageProgress(image,SegmentImageTag,(MagickOffsetType) y, 2*image->rows); if (proceed == MagickFalse) break; } /* Remove clusters that do not meet minimum cluster threshold. */ count=0; last_cluster=head; next_cluster=head; for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; if ((cluster->count > 0) && (cluster->count >= (count*cluster_threshold/100.0))) { /* Initialize cluster. */ cluster->id=count; cluster->red.center/=cluster->count; cluster->green.center/=cluster->count; cluster->blue.center/=cluster->count; count++; last_cluster=cluster; continue; } /* Delete cluster. */ if (cluster == head) head=next_cluster; else last_cluster->next=next_cluster; cluster=(Cluster *) RelinquishMagickMemory(cluster); } object=head; background=head; if (count > 1) { object=head->next; for (cluster=object; cluster->next != (Cluster *) NULL; ) { if (cluster->count < object->count) object=cluster; cluster=cluster->next; } background=head->next; for (cluster=background; cluster->next != (Cluster *) NULL; ) { if (cluster->count > background->count) background=cluster; cluster=cluster->next; } } if (background != (Cluster *) NULL) { threshold=(background->red.center+object->red.center)/2.0; pixel->red=(MagickRealType) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->green.center+object->green.center)/2.0; pixel->green=(MagickRealType) ScaleCharToQuantum((unsigned char) (threshold+0.5)); threshold=(background->blue.center+object->blue.center)/2.0; pixel->blue=(MagickRealType) ScaleCharToQuantum((unsigned char) (threshold+0.5)); } /* Relinquish resources. */ for (cluster=head; cluster != (Cluster *) NULL; cluster=next_cluster) { next_cluster=cluster->next; cluster=(Cluster *) RelinquishMagickMemory(cluster); } for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeHistogram() computes the histogram for an image. % % The format of the InitializeHistogram method is: % % InitializeHistogram(const Image *image,ssize_t **histogram) % % A description of each parameter follows. % % o image: Specifies a pointer to an Image structure; returned from % ReadImage. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % */ static void InitializeHistogram(const Image *image,ssize_t **histogram, ExceptionInfo *exception) { register const PixelPacket *p; register ssize_t i, x; ssize_t y; /* Initialize histogram. */ for (i=0; i <= 255; i++) { histogram[Red][i]=0; histogram[Green][i]=0; histogram[Blue][i]=0; } for (y=0; y < (ssize_t) image->rows; y++) { p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const PixelPacket *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { histogram[Red][(ssize_t) ScaleQuantumToChar(GetPixelRed(p))]++; histogram[Green][(ssize_t) ScaleQuantumToChar(GetPixelGreen(p))]++; histogram[Blue][(ssize_t) ScaleQuantumToChar(GetPixelBlue(p))]++; p++; } } } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e I n t e r v a l T r e e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializeIntervalTree() initializes an interval tree from the lists of % zero crossings. % % The format of the InitializeIntervalTree method is: % % InitializeIntervalTree(IntervalTree **list,ssize_t *number_nodes, % IntervalTree *node) % % A description of each parameter follows. % % o zero_crossing: Specifies an array of structures of type ZeroCrossing. % % o number_crossings: This size_t specifies the number of elements % in the zero_crossing array. % */ static void InitializeList(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) list[(*number_nodes)++]=node; InitializeList(list,number_nodes,node->sibling); InitializeList(list,number_nodes,node->child); } static void MeanStability(IntervalTree *node) { register IntervalTree *child; if (node == (IntervalTree *) NULL) return; node->mean_stability=0.0; child=node->child; if (child != (IntervalTree *) NULL) { register ssize_t count; register MagickRealType sum; sum=0.0; count=0; for ( ; child != (IntervalTree *) NULL; child=child->sibling) { sum+=child->stability; count++; } node->mean_stability=sum/(MagickRealType) count; } MeanStability(node->sibling); MeanStability(node->child); } static void Stability(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->child == (IntervalTree *) NULL) node->stability=0.0; else node->stability=node->tau-(node->child)->tau; Stability(node->sibling); Stability(node->child); } static IntervalTree *InitializeIntervalTree(const ZeroCrossing *zero_crossing, const size_t number_crossings) { IntervalTree *head, **list, *node, *root; register ssize_t i; ssize_t j, k, left, number_nodes; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return((IntervalTree *) NULL); /* The root is the entire histogram. */ root=(IntervalTree *) AcquireCriticalMemory(sizeof(*root)); root->child=(IntervalTree *) NULL; root->sibling=(IntervalTree *) NULL; root->tau=0.0; root->left=0; root->right=255; root->mean_stability=0.0; root->stability=0.0; (void) memset(list,0,TreeLength*sizeof(*list)); for (i=(-1); i < (ssize_t) number_crossings; i++) { /* Initialize list with all nodes with no children. */ number_nodes=0; InitializeList(list,&number_nodes,root); /* Split list. */ for (j=0; j < number_nodes; j++) { head=list[j]; left=head->left; node=head; for (k=head->left+1; k < head->right; k++) { if (zero_crossing[i+1].crossings[k] != 0) { if (node == head) { node->child=(IntervalTree *) AcquireMagickMemory( sizeof(*node->child)); node=node->child; } else { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; } if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=k; left=k; } } if (left != head->left) { node->sibling=(IntervalTree *) AcquireMagickMemory( sizeof(*node->sibling)); node=node->sibling; if (node == (IntervalTree *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); FreeNodes(root); return((IntervalTree *) NULL); } node->tau=zero_crossing[i+1].tau; node->child=(IntervalTree *) NULL; node->sibling=(IntervalTree *) NULL; node->left=left; node->right=head->right; } } } /* Determine the stability: difference between a nodes tau and its child. */ Stability(root->child); MeanStability(root->child); list=(IntervalTree **) RelinquishMagickMemory(list); return(root); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p t i m a l T a u % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OptimalTau() finds the optimal tau for each band of the histogram. % % The format of the OptimalTau method is: % % MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau, % const double min_tau,const double delta_tau, % const double smooth_threshold,short *extrema) % % A description of each parameter follows. % % o histogram: Specifies an array of integers representing the number % of pixels for each intensity of a particular color component. % % o extrema: Specifies a pointer to an array of integers. They % represent the peaks and valleys of the histogram for each color % component. % */ static void ActiveNodes(IntervalTree **list,ssize_t *number_nodes, IntervalTree *node) { if (node == (IntervalTree *) NULL) return; if (node->stability >= node->mean_stability) { list[(*number_nodes)++]=node; ActiveNodes(list,number_nodes,node->sibling); } else { ActiveNodes(list,number_nodes,node->sibling); ActiveNodes(list,number_nodes,node->child); } } static void FreeNodes(IntervalTree *node) { if (node == (IntervalTree *) NULL) return; FreeNodes(node->sibling); FreeNodes(node->child); node=(IntervalTree *) RelinquishMagickMemory(node); } static MagickRealType OptimalTau(const ssize_t *histogram,const double max_tau, const double min_tau,const double delta_tau,const double smooth_threshold, short *extrema) { IntervalTree **list, *node, *root; MagickBooleanType peak; MagickRealType average_tau, *derivative, *second_derivative, tau, value; register ssize_t i, x; size_t count, number_crossings; ssize_t index, j, k, number_nodes; ZeroCrossing *zero_crossing; /* Allocate interval tree. */ list=(IntervalTree **) AcquireQuantumMemory((size_t) TreeLength, sizeof(*list)); if (list == (IntervalTree **) NULL) return(0.0); /* Allocate zero crossing list. */ count=(size_t) ((max_tau-min_tau)/delta_tau)+2; zero_crossing=(ZeroCrossing *) AcquireQuantumMemory((size_t) count, sizeof(*zero_crossing)); if (zero_crossing == (ZeroCrossing *) NULL) { list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } for (i=0; i < (ssize_t) count; i++) zero_crossing[i].tau=(-1.0); /* Initialize zero crossing list. */ derivative=(MagickRealType *) AcquireCriticalMemory(256*sizeof(*derivative)); second_derivative=(MagickRealType *) AcquireCriticalMemory(256* sizeof(*second_derivative)); i=0; for (tau=max_tau; tau >= min_tau; tau-=delta_tau) { zero_crossing[i].tau=tau; ScaleSpace(histogram,tau,zero_crossing[i].histogram); DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); i++; } /* Add an entry for the original histogram. */ zero_crossing[i].tau=0.0; for (j=0; j <= 255; j++) zero_crossing[i].histogram[j]=(MagickRealType) histogram[j]; DerivativeHistogram(zero_crossing[i].histogram,derivative); DerivativeHistogram(derivative,second_derivative); ZeroCrossHistogram(second_derivative,smooth_threshold, zero_crossing[i].crossings); number_crossings=(size_t) i; derivative=(MagickRealType *) RelinquishMagickMemory(derivative); second_derivative=(MagickRealType *) RelinquishMagickMemory(second_derivative); /* Ensure the scale-space fingerprints form lines in scale-space, not loops. */ ConsolidateCrossings(zero_crossing,number_crossings); /* Force endpoints to be included in the interval. */ for (i=0; i <= (ssize_t) number_crossings; i++) { for (j=0; j < 255; j++) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[0]=(-zero_crossing[i].crossings[j]); for (j=255; j > 0; j--) if (zero_crossing[i].crossings[j] != 0) break; zero_crossing[i].crossings[255]=(-zero_crossing[i].crossings[j]); } /* Initialize interval tree. */ root=InitializeIntervalTree(zero_crossing,number_crossings); if (root == (IntervalTree *) NULL) { zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(0.0); } /* Find active nodes: stability is greater (or equal) to the mean stability of its children. */ number_nodes=0; ActiveNodes(list,&number_nodes,root->child); /* Initialize extrema. */ for (i=0; i <= 255; i++) extrema[i]=0; for (i=0; i < number_nodes; i++) { /* Find this tau in zero crossings list. */ k=0; node=list[i]; for (j=0; j <= (ssize_t) number_crossings; j++) if (zero_crossing[j].tau == node->tau) k=j; /* Find the value of the peak. */ peak=zero_crossing[k].crossings[node->right] == -1 ? MagickTrue : MagickFalse; index=node->left; value=zero_crossing[k].histogram[index]; for (x=node->left; x <= node->right; x++) { if (peak != MagickFalse) { if (zero_crossing[k].histogram[x] > value) { value=zero_crossing[k].histogram[x]; index=x; } } else if (zero_crossing[k].histogram[x] < value) { value=zero_crossing[k].histogram[x]; index=x; } } for (x=node->left; x <= node->right; x++) { if (index == 0) index=256; if (peak != MagickFalse) extrema[x]=(short) index; else extrema[x]=(short) (-index); } } /* Determine the average tau. */ average_tau=0.0; for (i=0; i < number_nodes; i++) average_tau+=list[i]->tau; average_tau/=(MagickRealType) number_nodes; /* Relinquish resources. */ FreeNodes(root); zero_crossing=(ZeroCrossing *) RelinquishMagickMemory(zero_crossing); list=(IntervalTree **) RelinquishMagickMemory(list); return(average_tau); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S c a l e S p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ScaleSpace() performs a scale-space filter on the 1D histogram. % % The format of the ScaleSpace method is: % % ScaleSpace(const ssize_t *histogram,const MagickRealType tau, % MagickRealType *scale_histogram) % % A description of each parameter follows. % % o histogram: Specifies an array of MagickRealTypes representing the number % of pixels for each intensity of a particular color component. % */ static void ScaleSpace(const ssize_t *histogram,const MagickRealType tau, MagickRealType *scale_histogram) { double alpha, beta, *gamma, sum; register ssize_t u, x; gamma=(double *) AcquireQuantumMemory(256,sizeof(*gamma)); if (gamma == (double *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToAllocateGammaMap"); alpha=1.0/(tau*sqrt(2.0*MagickPI)); beta=(-1.0/(2.0*tau*tau)); for (x=0; x <= 255; x++) gamma[x]=0.0; for (x=0; x <= 255; x++) { gamma[x]=exp((double) beta*x*x); if (gamma[x] < MagickEpsilon) break; } for (x=0; x <= 255; x++) { sum=0.0; for (u=0; u <= 255; u++) sum+=(double) histogram[u]*gamma[MagickAbsoluteValue(x-u)]; scale_histogram[x]=(MagickRealType) (alpha*sum); } gamma=(double *) RelinquishMagickMemory(gamma); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e g m e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SegmentImage() segment an image by analyzing the histograms of the color % components and identifying units that are homogeneous with the fuzzy % C-means technique. % % The format of the SegmentImage method is: % % MagickBooleanType SegmentImage(Image *image, % const ColorspaceType colorspace,const MagickBooleanType verbose, % const double cluster_threshold,const double smooth_threshold) % % A description of each parameter follows. % % o image: the image. % % o colorspace: Indicate the colorspace. % % o verbose: Set to MagickTrue to print detailed information about the % identified classes. % % o cluster_threshold: This represents the minimum number of pixels % contained in a hexahedra before it can be considered valid (expressed % as a percentage). % % o smooth_threshold: the smoothing threshold eliminates noise in the second % derivative of the histogram. As the value is increased, you can expect a % smoother second derivative. % */ MagickExport MagickBooleanType SegmentImage(Image *image, const ColorspaceType colorspace,const MagickBooleanType verbose, const double cluster_threshold,const double smooth_threshold) { ColorspaceType previous_colorspace; MagickBooleanType status; register ssize_t i; short *extrema[MaxDimension]; ssize_t *histogram[MaxDimension]; /* Allocate histogram and extrema. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); for (i=0; i < MaxDimension; i++) { histogram[i]=(ssize_t *) AcquireQuantumMemory(256,sizeof(**histogram)); extrema[i]=(short *) AcquireQuantumMemory(256,sizeof(**extrema)); if ((histogram[i] == (ssize_t *) NULL) || (extrema[i] == (short *) NULL)) { for (i-- ; i >= 0; i--) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename) } } /* Initialize histogram. */ previous_colorspace=image->colorspace; (void) TransformImageColorspace(image,colorspace); InitializeHistogram(image,histogram,&image->exception); (void) OptimalTau(histogram[Red],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Red]); (void) OptimalTau(histogram[Green],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Green]); (void) OptimalTau(histogram[Blue],Tau,0.2,DeltaTau, smooth_threshold == 0.0 ? 1.0 : smooth_threshold,extrema[Blue]); /* Classify using the fuzzy c-Means technique. */ status=Classify(image,extrema,cluster_threshold,WeightingExponent,verbose); (void) TransformImageColorspace(image,previous_colorspace); /* Relinquish resources. */ for (i=0; i < MaxDimension; i++) { extrema[i]=(short *) RelinquishMagickMemory(extrema[i]); histogram[i]=(ssize_t *) RelinquishMagickMemory(histogram[i]); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Z e r o C r o s s H i s t o g r a m % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ZeroCrossHistogram() find the zero crossings in a histogram and marks % directions as: 1 is negative to positive; 0 is zero crossing; and -1 % is positive to negative. % % The format of the ZeroCrossHistogram method is: % % ZeroCrossHistogram(MagickRealType *second_derivative, % const MagickRealType smooth_threshold,short *crossings) % % A description of each parameter follows. % % o second_derivative: Specifies an array of MagickRealTypes representing the % second derivative of the histogram of a particular color component. % % o crossings: This array of integers is initialized with % -1, 0, or 1 representing the slope of the first derivative of the % of a particular color component. % */ static void ZeroCrossHistogram(MagickRealType *second_derivative, const MagickRealType smooth_threshold,short *crossings) { register ssize_t i; ssize_t parity; /* Merge low numbers to zero to help prevent noise. */ for (i=0; i <= 255; i++) if ((second_derivative[i] < smooth_threshold) && (second_derivative[i] >= -smooth_threshold)) second_derivative[i]=0.0; /* Mark zero crossings. */ parity=0; for (i=0; i <= 255; i++) { crossings[i]=0; if (second_derivative[i] < 0.0) { if (parity > 0) crossings[i]=(-1); parity=1; } else if (second_derivative[i] > 0.0) { if (parity < 0) crossings[i]=1; parity=(-1); } } }
exdot_omp.h
/* * %%%%%%%%%%%%%%%%%%%%%%%Original development%%%%%%%%%%%%%%%%%%%%%%%%% * Copyright (c) 2016 Inria and University Pierre and Marie Curie * %%%%%%%%%%%%%%%%%%%%%%%Modifications and further additions%%%%%%%%%% * Matthias Wiesenberger, 2017, within FELTOR and EXBLAS licenses */ /** * @file exdot_omp.h * @brief OpenMP version of exdot * * @authors * Developers : \n * Roman Iakymchuk -- roman.iakymchuk@lip6.fr \n * Sylvain Collange -- sylvain.collange@inria.fr \n * Matthias Wiesenberger -- mattwi@fysik.dtu.dk */ #pragma once #include <cassert> #include <cstdlib> #include <cstdio> #include <cmath> #include <iostream> #include "accumulate.h" #include "ExSUM.FPE.hpp" #include <omp.h> namespace dg { namespace exblas{ ///@cond namespace cpu{ //MW: does this implementation code a manual lock? /** * \brief Parallel reduction step * * \param step step among threads * \param acc1 superaccumulator of the first thread * \param acc2 superaccumulator of the second thread */ inline static void ReductionStep(int step, int64_t * acc1, int64_t * acc2, int volatile * ready) { #ifndef _WITHOUT_VCL _mm_prefetch((char const*)ready, _MM_HINT_T0); // Wait for thread 2 to be ready while(*ready < step) { // wait _mm_pause(); } #endif//_WITHOUT_VCL int imin = IMIN, imax = IMAX; Normalize( acc1, imin, imax); imin = IMIN, imax = IMAX; Normalize( acc2, imin, imax); for(int i = IMIN; i <= IMAX; ++i) { acc1[i] += acc2[i]; } } /** * \brief Final step of summation -- Parallel reduction among threads * * \param tid thread ID * \param tnum number of threads * \param acc superaccumulator */ inline static void Reduction(unsigned int tid, unsigned int tnum, std::vector<int32_t>& ready, std::vector<int64_t>& acc, int const linesize) { // Custom tree reduction for(unsigned int s = 1; (unsigned)(1 << (s-1)) < tnum; ++s) { // 1<<(s-1) = 0001, 0010, 0100, ... = 1,2,4,8,16,... int32_t volatile * c = &ready[tid * linesize]; ++*c; //set: ready for level s #ifdef _WITHOUT_VCL #pragma omp barrier //all threads are ready for level s #endif if(tid % (1 << s) == 0) { //1<<s = 2,4,8,16,32,... //only the tid thread executes this block, tid2 just sets ready unsigned int tid2 = tid | (1 << (s-1)); //effectively adds 1, 2, 4,... if(tid2 < tnum) { ReductionStep(s, &acc[tid*BIN_COUNT], &acc[tid2*BIN_COUNT], &ready[tid2 * linesize]); } } } } template<typename CACHE, typename PointerOrValue1, typename PointerOrValue2> void ExDOTFPE(int N, PointerOrValue1 a, PointerOrValue2 b, int64_t* h_superacc, bool* err) { // OpenMP sum+reduction int const linesize = 16; // * sizeof(int32_t) int maxthreads = omp_get_max_threads(); std::vector<int64_t> acc(maxthreads*BIN_COUNT,0); std::vector<int32_t> ready(maxthreads * linesize); std::vector<bool> error( maxthreads, false); #pragma omp parallel { unsigned int tid = omp_get_thread_num(); unsigned int tnum = omp_get_num_threads(); CACHE cache(&acc[tid*BIN_COUNT]); *(int32_t volatile *)(&ready[tid * linesize]) = 0; // Race here, who cares? #ifndef _WITHOUT_VCL int l = ((tid * int64_t(N)) / tnum) & ~7ul; // & ~7ul == round down to multiple of 8 int r = ((((tid+1) * int64_t(N)) / tnum) & ~7ul) - 1; for(int i = l; i < r; i+=8) { #ifndef _MSC_VER asm ("# myloop"); #endif //vcl::Vec8d r1 ; //vcl::Vec8d x = TwoProductFMA(make_vcl_vec8d(a,i), make_vcl_vec8d(b,i), r1); vcl::Vec8d x = make_vcl_vec8d(a,i)*make_vcl_vec8d(b,i); //MW: check sanity of input vcl::Vec8db finite = vcl::is_finite( x); if( !vcl::horizontal_and( finite) ) error[tid] = true; cache.Accumulate(x); //cache.Accumulate(r1); //MW: exact product but halfs the speed } if( tid+1==tnum && r != N-1) { r+=1; //accumulate remainder //vcl::Vec8d r1; //vcl::Vec8d x = TwoProductFMA(make_vcl_vec8d(a,r,N-r), make_vcl_vec8d(b,r,N-r), r1); vcl::Vec8d x = make_vcl_vec8d(a,r,N-r)*make_vcl_vec8d(b,r,N-r); //MW: check sanity of input vcl::Vec8db finite = vcl::is_finite( x); if( !vcl::horizontal_and( finite) ) error[tid] = true; cache.Accumulate(x); //cache.Accumulate(r1); } #else// _WITHOUT_VCL int l = ((tid * int64_t(N)) / tnum); int r = ((((tid+1) * int64_t(N)) / tnum) ) - 1; for(int i = l; i <= r; i++) { //double r1; //double x = TwoProductFMA(get_element(a,i),get_element(b,i),r1); double x = get_element(a,i)*get_element(b,i); cache.Accumulate(x); //cache.Accumulate(r1); } #endif// _WITHOUT_VCL cache.Flush(); int imin=IMIN, imax=IMAX; Normalize(&acc[tid*BIN_COUNT], imin, imax); Reduction(tid, tnum, ready, acc, linesize); } for( int i=IMIN; i<=IMAX; i++) h_superacc[i] = acc[i]; for ( int i=0; i<maxthreads; i++) if( error[i] == true) *err = true; } template<typename CACHE, typename PointerOrValue1, typename PointerOrValue2, typename PointerOrValue3> void ExDOTFPE(int N, PointerOrValue1 a, PointerOrValue2 b, PointerOrValue3 c, int64_t* h_superacc, bool* err) { // OpenMP sum+reduction int const linesize = 16; // * sizeof(int32_t) (MW avoid false sharing?) int maxthreads = omp_get_max_threads(); std::vector<int64_t> acc(maxthreads*BIN_COUNT,0); std::vector<int32_t> ready(maxthreads * linesize); std::vector<bool> error( maxthreads, false); #pragma omp parallel { unsigned int tid = omp_get_thread_num(); unsigned int tnum = omp_get_num_threads(); CACHE cache(&acc[tid*BIN_COUNT]); *(int32_t volatile *)(&ready[tid * linesize]) = 0; // Race here, who cares? #ifndef _WITHOUT_VCL int l = ((tid * int64_t(N)) / tnum) & ~7ul;// & ~7ul == round down to multiple of 8 int r = ((((tid+1) * int64_t(N)) / tnum) & ~7ul) - 1; for(int i = l; i < r; i+=8) { #ifndef _MSC_VER asm ("# myloop"); #endif //vcl::Vec8d r1 , r2, cvec = vcl::Vec8d().load(c+i); //vcl::Vec8d x = TwoProductFMA(vcl::Vec8d().load(a+i), vcl::Vec8d().load(b+i), r1); //vcl::Vec8d x2 = TwoProductFMA(x , cvec, r2); //vcl::Vec8d x1 = vcl::mul_add(vcl::Vec8d().load(a+i),vcl::Vec8d().load(b+i), 0); //vcl::Vec8d x2 = vcl::mul_add( x1 ,vcl::Vec8d().load(c+i), 0); vcl::Vec8d x1 = make_vcl_vec8d(a,i)*make_vcl_vec8d(b,i); vcl::Vec8d x2 = x1 *make_vcl_vec8d(c,i); vcl::Vec8db finite = vcl::is_finite( x2); if( !vcl::horizontal_and( finite) ) error[tid] = true; cache.Accumulate(x2); //cache.Accumulate(r2); //x2 = TwoProductFMA(r1, cvec, r2); //cache.Accumulate(x2); //cache.Accumulate(r2); } if( tid+1 == tnum && r != N-1) { r+=1; //accumulate remainder //vcl::Vec8d r1 , r2, cvec = vcl::Vec8d().load_partial(N-r, c+r); //vcl::Vec8d x = TwoProductFMA(vcl::Vec8d().load_partial(N-r, a+r), vcl::Vec8d().load_partial(N-r,b+r), r1); //vcl::Vec8d x2 = TwoProductFMA(x , cvec, r2); //vcl::Vec8d x1 = vcl::mul_add(vcl::Vec8d().load_partial(N-r, a+r),vcl::Vec8d().load_partial(N-r,b+r), 0); //vcl::Vec8d x2 = vcl::mul_add( x1 ,vcl::Vec8d().load_partial(N-r,c+r), 0); vcl::Vec8d x1 = make_vcl_vec8d(a,r,N-r)*make_vcl_vec8d(b,r,N-r); vcl::Vec8d x2 = x1 *make_vcl_vec8d(c,r,N-r); vcl::Vec8db finite = vcl::is_finite( x2); if( !vcl::horizontal_and( finite) ) error[tid] = true; cache.Accumulate(x2); //cache.Accumulate(r2); //x2 = TwoProductFMA(r1, cvec, r2); //cache.Accumulate(x2); //cache.Accumulate(r2); } #else// _WITHOUT_VCL int l = ((tid * int64_t(N)) / tnum); int r = ((((tid+1) * int64_t(N)) / tnum) ) - 1; for(int i = l; i <= r; i++) { //double x1 = a[i]*b[i]; //double x2 = x1*c[i]; double x1 = get_element(a,i)*get_element(b,i); double x2 = x1*get_element(c,i); cache.Accumulate(x2); } #endif// _WITHOUT_VCL cache.Flush(); int imin=IMIN, imax=IMAX; Normalize(&acc[tid*BIN_COUNT], imin, imax); Reduction(tid, tnum, ready, acc, linesize); } for( int i=IMIN; i<=IMAX; i++) h_superacc[i] = acc[i]; for ( int i=0; i<maxthreads; i++) if( error[i] == true) *err = true; } }//namespace cpu ///@endcond ///@brief OpenMP parallel version of exact triple dot product ///@copydoc hide_exdot2 ///@copydoc hide_hostacc template<class PointerOrValue1, class PointerOrValue2, size_t NBFPE=8> void exdot_omp(unsigned size, PointerOrValue1 x1_ptr, PointerOrValue2 x2_ptr, int64_t* h_superacc, int* status){ static_assert( has_floating_value<PointerOrValue1>::value, "PointerOrValue1 needs to be T or T* with T one of (const) float or (const) double"); static_assert( has_floating_value<PointerOrValue2>::value, "PointerOrValue2 needs to be T or T* with T one of (const) float or (const) double"); bool error = false; #ifndef _WITHOUT_VCL cpu::ExDOTFPE<cpu::FPExpansionVect<vcl::Vec8d, NBFPE, cpu::FPExpansionTraits<true> > >((int)size,x1_ptr,x2_ptr, h_superacc, &error); #else cpu::ExDOTFPE<cpu::FPExpansionVect<double, NBFPE, cpu::FPExpansionTraits<true> > >((int)size,x1_ptr,x2_ptr, h_superacc, &error); #endif//_WITHOUT_VCL *status = 0; if( error ) *status = 1; } ///@brief OpenMP parallel version of exact triple dot product ///@copydoc hide_exdot3 ///@copydoc hide_hostacc template<class PointerOrValue1, class PointerOrValue2, class PointerOrValue3, size_t NBFPE=8> void exdot_omp(unsigned size, PointerOrValue1 x1_ptr, PointerOrValue2 x2_ptr, PointerOrValue3 x3_ptr, int64_t* h_superacc, int* status) { static_assert( has_floating_value<PointerOrValue1>::value, "PointerOrValue1 needs to be T or T* with T one of (const) float or (const) double"); static_assert( has_floating_value<PointerOrValue2>::value, "PointerOrValue2 needs to be T or T* with T one of (const) float or (const) double"); static_assert( has_floating_value<PointerOrValue3>::value, "PointerOrValue3 needs to be T or T* with T one of (const) float or (const) double"); bool error = false; #ifndef _WITHOUT_VCL cpu::ExDOTFPE<cpu::FPExpansionVect<vcl::Vec8d, NBFPE, cpu::FPExpansionTraits<true> > >((int)size,x1_ptr,x2_ptr, x3_ptr, h_superacc, &error); #else cpu::ExDOTFPE<cpu::FPExpansionVect<double, NBFPE, cpu::FPExpansionTraits<true> > >((int)size,x1_ptr,x2_ptr, x3_ptr, h_superacc, &error); #endif//_WITHOUT_VCL *status = 0; if( error ) *status = 1; } }//namespace exblas } //namespace dg
rawSHA512_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2010 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. * * Rewritten Spring 2013, JimF. SSE code added and released with the following terms: * No copyright is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2011 JimF * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_raw0_SHA512; #elif FMT_REGISTERS_H john_register_one(&fmt_raw0_SHA512); #else #include "arch.h" #include "sha2.h" #include "stdint.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "formats.h" #include "rawSHA512_common.h" //#undef SIMD_COEF_64 //#undef SIMD_PARA_SHA512 /* * Only effective for SIMD. * Undef to disable reversing steps for benchmarking. */ #define REVERSE_STEPS #ifdef _OPENMP #ifdef SIMD_COEF_64 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-SHA512" #define FORMAT_NAME "" #ifdef SIMD_COEF_64 #define ALGORITHM_NAME SHA512_ALGORITHM_NAME #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #endif #ifdef SIMD_COEF_64 #define PLAINTEXT_LENGTH 111 #else #define PLAINTEXT_LENGTH 125 #endif #define BINARY_SIZE 8 #define SALT_SIZE 0 #define SALT_ALIGN 1 #ifdef SIMD_COEF_64 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #ifdef SIMD_COEF_64 #define GETPOS(i, index) ( (index&(SIMD_COEF_64-1))*8 + ((i)&(0xffffffff-7))*SIMD_COEF_64 + (7-((i)&7)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64*8 ) static ARCH_WORD_64 (*saved_key); static ARCH_WORD_64 (*crypt_out); #else static int (*saved_len); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_64 (*crypt_out)[DIGEST_SIZE / sizeof(ARCH_WORD_64)]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; 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 #ifndef SIMD_COEF_64 saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); #else saved_key = mem_calloc_align(self->params.max_keys_per_crypt * SHA_BUF_SIZ, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_out = mem_calloc_align(self->params.max_keys_per_crypt * 8, sizeof(*crypt_out), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); #ifndef SIMD_COEF_64 MEM_FREE(saved_len); #endif } static void *get_binary(char *ciphertext) { static ARCH_WORD_64 *outw; unsigned char *out; char *p; int i; if (!outw) outw = mem_calloc_tiny(DIGEST_SIZE, BINARY_ALIGN); out = (unsigned char*)outw; p = ciphertext + TAG_LENGTH; for (i = 0; i < DIGEST_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef SIMD_COEF_64 alter_endianity_to_BE64(out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha512_reverse(outw); #endif #endif return out; } #ifdef SIMD_COEF_64 #define HASH_IDX (((unsigned int)index&(SIMD_COEF_64-1))+(unsigned int)index/SIMD_COEF_64*8*SIMD_COEF_64) static int get_hash_0 (int index) { return crypt_out[HASH_IDX] & PH_MASK_0; } static int get_hash_1 (int index) { return crypt_out[HASH_IDX] & PH_MASK_1; } static int get_hash_2 (int index) { return crypt_out[HASH_IDX] & PH_MASK_2; } static int get_hash_3 (int index) { return crypt_out[HASH_IDX] & PH_MASK_3; } static int get_hash_4 (int index) { return crypt_out[HASH_IDX] & PH_MASK_4; } static int get_hash_5 (int index) { return crypt_out[HASH_IDX] & PH_MASK_5; } static int get_hash_6 (int index) { return crypt_out[HASH_IDX] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } #endif static int binary_hash_0(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_0; } static int binary_hash_1(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_1; } static int binary_hash_2(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_2; } static int binary_hash_3(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_3; } static int binary_hash_4(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_4; } static int binary_hash_5(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_5; } static int binary_hash_6(void *binary) { return ((ARCH_WORD_64*)binary)[0] & PH_MASK_6; } static void set_key(char *key, int index) { #ifdef SIMD_COEF_64 #if ARCH_ALLOWS_UNALIGNED const ARCH_WORD_64 *wkey = (ARCH_WORD_64*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint64_t)); const ARCH_WORD_64 *wkey = is_aligned(key, sizeof(uint64_t)) ? (ARCH_WORD_64*)key : (ARCH_WORD_64*)strcpy(buf_aligned, key); #endif ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64*)saved_key)[(index&(SIMD_COEF_64-1)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64]; ARCH_WORD_64 *keybuf_word = keybuffer; unsigned int len; ARCH_WORD_64 temp; len = 0; while((unsigned char)(temp = *wkey++)) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24)); len+=3; goto key_cleaning; } if (!(temp & 0xff00000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32)); len+=4; goto key_cleaning; } if (!(temp & 0xff0000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40)); len+=5; goto key_cleaning; } if (!(temp & 0xff000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48)); len+=6; goto key_cleaning; } if (!(temp & 0xff00000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56)); len+=7; goto key_cleaning; } *keybuf_word = JOHNSWAP64(temp); len += 8; keybuf_word += SIMD_COEF_64; } *keybuf_word = 0x8000000000000000ULL; key_cleaning: keybuf_word += SIMD_COEF_64; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_64; } keybuffer[15*SIMD_COEF_64] = len << 3; #else int len = strlen(key); saved_len[index] = len; if (len > PLAINTEXT_LENGTH) len = saved_len[index] = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, len); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_64 unsigned i; ARCH_WORD_64 s; static char out[PLAINTEXT_LENGTH + 1]; unsigned char *wucp = (unsigned char*)saved_key; s = ((ARCH_WORD_64*)saved_key)[15*SIMD_COEF_64 + (index&(SIMD_COEF_64-1)) + index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64] >> 3; for(i = 0; i < (unsigned)s; i++) out[i] = wucp[ GETPOS(i, index) ]; out[i] = 0; return (char*) out; #else saved_key[index][saved_len[index]] = 0; return saved_key[index]; #endif } #ifndef REVERSE_STEPS #undef SSEi_REVERSE_STEPS #define SSEi_REVERSE_STEPS 0 #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_64 SIMDSHA512body(&saved_key[index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64], &crypt_out[index/SIMD_COEF_64*8*SIMD_COEF_64], NULL, SSEi_REVERSE_STEPS | SSEi_MIXED_IN); #else SHA512_CTX ctx; SHA512_Init(&ctx); SHA512_Update(&ctx, saved_key[index], saved_len[index]); SHA512_Final((unsigned char *)crypt_out[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_64 if (((ARCH_WORD_64*)binary)[0] == crypt_out[HASH_IDX]) #else if ( ((ARCH_WORD_64*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_64 return ((ARCH_WORD_64*)binary)[0] == crypt_out[HASH_IDX]; #else return *(ARCH_WORD_64*)binary == crypt_out[index][0]; #endif } static int cmp_exact(char *source, int index) { ARCH_WORD_64 *binary = get_binary(source); char *key = get_key(index); SHA512_CTX ctx; ARCH_WORD_64 crypt_out[DIGEST_SIZE / sizeof(ARCH_WORD_64)]; SHA512_Init(&ctx); SHA512_Update(&ctx, key, strlen(key)); SHA512_Final((unsigned char*)crypt_out, &ctx); #ifdef SIMD_COEF_64 alter_endianity_to_BE64(crypt_out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha512_reverse(crypt_out); #endif #endif return !memcmp(binary, crypt_out, DIGEST_SIZE); } /* * The '0_' makes sure this format registers before others, * if ambiguous. Do not copy it for other formats. */ struct fmt_main fmt_raw0_SHA512 = { { FORMAT_LABEL, FORMAT_NAME, "SHA512 " 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 | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE, { NULL }, { FORMAT_TAG, XSHA512_FORMAT_TAG, NSLDAP_FORMAT_TAG }, sha512_common_tests_rawsha512_111 }, { init, done, fmt_default_reset, fmt_default_prepare, sha512_common_valid, sha512_common_split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { binary_hash_0, binary_hash_1, binary_hash_2, binary_hash_3, binary_hash_4, binary_hash_5, binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
numint_uniform_grid.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. * * Fast numerical integration on uniform grids. * (See also cp2k multigrid algorithm) * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <assert.h> #include <complex.h> #include "config.h" #include "cint.h" #include "np_helper/np_helper.h" #include "gto/grid_ao_drv.h" #include "vhf/fblas.h" #ifndef __USE_ISOC99 #define rint(x) (int)round(x) #endif #define PLAIN 0 #define HERMITIAN 1 #define ANTIHERMI 2 #define SYMMETRIC 3 #define OF_CMPLX 2 #define EIJCUTOFF 60 #define EXPMAX 700 #define EXPMIN -700 #define MAX_THREADS 256 #define PTR_EXPDROP 16 #define SQUARE(x) (*(x) * *(x) + *(x+1) * *(x+1) + *(x+2) * *(x+2)) double CINTsquare_dist(const double *r1, const double *r2); double CINTcommon_fac_sp(int l); static const int _LEN_CART[] = { 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 66, 78, 91, 105, 120, 136 }; static const int _CUM_LEN_CART[] = { 1, 4, 10, 20, 35, 56, 84, 120, 165, 220, 286, 364, 455, 560, 680, 816, }; static int _MAX_RR_SIZE[] = { 1, 4, 12, 30, 60, 120, 210, 350, 560, 840, 1260, 1800, 2520, 3465, 4620, 6160, 8008, 10296, 13104, 16380, 20475, }; /* * WHEREX_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if x > 0] * WHEREY_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if y > 0] * WHEREZ_IF_L_INC1 = [xyz2addr(x,y,z) for x,y,z in loopcart(L_MAX) if z > 0] */ static const int _UPIDY[] = { 1, 3, 4, 6, 7, 8, 10, 11, 12, 13, 15, 16, 17, 18, 19, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31, 32, 33, 34, 36, 37, 38, 39, 40, 41, 42, 43, 45, 46, 47, 48, 49, 50, 51, 52, 53, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103, 105,106,107,108,109,110,111,112,113,114,115,116,117,118, 120,121,122,123,124,125,126,127,128,129,130,131,132,133,134, }; static const int _UPIDZ[] = { 2, 4, 5, 7, 8, 9, 11, 12, 13, 14, 16, 17, 18, 19, 20, 22, 23, 24, 25, 26, 27, 29, 30, 31, 32, 33, 34, 35, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104, 106,107,108,109,110,111,112,113,114,115,116,117,118,119, 121,122,123,124,125,126,127,128,129,130,131,132,133,134,135, }; #define WHEREX_IF_L_INC1(i) i #define WHEREY_IF_L_INC1(i) _UPIDY[i] #define WHEREZ_IF_L_INC1(i) _UPIDZ[i] #define STARTX_IF_L_DEC1(l) 0 #define STARTY_IF_L_DEC1(l) (((l)<2)?0:_LEN_CART[(l)-2]) #define STARTZ_IF_L_DEC1(l) (_LEN_CART[(l)-1]-1) void GTOplain_vrr2d_ket_inc1(double *out, const double *g, double *rirj, int li, int lj); /* (li+lj,0) => (li,lj) */ // Input g is used as buffer in the iterations. // Ensure size of g > _MAX_RR_SIZE[li+lj] static void _plain_vrr2d(double *out, double *g, double *gbuf2, int li, int lj, double *ri, double *rj) { const int nmax = li + lj; double *g00, *g01, *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00; int i, j; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; g00 = gbuf2; g01 = g; for (j = 1; j < lj; j++) { gswap = g00; g00 = g01; g01 = gswap; pg00 = g00; pg01 = g01; for (i = li; i <= nmax-j; i++) { GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; col_01 = _LEN_CART[j]; row_00 = _LEN_CART[i ]; col_00 = _LEN_CART[j-1]; pg00 += row_00*col_00; pg01 += row_01*col_01; } } GTOplain_vrr2d_ket_inc1(out, g01, rirj, li, lj); } /* * rcut is the distance over which the integration (from rcut to infty) is * smaller than the required precision * integral ~= \int_{rcut}^infty r^{l+2} exp(-alpha r^2) dr * * * if l is odd: * integral = \sum_n (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n * * exp(-alpha {rcut}^2) * * * elif l is even and rcut > 1: * integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n * + 1/(2 alpha)^(l/2+2)] * exp(-alpha {rcut}^2) * * * elif l is even and rcut < 1: * integral < [\sum_{n<=l/2+1} (l+1)!!/(l+3-2n)!! * rcut^{l+3-2n}/(2 alpha)^n] * exp(-alpha {rcut}^2) * + (l+1)!! / (2 alpha)^{l/2+1} * \sqrt(pi/alpha)/2 */ static double gto_rcut(double alpha, int l, double c, double log_prec) { double log_c = log(fabs(c)); double prod = 0; double r = 10.; double log_2a = log(2*alpha); double log_r = log(r); if (2*log_r + log_2a > 1) { // r^2 >~ 3/(2a) prod = (l+1) * log_r - log_2a; } else { prod = -(l+4)/2 * log_2a; } //log_r = .5 * (prod / alpha); //if (2*log_r + log_2a > 1) { // prod = (l+1) * log_r - log_2a; //} else { // prod = -(l+4)/2 * log_2a; //} prod += log_c - log_prec; if (prod < alpha) { // if rcut < 1, estimating based on exp^{-a*rcut^2} prod = log_c - log_prec; } if (prod > 0) { r = sqrt(prod / alpha); } else { r = 0; } return r; } static int _has_overlap(int nx0, int nx1, int nx_per_cell) { return nx0 < nx1 + 3; } static int _num_grids_on_x(int nimgx, int nx0, int nx1, int nx_per_cell) { int ngridx; if (nimgx == 1) { ngridx = nx1 - nx0; } else if (nimgx == 2 && !_has_overlap(nx0, nx1, nx_per_cell)) { ngridx = nx1 - nx0 + nx_per_cell; } else { ngridx = nx_per_cell; } return ngridx; } static int _orth_components(double *xs_exp, int *img_slice, int *grid_slice, double a, double b, double cutoff, double xi, double xj, double ai, double aj, int periodic, int nx_per_cell, int topl, int offset, int submesh, double *cache) { double aij = ai + aj; double xij = (ai * xi + aj * xj) / aij; double heights_inv = b; double xij_frac = xij * heights_inv; double edge0 = xij_frac - cutoff * heights_inv; double edge1 = xij_frac + cutoff * heights_inv; if (edge0 == edge1) { // cutoff may be so small that it does not provide difference to edge0 and // edge1. When edge0 and edge1 are right on the edge of the box (== integer), // nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition. return 0; } int nimg0 = 0; int nimg1 = 1; // If submesh is not identical to mesh, it means the product of the basis // functions should be completely inside the unit cell. Only one image needs to // be considered. if (offset != 0 || submesh != nx_per_cell) { // |i> is the steep function and centered inside image 0. Moving |j> all around // will not change the center of |ij>. The periodic system can be treated as // non-periodic system so that only one image needs to be considered. nimg0 = (int)floor(xij_frac); nimg1 = nimg0 + 1; edge0 = MAX(edge0, nimg0); edge1 = MIN(edge1, nimg1); } else if (periodic) { nimg0 = (int)floor(edge0); nimg1 = (int)ceil (edge1); } int nimg = nimg1 - nimg0; int nmx0 = nimg0 * nx_per_cell; int nmx1 = nimg1 * nx_per_cell; int nmx = nmx1 - nmx0; int nx0 = (int)floor(edge0 * nx_per_cell); int nx1 = (int)ceil (edge1 * nx_per_cell); int nx0_edge; int nx1_edge; // to ensure nx0, nx1 being inside the unit cell if (periodic) { nx0 = (nx0 - nmx0) % nx_per_cell; nx1 = (nx1 - nmx0) % nx_per_cell; if (nx1 == 0) { nx1 = nx_per_cell; } } // If only 1 image is required, after drawing the grids to the unit cell // as above, the periodic system can be treated as a non-periodic // system, which requires [nx0:nx1] being inside submesh. It is // necessary because xij+/-cutoff may be out of the submesh for periodic // systems when offset and submesh are specified. if (nimg == 1) { nx0 = MIN(nx0, offset + submesh); nx0 = MAX(nx0, offset); nx1 = MIN(nx1, offset + submesh); nx1 = MAX(nx1, offset); nx0_edge = nx0; nx1_edge = nx1; } else { nx0_edge = 0; nx1_edge = nmx; } img_slice[0] = nimg0; img_slice[1] = nimg1; grid_slice[0] = nx0; grid_slice[1] = nx1; int ngridx = _num_grids_on_x(nimg, nx0, nx1, nx_per_cell); if (ngridx == 0) { return 0; } int i, m, l; double *px0; double *gridx = cache; double *xs_all = cache + nmx; if (nimg == 1) { xs_all = xs_exp; } int grid_close_to_xij = rint(xij_frac * nx_per_cell) - nmx0; grid_close_to_xij = MIN(grid_close_to_xij, nx1_edge); grid_close_to_xij = MAX(grid_close_to_xij, nx0_edge); double img0_x = a * nimg0; double dx = a / nx_per_cell; double base_x = img0_x + dx * grid_close_to_xij; double x0xij = base_x - xij; double _x0x0 = -aij * x0xij * x0xij; if (_x0x0 < EXPMIN) { return 0; } double _dxdx = -aij * dx * dx; double _x0dx = -2 * aij * x0xij * dx; double exp_dxdx = exp(_dxdx); double exp_2dxdx = exp_dxdx * exp_dxdx; double exp_x0dx = exp(_x0dx + _dxdx); double exp_x0x0 = exp(_x0x0); for (i = grid_close_to_xij; i < nx1_edge; i++) { xs_all[i] = exp_x0x0; exp_x0x0 *= exp_x0dx; exp_x0dx *= exp_2dxdx; } exp_x0dx = exp(_dxdx - _x0dx); exp_x0x0 = exp(_x0x0); for (i = grid_close_to_xij-1; i >= nx0_edge; i--) { exp_x0x0 *= exp_x0dx; exp_x0dx *= exp_2dxdx; xs_all[i] = exp_x0x0; } if (topl > 0) { double x0xi = img0_x - xi; for (i = nx0_edge; i < nx1_edge; i++) { gridx[i] = x0xi + i * dx; } for (l = 1; l <= topl; l++) { px0 = xs_all + (l-1) * nmx; for (i = nx0_edge; i < nx1_edge; i++) { px0[nmx+i] = px0[i] * gridx[i]; } } } if (nimg > 1) { for (l = 0; l <= topl; l++) { px0 = xs_all + l * nmx; for (i = 0; i < nx_per_cell; i++) { xs_exp[l*nx_per_cell+i] = px0[i]; } for (m = 1; m < nimg; m++) { px0 = xs_all + l * nmx + m*nx_per_cell; for (i = 0; i < nx_per_cell; i++) { xs_exp[l*nx_per_cell+i] += px0[i]; } } } } return ngridx; } static int _init_orth_data(double **xs_exp, double **ys_exp, double **zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, int topl, int dimension, double cutoff, double ai, double aj, double *ri, double *rj, double *a, double *b, double *cache) { int l1 = topl + 1; *xs_exp = cache; *ys_exp = *xs_exp + l1 * mesh[0]; *zs_exp = *ys_exp + l1 * mesh[1]; int data_size = l1 * (mesh[0] + mesh[1] + mesh[2]); cache += data_size; int ngridx = _orth_components(*xs_exp, img_slice, grid_slice, a[0], b[0], cutoff, ri[0], rj[0], ai, aj, (dimension>=1), mesh[0], topl, offset[0], submesh[0], cache); if (ngridx == 0) { return 0; } int ngridy = _orth_components(*ys_exp, img_slice+2, grid_slice+2, a[4], b[4], cutoff, ri[1], rj[1], ai, aj, (dimension>=2), mesh[1], topl, offset[1], submesh[1], cache); if (ngridy == 0) { return 0; } int ngridz = _orth_components(*zs_exp, img_slice+4, grid_slice+4, a[8], b[8], cutoff, ri[2], rj[2], ai, aj, (dimension>=3), mesh[2], topl, offset[2], submesh[2], cache); if (ngridz == 0) { return 0; } return data_size; } static void _orth_ints(double *out, double *weights, int floorl, int topl, double fac, double *xs_exp, double *ys_exp, double *zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, double *cache) { int l1 = topl + 1; int nimgx0 = img_slice[0]; int nimgx1 = img_slice[1]; int nimgy0 = img_slice[2]; int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; int nimgx = nimgx1 - nimgx0; int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]); int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]); //int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]); const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; int xcols = mesh[1] * mesh[2]; int ycols = mesh[2]; double *weightyz = cache; double *weightz = weightyz + l1*xcols; double *pz, *pweightz; double val; int lx, ly, lz; int l, i, n; //TODO: optimize the case in which nimgy << mesh[1] and nimgz << mesh[2] if (nimgx == 1) { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx, &fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh, &D0, weightyz, &xcols); } else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &nx1, &fac, weights, &xcols, xs_exp, mesh, &D0, weightyz, &xcols); ngridx = mesh[0] - nx0; dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, &ngridx, &fac, weights+nx0*xcols, &xcols, xs_exp+nx0, mesh, &D1, weightyz, &xcols); } else { dgemm_(&TRANS_N, &TRANS_N, &xcols, &l1, mesh, &fac, weights, &xcols, xs_exp, mesh, &D0, weightyz, &xcols); } if (nimgy == 1) { for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy, &D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); // call _orth_dot_z if ngridz << nimgz } } else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) { ngridy = mesh[1] - ny0; for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ny1, &D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, &ngridy, &D1, weightyz+lx*xcols+ny0*ycols, &ycols, ys_exp+ny0, mesh+1, &D1, weightz+lx*l1*ycols, &ycols); // call _orth_dot_z if ngridz << nimgz } } else { for (lx = 0; lx <= topl; lx++) { dgemm_(&TRANS_N, &TRANS_N, &ycols, &l1, mesh+1, &D1, weightyz+lx*xcols, &ycols, ys_exp, mesh+1, &D0, weightz+lx*l1*ycols, &ycols); } } if (nimgz == 1) { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = nz0; i < nz1; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = 0; i < nz1; i++) { val += pweightz[i] * pz[i]; } for (i = nz0; i < mesh[2]; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } else { for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; pz = zs_exp + lz * mesh[2]; pweightz = weightz + (lx * l1 + ly) * mesh[2]; val = 0; for (i = 0; i < mesh[2]; i++) { val += pweightz[i] * pz[i]; } out[n] = val; } } } } } int NUMINTeval_lda_orth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int offset_g1d = _CUM_LEN_CART[floorl] - _LEN_CART[floorl]; int len_g3d = _CUM_LEN_CART[topl] - offset_g1d; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); double *g3d = cache; cache += len_g3d; int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return 0; } cache += data_size; _orth_ints(g3d, weights, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); cache = g3d + _MAX_RR_SIZE[topl]; _plain_vrr2d(out, g3d, cache, li, lj, ri, rj); return 1; } static void _rr_nablax_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREX_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { //lz = li_1 - lx - ly; fac = lx + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREX_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _rr_nablay_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREY_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { //lz = li_1 - lx - ly; fac = ly + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREY_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _rr_nablaz_i(double *out, double *li_up, double *li_down, int li, int lj, double ai) { int di = _LEN_CART[li]; int di1 = _LEN_CART[li+1]; int dj = _LEN_CART[lj]; int li_1 = li - 1; int i, j, lx, ly, lz; double fac = -2 * ai; for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { out[di*j+i] += li_up[di1*j+WHEREZ_IF_L_INC1(i)] * fac; } } if (li_1 >= 0) { di1 = _LEN_CART[li_1]; for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac = lz + 1; for (j = 0; j < dj; j++) { out[di*j+WHEREZ_IF_L_INC1(i)] += li_down[di1*j+i] * fac; } } } } } static void _plain_vrr2d_updown(double *out_up, double *out_down, double *g, double *gbuf2, int li, int lj, double *ri, double *rj) { int nmax = li + 1 + lj; int li_1 = MAX(li - 1, 0); double *g00, *g01, *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00; int i, j; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; g00 = gbuf2; g01 = g; for (j = 1; j < lj; j++) { gswap = g00; g00 = g01; g01 = gswap; pg00 = g00; pg01 = g01; for (i = li_1; i <= nmax-j; i++) { GTOplain_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; col_01 = _LEN_CART[j]; row_00 = _LEN_CART[i ]; col_00 = _LEN_CART[j-1]; pg00 += row_00*col_00; pg01 += row_01*col_01; } } if (li == 0) { g01 += _LEN_CART[MAX(lj-1, 0)]; } else { GTOplain_vrr2d_ket_inc1(out_down, g01, rirj, li_1, lj); g01 += (_LEN_CART[li_1] + _LEN_CART[li]) * _LEN_CART[MAX(lj-1, 0)]; } GTOplain_vrr2d_ket_inc1(out_up, g01, rirj, li+1, lj); } int NUMINTeval_gga_orth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = MAX(li - 1, 0); int topl = li + 1 + lj; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); double *out_up = cache; double *out_down = out_up + _LEN_CART[li+1] * dj; double *g3d = out_down + di * dj; cache = g3d + _MAX_RR_SIZE[topl]; int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return 0; } cache += data_size; size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2]; double *vx = weights + ngrids; double *vy = vx + ngrids; double *vz = vy + ngrids; _orth_ints(g3d, weights, li, li+lj, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d(out, g3d, cache, li, lj, ri, rj); _orth_ints(g3d, vx, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablax_i(out, out_up, out_down, li, lj, ai); _orth_ints(g3d, vy, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablay_i(out, out_up, out_down, li, lj, ai); _orth_ints(g3d, vz, floorl, topl, fac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); _plain_vrr2d_updown(out_up, out_down, g3d, cache, li, lj, ri, rj); _rr_nablaz_i(out, out_up, out_down, li, lj, ai); return 1; } static int _MAX_AFFINE_SIZE[] = { 1, 8, 32, 108, 270, 640, 1280, 2500, 4375, 7560, 12096, 19208, 28812, 43008, 61440, 87480, }; /* * x = a00 x' + a10 y' + a20 z' * y = a01 x' + a11 y' + a21 z' * z = a02 x' + a12 y' + a22 z' * Given f(x',y',z') use the above equations to evaluate f(x,y,z) */ static void _affine_trans(double *out, double *int3d, double *a, int floorl, int topl, double *cache) { if (topl == 0) { out[0] = int3d[0]; return; } int lx, ly, lz, l, m, n, i; int l1, l1l1, l1l1l1, lll; double *old = int3d; double *new = cache + _MAX_AFFINE_SIZE[topl]; double *oldx, *oldy, *oldz, *newx, *tmp; double vx, vy, vz; if (floorl == 0) { out[0] = int3d[0]; out += 1; } for (m = 1, l = topl; m <= topl; m++, l--) { l1 = l + 1; l1l1 = l1 * l1; lll = l * l * l; l1l1l1 = l1l1 * l1; newx = new; // attach x for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[0] + vy * a[3] + vz * a[6]; } } } newx += lll; } // attach y for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[1] + vy * a[4] + vz * a[7]; } } } newx += lll; } // attach z i = STARTZ_IF_L_DEC1(m); oldx = old + i * l1l1l1 + l1l1; oldy = old + i * l1l1l1 + l1; oldz = old + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { vx = oldx[lx*l1l1+ly*l1+lz]; vy = oldy[lx*l1l1+ly*l1+lz]; vz = oldz[lx*l1l1+ly*l1+lz]; newx[n] = vx * a[2] + vy * a[5] + vz * a[8]; } } } if (floorl <= m) { for (i = 0; i < _LEN_CART[m]; i++) { out[i] = new[i * lll]; } out += _LEN_CART[m]; } if (m == 1) { old = new; new = cache; } else { tmp = old; old = new; new = tmp; } } } static void _reverse_affine_trans(double *out3d, double *in, double *a, int floorl, int topl, double *cache) { if (topl == 0) { out3d[0] = in[0]; return; } int lx, ly, lz, l, m, n, i; int l1, l1l1, l1l1l1, lll; double *cart = in; double *old = cache; double *new = cache + _MAX_AFFINE_SIZE[topl]; double *oldx, *newx, *newy, *newz, *tmp; for (l = floorl; l <= topl; l++) { cart += _LEN_CART[l]; } for (l = 1, m = topl; l <= topl; l++, m--) { l1 = l + 1; l1l1 = l1 * l1; lll = l * l * l; l1l1l1 = l1l1 * l1; if (l == topl) { new = out3d; } for (n = 0; n < l1l1l1*_LEN_CART[m-1]; n++) { new[n] = 0; } if (floorl <= m) { cart -= _LEN_CART[m]; for (i = 0; i < _LEN_CART[m]; i++) { old[i * lll] = cart[i]; } } oldx = old; // attach x for (i = STARTX_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[0] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[3] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[6] * oldx[n]; } } } oldx += lll; } // attach y for (i = STARTY_IF_L_DEC1(m); i < _LEN_CART[m-1]; i++) { newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[1] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[4] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[7] * oldx[n]; } } } oldx += lll; } // attach z i = STARTZ_IF_L_DEC1(m); newx = new + i * l1l1l1 + l1l1; newy = new + i * l1l1l1 + l1; newz = new + i * l1l1l1 + 1; for (n = 0, lx = 0; lx < l; lx++) { for (ly = 0; ly < l; ly++) { for (lz = 0; lz < l; lz++, n++) { newx[lx*l1l1+ly*l1+lz] += a[2] * oldx[n]; newy[lx*l1l1+ly*l1+lz] += a[5] * oldx[n]; newz[lx*l1l1+ly*l1+lz] += a[8] * oldx[n]; } } } tmp = new; new = old; old = tmp; } if (floorl == 0) { out3d[0] = in[0]; } } static int _nonorth_components(double *xs_exp, int *img_slice, int *grid_slice, double *b, int periodic, int nx_per_cell, int topl, int offset, int submesh, double xi_frac, double xij_frac, double cutoff) { double heights_inv = sqrt(SQUARE(b)); double edge0 = xij_frac - cutoff * heights_inv; double edge1 = xij_frac + cutoff * heights_inv; if (edge0 == edge1) { // cutoff may be so small that it does not provide difference to edge0 and // edge1. When edge0 and edge1 are right on the edge of the box (== integer), // nimg0 may be equal to nimg1 and nimg can be 0. Skip this extreme condition. return 0; } int nimg0 = 0; int nimg1 = 1; // If submesh is not identical to mesh, it means the product of the basis // functions should be completely inside the unit cell. Only one image needs to // be considered. if (offset != 0 || submesh != nx_per_cell) { // |i> is the steep function and centered inside image 0. Moving |j> all around // will not change the center of |ij>. The periodic system can be treated as // non-periodic system so that only one image needs to be considered. nimg0 = (int)floor(xij_frac); nimg1 = nimg0 + 1; edge0 = MAX(edge0, nimg0); edge1 = MIN(edge1, nimg1); } else if (periodic) { nimg0 = (int)floor(edge0); nimg1 = (int)ceil (edge1); } int nimg = nimg1 - nimg0; int nmx0 = nimg0 * nx_per_cell; int nx0 = (int)floor(edge0 * nx_per_cell); int nx1 = (int)ceil (edge1 * nx_per_cell); if (nimg == 1) { nx0 = MIN(nx0, nmx0 + offset + submesh); nx0 = MAX(nx0, nmx0 + offset); nx1 = MIN(nx1, nmx0 + offset + submesh); nx1 = MAX(nx1, nmx0 + offset); } img_slice[0] = nimg0; img_slice[1] = nimg1; grid_slice[0] = nx0; grid_slice[1] = nx1; int nx = nx1 - nx0; if (nx <= 0) { return 0; } int i, l; double x0; double dx = 1. / nx_per_cell; double *pxs_exp; for (i = 0; i < nx; i++) { xs_exp[i] = 1; } for (l = 1; l <= topl; l++) { pxs_exp = xs_exp + (l-1) * nx; x0 = nx0 * dx - xi_frac; for (i = 0; i < nx; i++, x0+=dx) { xs_exp[l*nx+i] = x0 * pxs_exp[i]; } } return nx; } static void _nonorth_dot_z(double *val, double *weights, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { int iz, iz1; if (e_z0z0 == 0) { for (iz = 0; iz < nz1-nz0; iz++) { val[iz] = 0; } return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; //:iz1 = grid_close_to_zij % meshz + meshz; //:for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { //: if (iz1 >= meshz) { //: iz1 -= meshz; //: } //: val[iz] = weights[iz1] * exp_z0z0; //: exp_z0z0 *= exp_z0dz; //: exp_z0dz *= exp_2dzdz; //:} iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } iz = grid_close_to_zij-nz0; while (iz+meshz-iz1 < nz1-nz0) { for (; iz1 < meshz; iz1++, iz++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } iz1 = 0; } for (; iz < nz1-nz0; iz++, iz1++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } //:iz1 = (grid_close_to_zij-1) % meshz; //:for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { //: if (iz1 < 0) { //: iz1 += meshz; //: } //: exp_z0z0 *= exp_z0dz; //: exp_z0dz *= exp_2dzdz; //: val[iz] = weights[iz1] * exp_z0z0; //:} iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } iz = grid_close_to_zij-nz0 - 1; while (iz-iz1 >= 0) { for (; iz1 >= 0; iz1--, iz--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } iz1 = meshz - 1; } for (; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } } static void _nonorth_dot_z_1img(double *val, double *weights, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { int iz, iz1; if (e_z0z0 == 0) { for (iz = 0; iz < nz1-nz0; iz++) { val[iz] = 0; } return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { val[iz] = weights[iz1] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; val[iz] = weights[iz1] * exp_z0z0; } } static void _nonorth_ints(double *out, double *weights, double fac, double aij, int topl, int dimension, double *a, double *rij_frac, int *mesh, int *img_slice, int *grid_slice, double *xs_exp, double *ys_exp, double *zs_exp, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int l1l1l1 = l1l1 * l1; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = nx1 - nx0; int ngridy = ny1 - ny0; int ngridz = nz1 - nz0; //int nimgx0 = img_slice[0]; //int nimgx1 = img_slice[1]; //int nimgy0 = img_slice[2]; //int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; //int nimgx = nimgx1 - nimgx0; //int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; // aa = einsum('ij,kj->ik', a, a) //double aa[9]; //int n3 = 3; //dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3, // &aij, a, &n3, a, &n3, &D0, aa, &n3); double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]); double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]); double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]); double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]); double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]); int ix, iy, ix1, iy1, n; double dx = 1. / mesh[0]; double dy = 1. / mesh[1]; double dz = 1. / mesh[2]; double *cache_xyz = cache; double *weight_x = cache_xyz + l1l1l1; double *weight_z = weight_x + l1l1 * ngridx; double *weight_yz = weight_z + l1 * ngridz; double *pweights; //int grid_close_to_xij = rint(rij_frac[0] * mesh[0]); int grid_close_to_yij = rint(rij_frac[1] * mesh[1]); int grid_close_to_zij = rint(rij_frac[2] * mesh[2]); //grid_close_to_xij = MIN(grid_close_to_xij, nx1); //grid_close_to_xij = MAX(grid_close_to_xij, nx0); grid_close_to_yij = MIN(grid_close_to_yij, ny1); grid_close_to_yij = MAX(grid_close_to_yij, ny0); grid_close_to_zij = MIN(grid_close_to_zij, nz1); grid_close_to_zij = MAX(grid_close_to_zij, nz0); double img0_x = 0; double img0_y = 0; double img0_z = 0; double base_x = img0_x;// + dx * grid_close_to_xij; double base_y = img0_y + dy * grid_close_to_yij; double base_z = img0_z + dz * grid_close_to_zij; double x0xij = base_x - rij_frac[0]; double y0yij = base_y - rij_frac[1]; double z0zij = base_z - rij_frac[2]; double _dydy = -dy * dy * aa_yy; double _dzdz = -dz * dz * aa_zz; double _dydz = -dy * dz * aa_yz * 2; double exp_dydy = exp(_dydy); double exp_2dydy = exp_dydy * exp_dydy; double exp_dzdz = exp(_dzdz); double exp_dydz = exp(_dydz); double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz; double x1xij, tmpx, tmpy, tmpz; double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz; double exp_xyz0xyz0, exp_xyz0dz; double exp_y0dy, exp_z0z0, exp_z0dz; ix1 = nx0 % mesh[0] + mesh[0]; for (ix = nx0; ix < nx1; ix++, ix1++) { if (ix1 >= mesh[0]) { ix1 -= mesh[0]; } x1xij = x0xij + ix*dx; tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz; tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz; tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz; _xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz; if (_xyz0xyz0 < EXPMIN) { // _xyz0dy (and _xyz0dz) can be very big, even greater than the effective range // of exp function (and produce inf). When exp_xyz0xyz0 is 0 and exp_xyz0dy is // inf, the product will be ill-defined. |_xyz0dy| should be smaller than // |_xyz0xyz0| in any situations. exp_xyz0xyz0 should dominate the product // exp_xyz0xyz0 * exp_xyz0dy. When exp_xyz0xyz0 is 0, the product should be 0. // All the rest exp products should be smaller than exp_xyz0xyz0 and can be // neglected. pweights = weight_x + (ix-nx0)*l1l1; for (n = 0; n < l1l1; n++) { pweights[n] = 0; } continue; } _xyz0dy = -2 * dy * tmpy; _xyz0dz = -2 * dz * tmpz; exp_xyz0xyz0 = fac * exp(_xyz0xyz0); exp_xyz0dz = exp(_xyz0dz); //exp_xyz0dy = exp(_xyz0dy); //exp_y0dy = exp_xyz0dy * exp_dydy; exp_y0dy = exp(_xyz0dy + _dydy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = grid_close_to_yij % mesh[1] + mesh[1]; for (iy = grid_close_to_yij; iy < ny1; iy++, iy1++) { if (iy1 >= mesh[1]) { iy1 -= mesh[1]; } pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2]; if (nimgz == 1) { _nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } _z0dz += _dydz; exp_z0z0 *= exp_y0dy; exp_z0dz *= exp_dydz; exp_y0dy *= exp_2dydy; } exp_y0dy = exp(_dydy - _xyz0dy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = (grid_close_to_yij-1) % mesh[1]; for (iy = grid_close_to_yij-1; iy >= ny0; iy--, iy1--) { if (iy1 < 0) { iy1 += mesh[1]; } exp_z0z0 *= exp_y0dy; exp_y0dy *= exp_2dydy; _z0dz -= _dydz; if (exp_dydz != 0) { exp_z0dz *= exp_dydz_i; } else { exp_z0dz = exp(_z0dz); } pweights = weights + (ix1 * mesh[1] + iy1) * mesh[2]; if (nimgz == 1) { _nonorth_dot_z_1img(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_dot_z(weight_yz+(iy-ny0)*ngridz, pweights, mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1, &ngridy, &D1, weight_yz, &ngridz, ys_exp, &ngridy, &D0, weight_z, &ngridz); dgemm_(&TRANS_T, &TRANS_N, &l1, &l1, &ngridz, &D1, zs_exp, &ngridz, weight_z, &ngridz, &D0, weight_x+(ix-nx0)*l1l1, &l1); } dgemm_(&TRANS_N, &TRANS_N, &l1l1, &l1, &ngridx, &D1, weight_x, &l1l1, xs_exp, &ngridx, &D0, out, &l1l1); } static void _make_rij_frac(double *ri_frac, double *rij_frac, double *ri, double *rj, double ai, double aj, double *a, double *b) { double aij = ai + aj; double rij[3]; rij[0] = (ai * ri[0] + aj * rj[0]) / aij; rij[1] = (ai * ri[1] + aj * rj[1]) / aij; rij[2] = (ai * ri[2] + aj * rj[2]) / aij; // rij_frac = einsum('ij,j->ik', b, rij) rij_frac[0] = rij[0] * b[0] + rij[1] * b[1] + rij[2] * b[2]; rij_frac[1] = rij[0] * b[3] + rij[1] * b[4] + rij[2] * b[5]; rij_frac[2] = rij[0] * b[6] + rij[1] * b[7] + rij[2] * b[8]; ri_frac[0] = ri[0] * b[0] + ri[1] * b[1] + ri[2] * b[2]; ri_frac[1] = ri[0] * b[3] + ri[1] * b[4] + ri[2] * b[5]; ri_frac[2] = ri[0] * b[6] + ri[1] * b[7] + ri[2] * b[8]; } static int _init_nonorth_data(double **xs_exp, double **ys_exp, double **zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, int topl, int dimension, double cutoff, double *a, double *b, double *ri_frac, double *rij_frac, double *cache) { int l1 = topl + 1; *xs_exp = cache; int ngridx = _nonorth_components(*xs_exp, img_slice, grid_slice, b, (dimension>=1), mesh[0], topl, offset[0], submesh[0], ri_frac[0], rij_frac[0], cutoff); if (ngridx == 0) { return 0; } *ys_exp = *xs_exp + l1 * ngridx; int ngridy = _nonorth_components(*ys_exp, img_slice+2, grid_slice+2, b+3, (dimension>=2), mesh[1], topl, offset[1], submesh[1], ri_frac[1], rij_frac[1], cutoff); if (ngridy == 0) { return 0; } *zs_exp = *ys_exp + l1 * ngridy; int ngridz = _nonorth_components(*zs_exp, img_slice+4, grid_slice+4, b+6, (dimension>=3), mesh[2], topl, offset[2], submesh[2], ri_frac[2], rij_frac[2], cutoff); if (ngridz == 0) { return 0; } int data_size = l1 * (ngridx + ngridy + ngridz); return data_size; } int NUMINTeval_lda_nonorth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, mesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return 0; } cache += data_size; double *g3d = cache; double *buf = g3d + l1 * l1 * l1; cache = buf + _MAX_RR_SIZE[topl]; _nonorth_ints(g3d, weights, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d(out, buf, cache, li, lj, ri, rj); return 1; } int NUMINTeval_gga_nonorth(double *weights, double *out, int comp, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = MAX(li - 1, 0); int topl = li + 1 + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, mesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return 0; } cache += data_size; int dj = _LEN_CART[lj]; double *g3d = cache; double *buf = g3d + l1 * l1 * l1; double *out_up = cache; double *out_down = out_up + _LEN_CART[li+1] * dj; cache = buf + _MAX_RR_SIZE[topl]; size_t ngrids = ((size_t)mesh[0]) * mesh[1] * mesh[2]; double *vx = weights + ngrids; double *vy = vx + ngrids; double *vz = vy + ngrids; _nonorth_ints(g3d, weights, fac, aij, li+lj, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, li, li+lj, cache); _plain_vrr2d(out, buf, cache, li, lj, ri, rj); _nonorth_ints(g3d, vx, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablax_i(out, out_up, out_down, li, lj, ai); _nonorth_ints(g3d, vy, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablay_i(out, out_up, out_down, li, lj, ai); _nonorth_ints(g3d, vz, fac, aij, topl, dimension, a, rij_frac, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); _affine_trans(buf, g3d, a, floorl, topl, cache); _plain_vrr2d_updown(out_up, out_down, buf, cache, li, lj, ri, rj); _rr_nablaz_i(out, out_up, out_down, li, lj, ai); return 1; } static void _apply_ints(int (*eval_ints)(), double *weights, double *mat, size_t *dims, int comp, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, int *shls, int *atm, int *bas, double *env, double *cache) { int i_sh = shls[0]; int j_sh = shls[1]; int li = bas(ANG_OF, i_sh); int lj = bas(ANG_OF, j_sh); double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh)); double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh)); double ai = env[bas(PTR_EXP, i_sh)]; double aj = env[bas(PTR_EXP, j_sh)]; double ci = env[bas(PTR_COEFF, i_sh)]; double cj = env[bas(PTR_COEFF, j_sh)]; double aij = ai + aj; double rrij = CINTsquare_dist(ri, rj); double eij = (ai * aj / aij) * rrij; if (eij > EIJCUTOFF) { return; } fac *= exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj); if (fac < env[PTR_EXPDROP]) { return; } int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double *out = cache; cache += comp * di * dj; int value = (*eval_ints)(weights, out, comp, li, lj, ai, aj, ri, rj, fac, log_prec, dimension, a, b, offset, submesh, mesh, cache); if (value != 0) { size_t naoi = dims[0]; size_t naoj = dims[1]; int i, j, ic; for (ic = 0; ic < comp; ic++) { for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { mat[j*naoi+i] += out[j*di+i]; } } mat += naoi * naoj; out += di * dj; } } } static int _nonorth_cache_size(int *mesh, int l) { int dcart = _LEN_CART[l]; int deriv = 1; int topl = l + l + deriv; int l1 = topl + 1; const int nimgs = 1; int cache_size = 0; cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]) * nimgs; cache_size += mesh[1] * mesh[2]; // * nimgs * nimgs cache_size += l1 * mesh[2] * nimgs; cache_size += l1 * l1 * mesh[0]; cache_size = MAX(cache_size, _MAX_AFFINE_SIZE[topl]*2); cache_size += l1 * l1 * l1; cache_size += _MAX_RR_SIZE[topl]; return dcart*dcart + cache_size; } static int _max_cache_size(int (*fsize)(), int *shls_slice, int *bas, int *mesh) { int i, n; int i0 = MIN(shls_slice[0], shls_slice[2]); int i1 = MAX(shls_slice[1], shls_slice[3]); int cache_size = 0; for (i = i0; i < i1; i++) { n = (*fsize)(mesh, bas(ANG_OF, i)); cache_size = MAX(cache_size, n); } return cache_size+1000000; } 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]; } // Numerical integration for uncontracted Cartesian basis // F_mat needs to be initialized as 0 void NUMINT_fill2c(int (*eval_ints)(), double *weights, double *F_mat, int comp, int hermi, int *shls_slice, int *ao_loc, double log_prec, int dimension, int nimgs, double *Ls, double *a, double *b, int *offset, int *submesh, int *mesh, 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; const size_t naoi = ao_loc[ish1] - ao_loc[ish0]; const size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; const int cache_size = _max_cache_size(_nonorth_cache_size, shls_slice, bas, mesh); if (dimension == 0) { nimgs = 1; } #pragma omp parallel { size_t ncij = comp * naoi * naoj; size_t nijsh = nish * njsh; size_t dims[] = {naoi, naoj}; size_t ijm; int ish, jsh, ij, m, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); int ptrxyz; #pragma omp for schedule(dynamic) for (ijm = 0; ijm < nimgs*nijsh; ijm++) { m = ijm / nijsh; ij = ijm % nijsh; ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { // fill up only upper triangle of F_mat continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; if (dimension != 0) { ptrxyz = atm(PTR_COORD, bas(ATOM_OF,jsh)); shift_bas(env_loc, env, Ls, ptrxyz, m); } _apply_ints(eval_ints, weights, F_mat+m*ncij+j0*naoi+i0, dims, comp, 1., log_prec, dimension, a, b, offset, submesh, mesh, shls, atm, bas, env_loc, cache); } free(cache); free(env_loc); } } /************************************************* * * rho * *************************************************/ void GTOreverse_vrr2d_ket_inc1(double *g01, double *g00, double *rirj, int li, int lj); /* (li,lj) => (li+lj,0) */ void GTOreverse_vrr2d_ket(double *g00, double *g01, int li, int lj, double *ri, double *rj) { int nmax = li + lj; double *out = g00; double *gswap, *pg00, *pg01; int row_01, col_01, row_00, col_00, row_g; int i, j, n; double rirj[3]; rirj[0] = ri[0] - rj[0]; rirj[1] = ri[1] - rj[1]; rirj[2] = ri[2] - rj[2]; for (j = lj; j > 0; j--) { col_01 = _LEN_CART[j]; col_00 = _LEN_CART[j-1]; row_g = _CUM_LEN_CART[nmax+1-j] - _CUM_LEN_CART[li] + _LEN_CART[li]; for (n = 0; n < row_g*col_00; n++) { g00[n] = 0; } pg00 = g00; pg01 = g01; for (i = li; i <= nmax-j; i++) { GTOreverse_vrr2d_ket_inc1(pg01, pg00, rirj, i, j); row_01 = _LEN_CART[i]; row_00 = _LEN_CART[i]; pg00 += row_00 * col_00; pg01 += row_01 * col_01; } gswap = g00; g00 = g01; g01 = gswap; } if (out != g01) { row_g = _CUM_LEN_CART[nmax] - _CUM_LEN_CART[li] + _LEN_CART[li]; for (n = 0; n < row_g; n++) { out[n] = g01[n]; } } } static void _cart_to_xyz(double *dm_xyz, double *dm_cart, int floorl, int topl, int l1) { int l1l1 = l1 * l1; int l, lx, ly, lz, n; for (n = 0, l = floorl; l <= topl; l++) { for (lx = l; lx >= 0; lx--) { for (ly = l - lx; ly >= 0; ly--, n++) { lz = l - lx - ly; dm_xyz[lx*l1l1+ly*l1+lz] += dm_cart[n]; } } } } static void _orth_rho(double *rho, double *dm_xyz, double fac, int topl, int *offset, int *submesh, int *mesh, int *img_slice, int *grid_slice, double *xs_exp, double *ys_exp, double *zs_exp, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int nimgx0 = img_slice[0]; int nimgx1 = img_slice[1]; int nimgy0 = img_slice[2]; int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; int nimgx = nimgx1 - nimgx0; int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; int nx0 = MAX(grid_slice[0], offset[0]); int nx1 = MIN(grid_slice[1], offset[0]+submesh[0]); int ny0 = MAX(grid_slice[2], offset[1]); int ny1 = MIN(grid_slice[3], offset[1]+submesh[1]); int nz0 = MAX(grid_slice[4], offset[2]); int nz1 = MIN(grid_slice[5], offset[2]+submesh[2]); int ngridx = _num_grids_on_x(nimgx, nx0, nx1, mesh[0]); int ngridy = _num_grids_on_x(nimgy, ny0, ny1, mesh[1]); int ngridz = _num_grids_on_x(nimgz, nz0, nz1, mesh[2]); if (ngridx == 0 || ngridy == 0 || ngridz == 0) { return; } const char TRANS_N = 'N'; const char TRANS_T = 'T'; const double D0 = 0; const double D1 = 1; int xcols = submesh[1] * submesh[2]; double *xyr = cache; double *xqr = xyr + l1l1 * submesh[2]; int i, l; if (nimgz == 1) { for (l = 0; l <= topl; l++) { for (i = offset[2]; i < nz0; i++) { zs_exp[l*mesh[2]+i] = 0; } for (i = nz1; i < offset[2]+submesh[2]; i++) { zs_exp[l*mesh[2]+i] = 0; } } } else if (nimgz == 2 && !_has_overlap(nz0, nz1, mesh[2])) { for (l = 0; l <= topl; l++) { for (i = nz1; i < nz0; i++) { zs_exp[l*mesh[2]+i] = 0; } } } dgemm_(&TRANS_N, &TRANS_N, submesh+2, &l1l1, &l1, &fac, zs_exp+offset[2], mesh+2, dm_xyz, &l1, &D0, xyr, submesh+2); if (nimgy == 1) { for (l = 0; l <= topl; l++) { for (i = 0; i < (ny0-offset[1])*submesh[2]; i++) { xqr[l*xcols+i] = 0; } for (i = (ny1-offset[1])*submesh[2]; i < xcols; i++) { xqr[l*xcols+i] = 0; } dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1, &D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2); } } else if (nimgy == 2 && !_has_overlap(ny0, ny1, mesh[1])) { for (l = 0; l <= topl; l++) { ngridy = ny1 - offset[1]; dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1, &D0, xqr+l*xcols, submesh+2); for (i = (ny1-offset[1])*submesh[2]; i < (ny0-offset[1])*submesh[2]; i++) { xqr[l*xcols+i] = 0; } ngridy = offset[1] + submesh[1] - ny0; dgemm_(&TRANS_N, &TRANS_T, submesh+2, &ngridy, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+ny0, mesh+1, &D0, xqr+l*xcols+(ny0-offset[1])*submesh[2], submesh+2); } } else { for (l = 0; l <= topl; l++) { dgemm_(&TRANS_N, &TRANS_T, submesh+2, submesh+1, &l1, &D1, xyr+l*l1*submesh[2], submesh+2, ys_exp+offset[1], mesh+1, &D0, xqr+l*xcols, submesh+2); } } if (nimgx == 1) { dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+nx0, mesh, &D1, rho+(nx0-offset[0])*xcols, &xcols); } else if (nimgx == 2 && !_has_overlap(nx0, nx1, mesh[0])) { ngridx = nx1 - offset[2]; dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+offset[0], mesh, &D1, rho, &xcols); ngridx = offset[0] + submesh[0] - nx0; dgemm_(&TRANS_N, &TRANS_T, &xcols, &ngridx, &l1, &D1, xqr, &xcols, xs_exp+nx0, mesh, &D1, rho+(nx0-offset[0])*xcols, &xcols); } else { dgemm_(&TRANS_N, &TRANS_T, &xcols, submesh, &l1, &D1, xqr, &xcols, xs_exp+offset[0], mesh, &D1, rho, &xcols); } } static void _dm_vrr6d(double *dm_cart, double *dm, size_t naoi, int li, int lj, double *ri, double *rj, double *cache) { int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; double *dm_6d = cache; int i, j; for (j = 0; j < dj; j++) { for (i = 0; i < di; i++) { dm_6d[j*di+i] = dm[j*naoi+i]; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li, lj, ri, rj); } void NUMINTrho_lda_orth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + lj; int l1 = topl + 1; int l1l1l1 = l1 * l1 * l1; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return; } cache += data_size; double *dm_xyz = cache; cache += l1l1l1; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li, topl, l1); _orth_rho(rho, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); } void NUMINTrho_gga_orth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + 1 + lj; int l1 = topl + 1; int l1l1l1 = l1 * l1 * l1; double cutoff = gto_rcut(ai+aj, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double *xs_exp, *ys_exp, *zs_exp; int data_size = _init_orth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, ai, aj, ri, rj, a, b, cache); if (data_size == 0) { return; } cache += data_size; size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; double *rhox = rho + ngrids; double *rhoy = rhox + ngrids; double *rhoz = rhoy + ngrids; double *dm_xyz = cache; cache += l1l1l1; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; int i, j, lx, ly, lz; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); lx = l1 - 1; NPdset0(dm_xyz, lx * lx * lx); _cart_to_xyz(dm_xyz, dm_cart, li, topl-1, lx); _orth_rho(rho, dm_xyz, fac, li+lj, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); int di1 = _LEN_CART[li+1]; int li_1 = li - 1; int di_1 = _LEN_CART[MAX(0, li_1)]; double ai2 = -2 * ai; double fac_li; NPdset0(dm_6d, di1*dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = lx + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhox, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = ly + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhoy, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); NPdset0(dm_xyz, l1l1l1); _cart_to_xyz(dm_xyz, dm_cart, li+1, topl, l1); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac_li = lz + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _cart_to_xyz(dm_xyz, dm_cart, li_1, topl-2, l1); } _orth_rho(rhoz, dm_xyz, fac, topl, offset, submesh, mesh, img_slice, grid_slice, xs_exp, ys_exp, zs_exp, cache); } static void _nonorth_rho_z(double *rho, double *rhoz, int offset, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz + meshz; for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { if (iz1 >= meshz) { iz1 -= meshz; } rho[iz1] += rhoz[iz] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { if (iz1 < 0) { iz1 += meshz; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; rho[iz1] += rhoz[iz] * exp_z0z0; } } static void _nonorth_rho_z_1img(double *rho, double *rhoz, int offset, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { rho[iz1] += rhoz[iz] * exp_z0z0; exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; if (iz1 < 0) { iz1 += meshz; } for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; rho[iz1] += rhoz[iz] * exp_z0z0; } } static void _nonorth_rho_z_with_mask(double *rho, double *rhoz, int8_t *skip, int offset, int submeshz, int meshz, int nz0, int nz1, int grid_close_to_zij, double e_z0z0, double e_z0dz, double e_dzdz, double _z0dz, double _dzdz) { if (e_z0z0 == 0) { return; } double exp_2dzdz = e_dzdz * e_dzdz; double exp_z0z0, exp_z0dz; int iz, iz1; rho -= offset; // for the original indexing rho[iz1-offset] exp_z0z0 = e_z0z0; exp_z0dz = e_z0dz * e_dzdz; iz1 = grid_close_to_zij % meshz + meshz; for (iz = grid_close_to_zij-nz0; iz < nz1-nz0; iz++, iz1++) { if (iz1 >= meshz) { iz1 -= meshz; } if (!skip[iz]) { rho[iz1] += rhoz[iz] * exp_z0z0; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; } exp_z0z0 = e_z0z0; if (e_z0dz != 0) { exp_z0dz = e_dzdz / e_z0dz; } else { exp_z0dz = exp(_dzdz - _z0dz); } iz1 = (grid_close_to_zij-1) % meshz; for (iz = grid_close_to_zij-nz0-1; iz >= 0; iz--, iz1--) { if (iz1 < 0) { iz1 += meshz; } exp_z0z0 *= exp_z0dz; exp_z0dz *= exp_2dzdz; if (!skip[iz]) { rho[iz1] += rhoz[iz] * exp_z0z0; } } } static int _make_grid_mask(int8_t *skip, int nx0, int nx1, int mesh, int offset, int submesh) { if (offset == 0 && submesh == mesh) { // allows nimg > 1 return 0; } else if (offset <= nx0 && nx1 <= offset+submesh) { // requires nimg == 1 return 0; } int i, i1; i1 = nx0 % mesh + mesh; for (i = 0; i < nx1-nx0; i++, i1++) { if (i1 >= mesh) { i1 -= mesh; } if (offset <= i1 && i1 < offset+submesh) { skip[i] = 0; } else { skip[i] = 1; } } return 1; } static void _nonorth_rho(double *rho, double *dm_xyz, double fac, double aij, int topl, int dimension, double *a, double *rij_frac, double *xs_exp, double *ys_exp, double *zs_exp, int *img_slice, int *grid_slice, int *offset, int *submesh, int *mesh, double *cache) { int l1 = topl + 1; int l1l1 = l1 * l1; int nx0 = grid_slice[0]; int nx1 = grid_slice[1]; int ny0 = grid_slice[2]; int ny1 = grid_slice[3]; int nz0 = grid_slice[4]; int nz1 = grid_slice[5]; int ngridx = nx1 - nx0; int ngridy = ny1 - ny0; int ngridz = nz1 - nz0; //int nimgx0 = img_slice[0]; //int nimgx1 = img_slice[1]; //int nimgy0 = img_slice[2]; //int nimgy1 = img_slice[3]; int nimgz0 = img_slice[4]; int nimgz1 = img_slice[5]; //int nimgx = nimgx1 - nimgx0; //int nimgy = nimgy1 - nimgy0; int nimgz = nimgz1 - nimgz0; const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D0 = 0; const double D1 = 1; const int inc1 = 1; // aa = einsum('ij,kj->ik', a, a) //double aa[9]; //int n3 = 3; //dgemm_(&TRANS_T, &TRANS_N, &n3, &n3, &n3, // &aij, a, &n3, a, &n3, &D0, aa, &n3); double aa_xx = aij * (a[0] * a[0] + a[1] * a[1] + a[2] * a[2]); double aa_xy = aij * (a[0] * a[3] + a[1] * a[4] + a[2] * a[5]); double aa_xz = aij * (a[0] * a[6] + a[1] * a[7] + a[2] * a[8]); double aa_yy = aij * (a[3] * a[3] + a[4] * a[4] + a[5] * a[5]); double aa_yz = aij * (a[3] * a[6] + a[4] * a[7] + a[5] * a[8]); double aa_zz = aij * (a[6] * a[6] + a[7] * a[7] + a[8] * a[8]); int ix, iy, ix1, iy1; double dx = 1. / mesh[0]; double dy = 1. / mesh[1]; double dz = 1. / mesh[2]; //int grid_close_to_xij = rint(rij_frac[0] * mesh[0]); int grid_close_to_yij = rint(rij_frac[1] * mesh[1]); int grid_close_to_zij = rint(rij_frac[2] * mesh[2]); //grid_close_to_xij = MIN(grid_close_to_xij, nx1); //grid_close_to_xij = MAX(grid_close_to_xij, nx0); grid_close_to_yij = MIN(grid_close_to_yij, ny1); grid_close_to_yij = MAX(grid_close_to_yij, ny0); grid_close_to_zij = MIN(grid_close_to_zij, nz1); grid_close_to_zij = MAX(grid_close_to_zij, nz0); double img0_x = 0; double img0_y = 0; double img0_z = 0; double base_x = img0_x;// + dx * grid_close_to_xij; double base_y = img0_y + dy * grid_close_to_yij; double base_z = img0_z + dz * grid_close_to_zij; double x0xij = base_x - rij_frac[0]; double y0yij = base_y - rij_frac[1]; double z0zij = base_z - rij_frac[2]; double _dydy = -dy * dy * aa_yy; double _dzdz = -dz * dz * aa_zz; double _dydz = -dy * dz * aa_yz * 2; double exp_dydy = exp(_dydy); double exp_2dydy = exp_dydy * exp_dydy; double exp_dzdz = exp(_dzdz); double exp_dydz = exp(_dydz); double exp_dydz_i = (exp_dydz == 0) ? 0 : 1./exp_dydz; double x1xij, tmpx, tmpy, tmpz; double _xyz0xyz0, _xyz0dy, _xyz0dz, _z0dz; double exp_xyz0xyz0, exp_xyz0dz; double exp_y0dy, exp_z0z0, exp_z0dz; int xcols = ngridy * ngridz; double *xyr = cache; double *xqr = xyr + l1l1 * ngridz; double *rhoz = xqr + l1 * ngridy * ngridz; double *prho; int l; int8_t x_skip[ngridx]; int8_t y_skip[ngridy]; int8_t z_skip[ngridz]; int with_x_mask = _make_grid_mask(x_skip, nx0, nx1, mesh[0], offset[0], submesh[0]); int with_y_mask = _make_grid_mask(y_skip, ny0, ny1, mesh[1], offset[1], submesh[1]); int with_z_mask = _make_grid_mask(z_skip, nz0, nz1, mesh[2], offset[2], submesh[2]); dgemm_(&TRANS_N, &TRANS_N, &ngridz, &l1l1, &l1, &D1, zs_exp, &ngridz, dm_xyz, &l1, &D0, xyr, &ngridz); for (l = 0; l <= topl; l++) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &ngridy, &l1, &D1, xyr+l*l1*ngridz, &ngridz, ys_exp, &ngridy, &D0, xqr+l*xcols, &ngridz); } ix1 = nx0 % mesh[0] + mesh[0]; for (ix = 0; ix < nx1-nx0; ix++, ix1++) { if (ix1 >= mesh[0]) { ix1 -= mesh[0]; } if (with_x_mask && x_skip[ix]) { continue; } x1xij = x0xij + (nx0+ix)*dx; tmpx = x1xij * aa_xx + y0yij * aa_xy + z0zij * aa_xz; tmpy = x1xij * aa_xy + y0yij * aa_yy + z0zij * aa_yz; tmpz = x1xij * aa_xz + y0yij * aa_yz + z0zij * aa_zz; _xyz0xyz0 = -x1xij * tmpx - y0yij * tmpy - z0zij * tmpz; if (_xyz0xyz0 < EXPMIN) { continue; } _xyz0dy = -2 * dy * tmpy; _xyz0dz = -2 * dz * tmpz; exp_xyz0xyz0 = fac * exp(_xyz0xyz0); exp_xyz0dz = exp(_xyz0dz); //exp_xyz0dy = exp(_xyz0dy); //exp_y0dy = exp_xyz0dy * exp_dydy; exp_y0dy = exp(_xyz0dy + _dydy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = grid_close_to_yij % mesh[1] + mesh[1]; for (iy = grid_close_to_yij-ny0; iy < ny1-ny0; iy++, iy1++) { if (exp_z0z0 == 0) { break; } if (iy1 >= mesh[1]) { iy1 -= mesh[1]; } if (!with_y_mask || !y_skip[iy]) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1, &D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx, &D0, rhoz, &ngridz); prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2]; if (nimgz == 1) { _nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else if (with_z_mask) { _nonorth_rho_z_with_mask(prho, rhoz, z_skip, offset[2], submesh[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_rho_z(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } _z0dz += _dydz; exp_z0z0 *= exp_y0dy; exp_z0dz *= exp_dydz; exp_y0dy *= exp_2dydy; } exp_y0dy = exp(_dydy - _xyz0dy); exp_z0z0 = exp_xyz0xyz0; exp_z0dz = exp_xyz0dz; _z0dz = _xyz0dz; iy1 = (grid_close_to_yij-1) % mesh[1]; for (iy = grid_close_to_yij-ny0-1; iy >= 0; iy--, iy1--) { exp_z0z0 *= exp_y0dy; if (exp_z0z0 == 0) { break; } _z0dz -= _dydz; if (exp_dydz != 0) { exp_z0dz *= exp_dydz_i; } else { exp_z0dz = exp(_z0dz); } exp_y0dy *= exp_2dydy; if (iy1 < 0) { iy1 += mesh[1]; } if (!with_y_mask || !y_skip[iy]) { dgemm_(&TRANS_N, &TRANS_T, &ngridz, &inc1, &l1, &D1, xqr+iy*ngridz, &xcols, xs_exp+ix, &ngridx, &D0, rhoz, &ngridz); prho = rho + ((ix1-offset[0])*submesh[1] + iy1-offset[1]) * submesh[2]; if (nimgz == 1) { _nonorth_rho_z_1img(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else if (with_z_mask) { _nonorth_rho_z_with_mask(prho, rhoz, z_skip, offset[2], submesh[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } else { _nonorth_rho_z(prho, rhoz, offset[2], mesh[2], nz0, nz1, grid_close_to_zij, exp_z0z0, exp_z0dz, exp_dzdz, _z0dz, _dzdz); } } } } } void NUMINTrho_lda_nonorth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int floorl = li; int topl = li + lj; int l1 = topl + 1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return; } cache += data_size; double *dm_xyz = cache; cache += l1 * l1 * l1; double *dm_cart = cache; double *dm_cache = dm_cart + _CUM_LEN_CART[topl]; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_cart+_MAX_RR_SIZE[topl]); _reverse_affine_trans(dm_xyz, dm_cart, a, floorl, topl, dm_cache); _nonorth_rho(rho, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); } static void _merge_dm_xyz_updown(double *dm_xyz, double *dm_xyz1, int l1) { int l0 = l1 - 2; int l1l1 = l1 * l1; int l0l0 = l0 * l0; int i, j, k; for (i = 0; i < l0; i++) { for (j = 0; j < l0; j++) { for (k = 0; k < l0; k++) { dm_xyz[i*l1l1+j*l1+k] += dm_xyz1[i*l0l0+j*l0+k]; } } } } void NUMINTrho_gga_nonorth(double *rho, double *dm, int comp, size_t naoi, int li, int lj, double ai, double aj, double *ri, double *rj, double fac, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, double *cache) { int topl = li + 1 + lj; int l1 = topl + 1; int l1l1 = l1 * l1; double aij = ai + aj; double cutoff = gto_rcut(aij, topl, fac, log_prec); int img_slice[6]; int grid_slice[6]; double ri_frac[3]; double rij_frac[3]; double *xs_exp, *ys_exp, *zs_exp; _make_rij_frac(ri_frac, rij_frac, ri, rj, ai, aj, a, b); int data_size = _init_nonorth_data(&xs_exp, &ys_exp, &zs_exp, img_slice, grid_slice, offset, submesh, mesh, topl, dimension, cutoff, a, b, ri_frac, rij_frac, cache); if (data_size == 0) { return; } cache += data_size; size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; double *rhox = rho + ngrids; double *rhoy = rhox + ngrids; double *rhoz = rhoy + ngrids; double *dm_xyz = cache; double *dm_xyz1 = dm_xyz + l1l1 * l1; cache += l1l1 * l1 * 2; double *dm_cart = cache; double *dm_6d = dm_cart + _MAX_RR_SIZE[topl]; int di = _LEN_CART[li]; int dj = _LEN_CART[lj]; int i, j, lx, ly, lz; _dm_vrr6d(dm_cart, dm, naoi, li, lj, ri, rj, dm_6d); lx = l1 - 1; _reverse_affine_trans(dm_xyz, dm_cart, a, li, li+lj, dm_6d); _nonorth_rho(rho, dm_xyz, fac, aij, li+lj, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); int di1 = _LEN_CART[li+1]; int li_1 = li - 1; int di_1 = _LEN_CART[MAX(0, li_1)]; double ai2 = -2 * ai; double fac_li; NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREX_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = lx + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREX_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhox, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREY_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { fac_li = ly + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREY_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhoy, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); NPdset0(dm_6d, _LEN_CART[li+1] * dj); for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { dm_6d[di1*j+WHEREZ_IF_L_INC1(i)] = dm[naoi*j+i] * ai2; } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li+1, lj, ri, rj); _reverse_affine_trans(dm_xyz, dm_cart, a, li+1, topl, dm_6d); if (li_1 >= 0) { for (i = 0, lx = li_1; lx >= 0; lx--) { for (ly = li_1 - lx; ly >= 0; ly--, i++) { lz = li_1 - lx - ly; fac_li = lz + 1; for (j = 0; j < dj; j++) { dm_6d[di_1*j+i] = dm[naoi*j+WHEREZ_IF_L_INC1(i)] * fac_li; } } } GTOreverse_vrr2d_ket(dm_cart, dm_6d, li_1, lj, ri, rj); _reverse_affine_trans(dm_xyz1, dm_cart, a, li_1, topl-2, dm_6d); _merge_dm_xyz_updown(dm_xyz, dm_xyz1, l1); } _nonorth_rho(rhoz, dm_xyz, fac, aij, topl, dimension, a, rij_frac, xs_exp, ys_exp, zs_exp, img_slice, grid_slice, offset, submesh, mesh, cache); } static void _apply_rho(void (*eval_rho)(), double *rho, double *dm, size_t *dims, int comp, double log_prec, int dimension, double *a, double *b, int *offset, int *submesh, int *mesh, int *shls, int *atm, int natm, int *bas, int nbas, double *env, double *cache) { const size_t naoi = dims[0]; const int i_sh = shls[0]; const int j_sh = shls[1]; const int li = bas(ANG_OF, i_sh); const int lj = bas(ANG_OF, j_sh); double *ri = env + atm(PTR_COORD, bas(ATOM_OF, i_sh)); double *rj = env + atm(PTR_COORD, bas(ATOM_OF, j_sh)); double ai = env[bas(PTR_EXP, i_sh)]; double aj = env[bas(PTR_EXP, j_sh)]; double ci = env[bas(PTR_COEFF, i_sh)]; double cj = env[bas(PTR_COEFF, j_sh)]; double aij = ai + aj; double rrij = CINTsquare_dist(ri, rj); double eij = (ai * aj / aij) * rrij; if (eij > EIJCUTOFF) { return; } double fac = exp(-eij) * ci * cj * CINTcommon_fac_sp(li) * CINTcommon_fac_sp(lj); if (fac < env[PTR_EXPDROP]) { return; } (*eval_rho)(rho, dm, comp, naoi, li, lj, ai, aj, ri, rj, fac, log_prec, dimension, a, b, offset, submesh, mesh, cache); } static int _rho_cache_size(int l, int comp, int *mesh) { int l1 = l * 2 + 1; int cache_size = 0; cache_size += l1 * mesh[1] * mesh[2]; cache_size += l1 * l1 * mesh[2] * 2; cache_size = MAX(cache_size, 3*_MAX_RR_SIZE[l*2]); cache_size = MAX(cache_size, _CUM_LEN_CART[l*2]+2*_MAX_AFFINE_SIZE[l*2]); cache_size += l1 * (mesh[0] + mesh[1] + mesh[2]); cache_size += l1 * l1 * l1; return cache_size + 1000000; } /* * F_dm are a set of uncontracted cartesian density matrices * Note rho is updated inplace. */ void NUMINT_rho_drv(void (*eval_rho)(), double *rho, double *F_dm, int comp, int hermi, int *shls_slice, int *ao_loc, double log_prec, int dimension, int nimgs, double *Ls, double *a, double *b, int *offset, int *submesh, int *mesh, int *atm, int natm, int *bas, int nbas, double *env, int nenv) { int ish0 = shls_slice[0]; int ish1 = shls_slice[1]; int jsh0 = shls_slice[2]; int jsh1 = shls_slice[3]; int nish = ish1 - ish0; int njsh = jsh1 - jsh0; size_t naoi = ao_loc[ish1] - ao_loc[ish0]; size_t naoj = ao_loc[jsh1] - ao_loc[jsh0]; size_t nao2 = naoi * naoi; int lmax = 0; int ib; for (ib = 0; ib < nbas; ib++) { lmax = MAX(lmax, bas(ANG_OF, ib)); } int cache_size = _rho_cache_size(lmax, comp, submesh); size_t ngrids = ((size_t)submesh[0]) * submesh[1] * submesh[2]; if (dimension == 0) { nimgs = 1; } double *rhobufs[MAX_THREADS]; #pragma omp parallel { size_t ncij = naoi * naoj; size_t nijsh = nish * njsh; size_t dims[] = {naoi, naoj}; size_t ijm; int ish, jsh, ij, m, i0, j0; int shls[2]; double *cache = malloc(sizeof(double) * cache_size); double *env_loc = malloc(sizeof(double)*nenv); NPdcopy(env_loc, env, nenv); int ptrxyz; int thread_id = omp_get_thread_num(); double *rho_priv, *pdm; if (thread_id == 0) { rho_priv = rho; } else { rho_priv = calloc(comp*ngrids, sizeof(double)); } rhobufs[thread_id] = rho_priv; if (hermi) { // Note hermitian character of the density matrices can only be found by // rearranging the repeated images: // dmR - dmR[::-1].transpose(0,2,1) == 0 #pragma omp for schedule(static) for (m = 0; m < nimgs; m++) { pdm = F_dm + m * nao2; for (j0 = 1; j0 < naoi; j0++) { for (i0 = 0; i0 < j0; i0++) { pdm[j0*naoi+i0] *= 2; pdm[i0*naoi+j0] = 0; } } } } #pragma omp for schedule(dynamic) for (ijm = 0; ijm < nimgs*nijsh; ijm++) { m = ijm / nijsh; ij = ijm % nijsh; ish = ij / njsh; jsh = ij % njsh; if (hermi != PLAIN && ish > jsh) { continue; } ish += ish0; jsh += jsh0; shls[0] = ish; shls[1] = jsh; i0 = ao_loc[ish] - ao_loc[ish0]; j0 = ao_loc[jsh] - ao_loc[jsh0]; if (dimension != 0) { ptrxyz = atm(PTR_COORD, bas(ATOM_OF,ish)); shift_bas(env_loc, env, Ls, ptrxyz, m); } _apply_rho(eval_rho, rho_priv, F_dm+m*ncij+j0*naoi+i0, dims, comp, log_prec, dimension, a, b, offset, submesh, mesh, shls, atm, natm, bas, nbas, env_loc, cache); } NPomp_dsum_reduce_inplace(rhobufs, comp*ngrids); free(cache); free(env_loc); if (thread_id != 0) { free(rho_priv); } } }
c55c7aec73df0f31d67fbe39510946453b899e1d.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "omp.h" struct dataobj { void *restrict data; int * size; int * npsize; int * dsize; int * hsize; int * hofs; int * oofs; } ; struct profiler { double section0; double section1; double section2; } ; int Forward(struct dataobj *restrict damp_vec, const float dt, const float o_x, const float o_y, const float o_z, struct dataobj *restrict rec_vec, struct dataobj *restrict rec_coords_vec, struct dataobj *restrict src_vec, struct dataobj *restrict src_coords_vec, struct dataobj *restrict u_vec, struct dataobj *restrict vp_vec, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int p_rec_M, const int p_rec_m, const int p_src_M, const int p_src_m, const int time_M, const int time_m, struct profiler * timers) { float (*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[damp_vec->size[1]][damp_vec->size[2]]) damp_vec->data; float (*restrict rec)[rec_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_vec->size[1]]) rec_vec->data; float (*restrict rec_coords)[rec_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[rec_coords_vec->size[1]]) rec_coords_vec->data; float (*restrict src)[src_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_vec->size[1]]) src_vec->data; float (*restrict src_coords)[src_coords_vec->size[1]] __attribute__ ((aligned (64))) = (float (*)[src_coords_vec->size[1]]) src_coords_vec->data; float (*restrict u)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]] __attribute__ ((aligned (64))) = (float (*)[u_vec->size[1]][u_vec->size[2]][u_vec->size[3]]) u_vec->data; float (*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__ ((aligned (64))) = (float (*)[vp_vec->size[1]][vp_vec->size[2]]) vp_vec->data; #pragma omp target enter data map(to: rec[0:rec_vec->size[0]][0:rec_vec->size[1]]) #pragma omp target enter data map(to: u[0:u_vec->size[0]][0:u_vec->size[1]][0:u_vec->size[2]][0:u_vec->size[3]]) #pragma omp target enter data map(to: damp[0:damp_vec->size[0]][0:damp_vec->size[1]][0:damp_vec->size[2]]) #pragma omp target enter data map(to: rec_coords[0:rec_coords_vec->size[0]][0:rec_coords_vec->size[1]]) #pragma omp target enter data map(to: src[0:src_vec->size[0]][0:src_vec->size[1]]) #pragma omp target enter data map(to: src_coords[0:src_coords_vec->size[0]][0:src_coords_vec->size[1]]) #pragma omp target enter data map(to: vp[0:vp_vec->size[0]][0:vp_vec->size[1]][0:vp_vec->size[2]]) for (int time = time_m, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3); time <= time_M; time += 1, t0 = (time)%(3), t1 = (time + 1)%(3), t2 = (time + 2)%(3)) { struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); /* Begin section0 */ #pragma omp target teams distribute parallel for collapse(3) for (int x = x_m; x <= x_M; x += 1) { for (int y = y_m; y <= y_M; y += 1) { for (int z = z_m; z <= z_M; z += 1) { float r0 = vp[x + 12][y + 12][z + 12]*vp[x + 12][y + 12][z + 12]; u[t1][x + 12][y + 12][z + 12] = 2.0F*(5.0e-1F*r0*(dt*dt)*(-1.50312647e-7F*(u[t0][x + 6][y + 12][z + 12] + u[t0][x + 12][y + 6][z + 12] + u[t0][x + 12][y + 12][z + 6] + u[t0][x + 12][y + 12][z + 18] + u[t0][x + 12][y + 18][z + 12] + u[t0][x + 18][y + 12][z + 12]) + 2.59740254e-6F*(u[t0][x + 7][y + 12][z + 12] + u[t0][x + 12][y + 7][z + 12] + u[t0][x + 12][y + 12][z + 7] + u[t0][x + 12][y + 12][z + 17] + u[t0][x + 12][y + 17][z + 12] + u[t0][x + 17][y + 12][z + 12]) - 2.23214281e-5F*(u[t0][x + 8][y + 12][z + 12] + u[t0][x + 12][y + 8][z + 12] + u[t0][x + 12][y + 12][z + 8] + u[t0][x + 12][y + 12][z + 16] + u[t0][x + 12][y + 16][z + 12] + u[t0][x + 16][y + 12][z + 12]) + 1.32275129e-4F*(u[t0][x + 9][y + 12][z + 12] + u[t0][x + 12][y + 9][z + 12] + u[t0][x + 12][y + 12][z + 9] + u[t0][x + 12][y + 12][z + 15] + u[t0][x + 12][y + 15][z + 12] + u[t0][x + 15][y + 12][z + 12]) - 6.69642842e-4F*(u[t0][x + 10][y + 12][z + 12] + u[t0][x + 12][y + 10][z + 12] + u[t0][x + 12][y + 12][z + 10] + u[t0][x + 12][y + 12][z + 14] + u[t0][x + 12][y + 14][z + 12] + u[t0][x + 14][y + 12][z + 12]) + 4.28571419e-3F*(u[t0][x + 11][y + 12][z + 12] + u[t0][x + 12][y + 11][z + 12] + u[t0][x + 12][y + 12][z + 11] + u[t0][x + 12][y + 12][z + 13] + u[t0][x + 12][y + 13][z + 12] + u[t0][x + 13][y + 12][z + 12]) - 2.23708328e-2F*u[t0][x + 12][y + 12][z + 12]) + 5.0e-1F*(r0*dt*damp[x + 1][y + 1][z + 1]*u[t0][x + 12][y + 12][z + 12] - u[t2][x + 12][y + 12][z + 12]) + 1.0F*u[t0][x + 12][y + 12][z + 12])/(r0*dt*damp[x + 1][y + 1][z + 1] + 1); } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec-start_section0.tv_sec)+(double)(end_section0.tv_usec-start_section0.tv_usec)/1000000; struct timeval start_section1, end_section1; gettimeofday(&start_section1, NULL); /* Begin section1 */ #pragma omp target teams distribute parallel for collapse(1) for (int p_src = p_src_m; p_src <= p_src_M; p_src += 1) { int ii_src_0 = (int)(floor(-5.0e-2*o_x + 5.0e-2*src_coords[p_src][0])); int ii_src_1 = (int)(floor(-5.0e-2*o_y + 5.0e-2*src_coords[p_src][1])); int ii_src_2 = (int)(floor(-5.0e-2*o_z + 5.0e-2*src_coords[p_src][2])); int ii_src_3 = (int)(floor(-5.0e-2*o_z + 5.0e-2*src_coords[p_src][2])) + 1; int ii_src_4 = (int)(floor(-5.0e-2*o_y + 5.0e-2*src_coords[p_src][1])) + 1; int ii_src_5 = (int)(floor(-5.0e-2*o_x + 5.0e-2*src_coords[p_src][0])) + 1; float px = (float)(-o_x - 2.0e+1F*(int)(floor(-5.0e-2F*o_x + 5.0e-2F*src_coords[p_src][0])) + src_coords[p_src][0]); float py = (float)(-o_y - 2.0e+1F*(int)(floor(-5.0e-2F*o_y + 5.0e-2F*src_coords[p_src][1])) + src_coords[p_src][1]); float pz = (float)(-o_z - 2.0e+1F*(int)(floor(-5.0e-2F*o_z + 5.0e-2F*src_coords[p_src][2])) + src_coords[p_src][2]); if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1) { float r1 = (dt*dt)*(vp[ii_src_0 + 12][ii_src_1 + 12][ii_src_2 + 12]*vp[ii_src_0 + 12][ii_src_1 + 12][ii_src_2 + 12])*(-1.25e-4F*px*py*pz + 2.5e-3F*px*py + 2.5e-3F*px*pz - 5.0e-2F*px + 2.5e-3F*py*pz - 5.0e-2F*py - 5.0e-2F*pz + 1)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 12][ii_src_1 + 12][ii_src_2 + 12] += r1; } if (ii_src_0 >= x_m - 1 && ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_0 <= x_M + 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1) { float r2 = (dt*dt)*(vp[ii_src_0 + 12][ii_src_1 + 12][ii_src_3 + 12]*vp[ii_src_0 + 12][ii_src_1 + 12][ii_src_3 + 12])*(1.25e-4F*px*py*pz - 2.5e-3F*px*pz - 2.5e-3F*py*pz + 5.0e-2F*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 12][ii_src_1 + 12][ii_src_3 + 12] += r2; } if (ii_src_0 >= x_m - 1 && ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r3 = (dt*dt)*(vp[ii_src_0 + 12][ii_src_4 + 12][ii_src_2 + 12]*vp[ii_src_0 + 12][ii_src_4 + 12][ii_src_2 + 12])*(1.25e-4F*px*py*pz - 2.5e-3F*px*py - 2.5e-3F*py*pz + 5.0e-2F*py)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 12][ii_src_4 + 12][ii_src_2 + 12] += r3; } if (ii_src_0 >= x_m - 1 && ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_0 <= x_M + 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1) { float r4 = (dt*dt)*(vp[ii_src_0 + 12][ii_src_4 + 12][ii_src_3 + 12]*vp[ii_src_0 + 12][ii_src_4 + 12][ii_src_3 + 12])*(-1.25e-4F*px*py*pz + 2.5e-3F*py*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_0 + 12][ii_src_4 + 12][ii_src_3 + 12] += r4; } if (ii_src_1 >= y_m - 1 && ii_src_2 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_2 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r5 = (dt*dt)*(vp[ii_src_5 + 12][ii_src_1 + 12][ii_src_2 + 12]*vp[ii_src_5 + 12][ii_src_1 + 12][ii_src_2 + 12])*(1.25e-4F*px*py*pz - 2.5e-3F*px*py - 2.5e-3F*px*pz + 5.0e-2F*px)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 12][ii_src_1 + 12][ii_src_2 + 12] += r5; } if (ii_src_1 >= y_m - 1 && ii_src_3 >= z_m - 1 && ii_src_5 >= x_m - 1 && ii_src_1 <= y_M + 1 && ii_src_3 <= z_M + 1 && ii_src_5 <= x_M + 1) { float r6 = (dt*dt)*(vp[ii_src_5 + 12][ii_src_1 + 12][ii_src_3 + 12]*vp[ii_src_5 + 12][ii_src_1 + 12][ii_src_3 + 12])*(-1.25e-4F*px*py*pz + 2.5e-3F*px*pz)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 12][ii_src_1 + 12][ii_src_3 + 12] += r6; } if (ii_src_2 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_2 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r7 = (dt*dt)*(vp[ii_src_5 + 12][ii_src_4 + 12][ii_src_2 + 12]*vp[ii_src_5 + 12][ii_src_4 + 12][ii_src_2 + 12])*(-1.25e-4F*px*py*pz + 2.5e-3F*px*py)*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 12][ii_src_4 + 12][ii_src_2 + 12] += r7; } if (ii_src_3 >= z_m - 1 && ii_src_4 >= y_m - 1 && ii_src_5 >= x_m - 1 && ii_src_3 <= z_M + 1 && ii_src_4 <= y_M + 1 && ii_src_5 <= x_M + 1) { float r8 = 1.25e-4F*px*py*pz*(dt*dt)*(vp[ii_src_5 + 12][ii_src_4 + 12][ii_src_3 + 12]*vp[ii_src_5 + 12][ii_src_4 + 12][ii_src_3 + 12])*src[time][p_src]; #pragma omp atomic update u[t1][ii_src_5 + 12][ii_src_4 + 12][ii_src_3 + 12] += r8; } } /* End section1 */ gettimeofday(&end_section1, NULL); timers->section1 += (double)(end_section1.tv_sec-start_section1.tv_sec)+(double)(end_section1.tv_usec-start_section1.tv_usec)/1000000; struct timeval start_section2, end_section2; gettimeofday(&start_section2, NULL); /* Begin section2 */ #pragma omp target teams distribute parallel for collapse(1) for (int p_rec = p_rec_m; p_rec <= p_rec_M; p_rec += 1) { int ii_rec_0 = (int)(floor(-5.0e-2*o_x + 5.0e-2*rec_coords[p_rec][0])); int ii_rec_1 = (int)(floor(-5.0e-2*o_y + 5.0e-2*rec_coords[p_rec][1])); int ii_rec_2 = (int)(floor(-5.0e-2*o_z + 5.0e-2*rec_coords[p_rec][2])); int ii_rec_3 = (int)(floor(-5.0e-2*o_z + 5.0e-2*rec_coords[p_rec][2])) + 1; int ii_rec_4 = (int)(floor(-5.0e-2*o_y + 5.0e-2*rec_coords[p_rec][1])) + 1; int ii_rec_5 = (int)(floor(-5.0e-2*o_x + 5.0e-2*rec_coords[p_rec][0])) + 1; float px = (float)(-o_x - 2.0e+1F*(int)(floor(-5.0e-2F*o_x + 5.0e-2F*rec_coords[p_rec][0])) + rec_coords[p_rec][0]); float py = (float)(-o_y - 2.0e+1F*(int)(floor(-5.0e-2F*o_y + 5.0e-2F*rec_coords[p_rec][1])) + rec_coords[p_rec][1]); float pz = (float)(-o_z - 2.0e+1F*(int)(floor(-5.0e-2F*o_z + 5.0e-2F*rec_coords[p_rec][2])) + rec_coords[p_rec][2]); float sum = 0.0F; if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1) { sum += (-1.25e-4F*px*py*pz + 2.5e-3F*px*py + 2.5e-3F*px*pz - 5.0e-2F*px + 2.5e-3F*py*pz - 5.0e-2F*py - 5.0e-2F*pz + 1)*u[t0][ii_rec_0 + 12][ii_rec_1 + 12][ii_rec_2 + 12]; } if (ii_rec_0 >= x_m - 1 && ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1) { sum += (1.25e-4F*px*py*pz - 2.5e-3F*px*pz - 2.5e-3F*py*pz + 5.0e-2F*pz)*u[t0][ii_rec_0 + 12][ii_rec_1 + 12][ii_rec_3 + 12]; } if (ii_rec_0 >= x_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (1.25e-4F*px*py*pz - 2.5e-3F*px*py - 2.5e-3F*py*pz + 5.0e-2F*py)*u[t0][ii_rec_0 + 12][ii_rec_4 + 12][ii_rec_2 + 12]; } if (ii_rec_0 >= x_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_0 <= x_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1) { sum += (-1.25e-4F*px*py*pz + 2.5e-3F*py*pz)*u[t0][ii_rec_0 + 12][ii_rec_4 + 12][ii_rec_3 + 12]; } if (ii_rec_1 >= y_m - 1 && ii_rec_2 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_2 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (1.25e-4F*px*py*pz - 2.5e-3F*px*py - 2.5e-3F*px*pz + 5.0e-2F*px)*u[t0][ii_rec_5 + 12][ii_rec_1 + 12][ii_rec_2 + 12]; } if (ii_rec_1 >= y_m - 1 && ii_rec_3 >= z_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_1 <= y_M + 1 && ii_rec_3 <= z_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-1.25e-4F*px*py*pz + 2.5e-3F*px*pz)*u[t0][ii_rec_5 + 12][ii_rec_1 + 12][ii_rec_3 + 12]; } if (ii_rec_2 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_2 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += (-1.25e-4F*px*py*pz + 2.5e-3F*px*py)*u[t0][ii_rec_5 + 12][ii_rec_4 + 12][ii_rec_2 + 12]; } if (ii_rec_3 >= z_m - 1 && ii_rec_4 >= y_m - 1 && ii_rec_5 >= x_m - 1 && ii_rec_3 <= z_M + 1 && ii_rec_4 <= y_M + 1 && ii_rec_5 <= x_M + 1) { sum += 1.25e-4F*px*py*pz*u[t0][ii_rec_5 + 12][ii_rec_4 + 12][ii_rec_3 + 12]; } rec[time][p_rec] = sum; } /* End section2 */ gettimeofday(&end_section2, NULL); timers->section2 += (double)(end_section2.tv_sec-start_section2.tv_sec)+(double)(end_section2.tv_usec-start_section2.tv_usec)/1000000; } #pragma omp target update from(rec[0:rec_vec->size[0]][0:rec_vec->size[1]]) #pragma omp target exit data map(release: rec[0:rec_vec->size[0]][0:rec_vec->size[1]]) #pragma omp target update from(u[0:u_vec->size[0]][0:u_vec->size[1]][0:u_vec->size[2]][0:u_vec->size[3]]) #pragma omp target exit data map(release: u[0:u_vec->size[0]][0:u_vec->size[1]][0:u_vec->size[2]][0:u_vec->size[3]]) #pragma omp target exit data map(delete: damp[0:damp_vec->size[0]][0:damp_vec->size[1]][0:damp_vec->size[2]]) #pragma omp target exit data map(delete: rec_coords[0:rec_coords_vec->size[0]][0:rec_coords_vec->size[1]]) #pragma omp target exit data map(delete: src[0:src_vec->size[0]][0:src_vec->size[1]]) #pragma omp target exit data map(delete: src_coords[0:src_coords_vec->size[0]][0:src_coords_vec->size[1]]) #pragma omp target exit data map(delete: vp[0:vp_vec->size[0]][0:vp_vec->size[1]][0:vp_vec->size[2]]) return 0; } /* Backdoor edit at Wed Mar 4 04:57:41 2020*/
zhemm.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_tuning.h" #include "plasma_types.h" #include "plasma_workspace.h" /***************************************************************************//** * * @ingroup plasma_hemm * * Performs one of the matrix-matrix operations * * \f[ C = \alpha \times A \times B + \beta \times C \f] * or * \f[ C = \alpha \times B \times A + \beta \times C \f] * * where alpha and beta are scalars, A is a Hermitian matrix and B and * C are m-by-n matrices. * ******************************************************************************* * * @param[in] side * Specifies whether the Hermitian matrix A appears on the * left or right in the operation as follows: * - PlasmaLeft: \f[ C = \alpha \times A \times B + \beta \times C \f] * - PlasmaRight: \f[ C = \alpha \times B \times A + \beta \times C \f] * * @param[in] uplo * Specifies whether the upper or lower triangular part of * the Hermitian matrix A is to be referenced as follows: * - PlasmaLower: Only the lower triangular part of the * Hermitian matrix A is to be referenced. * - PlasmaUpper: Only the upper triangular part of the * Hermitian matrix A is to be referenced. * * @param[in] m * The number of rows of the matrix C. m >= 0. * * @param[in] n * The number of columns of the matrix C. n >= 0. * * @param[in] alpha * The scalar alpha. * * @param[in] pA * A is an lda-by-ka matrix, where ka is m when side = PlasmaLeft, * and is n otherwise. Only the uplo triangular part is referenced. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,ka). * * @param[in] pB * B is an ldb-by-n matrix, where the leading m-by-n part of * the array B must contain the matrix B. * * @param[in] ldb * The leading dimension of the array B. ldb >= max(1,m). * * @param[in] beta * The scalar beta. * * @param[in,out] pC * C is an ldc-by-n matrix. * On exit, the array is overwritten by the m-by-n updated matrix. * * @param[in] ldc * The leading dimension of the array C. ldc >= max(1,m). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * ******************************************************************************* * * @sa plasma_omp_zhemm * @sa plasma_chemm * ******************************************************************************/ int plasma_zhemm(plasma_enum_t side, plasma_enum_t uplo, int m, int n, plasma_complex64_t alpha, plasma_complex64_t *pA, int lda, plasma_complex64_t *pB, int ldb, plasma_complex64_t beta, plasma_complex64_t *pC, int ldc) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if ((side != PlasmaLeft) && (side != PlasmaRight)) { plasma_error("illegal value of side"); return -1; } if ((uplo != PlasmaLower) && (uplo != PlasmaUpper)) { plasma_error("illegal value of uplo"); return -2; } if (m < 0) { plasma_error("illegal value of m"); return -3; } if (n < 0) { plasma_error("illegal value of n"); return -4; } int am; if (side == PlasmaLeft) { am = m; } else { am = n; } if (lda < imax(1, am)) { plasma_error("illegal value of lda"); return -7; } if (ldb < imax(1, m)) { plasma_error("illegal value of ldb"); return -9; } if (ldc < imax(1, m)) { plasma_error("illegal value of ldc"); return -12; } // quick return if (m == 0 || n == 0 || (alpha == 0.0 && beta == 1.0)) return PlasmaSuccess; // Tune parameters. if (plasma->tuning) plasma_tune_symm(plasma, PlasmaComplexDouble, m, n); // Set tiling parameters. int nb = plasma->nb; // Create tile matrices. plasma_desc_t A; plasma_desc_t B; plasma_desc_t C; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, am, am, 0, 0, am, am, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &B); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); return retval; } retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, m, n, 0, 0, m, n, &C); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); plasma_desc_destroy(&A); plasma_desc_destroy(&B); return retval; } // Initialize sequence. plasma_sequence_t sequence; retval = plasma_sequence_init(&sequence); // Initialize request. plasma_request_t request; retval = plasma_request_init(&request); // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, &sequence, &request); plasma_omp_zge2desc(pB, ldb, B, &sequence, &request); plasma_omp_zge2desc(pC, ldc, C, &sequence, &request); // Call the tile async function. plasma_omp_zhemm(side, uplo, alpha, A, B, beta, C, &sequence, &request); // Translate back to LAPACK layout. plasma_omp_zdesc2ge(C, pC, ldc, &sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&B); plasma_desc_destroy(&C); // Return status. int status = sequence.status; return status; } /***************************************************************************//** * @ingroup plasma_hemm * * Performs Hermitian matrix multiplication. * Non-blocking tile version of plasma_zhemm(). * May return before the computation is finished. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] side * Specifies whether the Hermitian matrix A appears on the * left or right in the operation as follows: * - PlasmaLeft: \f[ C = \alpha \times A \times B + \beta \times C \f] * - PlasmaRight: \f[ C = \alpha \times B \times A + \beta \times C \f] * * @param[in] uplo * Specifies whether the upper or lower triangular part of * the Hermitian matrix A is to be referenced as follows: * - PlasmaLower: Only the lower triangular part of the * Hermitian matrix A is to be referenced. * - PlasmaUpper: Only the upper triangular part of the * Hermitian matrix A is to be referenced. * * @param[in] alpha * The scalar alpha. * * @param[in] A * Descriptor of matrix A. * * @param[in] B * Descriptor of matrix B. * * @param[in] beta * The scalar beta. * * @param[in,out] C * Descriptor of matrix C. * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). * * @param[out] request * Identifies this function call (for exception handling purposes). * ******************************************************************************* * * @sa plasma_zhemm * @sa plasma_omp_chemm * ******************************************************************************/ void plasma_omp_zhemm(plasma_enum_t side, plasma_enum_t uplo, plasma_complex64_t alpha, plasma_desc_t A, plasma_desc_t B, plasma_complex64_t beta, plasma_desc_t C, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if ((side != PlasmaLeft) && (side != PlasmaRight)) { plasma_error("illegal value of side"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if ((uplo != PlasmaLower) && (uplo != PlasmaUpper)) { plasma_error("illegal value of uplo"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(A) != PlasmaSuccess) { plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); plasma_error("invalid A"); return; } if (plasma_desc_check(B) != PlasmaSuccess) { plasma_error("invalid B"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (plasma_desc_check(C) != PlasmaSuccess) { plasma_error("invalid C"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (sequence == NULL) { plasma_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (C.m == 0 || C.n == 0 || ((alpha == 0.0 || A.n == 0) && beta == 1.0)) return; // Call the parallel function. plasma_pzhemm(side, uplo, alpha, A, B, beta, C, sequence, request); }
Parser.h
//===--- Parser.h - C Language Parser ---------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the Parser interface. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_PARSE_PARSER_H #define LLVM_CLANG_PARSE_PARSER_H #include "clang/AST/Availability.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/OperatorPrecedence.h" #include "clang/Basic/Specifiers.h" #include "clang/Lex/CodeCompletionHandler.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/DeclSpec.h" #include "clang/Sema/LoopHint.h" #include "clang/Sema/Sema.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/SaveAndRestore.h" #include <memory> #include <stack> namespace clang { class PragmaHandler; class Scope; class BalancedDelimiterTracker; class CorrectionCandidateCallback; class DeclGroupRef; class DiagnosticBuilder; class Parser; class ParsingDeclRAIIObject; class ParsingDeclSpec; class ParsingDeclarator; class ParsingFieldDeclarator; class ColonProtectionRAIIObject; class InMessageExpressionRAIIObject; class PoisonSEHIdentifiersRAIIObject; class VersionTuple; class OMPClause; class ObjCTypeParamList; class ObjCTypeParameter; /// Parser - This implements a parser for the C family of languages. After /// parsing units of the grammar, productions are invoked to handle whatever has /// been read. /// class Parser : public CodeCompletionHandler { friend class ColonProtectionRAIIObject; friend class InMessageExpressionRAIIObject; friend class PoisonSEHIdentifiersRAIIObject; friend class ObjCDeclContextSwitch; friend class ParenBraceBracketBalancer; friend class BalancedDelimiterTracker; Preprocessor &PP; /// Tok - The current token we are peeking ahead. All parsing methods assume /// that this is valid. Token Tok; // PrevTokLocation - The location of the token we previously // consumed. This token is used for diagnostics where we expected to // see a token following another token (e.g., the ';' at the end of // a statement). SourceLocation PrevTokLocation; unsigned short ParenCount = 0, BracketCount = 0, BraceCount = 0; unsigned short MisplacedModuleBeginCount = 0; /// Actions - These are the callbacks we invoke as we parse various constructs /// in the file. Sema &Actions; DiagnosticsEngine &Diags; /// ScopeCache - Cache scopes to reduce malloc traffic. enum { ScopeCacheSize = 16 }; unsigned NumCachedScopes; Scope *ScopeCache[ScopeCacheSize]; /// Identifiers used for SEH handling in Borland. These are only /// allowed in particular circumstances // __except block IdentifierInfo *Ident__exception_code, *Ident___exception_code, *Ident_GetExceptionCode; // __except filter expression IdentifierInfo *Ident__exception_info, *Ident___exception_info, *Ident_GetExceptionInfo; // __finally IdentifierInfo *Ident__abnormal_termination, *Ident___abnormal_termination, *Ident_AbnormalTermination; /// Contextual keywords for Microsoft extensions. IdentifierInfo *Ident__except; mutable IdentifierInfo *Ident_sealed; /// Ident_super - IdentifierInfo for "super", to support fast /// comparison. IdentifierInfo *Ident_super; /// Ident_vector, Ident_bool - cached IdentifierInfos for "vector" and /// "bool" fast comparison. Only present if AltiVec or ZVector are enabled. IdentifierInfo *Ident_vector; IdentifierInfo *Ident_bool; /// Ident_pixel - cached IdentifierInfos for "pixel" fast comparison. /// Only present if AltiVec enabled. IdentifierInfo *Ident_pixel; /// Objective-C contextual keywords. mutable IdentifierInfo *Ident_instancetype; /// \brief Identifier for "introduced". IdentifierInfo *Ident_introduced; /// \brief Identifier for "deprecated". IdentifierInfo *Ident_deprecated; /// \brief Identifier for "obsoleted". IdentifierInfo *Ident_obsoleted; /// \brief Identifier for "unavailable". IdentifierInfo *Ident_unavailable; /// \brief Identifier for "message". IdentifierInfo *Ident_message; /// \brief Identifier for "strict". IdentifierInfo *Ident_strict; /// \brief Identifier for "replacement". IdentifierInfo *Ident_replacement; /// Identifiers used by the 'external_source_symbol' attribute. IdentifierInfo *Ident_language, *Ident_defined_in, *Ident_generated_declaration; /// C++0x contextual keywords. mutable IdentifierInfo *Ident_final; mutable IdentifierInfo *Ident_GNU_final; mutable IdentifierInfo *Ident_override; // C++ type trait keywords that can be reverted to identifiers and still be // used as type traits. llvm::SmallDenseMap<IdentifierInfo *, tok::TokenKind> RevertibleTypeTraits; std::unique_ptr<PragmaHandler> AlignHandler; std::unique_ptr<PragmaHandler> GCCVisibilityHandler; std::unique_ptr<PragmaHandler> OptionsHandler; std::unique_ptr<PragmaHandler> PackHandler; std::unique_ptr<PragmaHandler> MSStructHandler; std::unique_ptr<PragmaHandler> UnusedHandler; std::unique_ptr<PragmaHandler> WeakHandler; std::unique_ptr<PragmaHandler> RedefineExtnameHandler; std::unique_ptr<PragmaHandler> FPContractHandler; std::unique_ptr<PragmaHandler> OpenCLExtensionHandler; std::unique_ptr<PragmaHandler> OpenMPHandler; std::unique_ptr<PragmaHandler> MSCommentHandler; std::unique_ptr<PragmaHandler> MSDetectMismatchHandler; std::unique_ptr<PragmaHandler> MSPointersToMembers; std::unique_ptr<PragmaHandler> MSVtorDisp; std::unique_ptr<PragmaHandler> MSInitSeg; std::unique_ptr<PragmaHandler> MSDataSeg; std::unique_ptr<PragmaHandler> MSBSSSeg; std::unique_ptr<PragmaHandler> MSConstSeg; std::unique_ptr<PragmaHandler> MSCodeSeg; std::unique_ptr<PragmaHandler> MSSection; std::unique_ptr<PragmaHandler> MSRuntimeChecks; std::unique_ptr<PragmaHandler> MSIntrinsic; std::unique_ptr<PragmaHandler> CUDAForceHostDeviceHandler; std::unique_ptr<PragmaHandler> OptimizeHandler; std::unique_ptr<PragmaHandler> LoopHintHandler; std::unique_ptr<PragmaHandler> UnrollHintHandler; std::unique_ptr<PragmaHandler> NoUnrollHintHandler; std::unique_ptr<PragmaHandler> FPHandler; std::unique_ptr<CommentHandler> CommentSemaHandler; /// Whether the '>' token acts as an operator or not. This will be /// true except when we are parsing an expression within a C++ /// template argument list, where the '>' closes the template /// argument list. bool GreaterThanIsOperator; /// ColonIsSacred - When this is false, we aggressively try to recover from /// code like "foo : bar" as if it were a typo for "foo :: bar". This is not /// safe in case statements and a few other things. This is managed by the /// ColonProtectionRAIIObject RAII object. bool ColonIsSacred; /// \brief When true, we are directly inside an Objective-C message /// send expression. /// /// This is managed by the \c InMessageExpressionRAIIObject class, and /// should not be set directly. bool InMessageExpression; /// The "depth" of the template parameters currently being parsed. unsigned TemplateParameterDepth; /// \brief RAII class that manages the template parameter depth. class TemplateParameterDepthRAII { unsigned &Depth; unsigned AddedLevels; public: explicit TemplateParameterDepthRAII(unsigned &Depth) : Depth(Depth), AddedLevels(0) {} ~TemplateParameterDepthRAII() { Depth -= AddedLevels; } void operator++() { ++Depth; ++AddedLevels; } void addDepth(unsigned D) { Depth += D; AddedLevels += D; } unsigned getDepth() const { return Depth; } }; /// Factory object for creating AttributeList objects. AttributeFactory AttrFactory; /// \brief Gathers and cleans up TemplateIdAnnotations when parsing of a /// top-level declaration is finished. SmallVector<TemplateIdAnnotation *, 16> TemplateIds; /// \brief Identifiers which have been declared within a tentative parse. SmallVector<IdentifierInfo *, 8> TentativelyDeclaredIdentifiers; IdentifierInfo *getSEHExceptKeyword(); /// True if we are within an Objective-C container while parsing C-like decls. /// /// This is necessary because Sema thinks we have left the container /// to parse the C-like decls, meaning Actions.getObjCDeclContext() will /// be NULL. bool ParsingInObjCContainer; bool SkipFunctionBodies; /// The location of the expression statement that is being parsed right now. /// Used to determine if an expression that is being parsed is a statement or /// just a regular sub-expression. SourceLocation ExprStatementTokLoc; public: Parser(Preprocessor &PP, Sema &Actions, bool SkipFunctionBodies); ~Parser() override; const LangOptions &getLangOpts() const { return PP.getLangOpts(); } const TargetInfo &getTargetInfo() const { return PP.getTargetInfo(); } Preprocessor &getPreprocessor() const { return PP; } Sema &getActions() const { return Actions; } AttributeFactory &getAttrFactory() { return AttrFactory; } const Token &getCurToken() const { return Tok; } Scope *getCurScope() const { return Actions.getCurScope(); } void incrementMSManglingNumber() const { return Actions.incrementMSManglingNumber(); } Decl *getObjCDeclContext() const { return Actions.getObjCDeclContext(); } // Type forwarding. All of these are statically 'void*', but they may all be // different actual classes based on the actions in place. typedef OpaquePtr<DeclGroupRef> DeclGroupPtrTy; typedef OpaquePtr<TemplateName> TemplateTy; typedef SmallVector<TemplateParameterList *, 4> TemplateParameterLists; typedef Sema::FullExprArg FullExprArg; // Parsing methods. /// Initialize - Warm up the parser. /// void Initialize(); /// Parse the first top-level declaration in a translation unit. bool ParseFirstTopLevelDecl(DeclGroupPtrTy &Result); /// ParseTopLevelDecl - Parse one top-level declaration. Returns true if /// the EOF was encountered. bool ParseTopLevelDecl(DeclGroupPtrTy &Result); bool ParseTopLevelDecl() { DeclGroupPtrTy Result; return ParseTopLevelDecl(Result); } /// ConsumeToken - Consume the current 'peek token' and lex the next one. /// This does not work with special tokens: string literals, code completion /// and balanced tokens must be handled using the specific consume methods. /// Returns the location of the consumed token. SourceLocation ConsumeToken() { assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } bool TryConsumeToken(tok::TokenKind Expected) { if (Tok.isNot(Expected)) return false; assert(!isTokenSpecial() && "Should consume special tokens with Consume*Token"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return true; } bool TryConsumeToken(tok::TokenKind Expected, SourceLocation &Loc) { if (!TryConsumeToken(Expected)) return false; Loc = PrevTokLocation; return true; } SourceLocation getEndOfPreviousToken() { return PP.getLocForEndOfToken(PrevTokLocation); } /// Retrieve the underscored keyword (_Nonnull, _Nullable) that corresponds /// to the given nullability kind. IdentifierInfo *getNullabilityKeyword(NullabilityKind nullability) { return Actions.getNullabilityKeyword(nullability); } private: //===--------------------------------------------------------------------===// // Low-Level token peeking and consumption methods. // /// isTokenParen - Return true if the cur token is '(' or ')'. bool isTokenParen() const { return Tok.getKind() == tok::l_paren || Tok.getKind() == tok::r_paren; } /// isTokenBracket - Return true if the cur token is '[' or ']'. bool isTokenBracket() const { return Tok.getKind() == tok::l_square || Tok.getKind() == tok::r_square; } /// isTokenBrace - Return true if the cur token is '{' or '}'. bool isTokenBrace() const { return Tok.getKind() == tok::l_brace || Tok.getKind() == tok::r_brace; } /// isTokenStringLiteral - True if this token is a string-literal. bool isTokenStringLiteral() const { return tok::isStringLiteral(Tok.getKind()); } /// isTokenSpecial - True if this token requires special consumption methods. bool isTokenSpecial() const { return isTokenStringLiteral() || isTokenParen() || isTokenBracket() || isTokenBrace() || Tok.is(tok::code_completion); } /// \brief Returns true if the current token is '=' or is a type of '='. /// For typos, give a fixit to '=' bool isTokenEqualOrEqualTypo(); /// \brief Return the current token to the token stream and make the given /// token the current token. void UnconsumeToken(Token &Consumed) { Token Next = Tok; PP.EnterToken(Consumed); PP.Lex(Tok); PP.EnterToken(Next); } /// ConsumeAnyToken - Dispatch to the right Consume* method based on the /// current token type. This should only be used in cases where the type of /// the token really isn't known, e.g. in error recovery. SourceLocation ConsumeAnyToken(bool ConsumeCodeCompletionTok = false) { if (isTokenParen()) return ConsumeParen(); if (isTokenBracket()) return ConsumeBracket(); if (isTokenBrace()) return ConsumeBrace(); if (isTokenStringLiteral()) return ConsumeStringToken(); if (Tok.is(tok::code_completion)) return ConsumeCodeCompletionTok ? ConsumeCodeCompletionToken() : handleUnexpectedCodeCompletionToken(); return ConsumeToken(); } /// ConsumeParen - This consume method keeps the paren count up-to-date. /// SourceLocation ConsumeParen() { assert(isTokenParen() && "wrong consume method"); if (Tok.getKind() == tok::l_paren) ++ParenCount; else if (ParenCount) --ParenCount; // Don't let unbalanced )'s drive the count negative. PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBracket - This consume method keeps the bracket count up-to-date. /// SourceLocation ConsumeBracket() { assert(isTokenBracket() && "wrong consume method"); if (Tok.getKind() == tok::l_square) ++BracketCount; else if (BracketCount) --BracketCount; // Don't let unbalanced ]'s drive the count negative. PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeBrace - This consume method keeps the brace count up-to-date. /// SourceLocation ConsumeBrace() { assert(isTokenBrace() && "wrong consume method"); if (Tok.getKind() == tok::l_brace) ++BraceCount; else if (BraceCount) --BraceCount; // Don't let unbalanced }'s drive the count negative. PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// ConsumeStringToken - Consume the current 'peek token', lexing a new one /// and returning the token kind. This method is specific to strings, as it /// handles string literal concatenation, as per C99 5.1.1.2, translation /// phase #6. SourceLocation ConsumeStringToken() { assert(isTokenStringLiteral() && "Should only consume string literals with this method"); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } /// \brief Consume the current code-completion token. /// /// This routine can be called to consume the code-completion token and /// continue processing in special cases where \c cutOffParsing() isn't /// desired, such as token caching or completion with lookahead. SourceLocation ConsumeCodeCompletionToken() { assert(Tok.is(tok::code_completion)); PrevTokLocation = Tok.getLocation(); PP.Lex(Tok); return PrevTokLocation; } ///\ brief When we are consuming a code-completion token without having /// matched specific position in the grammar, provide code-completion results /// based on context. /// /// \returns the source location of the code-completion token. SourceLocation handleUnexpectedCodeCompletionToken(); /// \brief Abruptly cut off parsing; mainly used when we have reached the /// code-completion point. void cutOffParsing() { if (PP.isCodeCompletionEnabled()) PP.setCodeCompletionReached(); // Cut off parsing by acting as if we reached the end-of-file. Tok.setKind(tok::eof); } /// \brief Determine if we're at the end of the file or at a transition /// between modules. bool isEofOrEom() { tok::TokenKind Kind = Tok.getKind(); return Kind == tok::eof || Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include; } /// \brief Initialize all pragma handlers. void initializePragmaHandlers(); /// \brief Destroy and reset all pragma handlers. void resetPragmaHandlers(); /// \brief Handle the annotation token produced for #pragma unused(...) void HandlePragmaUnused(); /// \brief Handle the annotation token produced for /// #pragma GCC visibility... void HandlePragmaVisibility(); /// \brief Handle the annotation token produced for /// #pragma pack... void HandlePragmaPack(); /// \brief Handle the annotation token produced for /// #pragma ms_struct... void HandlePragmaMSStruct(); /// \brief Handle the annotation token produced for /// #pragma comment... void HandlePragmaMSComment(); void HandlePragmaMSPointersToMembers(); void HandlePragmaMSVtorDisp(); void HandlePragmaMSPragma(); bool HandlePragmaMSSection(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSSegment(StringRef PragmaName, SourceLocation PragmaLocation); bool HandlePragmaMSInitSeg(StringRef PragmaName, SourceLocation PragmaLocation); /// \brief Handle the annotation token produced for /// #pragma align... void HandlePragmaAlign(); /// \brief Handle the annotation token produced for /// #pragma clang __debug dump... void HandlePragmaDump(); /// \brief Handle the annotation token produced for /// #pragma weak id... void HandlePragmaWeak(); /// \brief Handle the annotation token produced for /// #pragma weak id = id... void HandlePragmaWeakAlias(); /// \brief Handle the annotation token produced for /// #pragma redefine_extname... void HandlePragmaRedefineExtname(); /// \brief Handle the annotation token produced for /// #pragma STDC FP_CONTRACT... void HandlePragmaFPContract(); /// \brief Handle the annotation token produced for /// #pragma clang fp ... void HandlePragmaFP(); /// \brief Handle the annotation token produced for /// #pragma OPENCL EXTENSION... void HandlePragmaOpenCLExtension(); /// \brief Handle the annotation token produced for /// #pragma clang __debug captured StmtResult HandlePragmaCaptured(); /// \brief Handle the annotation token produced for /// #pragma clang loop and #pragma unroll. bool HandlePragmaLoopHint(LoopHint &Hint); /// GetLookAheadToken - This peeks ahead N tokens and returns that token /// without consuming any tokens. LookAhead(0) returns 'Tok', LookAhead(1) /// returns the token after Tok, etc. /// /// Note that this differs from the Preprocessor's LookAhead method, because /// the Parser always has one token lexed that the preprocessor doesn't. /// const Token &GetLookAheadToken(unsigned N) { if (N == 0 || Tok.is(tok::eof)) return Tok; return PP.LookAhead(N-1); } public: /// NextToken - This peeks ahead one token and returns it without /// consuming it. const Token &NextToken() { return PP.LookAhead(0); } /// getTypeAnnotation - Read a parsed type out of an annotation token. static ParsedType getTypeAnnotation(Token &Tok) { return ParsedType::getFromOpaquePtr(Tok.getAnnotationValue()); } private: static void setTypeAnnotation(Token &Tok, ParsedType T) { Tok.setAnnotationValue(T.getAsOpaquePtr()); } /// \brief Read an already-translated primary expression out of an annotation /// token. static ExprResult getExprAnnotation(Token &Tok) { return ExprResult::getFromOpaquePointer(Tok.getAnnotationValue()); } /// \brief Set the primary expression corresponding to the given annotation /// token. static void setExprAnnotation(Token &Tok, ExprResult ER) { Tok.setAnnotationValue(ER.getAsOpaquePointer()); } public: // If NeedType is true, then TryAnnotateTypeOrScopeToken will try harder to // find a type name by attempting typo correction. bool TryAnnotateTypeOrScopeToken(); bool TryAnnotateTypeOrScopeTokenAfterScopeSpec(CXXScopeSpec &SS, bool IsNewScope); bool TryAnnotateCXXScopeToken(bool EnteringContext = false); private: enum AnnotatedNameKind { /// Annotation has failed and emitted an error. ANK_Error, /// The identifier is a tentatively-declared name. ANK_TentativeDecl, /// The identifier is a template name. FIXME: Add an annotation for that. ANK_TemplateName, /// The identifier can't be resolved. ANK_Unresolved, /// Annotation was successful. ANK_Success }; AnnotatedNameKind TryAnnotateName(bool IsAddressOfOperand, std::unique_ptr<CorrectionCandidateCallback> CCC = nullptr); /// Push a tok::annot_cxxscope token onto the token stream. void AnnotateScopeToken(CXXScopeSpec &SS, bool IsNewAnnotation); /// TryAltiVecToken - Check for context-sensitive AltiVec identifier tokens, /// replacing them with the non-context-sensitive keywords. This returns /// true if the token was replaced. bool TryAltiVecToken(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid) { if (!getLangOpts().AltiVec && !getLangOpts().ZVector) return false; if (Tok.getIdentifierInfo() != Ident_vector && Tok.getIdentifierInfo() != Ident_bool && (!getLangOpts().AltiVec || Tok.getIdentifierInfo() != Ident_pixel)) return false; return TryAltiVecTokenOutOfLine(DS, Loc, PrevSpec, DiagID, isInvalid); } /// TryAltiVecVectorToken - Check for context-sensitive AltiVec vector /// identifier token, replacing it with the non-context-sensitive __vector. /// This returns true if the token was replaced. bool TryAltiVecVectorToken() { if ((!getLangOpts().AltiVec && !getLangOpts().ZVector) || Tok.getIdentifierInfo() != Ident_vector) return false; return TryAltiVecVectorTokenOutOfLine(); } bool TryAltiVecVectorTokenOutOfLine(); bool TryAltiVecTokenOutOfLine(DeclSpec &DS, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, bool &isInvalid); /// Returns true if the current token is the identifier 'instancetype'. /// /// Should only be used in Objective-C language modes. bool isObjCInstancetype() { assert(getLangOpts().ObjC1); if (Tok.isAnnotation()) return false; if (!Ident_instancetype) Ident_instancetype = PP.getIdentifierInfo("instancetype"); return Tok.getIdentifierInfo() == Ident_instancetype; } /// TryKeywordIdentFallback - For compatibility with system headers using /// keywords as identifiers, attempt to convert the current token to an /// identifier and optionally disable the keyword for the remainder of the /// translation unit. This returns false if the token was not replaced, /// otherwise emits a diagnostic and returns true. bool TryKeywordIdentFallback(bool DisableKeyword); /// \brief Get the TemplateIdAnnotation from the token. TemplateIdAnnotation *takeTemplateIdAnnotation(const Token &tok); /// TentativeParsingAction - An object that is used as a kind of "tentative /// parsing transaction". It gets instantiated to mark the token position and /// after the token consumption is done, Commit() or Revert() is called to /// either "commit the consumed tokens" or revert to the previously marked /// token position. Example: /// /// TentativeParsingAction TPA(*this); /// ConsumeToken(); /// .... /// TPA.Revert(); /// class TentativeParsingAction { Parser &P; Token PrevTok; size_t PrevTentativelyDeclaredIdentifierCount; unsigned short PrevParenCount, PrevBracketCount, PrevBraceCount; bool isActive; public: explicit TentativeParsingAction(Parser& p) : P(p) { PrevTok = P.Tok; PrevTentativelyDeclaredIdentifierCount = P.TentativelyDeclaredIdentifiers.size(); PrevParenCount = P.ParenCount; PrevBracketCount = P.BracketCount; PrevBraceCount = P.BraceCount; P.PP.EnableBacktrackAtThisPos(); isActive = true; } void Commit() { assert(isActive && "Parsing action was finished!"); P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.PP.CommitBacktrackedTokens(); isActive = false; } void Revert() { assert(isActive && "Parsing action was finished!"); P.PP.Backtrack(); P.Tok = PrevTok; P.TentativelyDeclaredIdentifiers.resize( PrevTentativelyDeclaredIdentifierCount); P.ParenCount = PrevParenCount; P.BracketCount = PrevBracketCount; P.BraceCount = PrevBraceCount; isActive = false; } ~TentativeParsingAction() { assert(!isActive && "Forgot to call Commit or Revert!"); } }; /// A TentativeParsingAction that automatically reverts in its destructor. /// Useful for disambiguation parses that will always be reverted. class RevertingTentativeParsingAction : private Parser::TentativeParsingAction { public: RevertingTentativeParsingAction(Parser &P) : Parser::TentativeParsingAction(P) {} ~RevertingTentativeParsingAction() { Revert(); } }; class UnannotatedTentativeParsingAction; /// ObjCDeclContextSwitch - An object used to switch context from /// an objective-c decl context to its enclosing decl context and /// back. class ObjCDeclContextSwitch { Parser &P; Decl *DC; SaveAndRestore<bool> WithinObjCContainer; public: explicit ObjCDeclContextSwitch(Parser &p) : P(p), DC(p.getObjCDeclContext()), WithinObjCContainer(P.ParsingInObjCContainer, DC != nullptr) { if (DC) P.Actions.ActOnObjCTemporaryExitContainerContext(cast<DeclContext>(DC)); } ~ObjCDeclContextSwitch() { if (DC) P.Actions.ActOnObjCReenterContainerContext(cast<DeclContext>(DC)); } }; /// ExpectAndConsume - The parser expects that 'ExpectedTok' is next in the /// input. If so, it is consumed and false is returned. /// /// If a trivial punctuator misspelling is encountered, a FixIt error /// diagnostic is issued and false is returned after recovery. /// /// If the input is malformed, this emits the specified diagnostic and true is /// returned. bool ExpectAndConsume(tok::TokenKind ExpectedTok, unsigned Diag = diag::err_expected, StringRef DiagMsg = ""); /// \brief The parser expects a semicolon and, if present, will consume it. /// /// If the next token is not a semicolon, this emits the specified diagnostic, /// or, if there's just some closing-delimiter noise (e.g., ')' or ']') prior /// to the semicolon, consumes that extra token. bool ExpectAndConsumeSemi(unsigned DiagID); /// \brief The kind of extra semi diagnostic to emit. enum ExtraSemiKind { OutsideFunction = 0, InsideStruct = 1, InstanceVariableList = 2, AfterMemberFunctionDefinition = 3 }; /// \brief Consume any extra semi-colons until the end of the line. void ConsumeExtraSemi(ExtraSemiKind Kind, unsigned TST = TST_unspecified); /// Return false if the next token is an identifier. An 'expected identifier' /// error is emitted otherwise. /// /// The parser tries to recover from the error by checking if the next token /// is a C++ keyword when parsing Objective-C++. Return false if the recovery /// was successful. bool expectIdentifier(); public: //===--------------------------------------------------------------------===// // Scope manipulation /// ParseScope - Introduces a new scope for parsing. The kind of /// scope is determined by ScopeFlags. Objects of this type should /// be created on the stack to coincide with the position where the /// parser enters the new scope, and this object's constructor will /// create that new scope. Similarly, once the object is destroyed /// the parser will exit the scope. class ParseScope { Parser *Self; ParseScope(const ParseScope &) = delete; void operator=(const ParseScope &) = delete; public: // ParseScope - Construct a new object to manage a scope in the // parser Self where the new Scope is created with the flags // ScopeFlags, but only when we aren't about to enter a compound statement. ParseScope(Parser *Self, unsigned ScopeFlags, bool EnteredScope = true, bool BeforeCompoundStmt = false) : Self(Self) { if (EnteredScope && !BeforeCompoundStmt) Self->EnterScope(ScopeFlags); else { if (BeforeCompoundStmt) Self->incrementMSManglingNumber(); this->Self = nullptr; } } // Exit - Exit the scope associated with this object now, rather // than waiting until the object is destroyed. void Exit() { if (Self) { Self->ExitScope(); Self = nullptr; } } ~ParseScope() { Exit(); } }; /// EnterScope - Start a new scope. void EnterScope(unsigned ScopeFlags); /// ExitScope - Pop a scope off the scope stack. void ExitScope(); private: /// \brief RAII object used to modify the scope flags for the current scope. class ParseScopeFlags { Scope *CurScope; unsigned OldFlags; ParseScopeFlags(const ParseScopeFlags &) = delete; void operator=(const ParseScopeFlags &) = delete; public: ParseScopeFlags(Parser *Self, unsigned ScopeFlags, bool ManageFlags = true); ~ParseScopeFlags(); }; //===--------------------------------------------------------------------===// // Diagnostic Emission and Error recovery. public: DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID); DiagnosticBuilder Diag(const Token &Tok, unsigned DiagID); DiagnosticBuilder Diag(unsigned DiagID) { return Diag(Tok, DiagID); } private: void SuggestParentheses(SourceLocation Loc, unsigned DK, SourceRange ParenRange); void CheckNestedObjCContexts(SourceLocation AtLoc); public: /// \brief Control flags for SkipUntil functions. enum SkipUntilFlags { StopAtSemi = 1 << 0, ///< Stop skipping at semicolon /// \brief Stop skipping at specified token, but don't skip the token itself StopBeforeMatch = 1 << 1, StopAtCodeCompletion = 1 << 2 ///< Stop at code completion }; friend constexpr SkipUntilFlags operator|(SkipUntilFlags L, SkipUntilFlags R) { return static_cast<SkipUntilFlags>(static_cast<unsigned>(L) | static_cast<unsigned>(R)); } /// SkipUntil - Read tokens until we get to the specified token, then consume /// it (unless StopBeforeMatch is specified). Because we cannot guarantee /// that the token will ever occur, this skips to the next token, or to some /// likely good stopping point. If Flags has StopAtSemi flag, skipping will /// stop at a ';' character. /// /// If SkipUntil finds the specified token, it returns true, otherwise it /// returns false. bool SkipUntil(tok::TokenKind T, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { return SkipUntil(llvm::makeArrayRef(T), Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2}; return SkipUntil(TokArray, Flags); } bool SkipUntil(tok::TokenKind T1, tok::TokenKind T2, tok::TokenKind T3, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)) { tok::TokenKind TokArray[] = {T1, T2, T3}; return SkipUntil(TokArray, Flags); } bool SkipUntil(ArrayRef<tok::TokenKind> Toks, SkipUntilFlags Flags = static_cast<SkipUntilFlags>(0)); /// SkipMalformedDecl - Read tokens until we get to some likely good stopping /// point for skipping past a simple-declaration. void SkipMalformedDecl(); private: //===--------------------------------------------------------------------===// // Lexing and parsing of C++ inline methods. struct ParsingClass; /// [class.mem]p1: "... the class is regarded as complete within /// - function bodies /// - default arguments /// - exception-specifications (TODO: C++0x) /// - and brace-or-equal-initializers for non-static data members /// (including such things in nested classes)." /// LateParsedDeclarations build the tree of those elements so they can /// be parsed after parsing the top-level class. class LateParsedDeclaration { public: virtual ~LateParsedDeclaration(); virtual void ParseLexedMethodDeclarations(); virtual void ParseLexedMemberInitializers(); virtual void ParseLexedMethodDefs(); virtual void ParseLexedAttributes(); }; /// Inner node of the LateParsedDeclaration tree that parses /// all its members recursively. class LateParsedClass : public LateParsedDeclaration { public: LateParsedClass(Parser *P, ParsingClass *C); ~LateParsedClass() override; void ParseLexedMethodDeclarations() override; void ParseLexedMemberInitializers() override; void ParseLexedMethodDefs() override; void ParseLexedAttributes() override; private: Parser *Self; ParsingClass *Class; }; /// Contains the lexed tokens of an attribute with arguments that /// may reference member variables and so need to be parsed at the /// end of the class declaration after parsing all other member /// member declarations. /// FIXME: Perhaps we should change the name of LateParsedDeclaration to /// LateParsedTokens. struct LateParsedAttribute : public LateParsedDeclaration { Parser *Self; CachedTokens Toks; IdentifierInfo &AttrName; SourceLocation AttrNameLoc; SmallVector<Decl*, 2> Decls; explicit LateParsedAttribute(Parser *P, IdentifierInfo &Name, SourceLocation Loc) : Self(P), AttrName(Name), AttrNameLoc(Loc) {} void ParseLexedAttributes() override; void addDecl(Decl *D) { Decls.push_back(D); } }; // A list of late-parsed attributes. Used by ParseGNUAttributes. class LateParsedAttrList: public SmallVector<LateParsedAttribute *, 2> { public: LateParsedAttrList(bool PSoon = false) : ParseSoon(PSoon) { } bool parseSoon() { return ParseSoon; } private: bool ParseSoon; // Are we planning to parse these shortly after creation? }; /// Contains the lexed tokens of a member function definition /// which needs to be parsed at the end of the class declaration /// after parsing all other member declarations. struct LexedMethod : public LateParsedDeclaration { Parser *Self; Decl *D; CachedTokens Toks; /// \brief Whether this member function had an associated template /// scope. When true, D is a template declaration. /// otherwise, it is a member function declaration. bool TemplateScope; explicit LexedMethod(Parser* P, Decl *MD) : Self(P), D(MD), TemplateScope(false) {} void ParseLexedMethodDefs() override; }; /// LateParsedDefaultArgument - Keeps track of a parameter that may /// have a default argument that cannot be parsed yet because it /// occurs within a member function declaration inside the class /// (C++ [class.mem]p2). struct LateParsedDefaultArgument { explicit LateParsedDefaultArgument(Decl *P, std::unique_ptr<CachedTokens> Toks = nullptr) : Param(P), Toks(std::move(Toks)) { } /// Param - The parameter declaration for this parameter. Decl *Param; /// Toks - The sequence of tokens that comprises the default /// argument expression, not including the '=' or the terminating /// ')' or ','. This will be NULL for parameters that have no /// default argument. std::unique_ptr<CachedTokens> Toks; }; /// LateParsedMethodDeclaration - A method declaration inside a class that /// contains at least one entity whose parsing needs to be delayed /// until the class itself is completely-defined, such as a default /// argument (C++ [class.mem]p2). struct LateParsedMethodDeclaration : public LateParsedDeclaration { explicit LateParsedMethodDeclaration(Parser *P, Decl *M) : Self(P), Method(M), TemplateScope(false), ExceptionSpecTokens(nullptr) {} void ParseLexedMethodDeclarations() override; Parser* Self; /// Method - The method declaration. Decl *Method; /// \brief Whether this member function had an associated template /// scope. When true, D is a template declaration. /// othewise, it is a member function declaration. bool TemplateScope; /// DefaultArgs - Contains the parameters of the function and /// their default arguments. At least one of the parameters will /// have a default argument, but all of the parameters of the /// method will be stored so that they can be reintroduced into /// scope at the appropriate times. SmallVector<LateParsedDefaultArgument, 8> DefaultArgs; /// \brief The set of tokens that make up an exception-specification that /// has not yet been parsed. CachedTokens *ExceptionSpecTokens; }; /// LateParsedMemberInitializer - An initializer for a non-static class data /// member whose parsing must to be delayed until the class is completely /// defined (C++11 [class.mem]p2). struct LateParsedMemberInitializer : public LateParsedDeclaration { LateParsedMemberInitializer(Parser *P, Decl *FD) : Self(P), Field(FD) { } void ParseLexedMemberInitializers() override; Parser *Self; /// Field - The field declaration. Decl *Field; /// CachedTokens - The sequence of tokens that comprises the initializer, /// including any leading '='. CachedTokens Toks; }; /// LateParsedDeclarationsContainer - During parsing of a top (non-nested) /// C++ class, its method declarations that contain parts that won't be /// parsed until after the definition is completed (C++ [class.mem]p2), /// the method declarations and possibly attached inline definitions /// will be stored here with the tokens that will be parsed to create those /// entities. typedef SmallVector<LateParsedDeclaration*,2> LateParsedDeclarationsContainer; /// \brief Representation of a class that has been parsed, including /// any member function declarations or definitions that need to be /// parsed after the corresponding top-level class is complete. struct ParsingClass { ParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : TopLevelClass(TopLevelClass), TemplateScope(false), IsInterface(IsInterface), TagOrTemplate(TagOrTemplate) { } /// \brief Whether this is a "top-level" class, meaning that it is /// not nested within another class. bool TopLevelClass : 1; /// \brief Whether this class had an associated template /// scope. When true, TagOrTemplate is a template declaration; /// othewise, it is a tag declaration. bool TemplateScope : 1; /// \brief Whether this class is an __interface. bool IsInterface : 1; /// \brief The class or class template whose definition we are parsing. Decl *TagOrTemplate; /// LateParsedDeclarations - Method declarations, inline definitions and /// nested classes that contain pieces whose parsing will be delayed until /// the top-level class is fully defined. LateParsedDeclarationsContainer LateParsedDeclarations; }; /// \brief The stack of classes that is currently being /// parsed. Nested and local classes will be pushed onto this stack /// when they are parsed, and removed afterward. std::stack<ParsingClass *> ClassStack; ParsingClass &getCurrentClass() { assert(!ClassStack.empty() && "No lexed method stacks!"); return *ClassStack.top(); } /// \brief RAII object used to manage the parsing of a class definition. class ParsingClassDefinition { Parser &P; bool Popped; Sema::ParsingClassState State; public: ParsingClassDefinition(Parser &P, Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface) : P(P), Popped(false), State(P.PushParsingClass(TagOrTemplate, TopLevelClass, IsInterface)) { } /// \brief Pop this class of the stack. void Pop() { assert(!Popped && "Nested class has already been popped"); Popped = true; P.PopParsingClass(State); } ~ParsingClassDefinition() { if (!Popped) P.PopParsingClass(State); } }; /// \brief Contains information about any template-specific /// information that has been parsed prior to parsing declaration /// specifiers. struct ParsedTemplateInfo { ParsedTemplateInfo() : Kind(NonTemplate), TemplateParams(nullptr), TemplateLoc() { } ParsedTemplateInfo(TemplateParameterLists *TemplateParams, bool isSpecialization, bool lastParameterListWasEmpty = false) : Kind(isSpecialization? ExplicitSpecialization : Template), TemplateParams(TemplateParams), LastParameterListWasEmpty(lastParameterListWasEmpty) { } explicit ParsedTemplateInfo(SourceLocation ExternLoc, SourceLocation TemplateLoc) : Kind(ExplicitInstantiation), TemplateParams(nullptr), ExternLoc(ExternLoc), TemplateLoc(TemplateLoc), LastParameterListWasEmpty(false){ } /// \brief The kind of template we are parsing. enum { /// \brief We are not parsing a template at all. NonTemplate = 0, /// \brief We are parsing a template declaration. Template, /// \brief We are parsing an explicit specialization. ExplicitSpecialization, /// \brief We are parsing an explicit instantiation. ExplicitInstantiation } Kind; /// \brief The template parameter lists, for template declarations /// and explicit specializations. TemplateParameterLists *TemplateParams; /// \brief The location of the 'extern' keyword, if any, for an explicit /// instantiation SourceLocation ExternLoc; /// \brief The location of the 'template' keyword, for an explicit /// instantiation. SourceLocation TemplateLoc; /// \brief Whether the last template parameter list was empty. bool LastParameterListWasEmpty; SourceRange getSourceRange() const LLVM_READONLY; }; void LexTemplateFunctionForLateParsing(CachedTokens &Toks); void ParseLateTemplatedFuncDef(LateParsedTemplate &LPT); static void LateTemplateParserCallback(void *P, LateParsedTemplate &LPT); static void LateTemplateParserCleanupCallback(void *P); Sema::ParsingClassState PushParsingClass(Decl *TagOrTemplate, bool TopLevelClass, bool IsInterface); void DeallocateParsedClasses(ParsingClass *Class); void PopParsingClass(Sema::ParsingClassState); enum CachedInitKind { CIK_DefaultArgument, CIK_DefaultInitializer }; NamedDecl *ParseCXXInlineMethodDef(AccessSpecifier AS, AttributeList *AccessAttrs, ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo, const VirtSpecifiers& VS, SourceLocation PureSpecLoc); void ParseCXXNonStaticMemberInitializer(Decl *VarD); void ParseLexedAttributes(ParsingClass &Class); void ParseLexedAttributeList(LateParsedAttrList &LAs, Decl *D, bool EnterScope, bool OnDefinition); void ParseLexedAttribute(LateParsedAttribute &LA, bool EnterScope, bool OnDefinition); void ParseLexedMethodDeclarations(ParsingClass &Class); void ParseLexedMethodDeclaration(LateParsedMethodDeclaration &LM); void ParseLexedMethodDefs(ParsingClass &Class); void ParseLexedMethodDef(LexedMethod &LM); void ParseLexedMemberInitializers(ParsingClass &Class); void ParseLexedMemberInitializer(LateParsedMemberInitializer &MI); void ParseLexedObjCMethodDefs(LexedMethod &LM, bool parseMethod); bool ConsumeAndStoreFunctionPrologue(CachedTokens &Toks); bool ConsumeAndStoreInitializer(CachedTokens &Toks, CachedInitKind CIK); bool ConsumeAndStoreConditional(CachedTokens &Toks); bool ConsumeAndStoreUntil(tok::TokenKind T1, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true) { return ConsumeAndStoreUntil(T1, T1, Toks, StopAtSemi, ConsumeFinalToken); } bool ConsumeAndStoreUntil(tok::TokenKind T1, tok::TokenKind T2, CachedTokens &Toks, bool StopAtSemi = true, bool ConsumeFinalToken = true); //===--------------------------------------------------------------------===// // C99 6.9: External Definitions. struct ParsedAttributesWithRange : ParsedAttributes { ParsedAttributesWithRange(AttributeFactory &factory) : ParsedAttributes(factory) {} void clear() { ParsedAttributes::clear(); Range = SourceRange(); } SourceRange Range; }; DeclGroupPtrTy ParseExternalDeclaration(ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr); bool isDeclarationAfterDeclarator(); bool isStartOfFunctionDefinition(const ParsingDeclarator &Declarator); DeclGroupPtrTy ParseDeclarationOrFunctionDefinition( ParsedAttributesWithRange &attrs, ParsingDeclSpec *DS = nullptr, AccessSpecifier AS = AS_none); DeclGroupPtrTy ParseDeclOrFunctionDefInternal(ParsedAttributesWithRange &attrs, ParsingDeclSpec &DS, AccessSpecifier AS); void SkipFunctionBody(); Decl *ParseFunctionDefinition(ParsingDeclarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), LateParsedAttrList *LateParsedAttrs = nullptr); void ParseKNRParamDeclarations(Declarator &D); // EndLoc, if non-NULL, is filled with the location of the last token of // the simple-asm. ExprResult ParseSimpleAsm(SourceLocation *EndLoc = nullptr); ExprResult ParseAsmStringLiteral(); // Objective-C External Declarations void MaybeSkipAttributes(tok::ObjCKeywordKind Kind); DeclGroupPtrTy ParseObjCAtDirectives(); DeclGroupPtrTy ParseObjCAtClassDeclaration(SourceLocation atLoc); Decl *ParseObjCAtInterfaceDeclaration(SourceLocation AtLoc, ParsedAttributes &prefixAttrs); class ObjCTypeParamListScope; ObjCTypeParamList *parseObjCTypeParamList(); ObjCTypeParamList *parseObjCTypeParamListOrProtocolRefs( ObjCTypeParamListScope &Scope, SourceLocation &lAngleLoc, SmallVectorImpl<IdentifierLocPair> &protocolIdents, SourceLocation &rAngleLoc, bool mayBeProtocolList = true); void HelperActionsForIvarDeclarations(Decl *interfaceDecl, SourceLocation atLoc, BalancedDelimiterTracker &T, SmallVectorImpl<Decl *> &AllIvarDecls, bool RBraceMissing); void ParseObjCClassInstanceVariables(Decl *interfaceDecl, tok::ObjCKeywordKind visibility, SourceLocation atLoc); bool ParseObjCProtocolReferences(SmallVectorImpl<Decl *> &P, SmallVectorImpl<SourceLocation> &PLocs, bool WarnOnDeclarations, bool ForObjCContainer, SourceLocation &LAngleLoc, SourceLocation &EndProtoLoc, bool consumeLastToken); /// Parse the first angle-bracket-delimited clause for an /// Objective-C object or object pointer type, which may be either /// type arguments or protocol qualifiers. void parseObjCTypeArgsOrProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken, bool warnOnIncompleteProtocols); /// Parse either Objective-C type arguments or protocol qualifiers; if the /// former, also parse protocol qualifiers afterward. void parseObjCTypeArgsAndProtocolQualifiers( ParsedType baseType, SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs, SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc, SmallVectorImpl<Decl *> &protocols, SmallVectorImpl<SourceLocation> &protocolLocs, SourceLocation &protocolRAngleLoc, bool consumeLastToken); /// Parse a protocol qualifier type such as '<NSCopying>', which is /// an anachronistic way of writing 'id<NSCopying>'. TypeResult parseObjCProtocolQualifierType(SourceLocation &rAngleLoc); /// Parse Objective-C type arguments and protocol qualifiers, extending the /// current type with the parsed result. TypeResult parseObjCTypeArgsAndProtocolQualifiers(SourceLocation loc, ParsedType type, bool consumeLastToken, SourceLocation &endLoc); void ParseObjCInterfaceDeclList(tok::ObjCKeywordKind contextKey, Decl *CDecl); DeclGroupPtrTy ParseObjCAtProtocolDeclaration(SourceLocation atLoc, ParsedAttributes &prefixAttrs); struct ObjCImplParsingDataRAII { Parser &P; Decl *Dcl; bool HasCFunction; typedef SmallVector<LexedMethod*, 8> LateParsedObjCMethodContainer; LateParsedObjCMethodContainer LateParsedObjCMethods; ObjCImplParsingDataRAII(Parser &parser, Decl *D) : P(parser), Dcl(D), HasCFunction(false) { P.CurParsedObjCImpl = this; Finished = false; } ~ObjCImplParsingDataRAII(); void finish(SourceRange AtEnd); bool isFinished() const { return Finished; } private: bool Finished; }; ObjCImplParsingDataRAII *CurParsedObjCImpl; void StashAwayMethodOrFunctionBodyTokens(Decl *MDecl); DeclGroupPtrTy ParseObjCAtImplementationDeclaration(SourceLocation AtLoc); DeclGroupPtrTy ParseObjCAtEndDeclaration(SourceRange atEnd); Decl *ParseObjCAtAliasDeclaration(SourceLocation atLoc); Decl *ParseObjCPropertySynthesize(SourceLocation atLoc); Decl *ParseObjCPropertyDynamic(SourceLocation atLoc); IdentifierInfo *ParseObjCSelectorPiece(SourceLocation &MethodLocation); // Definitions for Objective-c context sensitive keywords recognition. enum ObjCTypeQual { objc_in=0, objc_out, objc_inout, objc_oneway, objc_bycopy, objc_byref, objc_nonnull, objc_nullable, objc_null_unspecified, objc_NumQuals }; IdentifierInfo *ObjCTypeQuals[objc_NumQuals]; bool isTokIdentifier_in() const; ParsedType ParseObjCTypeName(ObjCDeclSpec &DS, Declarator::TheContext Ctx, ParsedAttributes *ParamAttrs); void ParseObjCMethodRequirement(); Decl *ParseObjCMethodPrototype( tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition = true); Decl *ParseObjCMethodDecl(SourceLocation mLoc, tok::TokenKind mType, tok::ObjCKeywordKind MethodImplKind = tok::objc_not_keyword, bool MethodDefinition=true); void ParseObjCPropertyAttribute(ObjCDeclSpec &DS); Decl *ParseObjCMethodDefinition(); public: //===--------------------------------------------------------------------===// // C99 6.5: Expressions. /// TypeCastState - State whether an expression is or may be a type cast. enum TypeCastState { NotTypeCast = 0, MaybeTypeCast, IsTypeCast }; ExprResult ParseExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstantExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseConstraintExpression(); // Expr that doesn't include commas. ExprResult ParseAssignmentExpression(TypeCastState isTypeCast = NotTypeCast); ExprResult ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks, unsigned &NumLineToksConsumed, void *Info, bool IsUnevaluated); private: ExprResult ParseExpressionWithLeadingAt(SourceLocation AtLoc); ExprResult ParseExpressionWithLeadingExtension(SourceLocation ExtLoc); ExprResult ParseRHSOfBinaryExpression(ExprResult LHS, prec::Level MinPrec); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand, bool &NotCastExpr, TypeCastState isTypeCast, bool isVectorLiteral = false); ExprResult ParseCastExpression(bool isUnaryExpression, bool isAddressOfOperand = false, TypeCastState isTypeCast = NotTypeCast, bool isVectorLiteral = false); /// Returns true if the next token cannot start an expression. bool isNotExpressionStart(); /// Returns true if the next token would start a postfix-expression /// suffix. bool isPostfixExpressionSuffixStart() { tok::TokenKind K = Tok.getKind(); return (K == tok::l_square || K == tok::l_paren || K == tok::period || K == tok::arrow || K == tok::plusplus || K == tok::minusminus); } ExprResult ParsePostfixExpressionSuffix(ExprResult LHS); ExprResult ParseUnaryExprOrTypeTraitExpression(); ExprResult ParseBuiltinPrimaryExpression(); ExprResult ParseExprAfterUnaryExprOrTypeTrait(const Token &OpTok, bool &isCastExpr, ParsedType &CastTy, SourceRange &CastRange); typedef SmallVector<Expr*, 20> ExprListTy; typedef SmallVector<SourceLocation, 20> CommaLocsTy; /// ParseExpressionList - Used for C/C++ (argument-)expression-list. bool ParseExpressionList(SmallVectorImpl<Expr *> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs, std::function<void()> Completer = nullptr); /// ParseSimpleExpressionList - A simple comma-separated list of expressions, /// used for misc language extensions. bool ParseSimpleExpressionList(SmallVectorImpl<Expr*> &Exprs, SmallVectorImpl<SourceLocation> &CommaLocs); /// ParenParseOption - Control what ParseParenExpression will parse. enum ParenParseOption { SimpleExpr, // Only parse '(' expression ')' CompoundStmt, // Also allow '(' compound-statement ')' CompoundLiteral, // Also allow '(' type-name ')' '{' ... '}' CastExpr // Also allow '(' type-name ')' <anything> }; ExprResult ParseParenExpression(ParenParseOption &ExprType, bool stopIfCastExpr, bool isTypeCast, ParsedType &CastTy, SourceLocation &RParenLoc); ExprResult ParseCXXAmbiguousParenExpression( ParenParseOption &ExprType, ParsedType &CastTy, BalancedDelimiterTracker &Tracker, ColonProtectionRAIIObject &ColonProt); ExprResult ParseCompoundLiteralExpression(ParsedType Ty, SourceLocation LParenLoc, SourceLocation RParenLoc); ExprResult ParseStringLiteralExpression(bool AllowUserDefinedLiteral = false); ExprResult ParseGenericSelectionExpression(); ExprResult ParseObjCBoolLiteral(); ExprResult ParseFoldExpression(ExprResult LHS, BalancedDelimiterTracker &T); //===--------------------------------------------------------------------===// // C++ Expressions ExprResult tryParseCXXIdExpression(CXXScopeSpec &SS, bool isAddressOfOperand, Token &Replacement); ExprResult ParseCXXIdExpression(bool isAddressOfOperand = false); bool areTokensAdjacent(const Token &A, const Token &B); void CheckForTemplateAndDigraph(Token &Next, ParsedType ObjectTypePtr, bool EnteringContext, IdentifierInfo &II, CXXScopeSpec &SS); bool ParseOptionalCXXScopeSpecifier(CXXScopeSpec &SS, ParsedType ObjectType, bool EnteringContext, bool *MayBePseudoDestructor = nullptr, bool IsTypename = false, IdentifierInfo **LastII = nullptr, bool OnlyNamespace = false); //===--------------------------------------------------------------------===// // C++0x 5.1.2: Lambda expressions // [...] () -> type {...} ExprResult ParseLambdaExpression(); ExprResult TryParseLambdaExpression(); Optional<unsigned> ParseLambdaIntroducer(LambdaIntroducer &Intro, bool *SkippedInits = nullptr); bool TryParseLambdaIntroducer(LambdaIntroducer &Intro); ExprResult ParseLambdaExpressionAfterIntroducer( LambdaIntroducer &Intro); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Casts ExprResult ParseCXXCasts(); //===--------------------------------------------------------------------===// // C++ 5.2p1: C++ Type Identification ExprResult ParseCXXTypeid(); //===--------------------------------------------------------------------===// // C++ : Microsoft __uuidof Expression ExprResult ParseCXXUuidof(); //===--------------------------------------------------------------------===// // C++ 5.2.4: C++ Pseudo-Destructor Expressions ExprResult ParseCXXPseudoDestructor(Expr *Base, SourceLocation OpLoc, tok::TokenKind OpKind, CXXScopeSpec &SS, ParsedType ObjectType); //===--------------------------------------------------------------------===// // C++ 9.3.2: C++ 'this' pointer ExprResult ParseCXXThis(); //===--------------------------------------------------------------------===// // C++ 15: C++ Throw Expression ExprResult ParseThrowExpression(); ExceptionSpecificationType tryParseExceptionSpecification( bool Delayed, SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &DynamicExceptions, SmallVectorImpl<SourceRange> &DynamicExceptionRanges, ExprResult &NoexceptExpr, CachedTokens *&ExceptionSpecTokens); // EndLoc is filled with the location of the last token of the specification. ExceptionSpecificationType ParseDynamicExceptionSpecification( SourceRange &SpecificationRange, SmallVectorImpl<ParsedType> &Exceptions, SmallVectorImpl<SourceRange> &Ranges); //===--------------------------------------------------------------------===// // C++0x 8: Function declaration trailing-return-type TypeResult ParseTrailingReturnType(SourceRange &Range); //===--------------------------------------------------------------------===// // C++ 2.13.5: C++ Boolean Literals ExprResult ParseCXXBoolLiteral(); //===--------------------------------------------------------------------===// // C++ 5.2.3: Explicit type conversion (functional notation) ExprResult ParseCXXTypeConstructExpression(const DeclSpec &DS); /// ParseCXXSimpleTypeSpecifier - [C++ 7.1.5.2] Simple type specifiers. /// This should only be called when the current token is known to be part of /// simple-type-specifier. void ParseCXXSimpleTypeSpecifier(DeclSpec &DS); bool ParseCXXTypeSpecifierSeq(DeclSpec &DS); //===--------------------------------------------------------------------===// // C++ 5.3.4 and 5.3.5: C++ new and delete bool ParseExpressionListOrTypeId(SmallVectorImpl<Expr*> &Exprs, Declarator &D); void ParseDirectNewDeclarator(Declarator &D); ExprResult ParseCXXNewExpression(bool UseGlobal, SourceLocation Start); ExprResult ParseCXXDeleteExpression(bool UseGlobal, SourceLocation Start); //===--------------------------------------------------------------------===// // C++ if/switch/while condition expression. Sema::ConditionResult ParseCXXCondition(StmtResult *InitStmt, SourceLocation Loc, Sema::ConditionKind CK); //===--------------------------------------------------------------------===// // C++ Coroutines ExprResult ParseCoyieldExpression(); //===--------------------------------------------------------------------===// // C99 6.7.8: Initialization. /// ParseInitializer /// initializer: [C99 6.7.8] /// assignment-expression /// '{' ... ExprResult ParseInitializer() { if (Tok.isNot(tok::l_brace)) return ParseAssignmentExpression(); return ParseBraceInitializer(); } bool MayBeDesignationStart(); ExprResult ParseBraceInitializer(); ExprResult ParseInitializerWithPotentialDesignator(); //===--------------------------------------------------------------------===// // clang Expressions ExprResult ParseBlockLiteralExpression(); // ^{...} //===--------------------------------------------------------------------===// // Objective-C Expressions ExprResult ParseObjCAtExpression(SourceLocation AtLocation); ExprResult ParseObjCStringLiteral(SourceLocation AtLoc); ExprResult ParseObjCCharacterLiteral(SourceLocation AtLoc); ExprResult ParseObjCNumericLiteral(SourceLocation AtLoc); ExprResult ParseObjCBooleanLiteral(SourceLocation AtLoc, bool ArgValue); ExprResult ParseObjCArrayLiteral(SourceLocation AtLoc); ExprResult ParseObjCDictionaryLiteral(SourceLocation AtLoc); ExprResult ParseObjCBoxedExpr(SourceLocation AtLoc); ExprResult ParseObjCEncodeExpression(SourceLocation AtLoc); ExprResult ParseObjCSelectorExpression(SourceLocation AtLoc); ExprResult ParseObjCProtocolExpression(SourceLocation AtLoc); bool isSimpleObjCMessageExpression(); ExprResult ParseObjCMessageExpression(); ExprResult ParseObjCMessageExpressionBody(SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); ExprResult ParseAssignmentExprWithObjCMessageExprStart( SourceLocation LBracloc, SourceLocation SuperLoc, ParsedType ReceiverType, Expr *ReceiverExpr); bool ParseObjCXXMessageReceiver(bool &IsExpr, void *&TypeOrExpr); //===--------------------------------------------------------------------===// // C99 6.8: Statements and Blocks. /// A SmallVector of statements, with stack size 32 (as that is the only one /// used.) typedef SmallVector<Stmt*, 32> StmtVector; /// A SmallVector of expressions, with stack size 12 (the maximum used.) typedef SmallVector<Expr*, 12> ExprVector; /// A SmallVector of types. typedef SmallVector<ParsedType, 12> TypeVector; StmtResult ParseStatement(SourceLocation *TrailingElseLoc = nullptr, bool AllowOpenMPStandalone = false); enum AllowedConstructsKind { /// \brief Allow any declarations, statements, OpenMP directives. ACK_Any, /// \brief Allow only statements and non-standalone OpenMP directives. ACK_StatementsOpenMPNonStandalone, /// \brief Allow statements and all executable OpenMP directives ACK_StatementsOpenMPAnyExecutable }; StmtResult ParseStatementOrDeclaration(StmtVector &Stmts, AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc = nullptr); StmtResult ParseStatementOrDeclarationAfterAttributes( StmtVector &Stmts, AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); StmtResult ParseExprStatement(); StmtResult ParseLabeledStatement(ParsedAttributesWithRange &attrs); StmtResult ParseCaseStatement(bool MissingCase = false, ExprResult Expr = ExprResult()); StmtResult ParseDefaultStatement(); StmtResult ParseCompoundStatement(bool isStmtExpr = false); StmtResult ParseCompoundStatement(bool isStmtExpr, unsigned ScopeFlags); void ParseCompoundStatementLeadingPragmas(); StmtResult ParseCompoundStatementBody(bool isStmtExpr = false); bool ParseParenExprOrCondition(StmtResult *InitStmt, Sema::ConditionResult &CondResult, SourceLocation Loc, Sema::ConditionKind CK); StmtResult ParseIfStatement(SourceLocation *TrailingElseLoc); StmtResult ParseSwitchStatement(SourceLocation *TrailingElseLoc); StmtResult ParseWhileStatement(SourceLocation *TrailingElseLoc); StmtResult ParseDoStatement(); StmtResult ParseForStatement(SourceLocation *TrailingElseLoc); StmtResult ParseGotoStatement(); StmtResult ParseContinueStatement(); StmtResult ParseBreakStatement(); StmtResult ParseReturnStatement(); StmtResult ParseAsmStatement(bool &msAsm); StmtResult ParseMicrosoftAsmStatement(SourceLocation AsmLoc); StmtResult ParsePragmaLoopHint(StmtVector &Stmts, AllowedConstructsKind Allowed, SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs); /// \brief Describes the behavior that should be taken for an __if_exists /// block. enum IfExistsBehavior { /// \brief Parse the block; this code is always used. IEB_Parse, /// \brief Skip the block entirely; this code is never used. IEB_Skip, /// \brief Parse the block as a dependent block, which may be used in /// some template instantiations but not others. IEB_Dependent }; /// \brief Describes the condition of a Microsoft __if_exists or /// __if_not_exists block. struct IfExistsCondition { /// \brief The location of the initial keyword. SourceLocation KeywordLoc; /// \brief Whether this is an __if_exists block (rather than an /// __if_not_exists block). bool IsIfExists; /// \brief Nested-name-specifier preceding the name. CXXScopeSpec SS; /// \brief The name we're looking for. UnqualifiedId Name; /// \brief The behavior of this __if_exists or __if_not_exists block /// should. IfExistsBehavior Behavior; }; bool ParseMicrosoftIfExistsCondition(IfExistsCondition& Result); void ParseMicrosoftIfExistsStatement(StmtVector &Stmts); void ParseMicrosoftIfExistsExternalDeclaration(); void ParseMicrosoftIfExistsClassDeclaration(DeclSpec::TST TagType, AccessSpecifier& CurAS); bool ParseMicrosoftIfExistsBraceInitializer(ExprVector &InitExprs, bool &InitExprsOk); bool ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names, SmallVectorImpl<Expr *> &Constraints, SmallVectorImpl<Expr *> &Exprs); //===--------------------------------------------------------------------===// // C++ 6: Statements and Blocks StmtResult ParseCXXTryBlock(); StmtResult ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry = false); StmtResult ParseCXXCatchBlock(bool FnCatch = false); //===--------------------------------------------------------------------===// // MS: SEH Statements and Blocks StmtResult ParseSEHTryBlock(); StmtResult ParseSEHExceptBlock(SourceLocation Loc); StmtResult ParseSEHFinallyBlock(SourceLocation Loc); StmtResult ParseSEHLeaveStatement(); //===--------------------------------------------------------------------===// // Objective-C Statements StmtResult ParseObjCAtStatement(SourceLocation atLoc); StmtResult ParseObjCTryStmt(SourceLocation atLoc); StmtResult ParseObjCThrowStmt(SourceLocation atLoc); StmtResult ParseObjCSynchronizedStmt(SourceLocation atLoc); StmtResult ParseObjCAutoreleasePoolStmt(SourceLocation atLoc); //===--------------------------------------------------------------------===// // C99 6.7: Declarations. /// A context for parsing declaration specifiers. TODO: flesh this /// out, there are other significant restrictions on specifiers than /// would be best implemented in the parser. enum DeclSpecContext { DSC_normal, // normal context DSC_class, // class context, enables 'friend' DSC_type_specifier, // C++ type-specifier-seq or C specifier-qualifier-list DSC_trailing, // C++11 trailing-type-specifier in a trailing return type DSC_alias_declaration, // C++11 type-specifier-seq in an alias-declaration DSC_top_level, // top-level/namespace declaration context DSC_template_type_arg, // template type argument context DSC_objc_method_result, // ObjC method result context, enables 'instancetype' DSC_condition // condition declaration context }; /// Is this a context in which we are parsing just a type-specifier (or /// trailing-type-specifier)? static bool isTypeSpecifier(DeclSpecContext DSC) { switch (DSC) { case DSC_normal: case DSC_class: case DSC_top_level: case DSC_objc_method_result: case DSC_condition: return false; case DSC_template_type_arg: case DSC_type_specifier: case DSC_trailing: case DSC_alias_declaration: return true; } llvm_unreachable("Missing DeclSpecContext case"); } /// Is this a context in which we can perform class template argument /// deduction? static bool isClassTemplateDeductionContext(DeclSpecContext DSC) { switch (DSC) { case DSC_normal: case DSC_class: case DSC_top_level: case DSC_condition: case DSC_type_specifier: return true; case DSC_objc_method_result: case DSC_template_type_arg: case DSC_trailing: case DSC_alias_declaration: return false; } llvm_unreachable("Missing DeclSpecContext case"); } /// Information on a C++0x for-range-initializer found while parsing a /// declaration which turns out to be a for-range-declaration. struct ForRangeInit { SourceLocation ColonLoc; ExprResult RangeExpr; bool ParsedForRangeDecl() { return !ColonLoc.isInvalid(); } }; DeclGroupPtrTy ParseDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); DeclGroupPtrTy ParseSimpleDeclaration(unsigned Context, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs, bool RequireSemi, ForRangeInit *FRI = nullptr); bool MightBeDeclarator(unsigned Context); DeclGroupPtrTy ParseDeclGroup(ParsingDeclSpec &DS, unsigned Context, SourceLocation *DeclEnd = nullptr, ForRangeInit *FRI = nullptr); Decl *ParseDeclarationAfterDeclarator(Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo()); bool ParseAsmAttributesAfterDeclarator(Declarator &D); Decl *ParseDeclarationAfterDeclaratorAndAttributes( Declarator &D, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ForRangeInit *FRI = nullptr); Decl *ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope); Decl *ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope); /// \brief When in code-completion, skip parsing of the function/method body /// unless the body contains the code-completion point. /// /// \returns true if the function body was skipped. bool trySkippingFunctionBody(); bool ParseImplicitInt(DeclSpec &DS, CXXScopeSpec *SS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC, ParsedAttributesWithRange &Attrs); DeclSpecContext getDeclSpecContextFromDeclaratorContext(unsigned Context); void ParseDeclarationSpecifiers(DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), AccessSpecifier AS = AS_none, DeclSpecContext DSC = DSC_normal, LateParsedAttrList *LateAttrs = nullptr); bool DiagnoseMissingSemiAfterTagDefinition(DeclSpec &DS, AccessSpecifier AS, DeclSpecContext DSContext, LateParsedAttrList *LateAttrs = nullptr); void ParseSpecifierQualifierList(DeclSpec &DS, AccessSpecifier AS = AS_none, DeclSpecContext DSC = DSC_normal); void ParseObjCTypeQualifierList(ObjCDeclSpec &DS, Declarator::TheContext Context); void ParseEnumSpecifier(SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, DeclSpecContext DSC); void ParseEnumBody(SourceLocation StartLoc, Decl *TagDecl); void ParseStructUnionBody(SourceLocation StartLoc, unsigned TagType, Decl *TagDecl); void ParseStructDeclaration( ParsingDeclSpec &DS, llvm::function_ref<void(ParsingFieldDeclarator &)> FieldsCallback); bool isDeclarationSpecifier(bool DisambiguatingWithExpression = false); bool isTypeSpecifierQualifier(); /// isKnownToBeTypeSpecifier - Return true if we know that the specified token /// is definitely a type-specifier. Return false if it isn't part of a type /// specifier or if we're not sure. bool isKnownToBeTypeSpecifier(const Token &Tok) const; /// \brief Return true if we know that we are definitely looking at a /// decl-specifier, and isn't part of an expression such as a function-style /// cast. Return false if it's no a decl-specifier, or we're not sure. bool isKnownToBeDeclarationSpecifier() { if (getLangOpts().CPlusPlus) return isCXXDeclarationSpecifier() == TPResult::True; return isDeclarationSpecifier(true); } /// isDeclarationStatement - Disambiguates between a declaration or an /// expression statement, when parsing function bodies. /// Returns true for declaration, false for expression. bool isDeclarationStatement() { if (getLangOpts().CPlusPlus) return isCXXDeclarationStatement(); return isDeclarationSpecifier(true); } /// isForInitDeclaration - Disambiguates between a declaration or an /// expression in the context of the C 'clause-1' or the C++ // 'for-init-statement' part of a 'for' statement. /// Returns true for declaration, false for expression. bool isForInitDeclaration() { if (getLangOpts().CPlusPlus) return isCXXSimpleDeclaration(/*AllowForRangeDecl=*/true); return isDeclarationSpecifier(true); } /// \brief Determine whether this is a C++1z for-range-identifier. bool isForRangeIdentifier(); /// \brief Determine whether we are currently at the start of an Objective-C /// class message that appears to be missing the open bracket '['. bool isStartOfObjCClassMessageMissingOpenBracket(); /// \brief Starting with a scope specifier, identifier, or /// template-id that refers to the current class, determine whether /// this is a constructor declarator. bool isConstructorDeclarator(bool Unqualified, bool DeductionGuide = false); /// \brief Specifies the context in which type-id/expression /// disambiguation will occur. enum TentativeCXXTypeIdContext { TypeIdInParens, TypeIdUnambiguous, TypeIdAsTemplateArgument }; /// isTypeIdInParens - Assumes that a '(' was parsed and now we want to know /// whether the parens contain an expression or a type-id. /// Returns true for a type-id and false for an expression. bool isTypeIdInParens(bool &isAmbiguous) { if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdInParens, isAmbiguous); isAmbiguous = false; return isTypeSpecifierQualifier(); } bool isTypeIdInParens() { bool isAmbiguous; return isTypeIdInParens(isAmbiguous); } /// \brief Checks if the current tokens form type-id or expression. /// It is similar to isTypeIdInParens but does not suppose that type-id /// is in parenthesis. bool isTypeIdUnambiguously() { bool IsAmbiguous; if (getLangOpts().CPlusPlus) return isCXXTypeId(TypeIdUnambiguous, IsAmbiguous); return isTypeSpecifierQualifier(); } /// isCXXDeclarationStatement - C++-specialized function that disambiguates /// between a declaration or an expression statement, when parsing function /// bodies. Returns true for declaration, false for expression. bool isCXXDeclarationStatement(); /// isCXXSimpleDeclaration - C++-specialized function that disambiguates /// between a simple-declaration or an expression-statement. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. /// Returns false if the statement is disambiguated as expression. bool isCXXSimpleDeclaration(bool AllowForRangeDecl); /// isCXXFunctionDeclarator - Disambiguates between a function declarator or /// a constructor-style initializer, when parsing declaration statements. /// Returns true for function declarator and false for constructor-style /// initializer. Sets 'IsAmbiguous' to true to indicate that this declaration /// might be a constructor-style initializer. /// If during the disambiguation process a parsing error is encountered, /// the function returns true to let the declaration parsing code handle it. bool isCXXFunctionDeclarator(bool *IsAmbiguous = nullptr); struct ConditionDeclarationOrInitStatementState; enum class ConditionOrInitStatement { Expression, ///< Disambiguated as an expression (either kind). ConditionDecl, ///< Disambiguated as the declaration form of condition. InitStmtDecl, ///< Disambiguated as a simple-declaration init-statement. Error ///< Can't be any of the above! }; /// \brief Disambiguates between the different kinds of things that can happen /// after 'if (' or 'switch ('. This could be one of two different kinds of /// declaration (depending on whether there is a ';' later) or an expression. ConditionOrInitStatement isCXXConditionDeclarationOrInitStatement(bool CanBeInitStmt); bool isCXXTypeId(TentativeCXXTypeIdContext Context, bool &isAmbiguous); bool isCXXTypeId(TentativeCXXTypeIdContext Context) { bool isAmbiguous; return isCXXTypeId(Context, isAmbiguous); } /// TPResult - Used as the result value for functions whose purpose is to /// disambiguate C++ constructs by "tentatively parsing" them. enum class TPResult { True, False, Ambiguous, Error }; /// \brief Based only on the given token kind, determine whether we know that /// we're at the start of an expression or a type-specifier-seq (which may /// be an expression, in C++). /// /// This routine does not attempt to resolve any of the trick cases, e.g., /// those involving lookup of identifiers. /// /// \returns \c TPR_true if this token starts an expression, \c TPR_false if /// this token starts a type-specifier-seq, or \c TPR_ambiguous if it cannot /// tell. TPResult isExpressionOrTypeSpecifierSimple(tok::TokenKind Kind); /// isCXXDeclarationSpecifier - Returns TPResult::True if it is a /// declaration specifier, TPResult::False if it is not, /// TPResult::Ambiguous if it could be either a decl-specifier or a /// function-style cast, and TPResult::Error if a parsing error was /// encountered. If it could be a braced C++11 function-style cast, returns /// BracedCastResult. /// Doesn't consume tokens. TPResult isCXXDeclarationSpecifier(TPResult BracedCastResult = TPResult::False, bool *HasMissingTypename = nullptr); /// Given that isCXXDeclarationSpecifier returns \c TPResult::True or /// \c TPResult::Ambiguous, determine whether the decl-specifier would be /// a type-specifier other than a cv-qualifier. bool isCXXDeclarationSpecifierAType(); /// \brief Determine whether an identifier has been tentatively declared as a /// non-type. Such tentative declarations should not be found to name a type /// during a tentative parse, but also should not be annotated as a non-type. bool isTentativelyDeclared(IdentifierInfo *II); // "Tentative parsing" functions, used for disambiguation. If a parsing error // is encountered they will return TPResult::Error. // Returning TPResult::True/False indicates that the ambiguity was // resolved and tentative parsing may stop. TPResult::Ambiguous indicates // that more tentative parsing is necessary for disambiguation. // They all consume tokens, so backtracking should be used after calling them. TPResult TryParseSimpleDeclaration(bool AllowForRangeDecl); TPResult TryParseTypeofSpecifier(); TPResult TryParseProtocolQualifiers(); TPResult TryParsePtrOperatorSeq(); TPResult TryParseOperatorId(); TPResult TryParseInitDeclaratorList(); TPResult TryParseDeclarator(bool mayBeAbstract, bool mayHaveIdentifier=true); TPResult TryParseParameterDeclarationClause(bool *InvalidAsDeclaration = nullptr, bool VersusTemplateArg = false); TPResult TryParseFunctionDeclarator(); TPResult TryParseBracketDeclarator(); TPResult TryConsumeDeclarationSpecifier(); public: TypeResult ParseTypeName(SourceRange *Range = nullptr, Declarator::TheContext Context = Declarator::TypeNameContext, AccessSpecifier AS = AS_none, Decl **OwnedType = nullptr, ParsedAttributes *Attrs = nullptr); private: void ParseBlockId(SourceLocation CaretLoc); // Check for the start of a C++11 attribute-specifier-seq in a context where // an attribute is not allowed. bool CheckProhibitedCXX11Attribute() { assert(Tok.is(tok::l_square)); if (!getLangOpts().CPlusPlus11 || NextToken().isNot(tok::l_square)) return false; return DiagnoseProhibitedCXX11Attribute(); } bool DiagnoseProhibitedCXX11Attribute(); void CheckMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation) { if (!getLangOpts().CPlusPlus11) return; if ((Tok.isNot(tok::l_square) || NextToken().isNot(tok::l_square)) && Tok.isNot(tok::kw_alignas)) return; DiagnoseMisplacedCXX11Attribute(Attrs, CorrectLocation); } void DiagnoseMisplacedCXX11Attribute(ParsedAttributesWithRange &Attrs, SourceLocation CorrectLocation); void stripTypeAttributesOffDeclSpec(ParsedAttributesWithRange &Attrs, DeclSpec &DS, Sema::TagUseKind TUK); void ProhibitAttributes(ParsedAttributesWithRange &attrs) { if (!attrs.Range.isValid()) return; DiagnoseProhibitedAttributes(attrs); attrs.clear(); } void DiagnoseProhibitedAttributes(ParsedAttributesWithRange &attrs); // Forbid C++11 attributes that appear on certain syntactic // locations which standard permits but we don't supported yet, // for example, attributes appertain to decl specifiers. void ProhibitCXX11Attributes(ParsedAttributesWithRange &Attrs, unsigned DiagID); /// \brief Skip C++11 attributes and return the end location of the last one. /// \returns SourceLocation() if there are no attributes. SourceLocation SkipCXX11Attributes(); /// \brief Diagnose and skip C++11 attributes that appear in syntactic /// locations where attributes are not allowed. void DiagnoseAndSkipCXX11Attributes(); /// \brief Parses syntax-generic attribute arguments for attributes which are /// known to the implementation, and adds them to the given ParsedAttributes /// list with the given attribute syntax. Returns the number of arguments /// parsed for the attribute. unsigned ParseAttributeArgsCommon(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void MaybeParseGNUAttributes(Declarator &D, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) { ParsedAttributes attrs(AttrFactory); SourceLocation endLoc; ParseGNUAttributes(attrs, &endLoc, LateAttrs, &D); D.takeAttributes(attrs, endLoc); } } void MaybeParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr) { if (Tok.is(tok::kw___attribute)) ParseGNUAttributes(attrs, endLoc, LateAttrs); } void ParseGNUAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr, LateParsedAttrList *LateAttrs = nullptr, Declarator *D = nullptr); void ParseGNUAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax, Declarator *D); IdentifierLoc *ParseIdentifierLoc(); unsigned ParseClangAttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void MaybeParseCXX11Attributes(Declarator &D) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrs(AttrFactory); SourceLocation endLoc; ParseCXX11Attributes(attrs, &endLoc); D.takeAttributes(attrs, endLoc); } } void MaybeParseCXX11Attributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier()) { ParsedAttributesWithRange attrsWithRange(AttrFactory); ParseCXX11Attributes(attrsWithRange, endLoc); attrs.takeAllFrom(attrsWithRange); } } void MaybeParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *endLoc = nullptr, bool OuterMightBeMessageSend = false) { if (getLangOpts().CPlusPlus11 && isCXX11AttributeSpecifier(false, OuterMightBeMessageSend)) ParseCXX11Attributes(attrs, endLoc); } void ParseCXX11AttributeSpecifier(ParsedAttributes &attrs, SourceLocation *EndLoc = nullptr); void ParseCXX11Attributes(ParsedAttributesWithRange &attrs, SourceLocation *EndLoc = nullptr); /// \brief Parses a C++-style attribute argument list. Returns true if this /// results in adding an attribute to the ParsedAttributes list. bool ParseCXX11AttributeArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc); IdentifierInfo *TryParseCXX11AttributeIdentifier(SourceLocation &Loc); void MaybeParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr) { if (getLangOpts().MicrosoftExt && Tok.is(tok::l_square)) ParseMicrosoftAttributes(attrs, endLoc); } void ParseMicrosoftUuidAttributeArgs(ParsedAttributes &Attrs); void ParseMicrosoftAttributes(ParsedAttributes &attrs, SourceLocation *endLoc = nullptr); void MaybeParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr) { const auto &LO = getLangOpts(); if (LO.DeclSpecKeyword && Tok.is(tok::kw___declspec)) ParseMicrosoftDeclSpecs(Attrs, End); } void ParseMicrosoftDeclSpecs(ParsedAttributes &Attrs, SourceLocation *End = nullptr); bool ParseMicrosoftDeclSpecArgs(IdentifierInfo *AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs); void ParseMicrosoftTypeAttributes(ParsedAttributes &attrs); void DiagnoseAndSkipExtendedMicrosoftTypeAttributes(); SourceLocation SkipExtendedMicrosoftTypeAttributes(); void ParseMicrosoftInheritanceClassAttributes(ParsedAttributes &attrs); void ParseBorlandTypeAttributes(ParsedAttributes &attrs); void ParseOpenCLKernelAttributes(ParsedAttributes &attrs); void ParseOpenCLQualifiers(ParsedAttributes &Attrs); /// \brief Parses opencl_unroll_hint attribute if language is OpenCL v2.0 /// or higher. /// \return false if error happens. bool MaybeParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) { if (getLangOpts().OpenCL) return ParseOpenCLUnrollHintAttribute(Attrs); return true; } /// \brief Parses opencl_unroll_hint attribute. /// \return false if error happens. bool ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs); void ParseNullabilityTypeSpecifiers(ParsedAttributes &attrs); VersionTuple ParseVersionTuple(SourceRange &Range); void ParseAvailabilityAttribute(IdentifierInfo &Availability, SourceLocation AvailabilityLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); Optional<AvailabilitySpec> ParseAvailabilitySpec(); ExprResult ParseAvailabilityCheckExpr(SourceLocation StartLoc); void ParseExternalSourceSymbolAttribute(IdentifierInfo &ExternalSourceSymbol, SourceLocation Loc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseObjCBridgeRelatedAttribute(IdentifierInfo &ObjCBridgeRelated, SourceLocation ObjCBridgeRelatedLoc, ParsedAttributes &attrs, SourceLocation *endLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseTypeTagForDatatypeAttribute(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseAttributeWithTypeArg(IdentifierInfo &AttrName, SourceLocation AttrNameLoc, ParsedAttributes &Attrs, SourceLocation *EndLoc, IdentifierInfo *ScopeName, SourceLocation ScopeLoc, AttributeList::Syntax Syntax); void ParseTypeofSpecifier(DeclSpec &DS); SourceLocation ParseDecltypeSpecifier(DeclSpec &DS); void AnnotateExistingDecltypeSpecifier(const DeclSpec &DS, SourceLocation StartLoc, SourceLocation EndLoc); void ParseUnderlyingTypeSpecifier(DeclSpec &DS); void ParseAtomicSpecifier(DeclSpec &DS); ExprResult ParseAlignArgument(SourceLocation Start, SourceLocation &EllipsisLoc); void ParseAlignmentSpecifier(ParsedAttributes &Attrs, SourceLocation *endLoc = nullptr); VirtSpecifiers::Specifier isCXX11VirtSpecifier(const Token &Tok) const; VirtSpecifiers::Specifier isCXX11VirtSpecifier() const { return isCXX11VirtSpecifier(Tok); } void ParseOptionalCXX11VirtSpecifierSeq(VirtSpecifiers &VS, bool IsInterface, SourceLocation FriendLoc); bool isCXX11FinalKeyword() const; /// DeclaratorScopeObj - RAII object used in Parser::ParseDirectDeclarator to /// enter a new C++ declarator scope and exit it when the function is /// finished. class DeclaratorScopeObj { Parser &P; CXXScopeSpec &SS; bool EnteredScope; bool CreatedScope; public: DeclaratorScopeObj(Parser &p, CXXScopeSpec &ss) : P(p), SS(ss), EnteredScope(false), CreatedScope(false) {} void EnterDeclaratorScope() { assert(!EnteredScope && "Already entered the scope!"); assert(SS.isSet() && "C++ scope was not set!"); CreatedScope = true; P.EnterScope(0); // Not a decl scope. if (!P.Actions.ActOnCXXEnterDeclaratorScope(P.getCurScope(), SS)) EnteredScope = true; } ~DeclaratorScopeObj() { if (EnteredScope) { assert(SS.isSet() && "C++ scope was cleared ?"); P.Actions.ActOnCXXExitDeclaratorScope(P.getCurScope(), SS); } if (CreatedScope) P.ExitScope(); } }; /// ParseDeclarator - Parse and verify a newly-initialized declarator. void ParseDeclarator(Declarator &D); /// A function that parses a variant of direct-declarator. typedef void (Parser::*DirectDeclParseFunction)(Declarator&); void ParseDeclaratorInternal(Declarator &D, DirectDeclParseFunction DirectDeclParser); enum AttrRequirements { AR_NoAttributesParsed = 0, ///< No attributes are diagnosed. AR_GNUAttributesParsedAndRejected = 1 << 0, ///< Diagnose GNU attributes. AR_GNUAttributesParsed = 1 << 1, AR_CXX11AttributesParsed = 1 << 2, AR_DeclspecAttributesParsed = 1 << 3, AR_AllAttributesParsed = AR_GNUAttributesParsed | AR_CXX11AttributesParsed | AR_DeclspecAttributesParsed, AR_VendorAttributesParsed = AR_GNUAttributesParsed | AR_DeclspecAttributesParsed }; void ParseTypeQualifierListOpt( DeclSpec &DS, unsigned AttrReqs = AR_AllAttributesParsed, bool AtomicAllowed = true, bool IdentifierRequired = false, Optional<llvm::function_ref<void()>> CodeCompletionHandler = None); void ParseDirectDeclarator(Declarator &D); void ParseDecompositionDeclarator(Declarator &D); void ParseParenDeclarator(Declarator &D); void ParseFunctionDeclarator(Declarator &D, ParsedAttributes &attrs, BalancedDelimiterTracker &Tracker, bool IsAmbiguous, bool RequiresArg = false); bool ParseRefQualifier(bool &RefQualifierIsLValueRef, SourceLocation &RefQualifierLoc); bool isFunctionDeclaratorIdentifierList(); void ParseFunctionDeclaratorIdentifierList( Declarator &D, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo); void ParseParameterDeclarationClause( Declarator &D, ParsedAttributes &attrs, SmallVectorImpl<DeclaratorChunk::ParamInfo> &ParamInfo, SourceLocation &EllipsisLoc); void ParseBracketDeclarator(Declarator &D); void ParseMisplacedBracketDeclarator(Declarator &D); //===--------------------------------------------------------------------===// // C++ 7: Declarations [dcl.dcl] /// The kind of attribute specifier we have found. enum CXX11AttributeKind { /// This is not an attribute specifier. CAK_NotAttributeSpecifier, /// This should be treated as an attribute-specifier. CAK_AttributeSpecifier, /// The next tokens are '[[', but this is not an attribute-specifier. This /// is ill-formed by C++11 [dcl.attr.grammar]p6. CAK_InvalidAttributeSpecifier }; CXX11AttributeKind isCXX11AttributeSpecifier(bool Disambiguate = false, bool OuterMightBeMessageSend = false); void DiagnoseUnexpectedNamespace(NamedDecl *Context); DeclGroupPtrTy ParseNamespace(unsigned Context, SourceLocation &DeclEnd, SourceLocation InlineLoc = SourceLocation()); void ParseInnerNamespace(std::vector<SourceLocation>& IdentLoc, std::vector<IdentifierInfo*>& Ident, std::vector<SourceLocation>& NamespaceLoc, unsigned int index, SourceLocation& InlineLoc, ParsedAttributes& attrs, BalancedDelimiterTracker &Tracker); Decl *ParseLinkage(ParsingDeclSpec &DS, unsigned Context); Decl *ParseExportDeclaration(); DeclGroupPtrTy ParseUsingDirectiveOrDeclaration( unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation &DeclEnd, ParsedAttributesWithRange &attrs); Decl *ParseUsingDirective(unsigned Context, SourceLocation UsingLoc, SourceLocation &DeclEnd, ParsedAttributes &attrs); struct UsingDeclarator { SourceLocation TypenameLoc; CXXScopeSpec SS; SourceLocation TemplateKWLoc; UnqualifiedId Name; SourceLocation EllipsisLoc; void clear() { TypenameLoc = TemplateKWLoc = EllipsisLoc = SourceLocation(); SS.clear(); Name.clear(); } }; bool ParseUsingDeclarator(unsigned Context, UsingDeclarator &D); DeclGroupPtrTy ParseUsingDeclaration(unsigned Context, const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); Decl *ParseAliasDeclarationAfterDeclarator( const ParsedTemplateInfo &TemplateInfo, SourceLocation UsingLoc, UsingDeclarator &D, SourceLocation &DeclEnd, AccessSpecifier AS, ParsedAttributes &Attrs, Decl **OwnedType = nullptr); Decl *ParseStaticAssertDeclaration(SourceLocation &DeclEnd); Decl *ParseNamespaceAlias(SourceLocation NamespaceLoc, SourceLocation AliasLoc, IdentifierInfo *Alias, SourceLocation &DeclEnd); //===--------------------------------------------------------------------===// // C++ 9: classes [class] and C structs/unions. bool isValidAfterTypeSpecifier(bool CouldBeBitfield); void ParseClassSpecifier(tok::TokenKind TagTokKind, SourceLocation TagLoc, DeclSpec &DS, const ParsedTemplateInfo &TemplateInfo, AccessSpecifier AS, bool EnteringContext, DeclSpecContext DSC, ParsedAttributesWithRange &Attributes); void SkipCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, unsigned TagType, Decl *TagDecl); void ParseCXXMemberSpecification(SourceLocation StartLoc, SourceLocation AttrFixitLoc, ParsedAttributesWithRange &Attrs, unsigned TagType, Decl *TagDecl); ExprResult ParseCXXMemberInitializer(Decl *D, bool IsFunction, SourceLocation &EqualLoc); bool ParseCXXMemberDeclaratorBeforeInitializer(Declarator &DeclaratorInfo, VirtSpecifiers &VS, ExprResult &BitfieldSize, LateParsedAttrList &LateAttrs); void MaybeParseAndDiagnoseDeclSpecAfterCXX11VirtSpecifierSeq(Declarator &D, VirtSpecifiers &VS); DeclGroupPtrTy ParseCXXClassMemberDeclaration( AccessSpecifier AS, AttributeList *Attr, const ParsedTemplateInfo &TemplateInfo = ParsedTemplateInfo(), ParsingDeclRAIIObject *DiagsFromTParams = nullptr); DeclGroupPtrTy ParseCXXClassMemberDeclarationWithPragmas( AccessSpecifier &AS, ParsedAttributesWithRange &AccessAttrs, DeclSpec::TST TagType, Decl *Tag); void ParseConstructorInitializer(Decl *ConstructorDecl); MemInitResult ParseMemInitializer(Decl *ConstructorDecl); void HandleMemberFunctionDeclDelays(Declarator& DeclaratorInfo, Decl *ThisDecl); //===--------------------------------------------------------------------===// // C++ 10: Derived classes [class.derived] TypeResult ParseBaseTypeSpecifier(SourceLocation &BaseLoc, SourceLocation &EndLocation); void ParseBaseClause(Decl *ClassDecl); BaseResult ParseBaseSpecifier(Decl *ClassDecl); AccessSpecifier getAccessSpecifierIfPresent() const; bool ParseUnqualifiedIdTemplateId(CXXScopeSpec &SS, SourceLocation TemplateKWLoc, IdentifierInfo *Name, SourceLocation NameLoc, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Id, bool AssumeTemplateId); bool ParseUnqualifiedIdOperator(CXXScopeSpec &SS, bool EnteringContext, ParsedType ObjectType, UnqualifiedId &Result); //===--------------------------------------------------------------------===// // OpenMP: Directives and clauses. /// Parse clauses for '#pragma omp declare simd'. DeclGroupPtrTy ParseOMPDeclareSimdClauses(DeclGroupPtrTy Ptr, CachedTokens &Toks, SourceLocation Loc); /// \brief Parses declarative OpenMP directives. DeclGroupPtrTy ParseOpenMPDeclarativeDirectiveWithExtDecl( AccessSpecifier &AS, ParsedAttributesWithRange &Attrs, DeclSpec::TST TagType = DeclSpec::TST_unspecified, Decl *TagDecl = nullptr); /// \brief Parse 'omp declare reduction' construct. DeclGroupPtrTy ParseOpenMPDeclareReductionDirective(AccessSpecifier AS); /// \brief Parses simple list of variables. /// /// \param Kind Kind of the directive. /// \param Callback Callback function to be called for the list elements. /// \param AllowScopeSpecifier true, if the variables can have fully /// qualified names. /// bool ParseOpenMPSimpleVarList( OpenMPDirectiveKind Kind, const llvm::function_ref<void(CXXScopeSpec &, DeclarationNameInfo)> & Callback, bool AllowScopeSpecifier); /// \brief Parses declarative or executable directive. /// /// \param Allowed ACK_Any, if any directives are allowed, /// ACK_StatementsOpenMPAnyExecutable - if any executable directives are /// allowed, ACK_StatementsOpenMPNonStandalone - if only non-standalone /// executable directives are allowed. /// StmtResult ParseOpenMPDeclarativeOrExecutableDirective(AllowedConstructsKind Allowed); /// \brief Parses clause of kind \a CKind for directive of a kind \a Kind. /// /// \param DKind Kind of current directive. /// \param CKind Kind of current clause. /// \param FirstClause true, if this is the first clause of a kind \a CKind /// in current directive. /// OMPClause *ParseOpenMPClause(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, bool FirstClause); /// \brief Parses clause with a single expression of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSingleExprClause(OpenMPClauseKind Kind); /// \brief Parses simple clause of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSimpleClause(OpenMPClauseKind Kind); /// \brief Parses clause with a single expression and an additional argument /// of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPSingleExprWithArgClause(OpenMPClauseKind Kind); /// \brief Parses clause without any additional arguments. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPClause(OpenMPClauseKind Kind); /// \brief Parses clause with the list of variables of a kind \a Kind. /// /// \param Kind Kind of current clause. /// OMPClause *ParseOpenMPVarListClause(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind); public: /// Parses simple expression in parens for single-expression clauses of OpenMP /// constructs. /// \param RLoc Returned location of right paren. ExprResult ParseOpenMPParensExpr(StringRef ClauseName, SourceLocation &RLoc); /// Data used for parsing list of variables in OpenMP clauses. struct OpenMPVarListDataTy { Expr *TailExpr = nullptr; SourceLocation ColonLoc; CXXScopeSpec ReductionIdScopeSpec; DeclarationNameInfo ReductionId; OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; OpenMPLinearClauseKind LinKind = OMPC_LINEAR_val; OpenMPMapClauseKind MapTypeModifier = OMPC_MAP_unknown; OpenMPMapClauseKind MapType = OMPC_MAP_unknown; bool IsMapTypeImplicit = false; SourceLocation DepLinMapLoc; }; /// Parses clauses with list. bool ParseOpenMPVarList(OpenMPDirectiveKind DKind, OpenMPClauseKind Kind, SmallVectorImpl<Expr *> &Vars, OpenMPVarListDataTy &Data); bool ParseUnqualifiedId(CXXScopeSpec &SS, bool EnteringContext, bool AllowDestructorName, bool AllowConstructorName, bool AllowDeductionGuide, ParsedType ObjectType, SourceLocation& TemplateKWLoc, UnqualifiedId &Result); private: //===--------------------------------------------------------------------===// // C++ 14: Templates [temp] // C++ 14.1: Template Parameters [temp.param] Decl *ParseDeclarationStartingWithTemplate(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none, AttributeList *AccessAttrs = nullptr); Decl *ParseTemplateDeclarationOrSpecialization(unsigned Context, SourceLocation &DeclEnd, AccessSpecifier AS, AttributeList *AccessAttrs); Decl *ParseSingleDeclarationAfterTemplate( unsigned Context, const ParsedTemplateInfo &TemplateInfo, ParsingDeclRAIIObject &DiagsFromParams, SourceLocation &DeclEnd, AccessSpecifier AS=AS_none, AttributeList *AccessAttrs = nullptr); bool ParseTemplateParameters(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams, SourceLocation &LAngleLoc, SourceLocation &RAngleLoc); bool ParseTemplateParameterList(unsigned Depth, SmallVectorImpl<Decl*> &TemplateParams); bool isStartOfTemplateTypeParameter(); Decl *ParseTemplateParameter(unsigned Depth, unsigned Position); Decl *ParseTypeParameter(unsigned Depth, unsigned Position); Decl *ParseTemplateTemplateParameter(unsigned Depth, unsigned Position); Decl *ParseNonTypeTemplateParameter(unsigned Depth, unsigned Position); void DiagnoseMisplacedEllipsis(SourceLocation EllipsisLoc, SourceLocation CorrectLoc, bool AlreadyHasEllipsis, bool IdentifierHasName); void DiagnoseMisplacedEllipsisInDeclarator(SourceLocation EllipsisLoc, Declarator &D); // C++ 14.3: Template arguments [temp.arg] typedef SmallVector<ParsedTemplateArgument, 16> TemplateArgList; bool ParseGreaterThanInTemplateList(SourceLocation &RAngleLoc, bool ConsumeLastToken, bool ObjCGenericList); bool ParseTemplateIdAfterTemplateName(TemplateTy Template, SourceLocation TemplateNameLoc, const CXXScopeSpec &SS, bool ConsumeLastToken, SourceLocation &LAngleLoc, TemplateArgList &TemplateArgs, SourceLocation &RAngleLoc); bool AnnotateTemplateIdToken(TemplateTy Template, TemplateNameKind TNK, CXXScopeSpec &SS, SourceLocation TemplateKWLoc, UnqualifiedId &TemplateName, bool AllowTypeAnnotation = true); void AnnotateTemplateIdTokenAsType(bool IsClassName = false); bool IsTemplateArgumentList(unsigned Skip = 0); bool ParseTemplateArgumentList(TemplateArgList &TemplateArgs); ParsedTemplateArgument ParseTemplateTemplateArgument(); ParsedTemplateArgument ParseTemplateArgument(); Decl *ParseExplicitInstantiation(unsigned Context, SourceLocation ExternLoc, SourceLocation TemplateLoc, SourceLocation &DeclEnd, AccessSpecifier AS = AS_none); //===--------------------------------------------------------------------===// // Modules DeclGroupPtrTy ParseModuleDecl(); DeclGroupPtrTy ParseModuleImport(SourceLocation AtLoc); bool parseMisplacedModuleImport(); bool tryParseMisplacedModuleImport() { tok::TokenKind Kind = Tok.getKind(); if (Kind == tok::annot_module_begin || Kind == tok::annot_module_end || Kind == tok::annot_module_include) return parseMisplacedModuleImport(); return false; } bool ParseModuleName( SourceLocation UseLoc, SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>> &Path, bool IsImport); //===--------------------------------------------------------------------===// // C++11/G++: Type Traits [Type-Traits.html in the GCC manual] ExprResult ParseTypeTrait(); //===--------------------------------------------------------------------===// // Embarcadero: Arary and Expression Traits ExprResult ParseArrayTypeTrait(); ExprResult ParseExpressionTrait(); //===--------------------------------------------------------------------===// // Preprocessor code-completion pass-through void CodeCompleteDirective(bool InConditional) override; void CodeCompleteInConditionalExclusion() override; void CodeCompleteMacroName(bool IsDefinition) override; void CodeCompletePreprocessorExpression() override; void CodeCompleteMacroArgument(IdentifierInfo *Macro, MacroInfo *MacroInfo, unsigned ArgumentIndex) override; void CodeCompleteNaturalLanguage() override; }; } // end namespace clang #endif
GB_binop__bget_int32.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__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_01__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_02__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_03__bget_int32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_int32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_int32) // C+=b function (dense accum): GB (_Cdense_accumb__bget_int32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_int32) // C=scalar+B GB (_bind1st__bget_int32) // C=scalar+B' GB (_bind1st_tran__bget_int32) // C=A+scalar GB (_bind2nd__bget_int32) // C=A'+scalar GB (_bind2nd_tran__bget_int32) // C type: int32_t // A type: int32_t // B,b type: int32_t // BinaryOp: cij = GB_BITGET (aij, bij, int32_t, 32) #define GB_ATYPE \ int32_t #define GB_BTYPE \ int32_t #define GB_CTYPE \ int32_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) \ int32_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int32_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int32_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITGET (x, y, int32_t, 32) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_INT32 || GxB_NO_BGET_INT32) //------------------------------------------------------------------------------ // 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__bget_int32) ( 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__bget_int32) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_int32) ( 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 int32_t int32_t bwork = (*((int32_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 int32_t *restrict Cx = (int32_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 int32_t *restrict Cx = (int32_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_int32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bget_int32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bget_int32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_int32) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_int32) ( 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 int32_t *Cx = (int32_t *) Cx_output ; int32_t x = (*((int32_t *) x_input)) ; int32_t *Bx = (int32_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 ; int32_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITGET (x, bij, int32_t, 32) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_int32) ( 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 ; int32_t *Cx = (int32_t *) Cx_output ; int32_t *Ax = (int32_t *) Ax_input ; int32_t y = (*((int32_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int32_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITGET (aij, y, int32_t, 32) ; } 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) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, int32_t, 32) ; \ } GrB_Info GB (_bind1st_tran__bget_int32) ( 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 \ int32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int32_t x = (*((const int32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int32_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) \ { \ int32_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (aij, y, int32_t, 32) ; \ } GrB_Info GB (_bind2nd_tran__bget_int32) ( 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 int32_t y = (*((const int32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
bfs_custom.c
/* Copyright (C) 2010-2011 The Trustees of Indiana University. */ /* */ /* Use, modification and distribution is subject to the Boost Software */ /* License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at */ /* http://www.boost.org/LICENSE_1_0.txt) */ /* */ /* Authors: Jeremiah Willcock */ /* Andrew Lumsdaine */ #include "common.h" #include "oned_csr.h" #include <mpi.h> #include <stdint.h> #include <inttypes.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <limits.h> #include <assert.h> /* Add your own BFS code into this file (or a copy of it). */ /* Data structure definitions: customize these for your own data distribution * and temporary data structures. */ static oned_csr_graph g; void make_graph_data_structure(const tuple_graph* const tg) { convert_graph_to_oned_csr(tg, &g); } void free_graph_data_structure(void) { free_oned_csr_graph(&g); } int bfs_writes_depth_map(void) { /* Change to 1 if high 16 bits of each entry of pred are the (zero-based) BFS * level number, with UINT16_MAX for unreachable vertices. */ return 0; } /* BFS implementation. */ void run_bfs(int64_t root, int64_t* pred) { /* Predefined entities you can use in your BFS (from common.h and oned_csr.h): * + rank: global variable containing MPI rank * + size: global variable containing MPI size * + DIV_SIZE: single-parameter macro that divides by size (using a shift * when properly set up) * + MOD_SIZE: single-parameter macro that reduces modulo size (using a * mask when properly set up) * + VERTEX_OWNER: single-parameter macro returning the owner of a global * vertex number * + VERTEX_LOCAL: single-parameter macro returning the local offset of a * global vertex number * + VERTEX_TO_GLOBAL: single-parameter macro converting a local vertex * offset to a global number * + g.nlocalverts: number of vertices stored on the local rank * + g.nglobalverts: total number of vertices in the graph * + g.nlocaledges: number of graph edges stored locally * + g.rowstarts, g.column: zero-based compressed sparse row data * structure for the local part of the graph * * All macros documented above evaluate their arguments exactly once. * * The graph is stored using a 1-D, cyclic distribution: all edges incident * to vertex v are stored on rank (v % size) (aka VERTEX_OWNER(v)). Edges * that are not self-loops are stored twice, once for each endpoint; * duplicates edges are kept. The neighbors of vertex v can be obtained on * rank VERTEX_OWNER(v); they are stored in elements * {g.rowstarts[VERTEX_LOCAL(v)] ... g.rowstarts[VERTEX_LOCAL(v) + 1] - 1} * (inclusive) of g.column. * * Upon exit, your BFS must have filled in: * + pred (an array of size g.nlocalverts): * - The predecessor of vertex v in the BFS tree should go into * pred[VERTEX_LOCAL(v)] on rank VERTEX_OWNER(v) * - The predecessor of root is root * - The predecessor of any unreachable vertex is -1 * * The validator will check this for correctness. */ } void get_vertex_distribution_for_pred(size_t count, const int64_t* vertex_p, int* owner_p, size_t* local_p) { const int64_t* restrict vertex = vertex_p; int* restrict owner = owner_p; size_t* restrict local = local_p; ptrdiff_t i; #pragma omp parallel for for (i = 0; i < (ptrdiff_t)count; ++i) { owner[i] = VERTEX_OWNER(vertex[i]); local[i] = VERTEX_LOCAL(vertex[i]); } } int64_t vertex_to_global_for_pred(int v_rank, size_t v_local) { return VERTEX_TO_GLOBAL(v_rank, v_local); } size_t get_nlocalverts_for_pred(void) { return g.nlocalverts; }
GB_unaryop__ainv_fp32_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__ainv_fp32_int32 // op(A') function: GB_tran__ainv_fp32_int32 // C type: float // A type: int32_t // cast: float cij = (float) aij // unaryop: cij = -aij #define GB_ATYPE \ int32_t #define GB_CTYPE \ float // 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) \ float z = (float) 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_AINV || GxB_NO_FP32 || GxB_NO_INT32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__ainv_fp32_int32 ( float *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__ainv_fp32_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
convolution_1x1.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. #if __ARM_NEON #include <arm_neon.h> #endif // __ARM_NEON static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); float32x4_t _p1 = vld1q_f32(r1); float32x4_t _p1n = vld1q_f32(r1+4); _outp = vfmaq_f32(_outp, _p1, _k1); _outpn = vfmaq_f32(_outpn, _p1n, _k1); float32x4_t _p2 = vld1q_f32(r2); float32x4_t _p2n = vld1q_f32(r2+4); _outp = vfmaq_f32(_outp, _p2, _k2); _outpn = vfmaq_f32(_outpn, _p2n, _k2); float32x4_t _p3 = vld1q_f32(r3); float32x4_t _p3n = vld1q_f32(r3+4); _outp = vfmaq_f32(_outp, _p3, _k3); _outpn = vfmaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; r1 += 8; r2 += 8; r3 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); float32x4x2_t _p1x2 = vld2q_f32(r1); float32x4_t _p1 = _p1x2.val[0]; float32x4x2_t _p1nx2 = vld2q_f32(r1+8); float32x4_t _p1n = _p1nx2.val[0]; _outp = vmlaq_f32(_outp, _p1, _k1); _outpn = vmlaq_f32(_outpn, _p1n, _k1); float32x4x2_t _p2x2 = vld2q_f32(r2); float32x4_t _p2 = _p2x2.val[0]; float32x4x2_t _p2nx2 = vld2q_f32(r2+8); float32x4_t _p2n = _p2nx2.val[0]; _outp = vmlaq_f32(_outp, _p2, _k2); _outpn = vmlaq_f32(_outpn, _p2n, _k2); float32x4x2_t _p3x2 = vld2q_f32(r3); float32x4_t _p3 = _p3x2.val[0]; float32x4x2_t _p3nx2 = vld2q_f32(r3+8); float32x4_t _p3n = _p3nx2.val[0]; _outp = vmlaq_f32(_outp, _p3, _k3); _outpn = vmlaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+8, _outpn); r0 += 16; r1 += 16; r2 += 16; r3 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } } #if NCNN_CNNCACHE static void conv1x1s1_neon_cached( const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, bool* cached_map) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); float32x4_t _p1 = vld1q_f32(r1); float32x4_t _p1n = vld1q_f32(r1+4); _outp = vfmaq_f32(_outp, _p1, _k1); _outpn = vfmaq_f32(_outpn, _p1n, _k1); float32x4_t _p2 = vld1q_f32(r2); float32x4_t _p2n = vld1q_f32(r2+4); _outp = vfmaq_f32(_outp, _p2, _k2); _outpn = vfmaq_f32(_outpn, _p2n, _k2); float32x4_t _p3 = vld1q_f32(r3); float32x4_t _p3n = vld1q_f32(r3+4); _outp = vfmaq_f32(_outp, _p3, _k3); _outpn = vfmaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; r1 += 8; r2 += 8; r3 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if __ARM_NEON int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon_cached( const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias, bool* cached_map) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); float32x4x2_t _p1x2 = vld2q_f32(r1); float32x4_t _p1 = _p1x2.val[0]; float32x4x2_t _p1nx2 = vld2q_f32(r1+8); float32x4_t _p1n = _p1nx2.val[0]; _outp = vmlaq_f32(_outp, _p1, _k1); _outpn = vmlaq_f32(_outpn, _p1n, _k1); float32x4x2_t _p2x2 = vld2q_f32(r2); float32x4_t _p2 = _p2x2.val[0]; float32x4x2_t _p2nx2 = vld2q_f32(r2+8); float32x4_t _p2n = _p2nx2.val[0]; _outp = vmlaq_f32(_outp, _p2, _k2); _outpn = vmlaq_f32(_outpn, _p2n, _k2); float32x4x2_t _p3x2 = vld2q_f32(r3); float32x4_t _p3 = _p3x2.val[0]; float32x4x2_t _p3nx2 = vld2q_f32(r3+8); float32x4_t _p3n = _p3nx2.val[0]; _outp = vmlaq_f32(_outp, _p3, _k3); _outpn = vmlaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+8, _outpn); r0 += 16; r1 += 16; r2 += 16; r3 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if __ARM_NEON int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } } #endif // NCNN_CNNCACHE
bt.c
/* * This software is Copyright (c) 2015 Sayantan Datta <std2048 at gmail dot com> * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * Based on paper 'Perfect Spatial Hashing' by Lefebvre & Hoppe */ #ifdef HAVE_OPENCL #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include <signal.h> #include <unistd.h> #include "misc.h" // error() #include "bt_twister.h" #include "bt_hash_types.h" #if _OPENMP > 201107 #define MAYBE_PARALLEL_FOR _Pragma("omp for") #define MAYBE_ATOMIC_WRITE _Pragma("omp atomic write") #define MAYBE_ATOMIC_CAPTURE _Pragma("omp atomic capture") #else #define MAYBE_PARALLEL_FOR _Pragma("omp single") #define MAYBE_ATOMIC_WRITE #define MAYBE_ATOMIC_CAPTURE #endif typedef struct { /* List of indexes linked to offset_data_idx */ unsigned int *hash_location_list; unsigned short collisions; unsigned short iter; unsigned int offset_table_idx; } auxilliary_offset_data; /* Interface pointers */ static unsigned int (*zero_check_ht)(unsigned int); static void (*assign_ht)(unsigned int, unsigned int); static void (*assign0_ht)(unsigned int); static unsigned int (*calc_ht_idx)(unsigned int, unsigned int); static unsigned int (*get_offset)(unsigned int, unsigned int); static void (*allocate_ht)(unsigned int, unsigned int); static int (*test_tables)(unsigned int, OFFSET_TABLE_WORD *, unsigned int, unsigned int, unsigned int, unsigned int); static unsigned int (*remove_duplicates)(unsigned int, unsigned int, unsigned int); static void *loaded_hashes; static unsigned int hash_type = 0; static unsigned int binary_size_actual = 0; static unsigned int num_loaded_hashes = 0; unsigned int hash_table_size = 0, shift64_ht_sz = 0, shift128_ht_sz = 0; static OFFSET_TABLE_WORD *offset_table = NULL; static unsigned int offset_table_size = 0, shift64_ot_sz = 0, shift128_ot_sz = 0; static auxilliary_offset_data *offset_data = NULL; unsigned long long total_memory_in_bytes = 0; static volatile sig_atomic_t signal_stop = 0; static unsigned int verbosity; static void alarm_handler(int sig) { if (sig == SIGALRM) signal_stop = 1; } static unsigned int coprime_check(unsigned int m,unsigned int n) { unsigned int rem; while (n != 0) { rem = m % n; m = n; n = rem; } return m; } static void release_all_lists() { unsigned int i; for (i = 0; i < offset_table_size; i++) bt_free((void **)&(offset_data[i].hash_location_list)); } int bt_malloc(void **ptr, size_t size) { *ptr = mem_alloc(size); if (*ptr || !size) return 0; return 1; } int bt_calloc(void **ptr, size_t num, size_t size) { *ptr = mem_calloc(num, size); if (*ptr || !num) return 0; return 1; } int bt_memalign_alloc(void **ptr, size_t alignment, size_t size) { *ptr = mem_alloc_align(size, alignment); if (*ptr || !size) return 0; return 1; } void bt_free(void **ptr) { MEM_FREE((*ptr)); *ptr = NULL; } void bt_error_fn(const char *str, char *file, int line) { fprintf(stderr, "%s in file:%s, line:%d.\n", str, file, line); error(); } void bt_warn_fn(const char *str, char *file, int line) { fprintf(stderr, "%s in file:%s, line:%d.\n", str, file, line); } static unsigned int modulo_op(void * hash, unsigned int N, uint64_t shift64, uint64_t shift128) { if (hash_type == 64) return modulo64_31b(*(uint64_t *)hash, N); else if (hash_type == 128) return modulo128_31b(*(uint128_t *)hash, N, shift64); else if (hash_type == 192) return modulo192_31b(*(uint192_t *)hash, N, shift64, shift128); else fprintf(stderr, "modulo op error\n"); return 0; } /* Exploits the fact that sorting with a bucket is not essential. */ static void in_place_bucket_sort(unsigned int num_buckets) { unsigned int *histogram; unsigned int *histogram_empty; unsigned int *prefix_sum; unsigned int i; if (bt_calloc((void **)&histogram, num_buckets + 1, sizeof(unsigned int))) bt_error("Failed to allocate memory: histogram."); if (bt_calloc((void **)&histogram_empty, num_buckets + 1, sizeof(unsigned int))) bt_error("Failed to allocate memory: histogram_empty."); if (bt_calloc((void **)&prefix_sum, num_buckets + 10, sizeof(unsigned int))) bt_error("Failed to allocate memory: prefix_sum."); i = 0; while (i < offset_table_size) histogram[num_buckets - offset_data[i++].collisions]++; for (i = 1; i <= num_buckets; i++) prefix_sum[i] = prefix_sum[i - 1] + histogram[i - 1]; i = 0; while (i < prefix_sum[num_buckets]) { unsigned int histogram_index = num_buckets - offset_data[i].collisions; if (i >= prefix_sum[histogram_index] && histogram_index < num_buckets && i < prefix_sum[histogram_index + 1]) { histogram_empty[histogram_index]++; i++; } else { auxilliary_offset_data tmp; unsigned int swap_index = prefix_sum[histogram_index] + histogram_empty[histogram_index]; histogram_empty[histogram_index]++; tmp = offset_data[i]; offset_data[i] = offset_data[swap_index]; offset_data[swap_index] = tmp; } } bt_free((void **)&histogram); bt_free((void **)&histogram_empty); bt_free((void **)&prefix_sum); } static void init_tables(unsigned int approx_offset_table_sz, unsigned int approx_hash_table_sz) { unsigned int i, max_collisions, offset_data_idx; uint64_t shift128; if (verbosity > 1) fprintf(stdout, "\nInitialing Tables..."); total_memory_in_bytes = 0; approx_hash_table_sz |= 1; /* Repeat until two sizes are coprimes */ while (coprime_check(approx_offset_table_sz, approx_hash_table_sz) != 1) approx_offset_table_sz++; offset_table_size = approx_offset_table_sz; hash_table_size = approx_hash_table_sz; if (hash_table_size > 0x7fffffff || offset_table_size > 0x7fffffff) bt_error("Reduce the number of loaded hashes to < 0x7fffffff."); shift64_ht_sz = (((1ULL << 63) % hash_table_size) * 2) % hash_table_size; shift64_ot_sz = (((1ULL << 63) % offset_table_size) * 2) % offset_table_size; shift128 = (uint64_t)shift64_ht_sz * shift64_ht_sz; shift128_ht_sz = shift128 % hash_table_size; shift128 = (uint64_t)shift64_ot_sz * shift64_ot_sz; shift128_ot_sz = shift128 % offset_table_size; if (bt_malloc((void **)&offset_table, offset_table_size * sizeof(OFFSET_TABLE_WORD))) bt_error("Failed to allocate memory: offset_table."); total_memory_in_bytes += offset_table_size * sizeof(OFFSET_TABLE_WORD); if (bt_malloc((void **)&offset_data, offset_table_size * sizeof(auxilliary_offset_data))) bt_error("Failed to allocate memory: offset_data."); total_memory_in_bytes += offset_table_size * sizeof(auxilliary_offset_data); max_collisions = 0; #if _OPENMP #pragma omp parallel private(i, offset_data_idx) #endif { #if _OPENMP #pragma omp for #endif for (i = 0; i < offset_table_size; i++) { //memset(&offset_data[i], 0, sizeof(auxilliary_offset_data)); offset_data[i].offset_table_idx = 0; offset_data[i].collisions = 0; offset_data[i].hash_location_list = NULL; offset_data[i].iter = 0; offset_table[i] = 0; } #if _OPENMP #pragma omp barrier #endif /* Build Auxiliary data structure for offset_table. */ #if _OPENMP #pragma omp for #endif for (i = 0; i < num_loaded_hashes; i++) { offset_data_idx = modulo_op(loaded_hashes + i * binary_size_actual, offset_table_size, shift64_ot_sz, shift128_ot_sz); #if _OPENMP #pragma omp atomic #endif offset_data[offset_data_idx].collisions++; } #if _OPENMP #pragma omp barrier #pragma omp single #endif for (i = 0; i < offset_table_size; i++) if (offset_data[i].collisions) { if (bt_malloc((void **)&offset_data[i].hash_location_list, offset_data[i].collisions * sizeof(unsigned int))) bt_error("Failed to allocate memory: offset_data[i].hash_location_list."); if (offset_data[i].collisions > max_collisions) max_collisions = offset_data[i].collisions; } #if _OPENMP #pragma omp barrier MAYBE_PARALLEL_FOR #endif for (i = 0; i < num_loaded_hashes; i++) { unsigned int iter; offset_data_idx = modulo_op(loaded_hashes + i * binary_size_actual, offset_table_size, shift64_ot_sz, shift128_ot_sz); #if _OPENMP MAYBE_ATOMIC_WRITE #endif offset_data[offset_data_idx].offset_table_idx = offset_data_idx; #if _OPENMP MAYBE_ATOMIC_CAPTURE #endif iter = offset_data[offset_data_idx].iter++; offset_data[offset_data_idx].hash_location_list[iter] = i; } #if _OPENMP #pragma omp barrier #endif } total_memory_in_bytes += num_loaded_hashes * sizeof(unsigned int); //qsort((void *)offset_data, offset_table_size, sizeof(auxilliary_offset_data), qsort_compare); in_place_bucket_sort(max_collisions); if (verbosity > 1) fprintf(stdout, "Done\n"); allocate_ht(num_loaded_hashes, verbosity); if (verbosity > 2) { fprintf(stdout, "Offset Table Size %Lf %% of Number of Loaded Hashes.\n", ((long double)offset_table_size / (long double)num_loaded_hashes) * 100.00); fprintf(stdout, "Offset Table Size(in GBs):%Lf\n", ((long double)offset_table_size * sizeof(OFFSET_TABLE_WORD)) / ((long double)1024 * 1024 * 1024)); fprintf(stdout, "Offset Table Aux Data Size(in GBs):%Lf\n", ((long double)offset_table_size * sizeof(auxilliary_offset_data)) / ((long double)1024 * 1024 * 1024)); fprintf(stdout, "Offset Table Aux List Size(in GBs):%Lf\n", ((long double)num_loaded_hashes * sizeof(unsigned int)) / ((long double)1024 * 1024 * 1024)); for (i = 0; i < offset_table_size && offset_data[i].collisions; i++) ; fprintf (stdout, "Unused Slots in Offset Table:%Lf %%\n", 100.00 * (long double)(offset_table_size - i) / (long double)(offset_table_size)); fprintf(stdout, "Total Memory Use(in GBs):%Lf\n", ((long double)total_memory_in_bytes) / ((long double) 1024 * 1024 * 1024)); } } static unsigned int check_n_insert_into_hash_table(unsigned int offset, auxilliary_offset_data * ptr, unsigned int *hash_table_idxs, unsigned int *store_hash_modulo_table_sz) { unsigned int i; i = 0; while (i < ptr -> collisions) { hash_table_idxs[i] = store_hash_modulo_table_sz[i] + offset; if (hash_table_idxs[i] >= hash_table_size) hash_table_idxs[i] -= hash_table_size; if (zero_check_ht(hash_table_idxs[i++])) return 0; } i = 0; while (i < ptr -> collisions) { if (zero_check_ht(hash_table_idxs[i])) { unsigned int j = 0; while (j < i) assign0_ht(hash_table_idxs[j++]); return 0; } assign_ht(hash_table_idxs[i], ptr -> hash_location_list[i]); i++; } return 1; } static void calc_hash_mdoulo_table_size(unsigned int *store, auxilliary_offset_data * ptr) { unsigned int i = 0; while (i < ptr -> collisions) { store[i] = modulo_op(loaded_hashes + (ptr -> hash_location_list[i]) * binary_size_actual, hash_table_size, shift64_ht_sz, shift128_ht_sz); i++; } } static unsigned int create_tables() { unsigned int i; unsigned int bitmap = ((1ULL << (sizeof(OFFSET_TABLE_WORD) * 8)) - 1) & 0xFFFFFFFF; unsigned int limit = bitmap % hash_table_size + 1; unsigned int hash_table_idx; unsigned int *store_hash_modulo_table_sz; unsigned int *hash_table_idxs; #ifdef ENABLE_BACKTRACKING OFFSET_TABLE_WORD last_offset; unsigned int backtracking = 0; #endif unsigned int trigger; long double done = 0; struct timeval t; if (bt_malloc((void **)&store_hash_modulo_table_sz, offset_data[0].collisions * sizeof(unsigned int))) bt_error("Failed to allocate memory: store_hash_modulo_table_sz."); if (bt_malloc((void **)&hash_table_idxs, offset_data[0].collisions * sizeof(unsigned int))) bt_error("Failed to allocate memory: hash_table_idxs."); gettimeofday(&t, NULL); seedMT(t.tv_sec + t.tv_usec); i = 0; trigger = 0; while (offset_data[i].collisions > 1) { OFFSET_TABLE_WORD offset; unsigned int num_iter; done += offset_data[i].collisions; calc_hash_mdoulo_table_size(store_hash_modulo_table_sz, &offset_data[i]); offset = (OFFSET_TABLE_WORD)(randomMT() & bitmap) % hash_table_size; #ifdef ENABLE_BACKTRACKING if (backtracking) { offset = (last_offset + 1) % hash_table_size; backtracking = 0; } #endif alarm(3); num_iter = 0; while (!check_n_insert_into_hash_table((unsigned int)offset, &offset_data[i], hash_table_idxs, store_hash_modulo_table_sz) && num_iter < limit) { offset++; if (offset >= hash_table_size) offset = 0; num_iter++; } offset_table[offset_data[i].offset_table_idx] = offset; if ((trigger & 0xffff) == 0) { trigger = 0; if (verbosity > 0) { fprintf(stdout, "\rProgress:%Lf %%, Number of collisions:%u", done / (long double)num_loaded_hashes * 100.00, offset_data[i].collisions); fflush(stdout); } alarm(0); } if (signal_stop) { alarm(0); signal_stop = 0; fprintf(stderr, "\nProgress is too slow!! trying next table size.\n"); bt_free((void **)&hash_table_idxs); bt_free((void **)&store_hash_modulo_table_sz); return 0; } trigger++; if (num_iter == limit) { #ifdef ENABLE_BACKTRACKING if (num_loaded_hashes > 1000000) { unsigned int j, backtrack_steps, iter; done -= offset_data[i].collisions; offset_table[offset_data[i].offset_table_idx] = 0; backtrack_steps = 1; j = 1; while (j <= backtrack_steps && (int)(i - j) >= 0) { last_offset = offset_table[offset_data[i - j].offset_table_idx]; iter = 0; while (iter < offset_data[i - j].collisions) { hash_table_idx = calc_ht_idx(offset_data[i - j].hash_location_list[iter], last_offset); assign0_ht(hash_table_idx); iter++; } offset_table[offset_data[i - j].offset_table_idx] = 0; done -= offset_data[i - j].collisions; j++; } i -= (j - 1); backtracking = 1; continue; } #endif bt_free((void **)&hash_table_idxs); bt_free((void **)&store_hash_modulo_table_sz); return 0; } i++; } alarm(0); hash_table_idx = 0; while (offset_data[i].collisions > 0) { done++; while (hash_table_idx < hash_table_size) { if (!zero_check_ht(hash_table_idx)) { assign_ht(hash_table_idx, offset_data[i].hash_location_list[0]); break; } hash_table_idx++; } offset_table[offset_data[i].offset_table_idx] = get_offset(hash_table_idx, offset_data[i].hash_location_list[0]); if ((trigger & 0xffff) == 0) { trigger = 0; if (verbosity > 0) { fprintf(stdout, "\rProgress:%Lf %%, Number of collisions:%u", done / (long double)num_loaded_hashes * 100.00, offset_data[i].collisions); fflush(stdout); } } trigger++; i++; } bt_free((void **)&hash_table_idxs); bt_free((void **)&store_hash_modulo_table_sz); return 1; } static unsigned int next_prime(unsigned int num) { if (num == 1) return 2; else if (num == 2) return 3; else if (num == 3 || num == 4) return 5; else if (num == 5 || num == 6) return 7; else if (num >= 7 && num <= 9) return 1; /* else if (num == 11 || num == 12) return 13; else if (num >= 13 && num < 17) return 17; else if (num == 17 || num == 18) return 19; else if (num >= 19 && num < 23) return 23; else if (num >= 23 && num < 29) return 29; else if (num == 29 || num == 30 ) return 31; else if (num >= 31 && num < 37) return 37; else if (num >= 37 && num < 41) return 41; else if (num == 41 || num == 42 ) return 43; else if (num >= 43 && num < 47) return 47; else if (num >= 47 && num < 53) return 53; else if (num >= 53 && num < 59) return 59; else if (num == 59 || num == 60) return 61; else if (num >= 61 && num < 67) return 67; else if (num >= 67 && num < 71) return 71; else if (num == 71 || num == 72) return 73; else if (num >= 73 && num < 79) return 79; else if (num >= 79 && num < 83) return 83; else if (num >= 83 && num < 89) return 89; else if (num >= 89 && num < 97) return 97; else return 1;*/ return 1; } unsigned int create_perfect_hash_table(int htype, void *loaded_hashes_ptr, unsigned int num_ld_hashes, OFFSET_TABLE_WORD **offset_table_ptr, unsigned int *offset_table_sz_ptr, unsigned int *hash_table_sz_ptr, unsigned int verb) { long double multiplier_ht, multiplier_ot, inc_ht, inc_ot; unsigned int approx_hash_table_sz, approx_offset_table_sz, i, dupe_remove_ht_sz; struct sigaction new_action, old_action; struct itimerval old_it; total_memory_in_bytes = 0; hash_type = htype; loaded_hashes = loaded_hashes_ptr; verbosity = verb; if (hash_type == 64) { zero_check_ht = zero_check_ht_64; assign_ht = assign_ht_64; assign0_ht = assign0_ht_64; calc_ht_idx = calc_ht_idx_64; get_offset = get_offset_64; allocate_ht = allocate_ht_64; test_tables = test_tables_64; remove_duplicates = remove_duplicates_64; loaded_hashes_64 = (uint64_t *)loaded_hashes; binary_size_actual = 8; if (verbosity > 1) fprintf(stdout, "Using Hash type 64.\n"); } else if (hash_type == 128) { zero_check_ht = zero_check_ht_128; assign_ht = assign_ht_128; assign0_ht = assign0_ht_128; calc_ht_idx = calc_ht_idx_128; get_offset = get_offset_128; allocate_ht = allocate_ht_128; test_tables = test_tables_128; remove_duplicates = remove_duplicates_128; loaded_hashes_128 = (uint128_t *)loaded_hashes; binary_size_actual = 16; if (verbosity > 1) fprintf(stdout, "Using Hash type 128.\n"); } else if (hash_type == 192) { zero_check_ht = zero_check_ht_192; assign_ht = assign_ht_192; assign0_ht = assign0_ht_192; calc_ht_idx = calc_ht_idx_192; get_offset = get_offset_192; allocate_ht = allocate_ht_192; test_tables = test_tables_192; remove_duplicates = remove_duplicates_192; loaded_hashes_192 = (uint192_t *)loaded_hashes; binary_size_actual = 24; if (verbosity > 1) fprintf(stdout, "Using Hash type 192.\n"); } new_action.sa_handler = alarm_handler; sigemptyset(&new_action.sa_mask); new_action.sa_flags = 0; if (sigaction(SIGALRM, NULL, &old_action) < 0) bt_error("Error retriving signal info."); if (sigaction(SIGALRM, &new_action, NULL) < 0) bt_error("Error setting new signal handler."); if (getitimer(ITIMER_REAL, &old_it) < 0) bt_error("Error retriving timer info."); inc_ht = 0.005; inc_ot = 0.05; if (num_ld_hashes <= 100) { multiplier_ot = 1.501375173; inc_ht = 0.05; inc_ot = 0.5; dupe_remove_ht_sz = 128; } else if (num_ld_hashes <= 1000) { multiplier_ot = 1.101375173; dupe_remove_ht_sz = 1024; } else if (num_ld_hashes <= 10000) { multiplier_ot = 1.151375173; dupe_remove_ht_sz = 16384; } else if (num_ld_hashes <= 100000) { multiplier_ot = 1.20375173; dupe_remove_ht_sz = 131072; } else if (num_ld_hashes <= 1000000) { multiplier_ot = 1.25375173; dupe_remove_ht_sz = 1048576; } else if (num_ld_hashes <= 10000000) { multiplier_ot = 1.31375173; dupe_remove_ht_sz = 16777216; } else if (num_ld_hashes <= 20000000) { multiplier_ot = 1.35375173; dupe_remove_ht_sz = 33554432; } else if (num_ld_hashes <= 50000000) { multiplier_ot = 1.41375173; dupe_remove_ht_sz = 67108864; } else if (num_ld_hashes <= 110000000) { multiplier_ot = 1.51375173; dupe_remove_ht_sz = 134217728; } else if (num_ld_hashes <= 200000000) { multiplier_ot = 1.61375173; dupe_remove_ht_sz = 134217728 * 2; } else { fprintf(stderr, "This many number of hashes have never been tested before and might not succeed!!\n"); multiplier_ot = 3.01375173; dupe_remove_ht_sz = 134217728 * 4; } num_loaded_hashes = remove_duplicates(num_ld_hashes, dupe_remove_ht_sz, verbosity); if (!num_loaded_hashes) bt_error("Failed to remove duplicates."); multiplier_ht = 1.001097317; approx_offset_table_sz = (((long double)num_loaded_hashes / 4.0) * multiplier_ot + 10.00); approx_hash_table_sz = ((long double)num_loaded_hashes * multiplier_ht); i = 0; do { unsigned int temp; init_tables(approx_offset_table_sz, approx_hash_table_sz); if (create_tables()) { if (verbosity > 0) fprintf(stdout, "\n"); break; } if (verbosity > 0) fprintf(stdout, "\n"); release_all_lists(); bt_free((void **)&offset_data); bt_free((void **)&offset_table); if (hash_type == 64) bt_free((void **)&hash_table_64); else if (hash_type == 128) bt_free((void **)&hash_table_128); else if (hash_type == 192) bt_free((void **)&hash_table_192); temp = next_prime(approx_offset_table_sz % 10); approx_offset_table_sz /= 10; approx_offset_table_sz *= 10; approx_offset_table_sz += temp; i++; if (!(i % 5)) { multiplier_ot += inc_ot; multiplier_ht += inc_ht; approx_offset_table_sz = (((long double)num_loaded_hashes / 4.0) * multiplier_ot + 10.00); approx_hash_table_sz = ((long double)num_loaded_hashes * multiplier_ht); } } while(1); release_all_lists(); bt_free((void **)&offset_data); *offset_table_ptr = offset_table; *hash_table_sz_ptr = hash_table_size; *offset_table_sz_ptr = offset_table_size; if (sigaction(SIGALRM, &old_action, NULL) < 0) bt_error("Error restoring previous signal handler."); if (setitimer(ITIMER_REAL, &old_it, NULL) < 0) bt_error("Error restoring previous timer."); if (!test_tables(num_loaded_hashes, offset_table, offset_table_size, shift64_ot_sz, shift128_ot_sz, verbosity)) return 0; return num_loaded_hashes; } /*static int qsort_compare(const void *p1, const void *p2) { auxilliary_offset_data *a = (auxilliary_offset_data *)p1; auxilliary_offset_data *b = (auxilliary_offset_data *)p2; if (a[0].collisions > b[0].collisions) return -1; if (a[0].collisions == b[0].collisions) return 0; return 1; }*/ #endif
flexProxDualDataL1.h
#ifndef flexProxDualL1_H #define flexProxDualL1_H #include "flexProx.h" //! represents prox for a L1 data term /*! \f$ \alpha\|\cdot-f\|_1 \f$ */ template<typename T> class flexProxDualDataL1 : public flexProx<T> { #ifdef __CUDACC__ typedef thrust::device_vector<T> Tdata; #else typedef std::vector<T> Tdata; #endif public: flexProxDualDataL1() : flexProx<T>(dualL1DataProx) { } ~flexProxDualDataL1() { if (VERBOSE > 0) printf("Destructor prox\n!"); } #ifdef __CUDACC__ struct flexProxDualDataL1Functor { __host__ __device__ flexProxDualDataL1Functor(T alpha) : alpha(alpha){} template <typename Tuple> __host__ __device__ void operator()(Tuple t) { thrust::get<0>(t) = min(this->alpha, max(-this->alpha,thrust::get<1>(t) - this->alpha * thrust::get<2>(t) * thrust::get<3>(t))); } T alpha; }; #endif void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers) { } void applyProx(T alpha, flexBoxData<T>* data, const std::vector<int> &dualNumbers, const std::vector<int> &primalNumbers, std::vector<Tdata> &fList) { #ifdef __CUDACC__ for (int k = 0; k < dualNumbers.size(); k++) { auto startIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[k]].begin(), data->yTilde[dualNumbers[k]].begin(), data->sigmaElt[dualNumbers[k]].begin(), fList[k].begin())); auto endIterator = thrust::make_zip_iterator( thrust::make_tuple(data->y[dualNumbers[k]].end(), data->yTilde[dualNumbers[k]].end(), data->sigmaElt[dualNumbers[k]].end(), fList[k].end())); thrust::for_each(startIterator,endIterator,flexProxDualDataL1Functor(alpha)); } #else for (int i = 0; i < dualNumbers.size(); i++) { T* ptrY = data->y[dualNumbers[i]].data(); T* ptrYtilde = data->yTilde[dualNumbers[i]].data(); T* ptrSigma = data->sigmaElt[dualNumbers[i]].data(); T* ptrF = fList[i].data(); int numElements = (int)data->yTilde[dualNumbers[i]].size(); #pragma omp parallel for for (int j = 0; j < numElements; j++) { ptrY[j] = myMin<T>(alpha, myMax<T>(-alpha, ptrYtilde[j] - alpha * ptrSigma[j] * ptrF[j])); } } #endif } }; #endif
vsite.c
/* * This file is part of the GROMACS molecular simulation package. * * Copyright (c) 1991-2000, University of Groningen, The Netherlands. * Copyright (c) 2001-2004, The GROMACS development team, * check out http://www.gromacs.org for more information. * Copyright (c) 2012,2013, by the GROMACS development team, led by * David van der Spoel, Berk Hess, Erik Lindahl, and including many * others, as listed in the AUTHORS file in the top-level source * directory and at http://www.gromacs.org. * * GROMACS 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. * * GROMACS 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 GROMACS; if not, see * http://www.gnu.org/licenses, or write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * If you want to redistribute modifications to GROMACS, please * consider that scientific software is very special. Version * control is crucial - bugs must be traceable. We will be happy to * consider code for inclusion in the official distribution, but * derived work must not be called official GROMACS. Details are found * in the README & COPYING files - if they are missing, get the * official version at http://www.gromacs.org. * * To help us fund GROMACS development, we humbly ask that you cite * the research papers on the package. Check out http://www.gromacs.org. */ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include "typedefs.h" #include "vsite.h" #include "macros.h" #include "smalloc.h" #include "nrnb.h" #include "vec.h" #include "mvdata.h" #include "network.h" #include "mshift.h" #include "pbc.h" #include "domdec.h" #include "partdec.h" #include "mtop_util.h" #include "gmx_omp_nthreads.h" #include "gmx_omp.h" /* Routines to send/recieve coordinates and force * of constructing atoms. */ static void move_construct_x(t_comm_vsites *vsitecomm, rvec x[], t_commrec *cr) { rvec *sendbuf; rvec *recvbuf; int i, ia; sendbuf = vsitecomm->send_buf; recvbuf = vsitecomm->recv_buf; /* Prepare pulse left by copying to send buffer */ for (i = 0; i < vsitecomm->left_export_nconstruct; i++) { ia = vsitecomm->left_export_construct[i]; copy_rvec(x[ia], sendbuf[i]); } /* Pulse coordinates left */ gmx_tx_rx_real(cr, GMX_LEFT, (real *)sendbuf, 3*vsitecomm->left_export_nconstruct, GMX_RIGHT, (real *)recvbuf, 3*vsitecomm->right_import_nconstruct); /* Copy from receive buffer to coordinate array */ for (i = 0; i < vsitecomm->right_import_nconstruct; i++) { ia = vsitecomm->right_import_construct[i]; copy_rvec(recvbuf[i], x[ia]); } /* Prepare pulse right by copying to send buffer */ for (i = 0; i < vsitecomm->right_export_nconstruct; i++) { ia = vsitecomm->right_export_construct[i]; copy_rvec(x[ia], sendbuf[i]); } /* Pulse coordinates right */ gmx_tx_rx_real(cr, GMX_RIGHT, (real *)sendbuf, 3*vsitecomm->right_export_nconstruct, GMX_LEFT, (real *)recvbuf, 3*vsitecomm->left_import_nconstruct); /* Copy from receive buffer to coordinate array */ for (i = 0; i < vsitecomm->left_import_nconstruct; i++) { ia = vsitecomm->left_import_construct[i]; copy_rvec(recvbuf[i], x[ia]); } } static void move_construct_f(t_comm_vsites *vsitecomm, rvec f[], t_commrec *cr) { rvec *sendbuf; rvec *recvbuf; int i, ia; sendbuf = vsitecomm->send_buf; recvbuf = vsitecomm->recv_buf; /* Prepare pulse right by copying to send buffer */ for (i = 0; i < vsitecomm->right_import_nconstruct; i++) { ia = vsitecomm->right_import_construct[i]; copy_rvec(f[ia], sendbuf[i]); clear_rvec(f[ia]); /* Zero it here after moving, just to simplify debug book-keeping... */ } /* Pulse forces right */ gmx_tx_rx_real(cr, GMX_RIGHT, (real *)sendbuf, 3*vsitecomm->right_import_nconstruct, GMX_LEFT, (real *)recvbuf, 3*vsitecomm->left_export_nconstruct); /* Copy from receive buffer to coordinate array */ for (i = 0; i < vsitecomm->left_export_nconstruct; i++) { ia = vsitecomm->left_export_construct[i]; rvec_inc(f[ia], recvbuf[i]); } /* Prepare pulse left by copying to send buffer */ for (i = 0; i < vsitecomm->left_import_nconstruct; i++) { ia = vsitecomm->left_import_construct[i]; copy_rvec(f[ia], sendbuf[i]); clear_rvec(f[ia]); /* Zero it here after moving, just to simplify debug book-keeping... */ } /* Pulse coordinates left */ gmx_tx_rx_real(cr, GMX_LEFT, (real *)sendbuf, 3*vsitecomm->left_import_nconstruct, GMX_RIGHT, (real *)recvbuf, 3*vsitecomm->right_export_nconstruct); /* Copy from receive buffer to coordinate array */ for (i = 0; i < vsitecomm->right_export_nconstruct; i++) { ia = vsitecomm->right_export_construct[i]; rvec_inc(f[ia], recvbuf[i]); } /* All forces are now on the home processors */ } static void pd_clear_nonlocal_constructs(t_comm_vsites *vsitecomm, rvec f[]) { int i, ia; for (i = 0; i < vsitecomm->left_import_nconstruct; i++) { ia = vsitecomm->left_import_construct[i]; clear_rvec(f[ia]); } for (i = 0; i < vsitecomm->right_import_nconstruct; i++) { ia = vsitecomm->right_import_construct[i]; clear_rvec(f[ia]); } } static int pbc_rvec_sub(const t_pbc *pbc, const rvec xi, const rvec xj, rvec dx) { if (pbc) { return pbc_dx_aiuc(pbc, xi, xj, dx); } else { rvec_sub(xi, xj, dx); return CENTRAL; } } /* Vsite construction routines */ static void constr_vsite2(rvec xi, rvec xj, rvec x, real a, t_pbc *pbc) { real b; rvec dx; b = 1.0-a; /* 1 flop */ if (pbc) { pbc_dx_aiuc(pbc, xj, xi, dx); x[XX] = xi[XX] + a*dx[XX]; x[YY] = xi[YY] + a*dx[YY]; x[ZZ] = xi[ZZ] + a*dx[ZZ]; } else { x[XX] = b*xi[XX] + a*xj[XX]; x[YY] = b*xi[YY] + a*xj[YY]; x[ZZ] = b*xi[ZZ] + a*xj[ZZ]; /* 9 Flops */ } /* TOTAL: 10 flops */ } static void constr_vsite3(rvec xi, rvec xj, rvec xk, rvec x, real a, real b, t_pbc *pbc) { real c; rvec dxj, dxk; c = 1.0-a-b; /* 2 flops */ if (pbc) { pbc_dx_aiuc(pbc, xj, xi, dxj); pbc_dx_aiuc(pbc, xk, xi, dxk); x[XX] = xi[XX] + a*dxj[XX] + b*dxk[XX]; x[YY] = xi[YY] + a*dxj[YY] + b*dxk[YY]; x[ZZ] = xi[ZZ] + a*dxj[ZZ] + b*dxk[ZZ]; } else { x[XX] = c*xi[XX] + a*xj[XX] + b*xk[XX]; x[YY] = c*xi[YY] + a*xj[YY] + b*xk[YY]; x[ZZ] = c*xi[ZZ] + a*xj[ZZ] + b*xk[ZZ]; /* 15 Flops */ } /* TOTAL: 17 flops */ } static void constr_vsite3FD(rvec xi, rvec xj, rvec xk, rvec x, real a, real b, t_pbc *pbc) { rvec xij, xjk, temp; real c; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ /* temp goes from i to a point on the line jk */ temp[XX] = xij[XX] + a*xjk[XX]; temp[YY] = xij[YY] + a*xjk[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ]; /* 6 flops */ c = b*gmx_invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + c*temp[XX]; x[YY] = xi[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + c*temp[ZZ]; /* 6 Flops */ /* TOTAL: 34 flops */ } static void constr_vsite3FAD(rvec xi, rvec xj, rvec xk, rvec x, real a, real b, t_pbc *pbc) { rvec xij, xjk, xp; real a1, b1, c1, invdij; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); /* 6 flops */ invdij = gmx_invsqrt(iprod(xij, xij)); c1 = invdij * invdij * iprod(xij, xjk); xp[XX] = xjk[XX] - c1*xij[XX]; xp[YY] = xjk[YY] - c1*xij[YY]; xp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; a1 = a*invdij; b1 = b*gmx_invsqrt(iprod(xp, xp)); /* 45 */ x[XX] = xi[XX] + a1*xij[XX] + b1*xp[XX]; x[YY] = xi[YY] + a1*xij[YY] + b1*xp[YY]; x[ZZ] = xi[ZZ] + a1*xij[ZZ] + b1*xp[ZZ]; /* 12 Flops */ /* TOTAL: 63 flops */ } static void constr_vsite3OUT(rvec xi, rvec xj, rvec xk, rvec x, real a, real b, real c, t_pbc *pbc) { rvec xij, xik, temp; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); cprod(xij, xik, temp); /* 15 Flops */ x[XX] = xi[XX] + a*xij[XX] + b*xik[XX] + c*temp[XX]; x[YY] = xi[YY] + a*xij[YY] + b*xik[YY] + c*temp[YY]; x[ZZ] = xi[ZZ] + a*xij[ZZ] + b*xik[ZZ] + c*temp[ZZ]; /* 18 Flops */ /* TOTAL: 33 flops */ } static void constr_vsite4FD(rvec xi, rvec xj, rvec xk, rvec xl, rvec x, real a, real b, real c, t_pbc *pbc) { rvec xij, xjk, xjl, temp; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xj, xjk); pbc_rvec_sub(pbc, xl, xj, xjl); /* 9 flops */ /* temp goes from i to a point on the plane jkl */ temp[XX] = xij[XX] + a*xjk[XX] + b*xjl[XX]; temp[YY] = xij[YY] + a*xjk[YY] + b*xjl[YY]; temp[ZZ] = xij[ZZ] + a*xjk[ZZ] + b*xjl[ZZ]; /* 12 flops */ d = c*gmx_invsqrt(iprod(temp, temp)); /* 6 + 10 flops */ x[XX] = xi[XX] + d*temp[XX]; x[YY] = xi[YY] + d*temp[YY]; x[ZZ] = xi[ZZ] + d*temp[ZZ]; /* 6 Flops */ /* TOTAL: 43 flops */ } static void constr_vsite4FDN(rvec xi, rvec xj, rvec xk, rvec xl, rvec x, real a, real b, real c, t_pbc *pbc) { rvec xij, xik, xil, ra, rb, rja, rjb, rm; real d; pbc_rvec_sub(pbc, xj, xi, xij); pbc_rvec_sub(pbc, xk, xi, xik); pbc_rvec_sub(pbc, xl, xi, xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); /* 6 flops */ cprod(rja, rjb, rm); /* 9 flops */ d = c*gmx_invsqrt(norm2(rm)); /* 5+5+1 flops */ x[XX] = xi[XX] + d*rm[XX]; x[YY] = xi[YY] + d*rm[YY]; x[ZZ] = xi[ZZ] + d*rm[ZZ]; /* 6 Flops */ /* TOTAL: 47 flops */ } static int constr_vsiten(t_iatom *ia, t_iparams ip[], rvec *x, t_pbc *pbc) { rvec xs, x1, dx; dvec dsum; int n3, av, ai, i; real a; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; ai = ia[2]; copy_rvec(x[ai], x1); clear_dvec(dsum); for (i = 3; i < n3; i += 3) { ai = ia[i+2]; a = ip[ia[i]].vsiten.a; if (pbc) { pbc_dx_aiuc(pbc, x[ai], x1, dx); } else { rvec_sub(x[ai], x1, dx); } dsum[XX] += a*dx[XX]; dsum[YY] += a*dx[YY]; dsum[ZZ] += a*dx[ZZ]; /* 9 Flops */ } x[av][XX] = x1[XX] + dsum[XX]; x[av][YY] = x1[YY] + dsum[YY]; x[av][ZZ] = x1[ZZ] + dsum[ZZ]; return n3; } void construct_vsites_thread(gmx_vsite_t *vsite, rvec x[], t_nrnb *nrnb, real dt, rvec *v, t_iparams ip[], t_ilist ilist[], t_pbc *pbc_null) { gmx_bool bPBCAll; rvec xpbc, xv, vv, dx; real a1, b1, c1, inv_dt; int i, inc, ii, nra, nr, tp, ftype; t_iatom avsite, ai, aj, ak, al, pbc_atom; t_iatom *ia; t_pbc *pbc_null2; int *vsite_pbc, ishift; rvec reftmp, vtmp, rtmp; if (v != NULL) { inv_dt = 1.0/dt; } else { inv_dt = 1.0; } bPBCAll = (pbc_null != NULL && !vsite->bHaveChargeGroups); pbc_null2 = NULL; vsite_pbc = NULL; for (ftype = 0; (ftype < F_NRE); ftype++) { if ((interaction_function[ftype].flags & IF_VSITE) && ilist[ftype].nr > 0) { nra = interaction_function[ftype].nratoms; inc = 1 + nra; nr = ilist[ftype].nr; ia = ilist[ftype].iatoms; if (bPBCAll) { pbc_null2 = pbc_null; } else if (pbc_null != NULL) { vsite_pbc = vsite->vsite_pbc_loc[ftype-F_VSITE2]; } for (i = 0; i < nr; ) { tp = ia[0]; /* The vsite and constructing atoms */ avsite = ia[1]; ai = ia[2]; /* Constants for constructing vsites */ a1 = ip[tp].vsite.a; /* Check what kind of pbc we need to use */ if (bPBCAll) { /* No charge groups, vsite follows its own pbc */ pbc_atom = avsite; copy_rvec(x[avsite], xpbc); } else if (vsite_pbc != NULL) { pbc_atom = vsite_pbc[i/(1+nra)]; if (pbc_atom > -2) { if (pbc_atom >= 0) { /* We need to copy the coordinates here, * single for single atom cg's pbc_atom * is the vsite itself. */ copy_rvec(x[pbc_atom], xpbc); } pbc_null2 = pbc_null; } else { pbc_null2 = NULL; } } else { pbc_atom = -2; } /* Copy the old position */ copy_rvec(x[avsite], xv); /* Construct the vsite depending on type */ switch (ftype) { case F_VSITE2: aj = ia[3]; constr_vsite2(x[ai], x[aj], x[avsite], a1, pbc_null2); break; case F_VSITE3: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3FAD: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; constr_vsite3FAD(x[ai], x[aj], x[ak], x[avsite], a1, b1, pbc_null2); break; case F_VSITE3OUT: aj = ia[3]; ak = ia[4]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite3OUT(x[ai], x[aj], x[ak], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FD: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FD(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITE4FDN: aj = ia[3]; ak = ia[4]; al = ia[5]; b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; constr_vsite4FDN(x[ai], x[aj], x[ak], x[al], x[avsite], a1, b1, c1, pbc_null2); break; case F_VSITEN: inc = constr_vsiten(ia, ip, x, pbc_null2); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } if (pbc_atom >= 0) { /* Match the pbc of this vsite to the rest of its charge group */ ishift = pbc_dx_aiuc(pbc_null, x[avsite], xpbc, dx); if (ishift != CENTRAL) { rvec_add(xpbc, dx, x[avsite]); } } if (v != NULL) { /* Calculate velocity of vsite... */ rvec_sub(x[avsite], xv, vv); svmul(inv_dt, vv, v[avsite]); } /* Increment loop variables */ i += inc; ia += inc; } } } } void construct_vsites(FILE *log, gmx_vsite_t *vsite, rvec x[], t_nrnb *nrnb, real dt, rvec *v, t_iparams ip[], t_ilist ilist[], int ePBC, gmx_bool bMolPBC, t_graph *graph, t_commrec *cr, matrix box) { t_pbc pbc, *pbc_null; gmx_bool bDomDec; int nthreads; bDomDec = cr && DOMAINDECOMP(cr); /* We only need to do pbc when we have inter-cg vsites */ if (ePBC != epbcNONE && (bDomDec || bMolPBC) && vsite->n_intercg_vsite) { /* This is wasting some CPU time as we now do this multiple times * per MD step. But how often do we have vsites with full pbc? */ pbc_null = set_pbc_dd(&pbc, ePBC, cr != NULL ? cr->dd : NULL, FALSE, box); } else { pbc_null = NULL; } if (cr) { if (bDomDec) { dd_move_x_vsites(cr->dd, box, x); } else if (vsite->bPDvsitecomm) { /* I'm not sure whether the periodicity and shift are guaranteed * to be consistent between different nodes when running e.g. polymers * in parallel. In this special case we thus unshift/shift, * but only when necessary. This is to make sure the coordinates * we move don't end up a box away... */ if (graph != NULL) { unshift_self(graph, box, x); } move_construct_x(vsite->vsitecomm, x, cr); if (graph != NULL) { shift_self(graph, box, x); } } } if (vsite->nthreads == 1) { construct_vsites_thread(vsite, x, nrnb, dt, v, ip, ilist, pbc_null); } else { #pragma omp parallel num_threads(vsite->nthreads) { construct_vsites_thread(vsite, x, nrnb, dt, v, ip, vsite->tdata[gmx_omp_get_thread_num()].ilist, pbc_null); } /* Now we can construct the vsites that might depend on other vsites */ construct_vsites_thread(vsite, x, nrnb, dt, v, ip, vsite->tdata[vsite->nthreads].ilist, pbc_null); } } static void spread_vsite2(t_iatom ia[], real a, rvec x[], rvec f[], rvec fshift[], t_pbc *pbc, t_graph *g) { rvec fi, fj, dx; t_iatom av, ai, aj; ivec di; real b; int siv, sij; av = ia[1]; ai = ia[2]; aj = ia[3]; svmul(1-a, f[av], fi); svmul( a, f[av], fj); /* 7 flop */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); /* 6 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); } else { siv = CENTRAL; sij = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); } /* TOTAL: 13 flops */ } void construct_vsites_mtop(FILE *log, gmx_vsite_t *vsite, gmx_mtop_t *mtop, rvec x[]) { int as, mb, mol; gmx_molblock_t *molb; gmx_moltype_t *molt; as = 0; for (mb = 0; mb < mtop->nmolblock; mb++) { molb = &mtop->molblock[mb]; molt = &mtop->moltype[molb->type]; for (mol = 0; mol < molb->nmol; mol++) { construct_vsites(log, vsite, x+as, NULL, 0.0, NULL, mtop->ffparams.iparams, molt->ilist, epbcNONE, TRUE, NULL, NULL, NULL); as += molt->atoms.nr; } } } static void spread_vsite3(t_iatom ia[], real a, real b, rvec x[], rvec f[], rvec fshift[], t_pbc *pbc, t_graph *g) { rvec fi, fj, fk, dx; atom_id av, ai, aj, ak; ivec di; int siv, sij, sik; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; svmul(1-a-b, f[av], fi); svmul( a, f[av], fj); svmul( b, f[av], fk); /* 11 flops */ rvec_inc(f[ai], fi); rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 9 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ia[1]), di); siv = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, aj), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, ak), di); sik = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], x[av], dx); sij = pbc_dx_aiuc(pbc, x[ai], x[aj], dx); sik = pbc_dx_aiuc(pbc, x[ai], x[ak], dx); } else { siv = CENTRAL; sij = CENTRAL; sik = CENTRAL; } if (fshift && (siv != CENTRAL || sij != CENTRAL || sik != CENTRAL)) { rvec_inc(fshift[siv], f[av]); rvec_dec(fshift[CENTRAL], fi); rvec_dec(fshift[sij], fj); rvec_dec(fshift[sik], fk); } /* TOTAL: 20 flops */ } static void spread_vsite3FD(t_iatom ia[], real a, real b, rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, t_pbc *pbc, t_graph *g) { real fx, fy, fz, c, invl, fproj, a1; rvec xvi, xij, xjk, xix, fv, temp; t_iatom av, ai, aj, ak; int svi, sji, skj, d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[av], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ /* xix goes from i to point x on the line jk */ xix[XX] = xij[XX]+a*xjk[XX]; xix[YY] = xij[YY]+a*xjk[YY]; xix[ZZ] = xij[ZZ]+a*xjk[ZZ]; /* 6 flops */ invl = gmx_invsqrt(iprod(xix, xix)); c = b*invl; /* 4 + ?10? flops */ fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ temp[XX] = c*(fv[XX]-fproj*xix[XX]); temp[YY] = c*(fv[YY]-fproj*xix[YY]); temp[ZZ] = c*(fv[ZZ]-fproj*xix[ZZ]); /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 26 flops! */ a1 = 1-a; f[ai][XX] += fv[XX] - temp[XX]; f[ai][YY] += fv[YY] - temp[YY]; f[ai][ZZ] += fv[ZZ] - temp[ZZ]; f[aj][XX] += a1*temp[XX]; f[aj][YY] += a1*temp[YY]; f[aj][ZZ] += a1*temp[ZZ]; f[ak][XX] += a*temp[XX]; f[ak][YY] += a*temp[YY]; f[ak][ZZ] += a*temp[ZZ]; /* 19 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - (1 + a)*temp[XX]; fshift[CENTRAL][YY] += fv[YY] - (1 + a)*temp[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - (1 + a)*temp[ZZ]; fshift[ sji][XX] += temp[XX]; fshift[ sji][YY] += temp[YY]; fshift[ sji][ZZ] += temp[ZZ]; fshift[ skj][XX] += a*temp[XX]; fshift[ skj][YY] += a*temp[YY]; fshift[ skj][ZZ] += a*temp[ZZ]; } if (VirCorr) { /* When VirCorr=TRUE, the virial for the current forces is not * calculated from the redistributed forces. This means that * the effect of non-linear virtual site constructions on the virial * needs to be added separately. This contribution can be calculated * in many ways, but the simplest and cheapest way is to use * the first constructing atom ai as a reference position in space: * subtract (xv-xi)*fv and add (xj-xi)*fj + (xk-xi)*fk. */ rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { /* As xix is a linear combination of j and k, use that here */ dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 61 flops */ } static void spread_vsite3FAD(t_iatom ia[], real a, real b, rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, t_pbc *pbc, t_graph *g) { rvec xvi, xij, xjk, xperp, Fpij, Fppp, fv, f1, f2, f3; real a1, b1, c1, c2, invdij, invdij2, invdp, fproj; t_iatom av, ai, aj, ak; int svi, sji, skj, d; ivec di; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; copy_rvec(f[ia[1]], fv); sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); /* 6 flops */ invdij = gmx_invsqrt(iprod(xij, xij)); invdij2 = invdij * invdij; c1 = iprod(xij, xjk) * invdij2; xperp[XX] = xjk[XX] - c1*xij[XX]; xperp[YY] = xjk[YY] - c1*xij[YY]; xperp[ZZ] = xjk[ZZ] - c1*xij[ZZ]; /* xperp in plane ijk, perp. to ij */ invdp = gmx_invsqrt(iprod(xperp, xperp)); a1 = a*invdij; b1 = b*invdp; /* 45 flops */ /* a1, b1 and c1 are already calculated in constr_vsite3FAD storing them somewhere will save 45 flops! */ fproj = iprod(xij, fv)*invdij2; svmul(fproj, xij, Fpij); /* proj. f on xij */ svmul(iprod(xperp, fv)*invdp*invdp, xperp, Fppp); /* proj. f on xperp */ svmul(b1*fproj, xperp, f3); /* 23 flops */ rvec_sub(fv, Fpij, f1); /* f1 = f - Fpij */ rvec_sub(f1, Fppp, f2); /* f2 = f - Fpij - Fppp */ for (d = 0; (d < DIM); d++) { f1[d] *= a1; f2[d] *= b1; } /* 12 flops */ c2 = 1+c1; f[ai][XX] += fv[XX] - f1[XX] + c1*f2[XX] + f3[XX]; f[ai][YY] += fv[YY] - f1[YY] + c1*f2[YY] + f3[YY]; f[ai][ZZ] += fv[ZZ] - f1[ZZ] + c1*f2[ZZ] + f3[ZZ]; f[aj][XX] += f1[XX] - c2*f2[XX] - f3[XX]; f[aj][YY] += f1[YY] - c2*f2[YY] - f3[YY]; f[aj][ZZ] += f1[ZZ] - c2*f2[ZZ] - f3[ZZ]; f[ak][XX] += f2[XX]; f[ak][YY] += f2[YY]; f[ak][ZZ] += f2[ZZ]; /* 30 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - f1[XX] - (1-c1)*f2[XX] + f3[XX]; fshift[CENTRAL][YY] += fv[YY] - f1[YY] - (1-c1)*f2[YY] + f3[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - f1[ZZ] - (1-c1)*f2[ZZ] + f3[ZZ]; fshift[ sji][XX] += f1[XX] - c1 *f2[XX] - f3[XX]; fshift[ sji][YY] += f1[YY] - c1 *f2[YY] - f3[YY]; fshift[ sji][ZZ] += f1[ZZ] - c1 *f2[ZZ] - f3[ZZ]; fshift[ skj][XX] += f2[XX]; fshift[ skj][YY] += f2[YY]; fshift[ skj][ZZ] += f2[ZZ]; } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { /* Note that xik=xij+xjk, so we have to add xij*f2 */ dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*(f1[j] + (1 - c2)*f2[j] - f3[j]) + xjk[i]*f2[j]; } } } /* TOTAL: 113 flops */ } static void spread_vsite3OUT(t_iatom ia[], real a, real b, real c, rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, t_pbc *pbc, t_graph *g) { rvec xvi, xij, xik, fv, fj, fk; real cfx, cfy, cfz; atom_id av, ai, aj, ak; ivec di; int svi, sji, ski; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); ski = pbc_rvec_sub(pbc, x[ak], x[ai], xik); /* 6 Flops */ copy_rvec(f[av], fv); cfx = c*fv[XX]; cfy = c*fv[YY]; cfz = c*fv[ZZ]; /* 3 Flops */ fj[XX] = a*fv[XX] - xik[ZZ]*cfy + xik[YY]*cfz; fj[YY] = xik[ZZ]*cfx + a*fv[YY] - xik[XX]*cfz; fj[ZZ] = -xik[YY]*cfx + xik[XX]*cfy + a*fv[ZZ]; fk[XX] = b*fv[XX] + xij[ZZ]*cfy - xij[YY]*cfz; fk[YY] = -xij[ZZ]*cfx + b*fv[YY] + xij[XX]*cfz; fk[ZZ] = xij[YY]*cfx - xij[XX]*cfy + b*fv[ZZ]; /* 30 Flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); /* 15 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); ski = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || ski != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ]; rvec_inc(fshift[sji], fj); rvec_inc(fshift[ski], fk); } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j]; } } } /* TOTAL: 54 flops */ } static void spread_vsite4FD(t_iatom ia[], real a, real b, real c, rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, t_pbc *pbc, t_graph *g) { real d, invl, fproj, a1; rvec xvi, xij, xjk, xjl, xix, fv, temp; atom_id av, ai, aj, ak, al; ivec di; int svi, sji, skj, slj, m; av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; sji = pbc_rvec_sub(pbc, x[aj], x[ai], xij); skj = pbc_rvec_sub(pbc, x[ak], x[aj], xjk); slj = pbc_rvec_sub(pbc, x[al], x[aj], xjl); /* 9 flops */ /* xix goes from i to point x on the plane jkl */ for (m = 0; m < DIM; m++) { xix[m] = xij[m] + a*xjk[m] + b*xjl[m]; } /* 12 flops */ invl = gmx_invsqrt(iprod(xix, xix)); d = c*invl; /* 4 + ?10? flops */ copy_rvec(f[av], fv); fproj = iprod(xix, fv)*invl*invl; /* = (xix . f)/(xix . xix) */ for (m = 0; m < DIM; m++) { temp[m] = d*(fv[m] - fproj*xix[m]); } /* 16 */ /* c is already calculated in constr_vsite3FD storing c somewhere will save 35 flops! */ a1 = 1 - a - b; for (m = 0; m < DIM; m++) { f[ai][m] += fv[m] - temp[m]; f[aj][m] += a1*temp[m]; f[ak][m] += a*temp[m]; f[al][m] += b*temp[m]; } /* 26 Flops */ if (g) { ivec_sub(SHIFT_IVEC(g, ia[1]), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sji = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, aj), di); skj = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, aj), di); slj = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sji != CENTRAL || skj != CENTRAL || slj != CENTRAL)) { rvec_dec(fshift[svi], fv); for (m = 0; m < DIM; m++) { fshift[CENTRAL][m] += fv[m] - (1 + a + b)*temp[m]; fshift[ sji][m] += temp[m]; fshift[ skj][m] += a*temp[m]; fshift[ slj][m] += b*temp[m]; } } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xix[i]*temp[j]; } } } /* TOTAL: 77 flops */ } static void spread_vsite4FDN(t_iatom ia[], real a, real b, real c, rvec x[], rvec f[], rvec fshift[], gmx_bool VirCorr, matrix dxdf, t_pbc *pbc, t_graph *g) { rvec xvi, xij, xik, xil, ra, rb, rja, rjb, rab, rm, rt; rvec fv, fj, fk, fl; real invrm, denom; real cfx, cfy, cfz; ivec di; int av, ai, aj, ak, al; int svi, sij, sik, sil; /* DEBUG: check atom indices */ av = ia[1]; ai = ia[2]; aj = ia[3]; ak = ia[4]; al = ia[5]; copy_rvec(f[av], fv); sij = pbc_rvec_sub(pbc, x[aj], x[ai], xij); sik = pbc_rvec_sub(pbc, x[ak], x[ai], xik); sil = pbc_rvec_sub(pbc, x[al], x[ai], xil); /* 9 flops */ ra[XX] = a*xik[XX]; ra[YY] = a*xik[YY]; ra[ZZ] = a*xik[ZZ]; rb[XX] = b*xil[XX]; rb[YY] = b*xil[YY]; rb[ZZ] = b*xil[ZZ]; /* 6 flops */ rvec_sub(ra, xij, rja); rvec_sub(rb, xij, rjb); rvec_sub(rb, ra, rab); /* 9 flops */ cprod(rja, rjb, rm); /* 9 flops */ invrm = gmx_invsqrt(norm2(rm)); denom = invrm*invrm; /* 5+5+2 flops */ cfx = c*invrm*fv[XX]; cfy = c*invrm*fv[YY]; cfz = c*invrm*fv[ZZ]; /* 6 Flops */ cprod(rm, rab, rt); /* 9 flops */ rt[XX] *= denom; rt[YY] *= denom; rt[ZZ] *= denom; /* 3flops */ fj[XX] = ( -rm[XX]*rt[XX]) * cfx + ( rab[ZZ]-rm[YY]*rt[XX]) * cfy + (-rab[YY]-rm[ZZ]*rt[XX]) * cfz; fj[YY] = (-rab[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( rab[XX]-rm[ZZ]*rt[YY]) * cfz; fj[ZZ] = ( rab[YY]-rm[XX]*rt[ZZ]) * cfx + (-rab[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 30 flops */ cprod(rjb, rm, rt); /* 9 flops */ rt[XX] *= denom*a; rt[YY] *= denom*a; rt[ZZ] *= denom*a; /* 3flops */ fk[XX] = ( -rm[XX]*rt[XX]) * cfx + (-a*rjb[ZZ]-rm[YY]*rt[XX]) * cfy + ( a*rjb[YY]-rm[ZZ]*rt[XX]) * cfz; fk[YY] = ( a*rjb[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + (-a*rjb[XX]-rm[ZZ]*rt[YY]) * cfz; fk[ZZ] = (-a*rjb[YY]-rm[XX]*rt[ZZ]) * cfx + ( a*rjb[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ cprod(rm, rja, rt); /* 9 flops */ rt[XX] *= denom*b; rt[YY] *= denom*b; rt[ZZ] *= denom*b; /* 3flops */ fl[XX] = ( -rm[XX]*rt[XX]) * cfx + ( b*rja[ZZ]-rm[YY]*rt[XX]) * cfy + (-b*rja[YY]-rm[ZZ]*rt[XX]) * cfz; fl[YY] = (-b*rja[ZZ]-rm[XX]*rt[YY]) * cfx + ( -rm[YY]*rt[YY]) * cfy + ( b*rja[XX]-rm[ZZ]*rt[YY]) * cfz; fl[ZZ] = ( b*rja[YY]-rm[XX]*rt[ZZ]) * cfx + (-b*rja[XX]-rm[YY]*rt[ZZ]) * cfy + ( -rm[ZZ]*rt[ZZ]) * cfz; /* 36 flops */ f[ai][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; f[ai][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; f[ai][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(f[aj], fj); rvec_inc(f[ak], fk); rvec_inc(f[al], fl); /* 21 flops */ if (g) { ivec_sub(SHIFT_IVEC(g, av), SHIFT_IVEC(g, ai), di); svi = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, aj), SHIFT_IVEC(g, ai), di); sij = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, ak), SHIFT_IVEC(g, ai), di); sik = IVEC2IS(di); ivec_sub(SHIFT_IVEC(g, al), SHIFT_IVEC(g, ai), di); sil = IVEC2IS(di); } else if (pbc) { svi = pbc_rvec_sub(pbc, x[av], x[ai], xvi); } else { svi = CENTRAL; } if (fshift && (svi != CENTRAL || sij != CENTRAL || sik != CENTRAL || sil != CENTRAL)) { rvec_dec(fshift[svi], fv); fshift[CENTRAL][XX] += fv[XX] - fj[XX] - fk[XX] - fl[XX]; fshift[CENTRAL][YY] += fv[YY] - fj[YY] - fk[YY] - fl[YY]; fshift[CENTRAL][ZZ] += fv[ZZ] - fj[ZZ] - fk[ZZ] - fl[ZZ]; rvec_inc(fshift[sij], fj); rvec_inc(fshift[sik], fk); rvec_inc(fshift[sil], fl); } if (VirCorr) { rvec xiv; int i, j; pbc_rvec_sub(pbc, x[av], x[ai], xiv); for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { dxdf[i][j] += -xiv[i]*fv[j] + xij[i]*fj[j] + xik[i]*fk[j] + xil[i]*fl[j]; } } } /* Total: 207 flops (Yuck!) */ } static int spread_vsiten(t_iatom ia[], t_iparams ip[], rvec x[], rvec f[], rvec fshift[], t_pbc *pbc, t_graph *g) { rvec xv, dx, fi; int n3, av, i, ai; real a; ivec di; int siv; n3 = 3*ip[ia[0]].vsiten.n; av = ia[1]; copy_rvec(x[av], xv); for (i = 0; i < n3; i += 3) { ai = ia[i+2]; if (g) { ivec_sub(SHIFT_IVEC(g, ai), SHIFT_IVEC(g, av), di); siv = IVEC2IS(di); } else if (pbc) { siv = pbc_dx_aiuc(pbc, x[ai], xv, dx); } else { siv = CENTRAL; } a = ip[ia[i]].vsiten.a; svmul(a, f[av], fi); rvec_inc(f[ai], fi); if (fshift && siv != CENTRAL) { rvec_inc(fshift[siv], fi); rvec_dec(fshift[CENTRAL], fi); } /* 6 Flops */ } return n3; } static int vsite_count(const t_ilist *ilist, int ftype) { if (ftype == F_VSITEN) { return ilist[ftype].nr/3; } else { return ilist[ftype].nr/(1 + interaction_function[ftype].nratoms); } } static void spread_vsite_f_thread(gmx_vsite_t *vsite, rvec x[], rvec f[], rvec *fshift, gmx_bool VirCorr, matrix dxdf, t_iparams ip[], t_ilist ilist[], t_graph *g, t_pbc *pbc_null) { gmx_bool bPBCAll; real a1, b1, c1; int i, inc, m, nra, nr, tp, ftype; t_iatom *ia; t_pbc *pbc_null2; int *vsite_pbc; if (VirCorr) { clear_mat(dxdf); } bPBCAll = (pbc_null != NULL && !vsite->bHaveChargeGroups); /* this loop goes backwards to be able to build * * higher type vsites from lower types */ pbc_null2 = NULL; vsite_pbc = NULL; for (ftype = F_NRE-1; (ftype >= 0); ftype--) { if ((interaction_function[ftype].flags & IF_VSITE) && ilist[ftype].nr > 0) { nra = interaction_function[ftype].nratoms; inc = 1 + nra; nr = ilist[ftype].nr; ia = ilist[ftype].iatoms; if (bPBCAll) { pbc_null2 = pbc_null; } else if (pbc_null != NULL) { vsite_pbc = vsite->vsite_pbc_loc[ftype-F_VSITE2]; } for (i = 0; i < nr; ) { if (vsite_pbc != NULL) { if (vsite_pbc[i/(1+nra)] > -2) { pbc_null2 = pbc_null; } else { pbc_null2 = NULL; } } tp = ia[0]; /* Constants for constructing */ a1 = ip[tp].vsite.a; /* Construct the vsite depending on type */ switch (ftype) { case F_VSITE2: spread_vsite2(ia, a1, x, f, fshift, pbc_null2, g); break; case F_VSITE3: b1 = ip[tp].vsite.b; spread_vsite3(ia, a1, b1, x, f, fshift, pbc_null2, g); break; case F_VSITE3FD: b1 = ip[tp].vsite.b; spread_vsite3FD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3FAD: b1 = ip[tp].vsite.b; spread_vsite3FAD(ia, a1, b1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE3OUT: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite3OUT(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FD: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FD(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITE4FDN: b1 = ip[tp].vsite.b; c1 = ip[tp].vsite.c; spread_vsite4FDN(ia, a1, b1, c1, x, f, fshift, VirCorr, dxdf, pbc_null2, g); break; case F_VSITEN: inc = spread_vsiten(ia, ip, x, f, fshift, pbc_null2, g); break; default: gmx_fatal(FARGS, "No such vsite type %d in %s, line %d", ftype, __FILE__, __LINE__); } clear_rvec(f[ia[1]]); /* Increment loop variables */ i += inc; ia += inc; } } } } void spread_vsite_f(FILE *log, gmx_vsite_t *vsite, rvec x[], rvec f[], rvec *fshift, gmx_bool VirCorr, matrix vir, t_nrnb *nrnb, t_idef *idef, int ePBC, gmx_bool bMolPBC, t_graph *g, matrix box, t_commrec *cr) { t_pbc pbc, *pbc_null; int th; /* We only need to do pbc when we have inter-cg vsites */ if ((DOMAINDECOMP(cr) || bMolPBC) && vsite->n_intercg_vsite) { /* This is wasting some CPU time as we now do this multiple times * per MD step. But how often do we have vsites with full pbc? */ pbc_null = set_pbc_dd(&pbc, ePBC, cr->dd, FALSE, box); } else { pbc_null = NULL; } if (DOMAINDECOMP(cr)) { dd_clear_f_vsites(cr->dd, f); } else if (PARTDECOMP(cr) && vsite->vsitecomm != NULL) { pd_clear_nonlocal_constructs(vsite->vsitecomm, f); } if (vsite->nthreads == 1) { spread_vsite_f_thread(vsite, x, f, fshift, VirCorr, vsite->tdata[0].dxdf, idef->iparams, idef->il, g, pbc_null); } else { /* First spread the vsites that might depend on other vsites */ spread_vsite_f_thread(vsite, x, f, fshift, VirCorr, vsite->tdata[vsite->nthreads].dxdf, idef->iparams, vsite->tdata[vsite->nthreads].ilist, g, pbc_null); #pragma omp parallel num_threads(vsite->nthreads) { int thread; rvec *fshift_t; thread = gmx_omp_get_thread_num(); if (thread == 0 || fshift == NULL) { fshift_t = fshift; } else { int i; fshift_t = vsite->tdata[thread].fshift; for (i = 0; i < SHIFTS; i++) { clear_rvec(fshift_t[i]); } } spread_vsite_f_thread(vsite, x, f, fshift_t, VirCorr, vsite->tdata[thread].dxdf, idef->iparams, vsite->tdata[thread].ilist, g, pbc_null); } if (fshift != NULL) { int i; for (th = 1; th < vsite->nthreads; th++) { for (i = 0; i < SHIFTS; i++) { rvec_inc(fshift[i], vsite->tdata[th].fshift[i]); } } } } if (VirCorr) { int i, j; for (th = 0; th < (vsite->nthreads == 1 ? 1 : vsite->nthreads+1); th++) { for (i = 0; i < DIM; i++) { for (j = 0; j < DIM; j++) { vir[i][j] += -0.5*vsite->tdata[th].dxdf[i][j]; } } } } if (DOMAINDECOMP(cr)) { dd_move_f_vsites(cr->dd, f, fshift); } else if (vsite->bPDvsitecomm) { /* We only move forces here, and they are independent of shifts */ move_construct_f(vsite->vsitecomm, f, cr); } inc_nrnb(nrnb, eNR_VSITE2, vsite_count(idef->il, F_VSITE2)); inc_nrnb(nrnb, eNR_VSITE3, vsite_count(idef->il, F_VSITE3)); inc_nrnb(nrnb, eNR_VSITE3FD, vsite_count(idef->il, F_VSITE3FD)); inc_nrnb(nrnb, eNR_VSITE3FAD, vsite_count(idef->il, F_VSITE3FAD)); inc_nrnb(nrnb, eNR_VSITE3OUT, vsite_count(idef->il, F_VSITE3OUT)); inc_nrnb(nrnb, eNR_VSITE4FD, vsite_count(idef->il, F_VSITE4FD)); inc_nrnb(nrnb, eNR_VSITE4FDN, vsite_count(idef->il, F_VSITE4FDN)); inc_nrnb(nrnb, eNR_VSITEN, vsite_count(idef->il, F_VSITEN)); } static int *atom2cg(t_block *cgs) { int *a2cg, cg, i; snew(a2cg, cgs->index[cgs->nr]); for (cg = 0; cg < cgs->nr; cg++) { for (i = cgs->index[cg]; i < cgs->index[cg+1]; i++) { a2cg[i] = cg; } } return a2cg; } static int count_intercg_vsite(gmx_mtop_t *mtop, gmx_bool *bHaveChargeGroups) { int mb, mt, ftype, nral, i, cg, a; gmx_molblock_t *molb; gmx_moltype_t *molt; int *a2cg; t_ilist *il; t_iatom *ia; int n_intercg_vsite; *bHaveChargeGroups = FALSE; n_intercg_vsite = 0; for (mb = 0; mb < mtop->nmolblock; mb++) { molb = &mtop->molblock[mb]; molt = &mtop->moltype[molb->type]; if (molt->cgs.nr < molt->atoms.nr) { *bHaveChargeGroups = TRUE; } a2cg = atom2cg(&molt->cgs); for (ftype = 0; ftype < F_NRE; ftype++) { if (interaction_function[ftype].flags & IF_VSITE) { nral = NRAL(ftype); il = &molt->ilist[ftype]; ia = il->iatoms; for (i = 0; i < il->nr; i += 1+nral) { cg = a2cg[ia[1+i]]; for (a = 1; a < nral; a++) { if (a2cg[ia[1+a]] != cg) { n_intercg_vsite += molb->nmol; break; } } } } } sfree(a2cg); } return n_intercg_vsite; } static int **get_vsite_pbc(t_iparams *iparams, t_ilist *ilist, t_atom *atom, t_mdatoms *md, t_block *cgs, int *a2cg) { int ftype, nral, i, j, vsi, vsite, cg_v, cg_c, a, nc3 = 0; t_ilist *il; t_iatom *ia; int **vsite_pbc, *vsite_pbc_f; char *pbc_set; gmx_bool bViteOnlyCG_and_FirstAtom; /* Make an array that tells if the pbc of an atom is set */ snew(pbc_set, cgs->index[cgs->nr]); /* PBC is set for all non vsites */ for (a = 0; a < cgs->index[cgs->nr]; a++) { if ((atom && atom[a].ptype != eptVSite) || (md && md->ptype[a] != eptVSite)) { pbc_set[a] = 1; } } snew(vsite_pbc, F_VSITEN-F_VSITE2+1); for (ftype = 0; ftype < F_NRE; ftype++) { if (interaction_function[ftype].flags & IF_VSITE) { nral = NRAL(ftype); il = &ilist[ftype]; ia = il->iatoms; snew(vsite_pbc[ftype-F_VSITE2], il->nr/(1+nral)); vsite_pbc_f = vsite_pbc[ftype-F_VSITE2]; i = 0; while (i < il->nr) { vsi = i/(1+nral); vsite = ia[i+1]; cg_v = a2cg[vsite]; /* A value of -2 signals that this vsite and its contructing * atoms are all within the same cg, so no pbc is required. */ vsite_pbc_f[vsi] = -2; /* Check if constructing atoms are outside the vsite's cg */ nc3 = 0; if (ftype == F_VSITEN) { nc3 = 3*iparams[ia[i]].vsiten.n; for (j = 0; j < nc3; j += 3) { if (a2cg[ia[i+j+2]] != cg_v) { vsite_pbc_f[vsi] = -1; } } } else { for (a = 1; a < nral; a++) { if (a2cg[ia[i+1+a]] != cg_v) { vsite_pbc_f[vsi] = -1; } } } if (vsite_pbc_f[vsi] == -1) { /* Check if this is the first processed atom of a vsite only cg */ bViteOnlyCG_and_FirstAtom = TRUE; for (a = cgs->index[cg_v]; a < cgs->index[cg_v+1]; a++) { /* Non-vsites already have pbc set, so simply check for pbc_set */ if (pbc_set[a]) { bViteOnlyCG_and_FirstAtom = FALSE; break; } } if (bViteOnlyCG_and_FirstAtom) { /* First processed atom of a vsite only charge group. * The pbc of the input coordinates to construct_vsites * should be preserved. */ vsite_pbc_f[vsi] = vsite; } else if (cg_v != a2cg[ia[1+i+1]]) { /* This vsite has a different charge group index * than it's first constructing atom * and the charge group has more than one atom, * search for the first normal particle * or vsite that already had its pbc defined. * If nothing is found, use full pbc for this vsite. */ for (a = cgs->index[cg_v]; a < cgs->index[cg_v+1]; a++) { if (a != vsite && pbc_set[a]) { vsite_pbc_f[vsi] = a; if (gmx_debug_at) { fprintf(debug, "vsite %d match pbc with atom %d\n", vsite+1, a+1); } break; } } if (gmx_debug_at) { fprintf(debug, "vsite atom %d cg %d - %d pbc atom %d\n", vsite+1, cgs->index[cg_v]+1, cgs->index[cg_v+1], vsite_pbc_f[vsi]+1); } } } if (ftype == F_VSITEN) { /* The other entries in vsite_pbc_f are not used for center vsites */ i += nc3; } else { i += 1+nral; } /* This vsite now has its pbc defined */ pbc_set[vsite] = 1; } } } sfree(pbc_set); return vsite_pbc; } gmx_vsite_t *init_vsite(gmx_mtop_t *mtop, t_commrec *cr, gmx_bool bSerial_NoPBC) { int nvsite, i; int *a2cg, cg; gmx_vsite_t *vsite; int mt; gmx_moltype_t *molt; int nthreads; /* check if there are vsites */ nvsite = 0; for (i = 0; i < F_NRE; i++) { if (interaction_function[i].flags & IF_VSITE) { nvsite += gmx_mtop_ftype_count(mtop, i); } } if (nvsite == 0) { return NULL; } snew(vsite, 1); vsite->n_intercg_vsite = count_intercg_vsite(mtop, &vsite->bHaveChargeGroups); /* If we don't have charge groups, the vsite follows its own pbc */ if (!bSerial_NoPBC && vsite->bHaveChargeGroups && vsite->n_intercg_vsite > 0 && DOMAINDECOMP(cr)) { vsite->nvsite_pbc_molt = mtop->nmoltype; snew(vsite->vsite_pbc_molt, vsite->nvsite_pbc_molt); for (mt = 0; mt < mtop->nmoltype; mt++) { molt = &mtop->moltype[mt]; /* Make an atom to charge group index */ a2cg = atom2cg(&molt->cgs); vsite->vsite_pbc_molt[mt] = get_vsite_pbc(mtop->ffparams.iparams, molt->ilist, molt->atoms.atom, NULL, &molt->cgs, a2cg); sfree(a2cg); } snew(vsite->vsite_pbc_loc_nalloc, F_VSITEN-F_VSITE2+1); snew(vsite->vsite_pbc_loc, F_VSITEN-F_VSITE2+1); } if (bSerial_NoPBC) { vsite->nthreads = 1; } else { vsite->nthreads = gmx_omp_nthreads_get(emntVSITE); } if (!bSerial_NoPBC) { /* We need one extra thread data structure for the overlap vsites */ snew(vsite->tdata, vsite->nthreads+1); } vsite->th_ind = NULL; vsite->th_ind_nalloc = 0; return vsite; } static void prepare_vsite_thread(const t_ilist *ilist, gmx_vsite_thread_t *vsite_th) { int ftype; for (ftype = 0; ftype < F_NRE; ftype++) { if (interaction_function[ftype].flags & IF_VSITE) { if (ilist[ftype].nr > vsite_th->ilist[ftype].nalloc) { vsite_th->ilist[ftype].nalloc = over_alloc_large(ilist[ftype].nr); srenew(vsite_th->ilist[ftype].iatoms, vsite_th->ilist[ftype].nalloc); } vsite_th->ilist[ftype].nr = 0; } } } void split_vsites_over_threads(const t_ilist *ilist, const t_mdatoms *mdatoms, gmx_bool bLimitRange, gmx_vsite_t *vsite) { int th; int vsite_atom_range, natperthread; int *th_ind; int ftype; t_iatom *iat; t_ilist *il_th; int nral1, inc, i, j; if (vsite->nthreads == 1) { /* Nothing to do */ return; } #pragma omp parallel for num_threads(vsite->nthreads) schedule(static) for (th = 0; th < vsite->nthreads; th++) { prepare_vsite_thread(ilist, &vsite->tdata[th]); } /* Master threads does the (potential) overlap vsites */ prepare_vsite_thread(ilist, &vsite->tdata[vsite->nthreads]); /* The current way of distributing the vsites over threads in primitive. * We divide the atom range 0 - natoms_in_vsite uniformly over threads, * without taking into account how the vsites are distributed. * Without domain decomposition we bLimitRange=TRUE and we at least * tighten the upper bound of the range (useful for common systems * such as a vsite-protein in 3-site water). */ if (bLimitRange) { vsite_atom_range = -1; for (ftype = 0; ftype < F_NRE; ftype++) { if ((interaction_function[ftype].flags & IF_VSITE) && ftype != F_VSITEN) { nral1 = 1 + NRAL(ftype); iat = ilist[ftype].iatoms; for (i = 0; i < ilist[ftype].nr; i += nral1) { for (j = i+1; j < i+nral1; j++) { vsite_atom_range = max(vsite_atom_range, iat[j]); } } } } vsite_atom_range++; } else { vsite_atom_range = mdatoms->homenr; } natperthread = (vsite_atom_range + vsite->nthreads - 1)/vsite->nthreads; if (debug) { fprintf(debug, "virtual site thread dist: natoms %d, range %d, natperthread %d\n", mdatoms->nr, vsite_atom_range, natperthread); } /* To simplify the vsite assignment, we make an index which tells us * to which thread particles, both non-vsites and vsites, are assigned. */ if (mdatoms->nr > vsite->th_ind_nalloc) { vsite->th_ind_nalloc = over_alloc_large(mdatoms->nr); srenew(vsite->th_ind, vsite->th_ind_nalloc); } th_ind = vsite->th_ind; th = 0; for (i = 0; i < mdatoms->nr; i++) { if (mdatoms->ptype[i] == eptVSite) { /* vsites are not assigned to a thread yet */ th_ind[i] = -1; } else { /* assign non-vsite particles to thread th */ th_ind[i] = th; } if (i == (th + 1)*natperthread && th < vsite->nthreads) { th++; } } for (ftype = 0; ftype < F_NRE; ftype++) { if ((interaction_function[ftype].flags & IF_VSITE) && ftype != F_VSITEN) { nral1 = 1 + NRAL(ftype); inc = nral1; iat = ilist[ftype].iatoms; for (i = 0; i < ilist[ftype].nr; ) { th = iat[1+i]/natperthread; /* We would like to assign this vsite the thread th, * but it might depend on atoms outside the atom range of th * or on another vsite not assigned to thread th. */ if (ftype != F_VSITEN) { for (j = i+2; j < i+nral1; j++) { if (th_ind[iat[j]] != th) { /* Some constructing atoms are not assigned to * thread th, move this vsite to a separate batch. */ th = vsite->nthreads; } } } else { inc = iat[i]; for (j = i+2; j < i+inc; j += 3) { if (th_ind[iat[j]] != th) { th = vsite->nthreads; } } } /* Copy this vsite to the thread data struct of thread th */ il_th = &vsite->tdata[th].ilist[ftype]; for (j = i; j < i+inc; j++) { il_th->iatoms[il_th->nr++] = iat[j]; } /* Update this vsite's thread index entry */ th_ind[iat[1+i]] = th; i += inc; } } } if (debug) { for (ftype = 0; ftype < F_NRE; ftype++) { if ((interaction_function[ftype].flags & IF_VSITE) && ilist[ftype].nr > 0) { fprintf(debug, "%-20s thread dist:", interaction_function[ftype].longname); for (th = 0; th < vsite->nthreads+1; th++) { fprintf(debug, " %4d", vsite->tdata[th].ilist[ftype].nr); } fprintf(debug, "\n"); } } } } void set_vsite_top(gmx_vsite_t *vsite, gmx_localtop_t *top, t_mdatoms *md, t_commrec *cr) { int *a2cg; if (vsite->n_intercg_vsite > 0) { if (vsite->bHaveChargeGroups) { /* Make an atom to charge group index */ a2cg = atom2cg(&top->cgs); vsite->vsite_pbc_loc = get_vsite_pbc(top->idef.iparams, top->idef.il, NULL, md, &top->cgs, a2cg); sfree(a2cg); } if (PARTDECOMP(cr)) { snew(vsite->vsitecomm, 1); vsite->bPDvsitecomm = setup_parallel_vsites(&(top->idef), cr, vsite->vsitecomm); } } if (vsite->nthreads > 1) { if (vsite->bHaveChargeGroups || PARTDECOMP(cr)) { gmx_incons("Can not use threads virtual sites combined with charge groups or particle decomposition"); } split_vsites_over_threads(top->idef.il, md, !DOMAINDECOMP(cr), vsite); } }
TAD.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author Adam Gibson // #ifndef LIBND4J_TAD_H #define LIBND4J_TAD_H #include <helpers/shape.h> #include <pointercast.h> namespace shape { /** * Dimension collapse is an algorithm * for collapsing singular dimensions. * This algorithm will adjust the dimensions * wrt the original. * * The algorithm has 3 components: * trailing ones * middle ones * beginning ones * * dimensions that are specified to reduce along * that are singular should be truncated * * dimensions that are specified that are singular * at the beginning should be removed with middle dimensions * decremented. * * For any time there is a no op, a collapse will * set the first dimension to be -1. * * */ class TAD { public: Nd4jLong tadIndex = 0; int dimensionLength; int* dimension = nullptr; Nd4jLong *shapeInfo = nullptr; Nd4jLong *tadOnlyShapeInfo = nullptr; Nd4jLong numTads = 0; int tadRank = 0; Nd4jLong *tadShape = nullptr; Nd4jLong *tadStride = nullptr; Nd4jLong *tadOffsets = nullptr; Nd4jLong tadOffsetForBlock = 0; int rank = 0; int numOnes = 0; //pointers to original int originalDimensionLength; int *originalDimension = nullptr; Nd4jLong *originalShapeInfo = nullptr; bool squeezed = false; bool newSqueezeDimensions = false; int numOnesInMiddle = 0; bool wholeThing = false; //need to track whether we create a new dimension array or not, we could have just moved the pointer forward //due to leading ones bool createdNewDimension = false; // special case for CUDA, we're passing in __shared__ memory pointers to be used instead of new/malloc void *ptrManager = nullptr; int *ptrOutput = nullptr; #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF TAD() {} #ifdef __CUDACC__ __host__ __device__ #endif TAD(int tadIndex,Nd4jLong *shapeInfo,int *dimension,int dimensionLength); #ifdef __CUDACC__ __host__ __device__ #endif TAD(Nd4jLong *shapeInfo,int *dimension,int dimensionLength); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void setExternalBuffers(void *ptrManager); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void setOutputBuffer(int *ptrOutput); #ifdef __CUDACC__ __host__ __device__ #endif /** * This method is for GPU mostly, it allows to initialize TAD instance with precalculated tadOnlyShapeInfo */ INLINEDEF void initWithExternalTAD(Nd4jLong *existingTAD, Nd4jLong *originalShape, int *dimension, int dimensionLength); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void init(Nd4jLong *shapeInfo,int *dimension,int dimensionLength); template <typename T> #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void printTADsND(T *x); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void permuteShapeBufferInPlace(Nd4jLong *shapeBuffer, int* rearrange, Nd4jLong *out); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong* permuteShapeBuffer(Nd4jLong *shapeBuffer, int *rearrange); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void createTadOnlyShapeInfo(); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong lengthPerSlice(Nd4jLong *shapeBuffer); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong* tad2Sub(Nd4jLong index); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF ~TAD(); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF int* permuteDims(); /** * Compute the tad offset given a dimension. * * The general pattern for computing a tad offset is as follows: * Every $STRIDE that was removed (the first dimension) * do a jump by the major stride of the parent array * (stride[0] of the parent array) * * For example given a c ordered 2,2,3,2 with stride 12,6,2,1 * A tad of dimension 1 will jump 12 every 6 tads. * * You then end up with offsets of: * 0 * 1 * 2 * 3 * 4 * 5 * 12 * 13 * 14 * 15 * 16 * 17 * * notice there are 12 tads here. This same incremental jump will happen * every time. * Note here that by default the * stride of element wise stride is used for the hops. * * Sometimes a jump doesn't happen. If there are less tads * than the stride of the dimension you removed, the * element wise stride will always be used. * * For example in a dimension of 0,1, you end up with offsets of: * 0,1,2,3,4,5 * * Given that the inner most stride of the dimensions that was removed (1) * had a stride of 6, we never need to do a major stride jump. * */ #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong tadOffset(Nd4jLong index); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong* tensorShape(); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong* tad2Sub(Nd4jLong index, void *ptrManager); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void createOffsets(); #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong* shapeInfoOnlyShapeAndStride(); /** * Length of a tad given * the shape information */ #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong tadLength(Nd4jLong *shapeInfo, int *dimension, int dimensionLength); /** * Computes the number * of tensors along * a given dimension */ #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF Nd4jLong tensorsAlongDimension(Nd4jLong *shapeInfo, int *dimension, int dimensionLength); #ifdef __CUDACC__ __host__ __device__ INLINEDEF void createOffsetForBlock(int blockIdx) { this->tadOffsetForBlock = this->tadOffset(blockIdx); } #endif #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF void collapse(); }; //// #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF TAD::TAD(int tadIndex,Nd4jLong *shapeInfo,int *dimension,int dimensionLength) { this->tadIndex = tadIndex; this->init(shapeInfo, dimension, dimensionLength); } #ifdef __CUDACC__ __host__ __device__ #endif INLINEDEF TAD::TAD(Nd4jLong *shapeInfo,int *dimension,int dimensionLength) { this->init(shapeInfo, dimension, dimensionLength); } INLINEDEF void TAD::setExternalBuffers(void *ptrManager) { this->ptrManager = ptrManager; } INLINEDEF void TAD::setOutputBuffer(int *ptrOutput) { this->ptrOutput = ptrOutput; } INLINEDEF void TAD::initWithExternalTAD(Nd4jLong *existingTAD, Nd4jLong *originalShape, int *dimension, int dimensionLength) { this->tadOnlyShapeInfo = existingTAD; this->rank = shape::rank(originalShape); this->originalShapeInfo = originalShape; this->originalDimension = dimension; this->originalDimensionLength = dimensionLength; this->shapeInfo = originalShape; this->dimension = dimension; this->dimensionLength = dimensionLength; this->tadShape = shape::shapeOf(existingTAD); this->tadStride = shape::stride(existingTAD); Nd4jLong ews = shape::elementWiseStride(originalShape); this->numTads = shape::length(originalShape) / shape::length(existingTAD); // this->tensorsAlongDimension(this->shapeInfo, this->dimension, this->dimensionLength);//shape::length(originalShape) / shape::length(existingTAD); this->wholeThing = this->numTads == 1 || ((this->dimensionLength == this->rank || this->numTads == shape::length(this->shapeInfo)) && ews == 1); } INLINEDEF void TAD::init(Nd4jLong *shapeInfo, int *dimension,int dimensionLength) { this->originalShapeInfo = shapeInfo; this->originalDimension = dimension; this->originalDimensionLength = dimensionLength; //start off as original references this->shapeInfo = shapeInfo; this->dimensionLength = dimensionLength; this->dimension = dimension; this->rank = shape::rank(shapeInfo); this->numTads = dimensionLength == 0 ? 1 : this->tensorsAlongDimension(this->shapeInfo, this->dimension, this->dimensionLength); Nd4jLong ews = shape::elementWiseStride(shapeInfo); if(!shape::isVector(shapeInfo)) { wholeThing = this->numTads == 1 // if number of TADs is 1, we just have input shape == TAD shape || ((this->dimensionLength == this->rank // if number of dimensions is the same as input rank, that'll be wholeTad too, but only if EWS==1 (aka - not a View) || (this->numTads == shape::length(shapeInfo) && shape::order(shapeInfo) == 'c')) // OR number of tads equals to shapeInfo length AND input is in C order. if order is F - we'll have to calculate offsets && ews == 1); // as mentioned above - last 2 rules apply only to non-views } else if(shape::isScalar(shapeInfo)) { wholeThing = true; //vector case } else { // if(dimensionLength == 1 && shape::shapeOf(shapeInfo)[dimension[0]] == 1) { if(dimension == 0 && shape::shapeOf(shapeInfo)[dimension[0]] == 1) { wholeThing = true; } } } template <typename T> INLINEDEF void TAD::printTADsND(T *x) { if(wholeThing) { for(int i = 0; i < shape::length(tadOnlyShapeInfo); i++) { printf(" %f ",x[i]); } printf("\n"); } else { for (int i = 0; i < numTads; i++) { auto offset = tadOffsets[i]; Nd4jLong shapeIter[MAX_RANK]; Nd4jLong coord[MAX_RANK]; int dim; int rankIter = shape::rank(tadOnlyShapeInfo); Nd4jLong xStridesIter[MAX_RANK]; T *xPointer = x + offset; if (PrepareOneRawArrayIter<T>(rankIter, shape::shapeOf(tadOnlyShapeInfo), xPointer, shape::stride(tadOnlyShapeInfo), &rankIter, shapeIter, &xPointer, xStridesIter) >= 0) { ND4J_RAW_ITER_START(dim, shape::rank(tadOnlyShapeInfo), coord, shapeIter); { /* Process the innermost dimension */ printf(" %f ",xPointer[0]); } ND4J_RAW_ITER_ONE_NEXT(dim, rankIter, coord, shapeIter, xPointer, xStridesIter); printf("\n"); } else { printf("Unable to prepare array\n"); } } } } INLINEDEF void TAD::permuteShapeBufferInPlace(Nd4jLong* shapeBuffer, int* rearrange, Nd4jLong* out) { memcpy(out, shapeBuffer, sizeof(Nd4jLong) * shape::shapeInfoLength(this->rank)); doPermuteShapeBuffer(this->rank, out, rearrange); } INLINEDEF Nd4jLong* TAD::permuteShapeBuffer(Nd4jLong* shapeBuffer, int *rearrange) { int len = shape::shapeInfoLength(this->rank); Nd4jLong *copy = shape::copyOf(len,shapeBuffer); doPermuteShapeBuffer(rank, copy,rearrange); return copy; } INLINEDEF void TAD::createTadOnlyShapeInfo() { this->tadOnlyShapeInfo = this->shapeInfoOnlyShapeAndStride(); nd4j::ArrayOptions::setDataType(this->tadOnlyShapeInfo, nd4j::ArrayOptions::dataType(this->originalShapeInfo)); if (this->tadShape != nullptr) delete[] this->tadShape; this->tadShape = shape::shapeOf(this->tadOnlyShapeInfo); this->tadStride = shape::stride(this->tadOnlyShapeInfo); /* if(tadIndex > 0) { this->createOffsets(); this->tadOnlyShapeInfo[shape::shapeInfoLength(shape::rank(this->tadOnlyShapeInfo)) - 3] = this->tadOffsets[tadIndex]; }*/ } INLINEDEF Nd4jLong TAD::lengthPerSlice(Nd4jLong* shapeBuffer) { int dimension = 0; Nd4jLong *remove = shape::removeIndex(shape::shapeOf(shapeBuffer),&dimension,shape::rank(shapeBuffer),1); Nd4jLong prod = shape::prodLong(remove, shape::rank(shapeBuffer) - 1); delete[] remove; return prod; } INLINEDEF Nd4jLong* TAD::tad2Sub(Nd4jLong index) { Nd4jLong *shape = shape::shapeOf(shapeInfo); int rank = shape::rank(shapeInfo); int leftOverIndexLen = rank - originalDimensionLength; #ifdef __CUDACC__ Nd4jLong *ret; Nd4jLong *tadShape; Nd4jLong *leftOverIndexes; Nd4jLong *sub; if (ptrManager != nullptr) { UnifiedSharedMemory *manager = (UnifiedSharedMemory *) ptrManager; ret = (Nd4jLong *) manager->getTempRankBuffer1(); tadShape = (Nd4jLong *) manager->getTempRankBuffer2(); leftOverIndexes = (Nd4jLong *) manager->getTempRankBuffer3(); sub = (Nd4jLong *) manager->getTempRankBuffer4(); } else { ret = new Nd4jLong[rank]; tadShape = new Nd4jLong[leftOverIndexLen]; leftOverIndexes = new Nd4jLong[leftOverIndexLen]; sub = new Nd4jLong[rank]; } #else Nd4jLong *ret = new Nd4jLong[rank]; //shape of the tad Nd4jLong *tadShape = new Nd4jLong[leftOverIndexLen]; Nd4jLong *leftOverIndexes = new Nd4jLong[leftOverIndexLen]; Nd4jLong *sub = new Nd4jLong[rank]; #endif //indexes not specified in the tad indexes //every coordinate starts as zero memset(ret,0, shape::shapeInfoByteLength(rank)); //find the length of the elements we //are iterating over int len = 1; //left over index cursor for initializing elements int leftOverIndex = 0; for(int i = 0; i < rank; i++) { //look for dimensions NOT found in dimension length (basically compute shape - dimension (set difference) bool found = false; for(int j = 0; j < originalDimensionLength; j++) { //skip over specified dimensions when computing left over length if(i == originalDimension[j]) { found = true; break; } } //add to the indexes that aren't specified as part of the tad dimension //indexes if(!found) { //accumulate the list of indexes left over used for initializing the return value leftOverIndexes[leftOverIndex] = i; //accumulate the tad shape tadShape[leftOverIndex] = shape[i]; //accumulate the length (product) of the indexes that will be iterated over len *= shape[i]; leftOverIndex++; } } //sub for indices /* int *sub = new int[leftOverIndexLen]; shape::ind2subOrder(tadShape,index,len,sub); */ shape::ind2subC(leftOverIndexLen,tadShape, index,len, sub); for(int i = 0; i < leftOverIndexLen; i++) { ret[leftOverIndexes[i]] = sub[i]; } if (ptrManager == nullptr) { delete[] tadShape; delete[] leftOverIndexes; delete[] sub; } return ret; } INLINEDEF TAD::~TAD() { //we may have just moved the pointer forward, we may not need to delete the pointer here if(originalDimension != this->dimension && createdNewDimension) { delete[] this->dimension; } if(this->originalShapeInfo != this->shapeInfo) { delete[] this->shapeInfo; } if(this->tadOffsets != nullptr) { delete[] this->tadOffsets; } if(this->tadOnlyShapeInfo != nullptr && this->tadOnlyShapeInfo != shapeInfo) { delete[] this->tadOnlyShapeInfo; } } INLINEDEF int* TAD::permuteDims() { //permute dimensions for tad int dimIdx = 0; //loop backwards assuming dimension is sorted int *permuteDims = new int[shape::rank(shapeInfo)]; for(int i = 0; i < shape::rank(shapeInfo); i++) { bool found = false; for(int j = 0; j < originalDimensionLength; j++) { if(i == originalDimension[j]) { found = true; break; } } //not found, append it to the end for permute if(!found) permuteDims[dimIdx++] = i; } for(int i = originalDimensionLength - 1; i >= 0; i--) { permuteDims[dimIdx++] = originalDimension[i]; } /* for (int i = 0; i < originalDimensionLength; i++) { permuteDims[i] = originalDimension[i]; } */ //permute dimensions for tad return permuteDims; } INLINEDEF Nd4jLong TAD::tadOffset(Nd4jLong index) { if(tadOnlyShapeInfo == nullptr) { this->createTadOnlyShapeInfo(); } if(wholeThing) return index; if(dimensionLength > 1) { Nd4jLong *tad2Sub = this->tad2Sub(index, ptrManager); Nd4jLong ret = shape::getOffset(0,shape::shapeOf(shapeInfo),shape::stride(shapeInfo),tad2Sub,shape::rank(shapeInfo)); if(ret < 0) { if (ptrManager == nullptr) delete[] tad2Sub; return -1; } if (ptrManager == nullptr) delete[] tad2Sub; return ret; } else { Nd4jLong *tad2Sub = this->tad2Sub(index, ptrManager); Nd4jLong ret = shape::getOffset(0,shape::shapeOf(shapeInfo),shape::stride(shapeInfo),tad2Sub,shape::rank(shapeInfo)); if (ptrManager == nullptr) delete[] tad2Sub; return ret; } } INLINEDEF Nd4jLong* TAD::tensorShape() { if(this->tadShape != nullptr) return this->tadShape; Nd4jLong *theShape = shape::shapeOf(shapeInfo); Nd4jLong *tensorShape = shape::keep(theShape, this->dimension, dimensionLength,shape::rank(shapeInfo)); this->tadShape = tensorShape; this->tadRank = dimensionLength; return tensorShape; } INLINEDEF Nd4jLong* TAD::tad2Sub(Nd4jLong index, void *ptrManager) { auto shape = shape::shapeOf(shapeInfo); int rank = shape::rank(shapeInfo); int leftOverIndexLen = rank - originalDimensionLength; Nd4jLong *tadShape; Nd4jLong *leftOverIndexes; Nd4jLong *sub; Nd4jLong *ret; #ifdef __CUDACC__ if (ptrManager != nullptr) { UnifiedSharedMemory *manager = (UnifiedSharedMemory *) ptrManager; ret = (Nd4jLong *) manager->getTempRankBuffer1(); tadShape = (Nd4jLong *) manager->getTempRankBuffer2(); leftOverIndexes = (Nd4jLong *) manager->getTempRankBuffer3(); sub = (Nd4jLong *) manager->getTempRankBuffer4(); } else { ret = new Nd4jLong[rank]; //shape of the tad leftOverIndexes = new Nd4jLong[leftOverIndexLen]; sub = new Nd4jLong[rank]; tadShape = new Nd4jLong[leftOverIndexLen]; } #else ret = new Nd4jLong[rank]; //shape of the tad leftOverIndexes = new Nd4jLong[leftOverIndexLen]; sub = new Nd4jLong[rank]; tadShape = new Nd4jLong[leftOverIndexLen]; #endif //indexes not specified in the tad indexes //every coordinate starts as zero memset(ret,0,sizeof(Nd4jLong) * rank); //find the length of the elements we //are iterating over int len = 1; //left over index cursor for initializing elements int leftOverIndex = 0; for(int i = 0; i < rank; i++) { //look for dimensions NOT found in dimension length (basically compute shape - dimension (set difference) bool found = false; for(int j = 0; j < originalDimensionLength; j++) { //skip over specified dimensions when computing left over length if(i == originalDimension[j]) { found = true; break; } } //add to the indexes that aren't specified as part of the tad dimension //indexes if(!found) { //accumulate the list of indexes left over used for initializing the return value leftOverIndexes[leftOverIndex] = i; //accumulate the tad shape tadShape[leftOverIndex] = shape[i]; //accumulate the length (product) of the indexes that will be iterated over leftOverIndex++; len *= shape[i]; } } //sub for indices /* int *sub = new int[leftOverIndexLen]; shape::ind2subOrder(tadShape,index,len,sub); */ shape::ind2subC(leftOverIndexLen,tadShape,index,len, sub); for(int i = 0; i < leftOverIndexLen; i++) { ret[leftOverIndexes[i]] = sub[i]; } if (ptrManager == nullptr) { delete[] leftOverIndexes; delete[] tadShape; delete[] sub; } return ret; } INLINEDEF void TAD::createOffsets() { this->tadOffsets = new Nd4jLong[this->numTads]; #pragma omp parallel for if (this->numTads > 128) schedule(static) proc_bind(close) default(shared) for(int i = 0; i < this->numTads; i++) { this->tadOffsets[i] = this->tadOffset(i); } } INLINEDEF Nd4jLong* TAD::shapeInfoOnlyShapeAndStride() { if(wholeThing && (dimensionLength == 1 && dimension[0] == MAX_DIMENSION) || shape::isScalar(shapeInfo)) return shape::createScalarShapeInfo(); //ensure tad shapes get setup right for vectors if(dimensionLength > 1 && shape::isVector(shapeInfo)) return shape::copyOf(shape::shapeInfoLength(shape::rank(shapeInfo)),shapeInfo); // case when tad coincides with whole array if( this->numTads == 1 && ((shape::rank(originalShapeInfo) == originalDimensionLength) || originalDimensionLength == 0)) { // we might have special case here: skipped dimensions might be just full of ones Nd4jLong *ret = shape::copyOf(shape::shapeInfoLength(shape::rank(shapeInfo)), shapeInfo); if (shape::isDimPermuted<int>(dimension, (Nd4jLong) dimensionLength)) // check whether we need permutation shape::doPermuteShapeBuffer(ret, dimension); return ret; } Nd4jLong *theShape = shape::shapeOf(shapeInfo); int rank = shape::rank(shapeInfo); if(dimensionLength == 1) { if(dimension[0] == 0 && shape::isVector(shapeInfo) && theShape[1] == 1) { int permuted[2] = {1,0}; Nd4jLong *permutedRet2 = shape::permuteShapeBuffer(shapeInfo, permuted); return permutedRet2; } else if(dimension[0] == 1 && shape::isVector(shapeInfo) && theShape[0] == 1) { Nd4jLong *ret = shape::copyOf(shape::shapeInfoLength(shape::rank(shapeInfo)),shapeInfo); return ret; } else if(shape::shapeOf(shapeInfo)[dimension[0]] == 1) { Nd4jLong *scalarInfo = shape::createScalarShapeInfo(); scalarInfo[shape::shapeInfoLength(shape::rank(scalarInfo)) - 3] = this->tadIndex; return scalarInfo; } } Nd4jLong *tensorShape = this->tensorShape(); int *reverseDimensions = shape::reverseCopy(dimension, dimensionLength); int *rankRange = shape::range<int>(0, rank); int *remove = shape::removeIndex<int>(rankRange, dimension, (Nd4jLong) rank, (Nd4jLong) dimensionLength); //concat is wrong here with the length int *newPermuteDims = shape::concat(remove,rank - dimensionLength,reverseDimensions,dimensionLength); Nd4jLong* permuted = shape::permuteShapeBuffer(shapeInfo,newPermuteDims); Nd4jLong sliceIndex = shape::sliceOffsetForTensor(shape::rank(permuted), this->tadIndex, shape::shapeOf(shapeInfo), tensorShape, dimensionLength, dimension, dimensionLength); Nd4jLong *ret2 = shape::sliceOfShapeBuffer(sliceIndex, permuted); Nd4jLong tensorLength = shape::prodLong(tensorShape,tadRank); int compLength = shape::isVector(ret2) ? shape::length(ret2) : shape::prod(tensorShape,tadRank); // int temp; // const bool isLikeVector = shape::isLikeVector(ret2, temp); // if(dimensionLength == tadRank && compLength == shape::length(ret2) && !isLikeVector) { if(dimensionLength == tadRank && compLength == shape::length(ret2)) { if(dimensionLength == 1 && shape::isVector(ret2) && shape::shapeOf(ret2)[0] == 1) { //go to the bottom and return ret2 after proper freeing of pointers //basic idea; we *don't* permute row vectors } else if(dimensionLength > 1) { //permute *then* return ret2 int *finalPermuteDims = new int[shape::rank(ret2)]; int forward = 0; for(int i = shape::rank(ret2) - 1; i >= 0; i--) { finalPermuteDims[forward++] = i; } shape::permuteShapeBufferInPlace(ret2,finalPermuteDims,ret2); delete[] finalPermuteDims; } } else { Nd4jLong length = tensorLength; Nd4jLong lengthPerSlice = this->lengthPerSlice(ret2); if(lengthPerSlice < 1) { return ret2; } Nd4jLong offset = tadIndex * tensorLength /lengthPerSlice; if(sliceIndex == 0 && length == lengthPerSlice) { Nd4jLong *newRet2 = shape::sliceOfShapeBuffer(offset, ret2); delete[] ret2; ret2 = newRet2; int *finalPermuteDims = new int[shape::rank(ret2)]; int forward = 0; for(int i = shape::rank(ret2) - 1; i >= 0; i--) { finalPermuteDims[forward++] = i; } // bool isRowVector2 = shape::isRowVector(ret2) && !isLikeVector; bool isRowVector2 = shape::isRowVector(ret2); if(isRowVector2 == false) { shape::permuteShapeBufferInPlace(ret2, finalPermuteDims, ret2); } delete[] finalPermuteDims; } else if(length == lengthPerSlice) { offset -= shape::slices(ret2) * (offset / shape::slices(ret2)); Nd4jLong *newRet2 = shape::sliceOfShapeBuffer(offset,ret2); delete[] ret2; ret2 = newRet2; if(dimensionLength == 1 && shape::isVector(ret2) && shape::shapeOf(ret2)[0] == 1) { //go to the bottom and return ret2 after proper freeing of pointers //basic idea; we *don't* permute row vectors } else { int *finalPermuteDims = new int[shape::rank(ret2)]; int forward = 0; for(int i = shape::rank(ret2) - 1; i >= 0; i--) { finalPermuteDims[forward++] = i; } Nd4jLong *newRet = shape::permuteShapeBuffer(ret2, finalPermuteDims); delete[] ret2; delete[] finalPermuteDims; ret2 = newRet; } } else { //execute final part, note that this is mainly so delete[] gets called //at the bottom of the method while(shape::length(ret2) > length) { auto lengthPerSlice2 = this->lengthPerSlice(ret2); sliceIndex = sliceOffsetForTensor(sliceIndex,shape::length(ret2),lengthPerSlice2); sliceIndex -= shape::slices(ret2) * (sliceIndex / shape::slices(ret2)); auto newRet2 = shape::sliceOfShapeBuffer(sliceIndex,ret2); delete[] ret2; ret2 = newRet2; } //don't permute on a row vector if(dimensionLength == 1 && shape::isVector(ret2) && shape::shapeOf(ret2)[0] == 1) { //go to the bottom and return ret2 after proper freeing of pointers //basic idea; we *don't* permute row vectors } else if(dimensionLength > 1){ //permute *then* return ret int *finalPermuteDims = new int[shape::rank(ret2)]; int forward = 0; for(int i = shape::rank(ret2) - 1; i >= 0; i--) { finalPermuteDims[forward++] = i; } auto newPermute = shape::permuteShapeBuffer(ret2,finalPermuteDims); delete[] ret2; delete[] finalPermuteDims; ret2 = newPermute; } } } delete[] permuted; delete[] newPermuteDims; delete[] rankRange; delete[] remove; delete[] reverseDimensions; return ret2; } INLINEDEF Nd4jLong TAD::tadLength(Nd4jLong *shapeInfo, int *dimension, int dimensionLength) { if(dimensionLength == 1) { return shape::shapeOf(shapeInfo)[dimension[0]]; } else { Nd4jLong ret = 1; for(int i = 0; i < shape::rank(shapeInfo); i++) { for(int j = 0; j < dimensionLength; j++) { if(i == dimension[j]) ret *= shape::shapeOf(shapeInfo)[dimension[j]]; } } return ret; } } INLINEDEF Nd4jLong TAD::tensorsAlongDimension(Nd4jLong *shapeInfo, int *dimension, int dimensionLength) { return shape::length(shapeInfo) / this->tadLength(shapeInfo,dimension,dimensionLength); } INLINEDEF void TAD::collapse() { auto shape = shape::shapeOf(shapeInfo); //handle negative dimensions/backwards indexing for(int i = 0; i < dimensionLength; i++) { if((dimension)[i] < 0) (dimension)[i] += shape::rank(this->shapeInfo); } this->dimension = new int[dimensionLength]; memcpy(this->dimension,this->originalDimension, sizeof(int) * dimensionLength); //we can drop trailing dimensions where it's all singular for example: // shape: 4,3,1,2 //dimension: 0,2 // the problem for 0,2 is equivalent to: 0 //the rest of the algorithm handles cases suchas //shape: 4,1,1,2 //dimension: 0,1 //when this happens there are other dimensions (eg: at the end) that matter int trailingOneDimensions = 0; //trailing ones for(int i = dimensionLength - 1; i >= 0; i--) { if(shape[dimension[i]] != 1) { break; } else if(shape[dimension[i]] == 1) trailingOneDimensions++; } dimensionLength -= trailingOneDimensions; int leadingOneDimensions = 0; //trailing ones for(int i = 0; i < dimensionLength; i++) { if(shape[dimension[i]] != 1) { break; } else if(shape[dimension[i]] == 1) leadingOneDimensions++; } //bump the dimension pointer forward for however many leadingones there are dimension += leadingOneDimensions; //decrease the dimension length by the amount of leading ones dimensionLength -= leadingOneDimensions; bool preConverged = true; for(int i = 0; i < dimensionLength; i++) { if(shape[dimension[i]] == 1) { preConverged = false; break; } } //we took away all the singular dimensions, we can just return if(preConverged) return; //no more singular dimensions specified bool done = false; int onesDecrement = 0; bool changed = false; while(!done) { //terminate early: only singular dimensions specified for reduce if((dimensionLength) < 1) { done = true; //signal as a no op dimension[0] = -1; break; } //captures intermediary result from the for loop traceNew(3); int intermediaryResult[MAX_RANK]; for(int i = 0; i < dimensionLength; i++) { intermediaryResult[i] = (dimension)[i]; } bool oneEncountered = false; bool nonOneEncountered = false; bool hitBeginning = false; //assume intermediate collapsing of dimensions bool collapseMiddleDimensions = true; //note here that dimension length MAY end up being zero for(int i = (dimensionLength) - 1; i >= 0; i--) { if(shape[(dimension)[i]] == 1) { oneEncountered = true; //trailing ones if(!nonOneEncountered) { //just drop trailing ones dimensionLength--; nonOneEncountered = false; collapseMiddleDimensions = false; //intermediary result just needs to have the results copied from dimension since we're just removing the tail memcpy(intermediaryResult,dimension, sizeof(int) * dimensionLength); changed = true; //break the for loop and force it to go back around starting from the new index break; } else { //already decremented all dimensions //this was a result of hitting beginning ones //we will only need to loop once if(i == 0) { hitBeginning = true; } //will need to shift dimensions that aren't trailing ones //back by onesDecrement //mark the intermediary result as -1 for non inclusion intermediaryResult[i] = -1; onesDecrement++; } } else { intermediaryResult[i] = (dimension)[i]; nonOneEncountered = true; } } if(collapseMiddleDimensions && oneEncountered) { //collapse dimensions int newIntermediary[MAX_RANK]; int idx = 0; for(int i = 0; i < dimensionLength; i++) { //of note: dimension will decrease by the number of ones encountered if(intermediaryResult[i] >= 0) { //dimension 0 doesn't need to be decremented if(intermediaryResult[i] > 0) newIntermediary[idx++] = intermediaryResult[i] - onesDecrement; else newIntermediary[idx++] = intermediaryResult[i]; } } //decrement by the number of dimensions where ones appeared (dimensionLength) -= onesDecrement; //update to current result memcpy(dimension,newIntermediary, sizeof(int) * (dimensionLength)); changed = true; } //converged: no need to change result else { //update to current result memcpy(dimension,intermediaryResult, sizeof(int) * dimensionLength); } //converge when there are no singular dimensions specified in the reduce done = (!oneEncountered && nonOneEncountered) || hitBeginning; //delete[] intermediaryResult; } //nothing changed but need to collapse dimension if(!changed && this->numOnes > 0) { for(int i = 0; i < dimensionLength ;i++) { dimension[i] -= numOnes; } } } } #endif //LIBND4J_TAD_H
transform.h
/*! * Copyright 2018 XGBoost contributors */ #ifndef XGBOOST_COMMON_TRANSFORM_H_ #define XGBOOST_COMMON_TRANSFORM_H_ #include <dmlc/omp.h> #include <xgboost/data.h> #include <utility> #include <vector> #include <type_traits> // enable_if #include "host_device_vector.h" #include "common.h" #include "span.h" #if defined (__CUDACC__) #include "device_helpers.cuh" #endif // defined (__CUDACC__) namespace xgboost { namespace common { constexpr size_t kBlockThreads = 256; namespace detail { #if defined(__CUDACC__) template <typename Functor, typename... SpanType> __global__ void LaunchCUDAKernel(Functor _func, Range _range, SpanType... _spans) { for (auto i : dh::GridStrideRange(*_range.begin(), *_range.end())) { _func(i, _spans...); } } #endif // defined(__CUDACC__) } // namespace detail /*! \brief Do Transformation on HostDeviceVectors. * * \tparam CompiledWithCuda A bool parameter used to distinguish compilation * trajectories, users do not need to use it. * * Note: Using Transform is a VERY tricky thing to do. Transform uses template * argument to duplicate itself into two different types, one for CPU, * another for CUDA. The trick is not without its flaw: * * If you use it in a function that can be compiled by both nvcc and host * compiler, the behaviour is un-defined! Because your function is NOT * duplicated by `CompiledWithCuda`. At link time, cuda compiler resolution * will merge functions with same signature. */ template <bool CompiledWithCuda = WITH_CUDA()> class Transform { private: template <typename Functor> struct Evaluator { public: Evaluator(Functor func, Range range, GPUSet devices, bool reshard) : func_(func), range_{std::move(range)}, reshard_{reshard}, distribution_{std::move(GPUDistribution::Block(devices))} {} Evaluator(Functor func, Range range, GPUDistribution dist, bool reshard) : func_(func), range_{std::move(range)}, reshard_{reshard}, distribution_{std::move(dist)} {} /*! * \brief Evaluate the functor with input pointers to HostDeviceVector. * * \tparam HDV... HostDeviceVectors type. * \param vectors Pointers to HostDeviceVector. */ template <typename... HDV> void Eval(HDV... vectors) const { bool on_device = !distribution_.IsEmpty(); if (on_device) { LaunchCUDA(func_, vectors...); } else { LaunchCPU(func_, vectors...); } } private: // CUDA UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->DeviceSpan(_device); return span; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec, int _device) const { auto span = _vec->ConstDeviceSpan(_device); return span; } // CPU UnpackHDV template <typename T> Span<T> UnpackHDV(HostDeviceVector<T>* _vec) const { return Span<T> {_vec->HostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } template <typename T> Span<T const> UnpackHDV(const HostDeviceVector<T>* _vec) const { return Span<T const> {_vec->ConstHostPointer(), static_cast<typename Span<T>::index_type>(_vec->Size())}; } // Recursive unpack for Reshard. template <typename T> void UnpackReshard(GPUDistribution dist, const HostDeviceVector<T>* vector) const { vector->Reshard(dist); } template <typename Head, typename... Rest> void UnpackReshard(GPUDistribution dist, const HostDeviceVector<Head>* _vector, const HostDeviceVector<Rest>*... _vectors) const { _vector->Reshard(dist); UnpackReshard(dist, _vectors...); } #if defined(__CUDACC__) template <typename std::enable_if<CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { if (reshard_) UnpackReshard(distribution_, _vectors...); GPUSet devices = distribution_.Devices(); size_t range_size = *range_.end() - *range_.begin(); // Extract index to deal with possible old OpenMP. size_t device_beg = *(devices.begin()); size_t device_end = *(devices.end()); #pragma omp parallel for schedule(static, 1) if (devices.Size() > 1) for (omp_ulong device = device_beg; device < device_end; ++device) { // NOLINT // Ignore other attributes of GPUDistribution for spliting index. // This deals with situation like multi-class setting where // granularity is used in data vector. size_t shard_size = GPUDistribution::Block(devices).ShardSize( range_size, devices.Index(device)); Range shard_range {0, static_cast<Range::DifferenceType>(shard_size)}; dh::safe_cuda(cudaSetDevice(device)); const int GRID_SIZE = static_cast<int>(dh::DivRoundUp(*(range_.end()), kBlockThreads)); detail::LaunchCUDAKernel<<<GRID_SIZE, kBlockThreads>>>( _func, shard_range, UnpackHDV(_vectors, device)...); dh::safe_cuda(cudaGetLastError()); dh::safe_cuda(cudaDeviceSynchronize()); } } #else /*! \brief Dummy funtion defined when compiling for CPU. */ template <typename std::enable_if<!CompiledWithCuda>::type* = nullptr, typename... HDV> void LaunchCUDA(Functor _func, HDV*... _vectors) const { LOG(FATAL) << "Not part of device code. WITH_CUDA: " << WITH_CUDA(); } #endif // defined(__CUDACC__) template <typename... HDV> void LaunchCPU(Functor func, HDV*... vectors) const { omp_ulong end = static_cast<omp_ulong>(*(range_.end())); #pragma omp parallel for schedule(static) for (omp_ulong idx = 0; idx < end; ++idx) { func(idx, UnpackHDV(vectors)...); } } private: /*! \brief Callable object. */ Functor func_; /*! \brief Range object specifying parallel threads index range. */ Range range_; /*! \brief Whether resharding for vectors is required. */ bool reshard_; GPUDistribution distribution_; }; public: /*! * \brief Initialize a Transform object. * * \tparam Functor A callable object type. * \return A Evaluator having one method Eval. * * \param func A callable object, accepting a size_t thread index, * followed by a set of Span classes. * \param range Range object specifying parallel threads index range. * \param devices GPUSet specifying GPUs to use, when compiling for CPU, * this should be GPUSet::Empty(). * \param reshard Whether Reshard for HostDeviceVector is needed. */ template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUSet const devices, bool const reshard = true) { return Evaluator<Functor> {func, std::move(range), std::move(devices), reshard}; } template <typename Functor> static Evaluator<Functor> Init(Functor func, Range const range, GPUDistribution const dist, bool const reshard = true) { return Evaluator<Functor> {func, std::move(range), std::move(dist), reshard}; } }; } // namespace common } // namespace xgboost #endif // XGBOOST_COMMON_TRANSFORM_H_
sort.c
/**********************************************************************************************/ /* This program is part of the Barcelona OpenMP Tasks Suite */ /* Copyright (C) 2009 Barcelona Supercomputing Center - Centro Nacional de Supercomputacion */ /* Copyright (C) 2009 Universitat Politecnica de Catalunya */ /* */ /* This program is free software; you can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License, or */ /* (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU General Public License for more details. */ /* */ /* You should have received a copy of the GNU General Public License */ /* along with this program; if not, write to the Free Software */ /* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ /**********************************************************************************************/ /* * Original code from the Cilk project * * Copyright (c) 2000 Massachusetts Institute of Technology * Copyright (c) 2000 Matteo Frigo */ /* * this program uses an algorithm that we call `cilksort'. * The algorithm is essentially mergesort: * * cilksort(in[1..n]) = * spawn cilksort(in[1..n/2], tmp[1..n/2]) * spawn cilksort(in[n/2..n], tmp[n/2..n]) * sync * spawn cilkmerge(tmp[1..n/2], tmp[n/2..n], in[1..n]) * * * The procedure cilkmerge does the following: * * cilkmerge(A[1..n], B[1..m], C[1..(n+m)]) = * find the median of A \union B using binary * search. The binary search gives a pair * (ma, mb) such that ma + mb = (n + m)/2 * and all elements in A[1..ma] are smaller than * B[mb..m], and all the B[1..mb] are smaller * than all elements in A[ma..n]. * * spawn cilkmerge(A[1..ma], B[1..mb], C[1..(n+m)/2]) * spawn cilkmerge(A[ma..m], B[mb..n], C[(n+m)/2 .. (n+m)]) * sync * * The algorithm appears for the first time (AFAIK) in S. G. Akl and * N. Santoro, "Optimal Parallel Merging and Sorting Without Memory * Conflicts", IEEE Trans. Comp., Vol. C-36 No. 11, Nov. 1987 . The * paper does not express the algorithm using recursion, but the * idea of finding the median is there. * * For cilksort of n elements, T_1 = O(n log n) and * T_\infty = O(log^3 n). There is a way to shave a * log factor in the critical path (left as homework). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "bots.h" #include "app-desc.h" ELM *array, *tmp; static unsigned long rand_nxt = 0; static inline unsigned long my_rand(void) { rand_nxt = rand_nxt * 1103515245 + 12345; return rand_nxt; } static inline void my_srand(unsigned long seed) { rand_nxt = seed; } static inline ELM med3(ELM a, ELM b, ELM c) { if (a < b) { if (b < c) { return b; } else { if (a < c) return c; else return a; } } else { if (b > c) { return b; } else { if (a > c) return c; else return a; } } } /* * simple approach for now; a better median-finding * may be preferable */ static inline ELM choose_pivot(ELM *low, ELM *high) { return med3(*low, *high, low[(high - low) / 2]); } static ELM *seqpart(ELM *low, ELM *high) { ELM pivot; ELM h, l; ELM *curr_low = low; ELM *curr_high = high; pivot = choose_pivot(low, high); while (1) { while ((h = *curr_high) > pivot) curr_high--; while ((l = *curr_low) < pivot) curr_low++; if (curr_low >= curr_high) break; *curr_high-- = l; *curr_low++ = h; } /* * I don't know if this is really necessary. * The problem is that the pivot is not always the * first element, and the partition may be trivial. * However, if the partition is trivial, then * *high is the largest element, whence the following * code. */ if (curr_high < high) return curr_high; else return curr_high - 1; } #define swap(a, b) \ { \ ELM tmp;\ tmp = a;\ a = b;\ b = tmp;\ } static void insertion_sort(ELM *low, ELM *high) { ELM *p, *q; ELM a, b; for (q = low + 1; q <= high; ++q) { a = q[0]; for (p = q - 1; p >= low && (b = p[0]) > a; p--) p[1] = b; p[1] = a; } } /* * tail-recursive quicksort, almost unrecognizable :-) */ void seqquick(ELM *low, ELM *high) { ELM *p; while (high - low >= bots_app_cutoff_value_2) { p = seqpart(low, high); seqquick(low, p); low = p + 1; } insertion_sort(low, high); } void seqmerge(ELM *low1, ELM *high1, ELM *low2, ELM *high2, ELM *lowdest) { ELM a1, a2; /* * The following 'if' statement is not necessary * for the correctness of the algorithm, and is * in fact subsumed by the rest of the function. * However, it is a few percent faster. Here is why. * * The merging loop below has something like * if (a1 < a2) { * *dest++ = a1; * ++low1; * if (end of array) break; * a1 = *low1; * } * * Now, a1 is needed immediately in the next iteration * and there is no way to mask the latency of the load. * A better approach is to load a1 *before* the end-of-array * check; the problem is that we may be speculatively * loading an element out of range. While this is * probably not a problem in practice, yet I don't feel * comfortable with an incorrect algorithm. Therefore, * I use the 'fast' loop on the array (except for the last * element) and the 'slow' loop for the rest, saving both * performance and correctness. */ if (low1 < high1 && low2 < high2) { a1 = *low1; a2 = *low2; for (;;) { if (a1 < a2) { *lowdest++ = a1; a1 = *++low1; if (low1 >= high1) break; } else { *lowdest++ = a2; a2 = *++low2; if (low2 >= high2) break; } } } if (low1 <= high1 && low2 <= high2) { a1 = *low1; a2 = *low2; for (;;) { if (a1 < a2) { *lowdest++ = a1; ++low1; if (low1 > high1) break; a1 = *low1; } else { *lowdest++ = a2; ++low2; if (low2 > high2) break; a2 = *low2; } } } if (low1 > high1) { memcpy(lowdest, low2, sizeof(ELM) * (high2 - low2 + 1)); } else { memcpy(lowdest, low1, sizeof(ELM) * (high1 - low1 + 1)); } } #define swap_indices(a, b) \ { \ ELM *tmp;\ tmp = a;\ a = b;\ b = tmp;\ } ELM *binsplit(ELM val, ELM *low, ELM *high) { /* * returns index which contains greatest element <= val. If val is * less than all elements, returns low-1 */ ELM *mid; while (low != high) { mid = low + ((high - low + 1) >> 1); if (val <= *mid) high = mid - 1; else low = mid; } if (*low > val) return low - 1; else return low; } void cilkmerge_par(ELM *low1, ELM *high1, ELM *low2, ELM *high2, ELM *lowdest) { /* * Cilkmerge: Merges range [low1, high1] with range [low2, high2] * into the range [lowdest, ...] */ ELM *split1, *split2; /* * where each of the ranges are broken for * recursive merge */ long int lowsize; /* * total size of lower halves of two * ranges - 2 */ /* * We want to take the middle element (indexed by split1) from the * larger of the two arrays. The following code assumes that split1 * is taken from range [low1, high1]. So if [low1, high1] is * actually the smaller range, we should swap it with [low2, high2] */ if (high2 - low2 > high1 - low1) { swap_indices(low1, low2); swap_indices(high1, high2); } if (high2 < low2) { /* smaller range is empty */ memcpy(lowdest, low1, sizeof(ELM) * (high1 - low1)); return; } if (high2 - low2 < bots_app_cutoff_value ) { seqmerge(low1, high1, low2, high2, lowdest); return; } /* * Basic approach: Find the middle element of one range (indexed by * split1). Find where this element would fit in the other range * (indexed by split 2). Then merge the two lower halves and the two * upper halves. */ split1 = ((high1 - low1 + 1) / 2) + low1; split2 = binsplit(*split1, low2, high2); lowsize = split1 - low1 + split2 - low2; /* * directly put the splitting element into * the appropriate location */ *(lowdest + lowsize + 1) = *split1; #pragma omp task untied cilkmerge_par(low1, split1 - 1, low2, split2, lowdest); #pragma omp task untied cilkmerge_par(split1 + 1, high1, split2 + 1, high2, lowdest + lowsize + 2); #pragma omp taskwait return; } void cilksort_par(ELM *low, ELM *tmp, long size) { /* * divide the input in four parts of the same size (A, B, C, D) * Then: * 1) recursively sort A, B, C, and D (in parallel) * 2) merge A and B into tmp1, and C and D into tmp2 (in parallel) * 3) merge tmp1 and tmp2 into the original array */ long quarter = size / 4; ELM *A, *B, *C, *D, *tmpA, *tmpB, *tmpC, *tmpD; if (size < bots_app_cutoff_value_1 ) { /* quicksort when less than 1024 elements */ seqquick(low, low + size - 1); return; } A = low; tmpA = tmp; B = A + quarter; tmpB = tmpA + quarter; C = B + quarter; tmpC = tmpB + quarter; D = C + quarter; tmpD = tmpC + quarter; #pragma omp task untied cilksort_par(A, tmpA, quarter); #pragma omp task untied cilksort_par(B, tmpB, quarter); #pragma omp task untied cilksort_par(C, tmpC, quarter); #pragma omp task untied cilksort_par(D, tmpD, size - 3 * quarter); #pragma omp taskwait #pragma omp task untied cilkmerge_par(A, A + quarter - 1, B, B + quarter - 1, tmpA); #pragma omp task untied cilkmerge_par(C, C + quarter - 1, D, low + size - 1, tmpC); #pragma omp taskwait cilkmerge_par(tmpA, tmpC - 1, tmpC, tmpA + size - 1, A); } void scramble_array( ELM *array ) { unsigned long i; unsigned long j; for (i = 0; i < bots_arg_size; ++i) { j = my_rand(); j = j % bots_arg_size; swap(array[i], array[j]); } } void fill_array( ELM *array ) { unsigned long i; my_srand(1); /* first, fill with integers 1..size */ for (i = 0; i < bots_arg_size; ++i) { array[i] = i; } } void sort_init ( void ) { /* Checking arguments */ if (bots_arg_size < 4) { bots_message("%s can not be less than 4, using 4 as a parameter.\n", BOTS_APP_DESC_ARG_SIZE ); bots_arg_size = 4; } if (bots_app_cutoff_value < 2) { bots_message("%s can not be less than 2, using 2 as a parameter.\n", BOTS_APP_DESC_ARG_CUTOFF); bots_app_cutoff_value = 2; } else if (bots_app_cutoff_value > bots_arg_size ) { bots_message("%s can not be greather than vector size, using %d as a parameter.\n", BOTS_APP_DESC_ARG_CUTOFF, bots_arg_size); bots_app_cutoff_value = bots_arg_size; } if (bots_app_cutoff_value_1 > bots_arg_size ) { bots_message("%s can not be greather than vector size, using %d as a parameter.\n", BOTS_APP_DESC_ARG_CUTOFF_1, bots_arg_size); bots_app_cutoff_value_1 = bots_arg_size; } if (bots_app_cutoff_value_2 > bots_arg_size ) { bots_message("%s can not be greather than vector size, using %d as a parameter.\n", BOTS_APP_DESC_ARG_CUTOFF_2, bots_arg_size); bots_app_cutoff_value_2 = bots_arg_size; } if (bots_app_cutoff_value_2 > bots_app_cutoff_value_1) { bots_message("%s can not be greather than %s, using %d as a parameter.\n", BOTS_APP_DESC_ARG_CUTOFF_2, BOTS_APP_DESC_ARG_CUTOFF_1, bots_app_cutoff_value_1 ); bots_app_cutoff_value_2 = bots_app_cutoff_value_1; } array = (ELM *) malloc(bots_arg_size * sizeof(ELM)); tmp = (ELM *) malloc(bots_arg_size * sizeof(ELM)); fill_array(array); scramble_array(array); } void sort_par ( void ) { bots_message("Computing multisort algorithm (n=%d) ", bots_arg_size); #pragma omp parallel #pragma omp single nowait #pragma omp task untied cilksort_par(array, tmp, bots_arg_size); bots_message(" completed!\n"); } int sort_verify ( void ) { int i, success = 1; for (i = 0; i < bots_arg_size; ++i) if (array[i] != i) success = 0; return success ? BOTS_RESULT_SUCCESSFUL : BOTS_RESULT_UNSUCCESSFUL; }
coordinate_common.h
/*! * Copyright 2018 by Contributors * \author Rory Mitchell */ #pragma once #include <algorithm> #include <string> #include <utility> #include <vector> #include <limits> #include "./param.h" #include "../common/random.h" namespace xgboost { namespace linear { struct CoordinateParam : public dmlc::Parameter<CoordinateParam> { int top_k; DMLC_DECLARE_PARAMETER(CoordinateParam) { DMLC_DECLARE_FIELD(top_k) .set_lower_bound(0) .set_default(0) .describe("The number of top features to select in 'thrifty' feature_selector. " "The value of zero means using all the features."); } }; /** * \brief Calculate change in weight for a given feature. Applies l1/l2 penalty normalised by the * number of training instances. * * \param sum_grad The sum gradient. * \param sum_hess The sum hess. * \param w The weight. * \param reg_alpha Unnormalised L1 penalty. * \param reg_lambda Unnormalised L2 penalty. * * \return The weight update. */ inline double CoordinateDelta(double sum_grad, double sum_hess, double w, double reg_alpha, double reg_lambda) { if (sum_hess < 1e-5f) return 0.0f; const double sum_grad_l2 = sum_grad + reg_lambda * w; const double sum_hess_l2 = sum_hess + reg_lambda; const double tmp = w - sum_grad_l2 / sum_hess_l2; if (tmp >= 0) { return std::max(-(sum_grad_l2 + reg_alpha) / sum_hess_l2, -w); } else { return std::min(-(sum_grad_l2 - reg_alpha) / sum_hess_l2, -w); } } /** * \brief Calculate update to bias. * * \param sum_grad The sum gradient. * \param sum_hess The sum hess. * * \return The weight update. */ inline double CoordinateDeltaBias(double sum_grad, double sum_hess) { return -sum_grad / sum_hess; } /** * \brief Get the gradient with respect to a single feature. * * \param group_idx Zero-based index of the group. * \param num_group Number of groups. * \param fidx The target feature. * \param gpair Gradients. * \param p_fmat The feature matrix. * * \return The gradient and diagonal Hessian entry for a given feature. */ inline std::pair<double, double> GetGradient(int group_idx, int num_group, int fidx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat) { double sum_grad = 0.0, sum_hess = 0.0; for (const auto &batch : p_fmat->GetColumnBatches()) { auto col = batch[fidx]; const auto ndata = static_cast<bst_omp_uint>(col.size()); for (bst_omp_uint j = 0; j < ndata; ++j) { const bst_float v = col[j].fvalue; auto &p = gpair[col[j].index * num_group + group_idx]; if (p.GetHess() < 0.0f) continue; sum_grad += p.GetGrad() * v; sum_hess += p.GetHess() * v * v; } } return std::make_pair(sum_grad, sum_hess); } /** * \brief Get the gradient with respect to a single feature. Row-wise multithreaded. * * \param group_idx Zero-based index of the group. * \param num_group Number of groups. * \param fidx The target feature. * \param gpair Gradients. * \param p_fmat The feature matrix. * * \return The gradient and diagonal Hessian entry for a given feature. */ inline std::pair<double, double> GetGradientParallel(int group_idx, int num_group, int fidx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat) { double sum_grad = 0.0, sum_hess = 0.0; for (const auto &batch : p_fmat->GetColumnBatches()) { auto col = batch[fidx]; const auto ndata = static_cast<bst_omp_uint>(col.size()); #pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess) for (bst_omp_uint j = 0; j < ndata; ++j) { const bst_float v = col[j].fvalue; auto &p = gpair[col[j].index * num_group + group_idx]; if (p.GetHess() < 0.0f) continue; sum_grad += p.GetGrad() * v; sum_hess += p.GetHess() * v * v; } } return std::make_pair(sum_grad, sum_hess); } /** * \brief Get the gradient with respect to the bias. Row-wise multithreaded. * * \param group_idx Zero-based index of the group. * \param num_group Number of groups. * \param gpair Gradients. * \param p_fmat The feature matrix. * * \return The gradient and diagonal Hessian entry for the bias. */ inline std::pair<double, double> GetBiasGradientParallel(int group_idx, int num_group, const std::vector<GradientPair> &gpair, DMatrix *p_fmat) { double sum_grad = 0.0, sum_hess = 0.0; const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_); #pragma omp parallel for schedule(static) reduction(+ : sum_grad, sum_hess) for (bst_omp_uint i = 0; i < ndata; ++i) { auto &p = gpair[i * num_group + group_idx]; if (p.GetHess() >= 0.0f) { sum_grad += p.GetGrad(); sum_hess += p.GetHess(); } } return std::make_pair(sum_grad, sum_hess); } /** * \brief Updates the gradient vector with respect to a change in weight. * * \param fidx The feature index. * \param group_idx Zero-based index of the group. * \param num_group Number of groups. * \param dw The change in weight. * \param in_gpair The gradient vector to be updated. * \param p_fmat The input feature matrix. */ inline void UpdateResidualParallel(int fidx, int group_idx, int num_group, float dw, std::vector<GradientPair> *in_gpair, DMatrix *p_fmat) { if (dw == 0.0f) return; for (const auto &batch : p_fmat->GetColumnBatches()) { auto col = batch[fidx]; // update grad value const auto num_row = static_cast<bst_omp_uint>(col.size()); #pragma omp parallel for schedule(static) for (bst_omp_uint j = 0; j < num_row; ++j) { GradientPair &p = (*in_gpair)[col[j].index * num_group + group_idx]; if (p.GetHess() < 0.0f) continue; p += GradientPair(p.GetHess() * col[j].fvalue * dw, 0); } } } /** * \brief Updates the gradient vector based on a change in the bias. * * \param group_idx Zero-based index of the group. * \param num_group Number of groups. * \param dbias The change in bias. * \param in_gpair The gradient vector to be updated. * \param p_fmat The input feature matrix. */ inline void UpdateBiasResidualParallel(int group_idx, int num_group, float dbias, std::vector<GradientPair> *in_gpair, DMatrix *p_fmat) { if (dbias == 0.0f) return; const auto ndata = static_cast<bst_omp_uint>(p_fmat->Info().num_row_); #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < ndata; ++i) { GradientPair &g = (*in_gpair)[i * num_group + group_idx]; if (g.GetHess() < 0.0f) continue; g += GradientPair(g.GetHess() * dbias, 0); } } /** * \brief Abstract class for stateful feature selection or ordering * in coordinate descent algorithms. */ class FeatureSelector { public: /*! \brief factory method */ static FeatureSelector *Create(int choice); /*! \brief virtual destructor */ virtual ~FeatureSelector() = default; /** * \brief Setting up the selector state prior to looping through features. * * \param model The model. * \param gpair The gpair. * \param p_fmat The feature matrix. * \param alpha Regularisation alpha. * \param lambda Regularisation lambda. * \param param A parameter with algorithm-dependent use. */ virtual void Setup(const gbm::GBLinearModel &model, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda, int param) {} /** * \brief Select next coordinate to update. * * \param iteration The iteration in a loop through features * \param model The model. * \param group_idx Zero-based index of the group. * \param gpair The gpair. * \param p_fmat The feature matrix. * \param alpha Regularisation alpha. * \param lambda Regularisation lambda. * * \return The index of the selected feature. -1 indicates none selected. */ virtual int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) = 0; }; /** * \brief Deterministic selection by cycling through features one at a time. */ class CyclicFeatureSelector : public FeatureSelector { public: int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) override { return iteration % model.param.num_feature; } }; /** * \brief Similar to Cyclic but with random feature shuffling prior to each update. * \note Its randomness is controllable by setting a random seed. */ class ShuffleFeatureSelector : public FeatureSelector { public: void Setup(const gbm::GBLinearModel &model, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda, int param) override { if (feat_index_.size() == 0) { feat_index_.resize(model.param.num_feature); std::iota(feat_index_.begin(), feat_index_.end(), 0); } std::shuffle(feat_index_.begin(), feat_index_.end(), common::GlobalRandom()); } int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) override { return feat_index_[iteration % model.param.num_feature]; } protected: std::vector<bst_uint> feat_index_; }; /** * \brief A random (with replacement) coordinate selector. * \note Its randomness is controllable by setting a random seed. */ class RandomFeatureSelector : public FeatureSelector { public: int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) override { return common::GlobalRandom()() % model.param.num_feature; } }; /** * \brief Select coordinate with the greatest gradient magnitude. * \note It has O(num_feature^2) complexity. It is fully deterministic. * * \note It allows restricting the selection to top_k features per group with * the largest magnitude of univariate weight change, by passing the top_k value * through the `param` argument of Setup(). That would reduce the complexity to * O(num_feature*top_k). */ class GreedyFeatureSelector : public FeatureSelector { public: void Setup(const gbm::GBLinearModel &model, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda, int param) override { top_k_ = static_cast<bst_uint>(param); const bst_uint ngroup = model.param.num_output_group; if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max(); if (counter_.size() == 0) { counter_.resize(ngroup); gpair_sums_.resize(model.param.num_feature * ngroup); } for (bst_uint gid = 0u; gid < ngroup; ++gid) { counter_[gid] = 0u; } } int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) override { // k-th selected feature for a group auto k = counter_[group_idx]++; // stop after either reaching top-K or going through all the features in a group if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1; const int ngroup = model.param.num_output_group; const bst_omp_uint nfeat = model.param.num_feature; // Calculate univariate gradient sums std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.)); for (const auto &batch : p_fmat->GetColumnBatches()) { #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < nfeat; ++i) { const auto col = batch[i]; const bst_uint ndata = col.size(); auto &sums = gpair_sums_[group_idx * nfeat + i]; for (bst_uint j = 0u; j < ndata; ++j) { const bst_float v = col[j].fvalue; auto &p = gpair[col[j].index * ngroup + group_idx]; if (p.GetHess() < 0.f) continue; sums.first += p.GetGrad() * v; sums.second += p.GetHess() * v * v; } } } // Find a feature with the largest magnitude of weight change int best_fidx = 0; double best_weight_update = 0.0f; for (bst_omp_uint fidx = 0; fidx < nfeat; ++fidx) { auto &s = gpair_sums_[group_idx * nfeat + fidx]; float dw = std::abs(static_cast<bst_float>( CoordinateDelta(s.first, s.second, model[fidx][group_idx], alpha, lambda))); if (dw > best_weight_update) { best_weight_update = dw; best_fidx = fidx; } } return best_fidx; } protected: bst_uint top_k_; std::vector<bst_uint> counter_; std::vector<std::pair<double, double>> gpair_sums_; }; /** * \brief Thrifty, approximately-greedy feature selector. * * \note Prior to cyclic updates, reorders features in descending magnitude of * their univariate weight changes. This operation is multithreaded and is a * linear complexity approximation of the quadratic greedy selection. * * \note It allows restricting the selection to top_k features per group with * the largest magnitude of univariate weight change, by passing the top_k value * through the `param` argument of Setup(). */ class ThriftyFeatureSelector : public FeatureSelector { public: void Setup(const gbm::GBLinearModel &model, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda, int param) override { top_k_ = static_cast<bst_uint>(param); if (param <= 0) top_k_ = std::numeric_limits<bst_uint>::max(); const bst_uint ngroup = model.param.num_output_group; const bst_omp_uint nfeat = model.param.num_feature; if (deltaw_.size() == 0) { deltaw_.resize(nfeat * ngroup); sorted_idx_.resize(nfeat * ngroup); counter_.resize(ngroup); gpair_sums_.resize(nfeat * ngroup); } // Calculate univariate gradient sums std::fill(gpair_sums_.begin(), gpair_sums_.end(), std::make_pair(0., 0.)); for (const auto &batch : p_fmat->GetColumnBatches()) { // column-parallel is usually faster than row-parallel #pragma omp parallel for schedule(static) for (bst_omp_uint i = 0; i < nfeat; ++i) { const auto col = batch[i]; const bst_uint ndata = col.size(); for (bst_uint gid = 0u; gid < ngroup; ++gid) { auto &sums = gpair_sums_[gid * nfeat + i]; for (bst_uint j = 0u; j < ndata; ++j) { const bst_float v = col[j].fvalue; auto &p = gpair[col[j].index * ngroup + gid]; if (p.GetHess() < 0.f) continue; sums.first += p.GetGrad() * v; sums.second += p.GetHess() * v * v; } } } } // rank by descending weight magnitude within the groups std::fill(deltaw_.begin(), deltaw_.end(), 0.f); std::iota(sorted_idx_.begin(), sorted_idx_.end(), 0); bst_float *pdeltaw = &deltaw_[0]; for (bst_uint gid = 0u; gid < ngroup; ++gid) { // Calculate univariate weight changes for (bst_omp_uint i = 0; i < nfeat; ++i) { auto ii = gid * nfeat + i; auto &s = gpair_sums_[ii]; deltaw_[ii] = static_cast<bst_float>(CoordinateDelta( s.first, s.second, model[i][gid], alpha, lambda)); } // sort in descending order of deltaw abs values auto start = sorted_idx_.begin() + gid * nfeat; std::sort(start, start + nfeat, [pdeltaw](size_t i, size_t j) { return std::abs(*(pdeltaw + i)) > std::abs(*(pdeltaw + j)); }); counter_[gid] = 0u; } } int NextFeature(int iteration, const gbm::GBLinearModel &model, int group_idx, const std::vector<GradientPair> &gpair, DMatrix *p_fmat, float alpha, float lambda) override { // k-th selected feature for a group auto k = counter_[group_idx]++; // stop after either reaching top-N or going through all the features in a group if (k >= top_k_ || counter_[group_idx] == model.param.num_feature) return -1; // note that sorted_idx stores the "long" indices const size_t grp_offset = group_idx * model.param.num_feature; return static_cast<int>(sorted_idx_[grp_offset + k] - grp_offset); } protected: bst_uint top_k_; std::vector<bst_float> deltaw_; std::vector<size_t> sorted_idx_; std::vector<bst_uint> counter_; std::vector<std::pair<double, double>> gpair_sums_; }; inline FeatureSelector *FeatureSelector::Create(int choice) { switch (choice) { case kCyclic: return new CyclicFeatureSelector(); case kShuffle: return new ShuffleFeatureSelector(); case kThrifty: return new ThriftyFeatureSelector(); case kGreedy: return new GreedyFeatureSelector(); case kRandom: return new RandomFeatureSelector(); default: LOG(FATAL) << "unknown coordinate selector: " << choice; } return nullptr; } } // namespace linear } // namespace xgboost
omp_section_private.c
<ompts:test> <ompts:testdescription>Test which checks the omp section private directive by upcounting a variable in a to several sections splitted loop.</ompts:testdescription> <ompts:ompversion>2.0</ompts:ompversion> <ompts:directive>omp section private</ompts:directive> <ompts:dependences>omp critical</ompts:dependences> <ompts:testcode> #include <stdio.h> #include "omp_testsuite.h" int <ompts:testcode:functionname>omp_section_private</ompts:testcode:functionname>(FILE * logFile){ <ompts:orphan:vars> int sum; int sum0; int i; </ompts:orphan:vars> int known_sum; sum = 7; sum0 = 0; #pragma omp parallel { <ompts:orphan> #pragma omp sections <ompts:check>private(sum0,i)</ompts:check><ompts:crosscheck>private(i)</ompts:crosscheck> { #pragma omp section { <ompts:check> sum0 = 0; </ompts:check> for (i = 1; i < 400; i++) sum0 = sum0 + i; #pragma omp critical { sum = sum + sum0; } /*end of critical */ } #pragma omp section { <ompts:check> sum0 = 0; </ompts:check> for (i = 400; i < 700; i++) sum0 = sum0 + i; #pragma omp critical { sum = sum + sum0; } /*end of critical */ } #pragma omp section { <ompts:check> sum0 = 0; </ompts:check> for (i = 700; i < 1000; i++) sum0 = sum0 + i; #pragma omp critical { sum = sum + sum0; } /*end of critical */ } } /*end of sections*/ </ompts:orphan> } /* end of parallel */ known_sum = (999 * 1000) / 2 + 7; return (known_sum == sum); } /* end of check_section_private*/ </ompts:testcode> </ompts:test>
convolution_1x1_int8.h
// BUG1989 is pleased to support the open source community by supporting ncnn available. // // author:BUG1989 (https://github.com/BUG1989/) Long-term support. // author:FuGuangping (https://github.com/fu1899) Implemented the first version of INT8 quantization on ARMv7. // // Copyright (C) 2019 BUG1989. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static inline signed char float2int8(float v) { int int32 = round(v); if (int32 > 127) return 127; if (int32 < -127) return -127; return (signed char)int32; } #if __aarch64__ #if 1 #include "gemm_symm_int8.h" static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(outch, inch, (size_t)1u); const int8_t *a = _kernel; int8_t *sa = kernel_tm; reorder_a((int8_t*)a, sa, outch, inch, inch); } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t* pData = bottom_blob; int8_t *pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int32_t *pc = top_blob; const int8_t *pa = kernel; const int8_t *pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, nullptr, nullptr, opt); } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { const size_t n = bottom_blob.w * bottom_blob.h; const size_t k = bottom_blob.c; const size_t m = top_blob.c; ncnn::Mat scales_tm(m); ncnn::Mat bias_tm(m); float* scales = scales_tm; const float* bias = _bias; // outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); // the equation could convert to: // out = float2int8( (float)sum * (scale_requant_in * scale_requant_out) + (bias * scale_requant_out) ) // prebuild the list of (scales_requant_in*scale_requant_out) for (size_t i = 0; i < m; ++i) { scales_tm[i] = scales_requant[2*i] * scales_requant[2*i + 1]; } if (!_bias.empty()) { for (size_t i = 0; i < m; ++i) { bias_tm[i] = bias[i] * scales_requant[2*i + 1]; } bias = bias_tm; } ncnn::Mat bottom_tm(k * n, (size_t)1u, opt.workspace_allocator); { const int8_t *pData = bottom_blob; int8_t *pReorder = bottom_tm; reorder_b(pData, pReorder, k, n, bottom_blob.cstep); } // GEMM int8_t *pc = top_blob; const int8_t *pa = kernel; const int8_t *pb = bottom_tm; const size_t ldc = top_blob.cstep; int8kernel((void*)pc, pa, pb, m, k, n, ldc, scales, (float*)bias, opt); } #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; // kernel memory packed 4 x 4 kernel_tm.create(4*4, inch/4 + inch%4, outch/4 + outch%4, (size_t)1u); int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; const signed char* k0 = kernel + (p+0)*inch; const signed char* k1 = kernel + (p+1)*inch; const signed char* k2 = kernel + (p+2)*inch; const signed char* k3 = kernel + (p+3)*inch; signed char* ktmp = kernel_tm.channel(p/4); int q=0; for (; q+1<inch; q+=2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp[2] = k1[0]; ktmp[3] = k1[1]; ktmp[4] = k2[0]; ktmp[5] = k2[1]; ktmp[6] = k3[0]; ktmp[7] = k3[1]; ktmp += 8; k0 += 2; k1 += 2; k2 += 2; k3 += 2; } for (; q<inch; q++) { ktmp[0] = k0[0]; ktmp[1] = k1[0]; ktmp[2] = k2[0]; ktmp[3] = k3[0]; ktmp += 4; k0 += 1; k1 += 1; k2 += 1; k3 += 1; } } for (int p=remain_outch_start; p<outch; p++) { const signed char* k0 = kernel + (p+0)*inch; signed char* ktmp = kernel_tm.channel(p/4 + p%4); int q=0; for (; q+1<inch; q=q+2) { ktmp[0] = k0[0]; ktmp[1] = k0[1]; ktmp += 2; k0 += 2; } for (; q<inch; q++) { ktmp[0] = k0[0]; ktmp++; k0++; } } } static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size/4 + size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p+1); int* outptr2 = top_blob.channel(p+2); int* outptr3 = top_blob.channel(p+3); int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" "st1 {v20.4s}, [%0] \n" "st1 {v21.4s}, [%1] \n" "st1 {v22.4s}, [%2] \n" "st1 {v23.4s}, [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if 0//__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+3<inch; q=q+4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } vst1q_lane_s32(outptr0, _sum, 0); vst1q_lane_s32(outptr1, _sum, 1); vst1q_lane_s32(outptr2, _sum, 2); vst1q_lane_s32(outptr3, _sum, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } vst1q_s32(outptr0, _sum); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; #endif outptr0 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // bottom_tm memory packed 4 x 4 ncnn::Mat bottom_tm(4, inch, size/4 + size%4, (size_t)1u, opt.workspace_allocator); { int nn_size = size >> 2; int remain_size_start = nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 4; const signed char* img0 = bottom_blob.channel(0); const signed char* img1 = bottom_blob.channel(1); img0 += i; img1 += i; signed char* tmpptr = bottom_tm.channel(i/4); int q = 0; for (; q+1<inch; q=q+2) { tmpptr[0] = img0[0]; tmpptr[1] = img1[0]; tmpptr[2] = img0[1]; tmpptr[3] = img1[1]; tmpptr[4] = img0[2]; tmpptr[5] = img1[2]; tmpptr[6] = img0[3]; tmpptr[7] = img1[3]; tmpptr += 8; img0 += bottom_blob.cstep; img0 += bottom_blob.cstep; img1 += bottom_blob.cstep; img1 += bottom_blob.cstep; } for (; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = bottom_tm.channel(i/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr += 1; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = outch >> 2; remain_outch_start = nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p+1); signed char* outptr2 = top_blob.channel(p+2); signed char* outptr3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float scale_requant_in0 = scales_requant[2*p]; const float scale_requant_out0 = scales_requant[2*p+1]; const float scale_requant_in1 = scales_requant[2*(p+1)]; const float scale_requant_out1 = scales_requant[2*(p+1)+1]; const float scale_requant_in2 = scales_requant[2*(p+2)]; const float scale_requant_out2 = scales_requant[2*(p+2)+1]; const float scale_requant_in3 = scales_requant[2*(p+3)]; const float scale_requant_out3 = scales_requant[2*(p+3)+1]; float32x4_t _bias03, _scale_in03, _scale_out03; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _bias1 = vdupq_n_f32(bias1); float32x4_t _bias2 = vdupq_n_f32(bias2); float32x4_t _bias3 = vdupq_n_f32(bias3); _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4); #if 1 //__ARM_NEON asm volatile( "prfm pldl1keep, [%4, #128] \n" "prfm pldl1keep, [%5, #128] \n" "eor v16.16b, v16.16b, v16.16b \n" // sum0 "eor v17.16b, v17.16b, v17.16b \n" // sum1 "eor v18.16b, v18.16b, v18.16b \n" // sum2 "eor v19.16b, v19.16b, v19.16b \n" // sum3 "lsr w4, %w12, #2 \n"// r4 = nn = L >> 2 "cmp w4, #0 \n" "beq 1f \n" "0: \n"// for (; k+3<L; k=k+4) "ld1 {v0.16b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.16b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #16 \n" "add %5, %5, #16 \n" "rev32 v1.8h, v0.8h \n"// i1, i0, i3, i2 "rev64 v2.4s, v0.4s \n"// i2, i3, i0, i1 "rev64 v3.8h, v0.8h \n"// i3, i2, i1, i0 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "prfm pldl1keep, [%4, #1024] \n" "prfm pldl1keep, [%5, #1024] \n" "smlal2 v8.8h, v4.16b, v0.16b \n" "smlal2 v9.8h, v4.16b, v1.16b \n" "smlal2 v10.8h, v4.16b, v2.16b \n" "smlal2 v11.8h, v4.16b, v3.16b \n" "sadalp v16.4s, v8.8h \n"// i0k0, i1k1, i2k2, i3k3 "sadalp v17.4s, v9.8h \n"// i1k0, i0k1, i3k2, i2k3 "sadalp v18.4s, v10.8h \n"// i2k0, i3k1, i0k2, i1k3 "sadalp v19.4s, v11.8h \n"// i3k0, i2k1, i1k2, i0k3 "subs w4, w4, #1 \n" "bne 0b \n" "1: \n"// for (; k+1<L; k=k+2) // remain loop "and w4, %w12, #3 \n"// w4 = remain = K & 3; "cmp w4, #0 \n" "beq 3f \n" "lsr w4, w4, #1 \n"// r4 = nn = L >> 1 "cmp w4, #0 \n" "beq 3f \n" "2: \n"// for (; k+1<L; k=k+2) "ld1 {v0.8b}, [%4] \n"// i0, i1, i2, i3 "ld1 {v4.8b}, [%5] \n"// k0, k1, k2, k3 "add %4, %4, #8 \n" "add %5, %5, #8 \n" "rev32 v1.4h, v0.4h \n"// i2, i3, i0, i1 "rev64 v2.2s, v0.2s \n"// i1, i0, i3, i2 "rev64 v3.4h, v0.4h \n"// i0, i1, i2, i3 "smull v8.8h, v4.8b, v0.8b \n" "smull v9.8h, v4.8b, v1.8b \n" "smull v10.8h, v4.8b, v2.8b \n" "smull v11.8h, v4.8b, v3.8b \n" "sadalp v16.4s, v8.8h \n" "sadalp v17.4s, v9.8h \n" "sadalp v18.4s,v10.8h \n" "sadalp v19.4s,v11.8h \n" "subs w4, w4, #1 \n" "bne 2b \n" "3: \n"// realloc "mov v20.s[0], v16.s[0] \n" "mov v20.s[1], v17.s[0] \n" "mov v20.s[2], v18.s[0] \n" "mov v20.s[3], v19.s[0] \n" "mov v21.s[0], v17.s[1] \n" "mov v21.s[1], v16.s[1] \n" "mov v21.s[2], v19.s[1] \n" "mov v21.s[3], v18.s[1] \n" "mov v22.s[0], v18.s[2] \n" "mov v22.s[1], v19.s[2] \n" "mov v22.s[2], v16.s[2] \n" "mov v22.s[3], v17.s[2] \n" "mov v23.s[0], v19.s[3] \n" "mov v23.s[1], v18.s[3] \n" "mov v23.s[2], v17.s[3] \n" "mov v23.s[3], v16.s[3] \n" "and w4, %w12, #1 \n"// w4 = remain = K & 1; "cmp w4, #0 \n" "beq 5f \n" "4: \n" "ld1 {v0.8b}, [%4] \n" "ld1 {v1.8b}, [%5] \n" "add %4, %4, #4 \n" "add %5, %5, #4 \n" "sshll v0.8h, v0.8b, #0 \n"// i0[0], i1[0], i2[0], i3[0] "sshll v1.8h, v1.8b, #0 \n"// k0[0], k1[0], k2[0], k3[0] "smlal v20.4s, v0.4h, v1.h[0] \n"// i0k0, i1k0, i2k0, i3k0 "smlal v21.4s, v0.4h, v1.h[1] \n"// i0k1, i1k1, i2k1, i3k1 "smlal v22.4s, v0.4h, v1.h[2] \n"// i0k2, i1k2, i2k2, i3k2 "smlal v23.4s, v0.4h, v1.h[3] \n"// i0k3, i1k3, i2k3, i3k3 "subs w4, w4, #1 \n" "bne 2b \n" "5: \n" // top_s32 -> top_f32 "scvtf v20.4s, v20.4s \n" "scvtf v21.4s, v21.4s \n" "scvtf v22.4s, v22.4s \n" "scvtf v23.4s, v23.4s \n" // top_f32 = top_f32 * scale_in "fmul v20.4s, v20.4s, %17.s[0] \n" "fmul v21.4s, v21.4s, %17.s[1] \n" "fmul v22.4s, v22.4s, %17.s[2] \n" "fmul v23.4s, v23.4s, %17.s[3] \n" // top_f32 = top_f32 + bias "fadd v20.4s, v20.4s, %13.4s \n" "fadd v21.4s, v21.4s, %14.4s \n" "fadd v22.4s, v22.4s, %15.4s \n" "fadd v23.4s, v23.4s, %16.4s \n" // top_f32 = top_f32 * scale_out "fmul v20.4s, v20.4s, %18.s[0] \n" "fmul v21.4s, v21.4s, %18.s[1] \n" "fmul v22.4s, v22.4s, %18.s[2] \n" "fmul v23.4s, v23.4s, %18.s[3] \n" // top_f32 -> top_s32 "fcvtas v20.4s, v20.4s \n" "fcvtas v21.4s, v21.4s \n" "fcvtas v22.4s, v22.4s \n" "fcvtas v23.4s, v23.4s \n" // top_s32 -> top_s16 "sqxtn v7.4h, v20.4s \n" "sqxtn2 v7.8h, v21.4s \n" "sqxtn v8.4h, v22.4s \n" "sqxtn2 v8.8h, v23.4s \n" // top_s16 -> top_s8 "sqxtn v0.8b, v7.8h \n" "sqxtn v1.8b, v8.8h \n" // save top_s8 "st1 {v0.s}[0], [%0] \n" "st1 {v0.s}[1], [%1] \n" "st1 {v1.s}[0], [%2] \n" "st1 {v1.s}[1], [%3] \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias0), // %13 "w"(_bias1), // %14 "w"(_bias2), // %15 "w"(_bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "x4", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0_0 += tmpptr[0] * kptr[0]; sum0_0 += tmpptr[1] * kptr[1]; sum0_1 += tmpptr[2] * kptr[0]; sum0_1 += tmpptr[3] * kptr[1]; sum0_2 += tmpptr[4] * kptr[0]; sum0_2 += tmpptr[5] * kptr[1]; sum0_3 += tmpptr[6] * kptr[0]; sum0_3 += tmpptr[7] * kptr[1]; sum1_0 += tmpptr[0] * kptr[2]; sum1_0 += tmpptr[1] * kptr[3]; sum1_1 += tmpptr[2] * kptr[2]; sum1_1 += tmpptr[3] * kptr[3]; sum1_2 += tmpptr[4] * kptr[2]; sum1_2 += tmpptr[5] * kptr[3]; sum1_3 += tmpptr[6] * kptr[2]; sum1_3 += tmpptr[7] * kptr[3]; sum2_0 += tmpptr[0] * kptr[4]; sum2_0 += tmpptr[1] * kptr[5]; sum2_1 += tmpptr[2] * kptr[4]; sum2_1 += tmpptr[3] * kptr[5]; sum2_2 += tmpptr[4] * kptr[4]; sum2_2 += tmpptr[5] * kptr[5]; sum2_3 += tmpptr[6] * kptr[4]; sum2_3 += tmpptr[7] * kptr[5]; sum3_0 += tmpptr[0] * kptr[6]; sum3_0 += tmpptr[1] * kptr[7]; sum3_1 += tmpptr[2] * kptr[6]; sum3_1 += tmpptr[3] * kptr[7]; sum3_2 += tmpptr[4] * kptr[6]; sum3_2 += tmpptr[5] * kptr[7]; sum3_3 += tmpptr[6] * kptr[6]; sum3_3 += tmpptr[7] * kptr[7]; tmpptr += 8; kptr += 8; } for (; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = float2int8(((float)sum0_0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[1] = float2int8(((float)sum0_1 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[2] = float2int8(((float)sum0_2 * scale_requant_in0 + bias0) * scale_requant_out0); outptr0[3] = float2int8(((float)sum0_3 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1_0 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[1] = float2int8(((float)sum1_1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[2] = float2int8(((float)sum1_2 * scale_requant_in1 + bias1) * scale_requant_out1); outptr1[3] = float2int8(((float)sum1_3 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2_0 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[1] = float2int8(((float)sum2_1 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[2] = float2int8(((float)sum2_2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr2[3] = float2int8(((float)sum2_3 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3_0 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[1] = float2int8(((float)sum3_1 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[2] = float2int8(((float)sum3_2 * scale_requant_in3 + bias3) * scale_requant_out3); outptr3[3] = float2int8(((float)sum3_3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+3<inch; q=q+4) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8x2_t _k = vld2_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1];k0[2-3], k1[2-3], k2[2-3], k3[2-3] int16x8_t _r0_s16 = vmovl_s8(_r0); // i0[0],i0[1],i0[2],i0[3] int16x8_t _k02_s16 = vmovl_s8(_k.val[0]); // k0[0],k1[0],k2[0],k3[0],k0[2],k1[2],k2[2],k3[2] int16x8_t _k13_s16 = vmovl_s8(_k.val[1]); // k0[1],k1[1],k2[1],k3[1],k0[3],k1[3],k2[3],k3[3] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k02_s16), vget_low_s16(_r0_s16), 0); // i0[0]*k[0-3][0] _sum = vmlal_lane_s16(_sum, vget_low_s16(_k13_s16), vget_low_s16(_r0_s16), 1); // i0[1]*k[0-3][1] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k02_s16), vget_low_s16(_r0_s16), 2); // i0[2]*k[0-3][2] _sum = vmlal_lane_s16(_sum, vget_high_s16(_k13_s16), vget_low_s16(_r0_s16), 3); // i0[3]*k[0-3][3] tmpptr += 4; kptr += 16; } for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k0[0-1], k1[0-1], k2[0-1], k3[0-1] _r0[2] = _r0[0]; _r0[3] = _r0[1]; _r0[4] = _r0[0]; _r0[5] = _r0[1]; _r0[6] = _r0[0]; _r0[7] = _r0[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 2; kptr += 8; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-3] int8x8_t _k = vld1_s8(kptr); // k[0-3][0] int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vaddw_s16(_sum, vget_low_s16(_tp0)); tmpptr += 1; kptr += 4; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in03); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias03); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out03); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_lane_s8(outptr0, _sum_s8, 0); vst1_lane_s8(outptr1, _sum_s8, 1); vst1_lane_s8(outptr2, _sum_s8, 2); vst1_lane_s8(outptr3, _sum_s8, 3); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[0] * kptr[2]; sum1 += tmpptr[1] * kptr[3]; sum2 += tmpptr[0] * kptr[4]; sum2 += tmpptr[1] * kptr[5]; sum3 += tmpptr[0] * kptr[6]; sum3 += tmpptr[1] * kptr[7]; tmpptr += 2; kptr += 8; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr += 1; kptr += 4; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in0 + bias0) * scale_requant_out0); outptr1[0] = float2int8(((float)sum1 * scale_requant_in1 + bias1) * scale_requant_out1); outptr2[0] = float2int8(((float)sum2 * scale_requant_in2 + bias2) * scale_requant_out2); outptr3[0] = float2int8(((float)sum3 * scale_requant_in3 + bias3) * scale_requant_out3); #endif outptr0++; outptr1++; outptr2++; outptr3++; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); int i = 0; for (; i+3<size; i+=4) { signed char* tmpptr = bottom_tm.channel(i/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if 1 //__ARM_NEON int32x4_t _sum = vdupq_n_s32(0); int q=0; for (; q+1<inch; q=q+2) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0-1], i1[0-1], i2[0-1], i3[0-1] int8x8_t _k = vld1_s8(kptr); // k0[0-1] _k[2] = _k[0]; _k[3] = _k[1]; _k[4] = _k[0]; _k[5] = _k[1]; _k[6] = _k[0]; _k[7] = _k[1]; int16x8_t _tp0 = vmull_s8(_k, _r0); _sum = vpadalq_s16(_sum, _tp0); tmpptr += 8; kptr += 2; } for (; q<inch; q++) { int8x8_t _r0 = vld1_s8(tmpptr); // i0[0], i1[0], i2[0], i3[0] int8x8_t _k = vld1_s8(kptr); // k[0][0] int16x8_t _r0_s16 = vmovl_s8(_r0); int16x8_t _k_s16 = vmovl_s8(_k); _sum = vmlal_lane_s16(_sum, vget_low_s16(_r0_s16), vget_low_s16(_k_s16), 0); // i0k0, i1k0, i2k0, i3k0 tmpptr += 4; kptr += 1; } // top_s32 -> top_f32 float32x4_t _sum_f32 = vcvtq_f32_s32(_sum); // top_f32 = top_f32 * scale_in _sum_f32 = vmulq_f32(_sum_f32, _scale_in); // top_f32 = top_f32 + bias _sum_f32 = vaddq_f32(_sum_f32, _bias0); // top_f32 = top_f32 * scale_out _sum_f32 = vmulq_f32(_sum_f32, _scale_out); // top_f32 -> top_s32 _sum = vcvtaq_s32_f32(_sum_f32); // top_s32 -> top_s16 int16x4_t _sum_s16 = vqmovn_s32(_sum); int16x8_t _sum_s16_tp = vcombine_s16(_sum_s16, _sum_s16); // top_s16 -> top_s8 int8x8_t _sum_s8 = vqmovn_s16(_sum_s16_tp); // save top_s8 vst1_s8(outptr0, _sum_s8); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int q=0; for (; q+1<inch; q=q+2) { sum0 += tmpptr[0] * kptr[0]; sum0 += tmpptr[1] * kptr[1]; sum1 += tmpptr[2] * kptr[0]; sum1 += tmpptr[3] * kptr[1]; sum2 += tmpptr[4] * kptr[0]; sum2 += tmpptr[5] * kptr[1]; sum3 += tmpptr[6] * kptr[0]; sum3 += tmpptr[7] * kptr[1]; tmpptr += 8; kptr += 2; } for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0[1] = float2int8(((float)sum1 * scale_requant_in + bias0) * scale_requant_out); outptr0[2] = float2int8(((float)sum2 * scale_requant_in + bias0) * scale_requant_out); outptr0[3] = float2int8(((float)sum3 * scale_requant_in + bias0) * scale_requant_out); #endif outptr0 += 4; } for (; i<size; i++) { signed char* tmpptr = bottom_tm.channel(i/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = float2int8(((float)sum0 * scale_requant_in + bias0) * scale_requant_out); outptr0++; } } } #endif #else static void conv1x1s1_sgemm_transform_kernel_int8_neon(const Mat& _kernel, Mat& kernel_tm, int inch, int outch) { const signed char* kernel = _kernel; kernel_tm.create(4*4, inch/4 + inch%4, outch/4 + outch%4, (size_t)1u); int p = 0; for (; p+3<outch; p+=4) { const signed char* kernel0 = kernel + (p+0)*inch; const signed char* kernel1 = kernel + (p+1)*inch; const signed char* kernel2 = kernel + (p+2)*inch; const signed char* kernel3 = kernel + (p+3)*inch; signed char* ktmp = kernel_tm.channel(p/4); for (int q=0; q<inch; q++) { // kernel0...3 0 ktmp[0] = kernel0[0]; ktmp[1] = kernel1[0]; ktmp[2] = kernel2[0]; ktmp[3] = kernel3[0]; ktmp += 4; kernel0 += 1; kernel1 += 1; kernel2 += 1; kernel3 += 1; } } for (; p<outch; p++) { const signed char* kernel0 = kernel + p*inch; signed char* ktmp = kernel_tm.channel(p/4 + p%4); for (int q=0; q<inch; q++) { ktmp[0] = kernel0[0]; ktmp++; kernel0++; } } } /* * Convolution 1x1 quantized with sgemm int8 */ static void conv1x1s1_sgemm_int8_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; // interleave Mat tmp(8*4, inch/4+inch%4, size/8 + (size%8)/4 + size%4, 1u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 8; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8); for (int q=0; q<inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0" ); img0 += bottom_blob.cstep; #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = remain_size_start + ii * 4; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; int* outptr0 = top_blob.channel(p); int* outptr1 = top_blob.channel(p+1); int* outptr2 = top_blob.channel(p+2); int* outptr3 = top_blob.channel(p+3); int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d7}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q8, d4, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q9, d5, d0[1] \n" "vmlal.s16 q10, d4, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q11, d5, d0[2] \n" "vmlal.s16 q12, d4, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q13, d5, d0[3] \n" "vmlal.s16 q6, d6, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q7, d7, d1[0] \n" "vmlal.s16 q8, d6, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q9, d7, d1[1] \n" "vmlal.s16 q10, d6, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q11, d7, d1[2] \n" "vmlal.s16 q12, d6, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q13, d7, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n"// sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n"// sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n"// sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" "vst1.s32 {d16-d19}, [%1]! \n" "vst1.s32 {d20-d23}, [%2]! \n" "vst1.s32 {d24-d27}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4-d5}, [%4]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d4, d0[0] \n"// sum0 = (a00-a03) * k00 "vmlal.s16 q7, d4, d0[1] \n"// sum1 = (a00-a03) * k10 "vmlal.s16 q8, d4, d0[2] \n"// sum2 = (a00-a03) * k20 "vmlal.s16 q9, d4, d0[3] \n"// sum3 = (a00-a03) * k30 "vmlal.s16 q6, d5, d1[0] \n"// sum0 += (a10-a13) * k01 "vmlal.s16 q7, d5, d1[1] \n"// sum1 += (a10-a13) * k11 "vmlal.s16 q8, d5, d1[2] \n"// sum2 += (a10-a13) * k21 "vmlal.s16 q9, d5, d1[3] \n"// sum3 += (a10-a13) * k31 "vmlal.s16 q6, d6, d2[0] \n"// sum0 += (a20-a23) * k02 "vmlal.s16 q7, d6, d2[1] \n"// sum1 += (a20-a23) * k12 "vmlal.s16 q8, d6, d2[2] \n"// sum2 += (a20-a23) * k22 "vmlal.s16 q9, d6, d2[3] \n"// sum3 += (a20-a23) * k32 "vmlal.s16 q6, d7, d3[0] \n"// sum0 += (a30-a33) * k03 "vmlal.s16 q7, d7, d3[1] \n"// sum1 += (a30-a33) * k13 "vmlal.s16 q8, d7, d3[2] \n"// sum2 += (a30-a33) * k23 "vmlal.s16 q9, d7, d3[3] \n"// sum3 += (a30-a33) * k33 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n"// sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n"// sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n"// sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" "vst1.s32 {d14-d15}, [%1]! \n" "vst1.s32 {d16-d17}, [%2]! \n" "vst1.s32 {d18-d19}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n"// tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n"// a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n"// (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n"// (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n"// (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \n" "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d20[0]}, [%0]! \n" "vst1.s32 {d20[1]}, [%1]! \n" "vst1.s32 {d21[0]}, [%2]! \n" "vst1.s32 {d21[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch) // %12 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); int* outptr0 = out0; int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d15}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n"// (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n"// (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n"// (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vst1.s32 {d12-d13}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch) // %6 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } // // NOTE sgemm int8 // for (; p<outch; p++) // { // Mat out0 = top_blob.channel(p); // // int* outptr0 = out0; // // for (int i=0; i<size; i++) // { // int sum = 0; // // const signed char* kptr = _kernel.channel(p/8 + p%8); // // for (int q=0; q<inch; q++) // { // const signed char* img0 = bottom_blob.channel(q); // // sum += img0[i] * kptr[0]; // kptr ++; // } // // outptr0[i] = sum; // } // } } static void conv1x1s1_sgemm_int8_requant_neon(const Mat &bottom_blob, Mat &top_blob, const Mat &kernel, const Mat &_bias, std::vector<float> scales_requant, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; int outch = top_blob.c; const int size = w * h; const float* bias = _bias; // interleave Mat tmp(8*4, inch/4+inch%4, size/8 + (size%8)/4 + size%4, 1u, opt.workspace_allocator); { int nn_size = size >> 3; int remain_size_start = nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = ii * 8; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8); for (int q=0; q<inch; q++) { #if __ARM_NEON asm volatile( "pld [%0, #64] \n" "vld1.s8 {d0}, [%0] \n" "vst1.s8 {d0}, [%1]! \n" : "=r"(img0), // %0 "=r"(tmpptr) // %1 : "0"(img0), "1"(tmpptr) : "memory", "d0" ); img0 += bottom_blob.cstep; #else tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr[4] = img0[4]; tmpptr[5] = img0[5]; tmpptr[6] = img0[6]; tmpptr[7] = img0[7]; tmpptr += 8; img0 += bottom_blob.cstep; #endif // __ARM_NEON } } nn_size = (size - remain_size_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int ii=0; ii<nn_size; ii++) { int i = remain_size_start + ii * 4; const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr[1] = img0[1]; tmpptr[2] = img0[2]; tmpptr[3] = img0[3]; tmpptr += 4; img0 += bottom_blob.cstep; } } remain_size_start += nn_size << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int i=remain_size_start; i<size; i++) { const signed char* img0 = bottom_blob.channel(0); img0 += i; signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); for (int q=0; q<inch; q++) { tmpptr[0] = img0[0]; tmpptr++; img0 += bottom_blob.cstep; } } } // sgemm process int nn_outch = 0; int remain_outch_start = 0; nn_outch = (outch - remain_outch_start) >> 2; #pragma omp parallel for num_threads(opt.num_threads) for (int pp=0; pp<nn_outch; pp++) { int p = remain_outch_start + pp * 4; signed char* outptr0 = top_blob.channel(p); signed char* outptr1 = top_blob.channel(p+1); signed char* outptr2 = top_blob.channel(p+2); signed char* outptr3 = top_blob.channel(p+3); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; const float bias2 = bias ? bias[p+2] : 0.f; const float bias3 = bias ? bias[p+3] : 0.f; const float scale_requant_in0 = scales_requant[2*p]; const float scale_requant_out0 = scales_requant[2*p+1]; const float scale_requant_in1 = scales_requant[2*(p+1)]; const float scale_requant_out1 = scales_requant[2*(p+1)+1]; const float scale_requant_in2 = scales_requant[2*(p+2)]; const float scale_requant_out2 = scales_requant[2*(p+2)+1]; const float scale_requant_in3 = scales_requant[2*(p+3)]; const float scale_requant_out3 = scales_requant[2*(p+3)+1]; #if __ARM_NEON float32x4_t _bias03, _scale_in03, _scale_out03; _bias03[0] = bias0; _bias03[1] = bias1; _bias03[2] = bias2; _bias03[3] = bias3; _scale_in03[0] = scale_requant_in0; _scale_in03[1] = scale_requant_in1; _scale_in03[2] = scale_requant_in2; _scale_in03[3] = scale_requant_in3; _scale_out03[0] = scale_requant_out0; _scale_out03[1] = scale_requant_out1; _scale_out03[2] = scale_requant_out2; _scale_out03[3] = scale_requant_out3; #endif // __ARM_NEON int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "vmov.s32 q10, #0 \n" "vmov.s32 q11, #0 \n" "vmov.s32 q12, #0 \n" "vmov.s32 q13, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d31}, [%4]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d31 \n"// a30-a37 "vmovl.s8 q4, d30 \n"// a20-a27 "vmovl.s8 q15, d29 \n"// a10-a17 "vmovl.s8 q14, d28 \n"// a00-a07 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n"// sum0 = (a00-a07) * k00 "vmlal.s16 q7, d29, d0[0] \n" "vmlal.s16 q8, d28, d0[1] \n"// sum1 = (a00-a07) * k10 "vmlal.s16 q9, d29, d0[1] \n" "vmlal.s16 q10, d28, d0[2] \n"// sum2 = (a00-a07) * k20 "vmlal.s16 q11, d29, d0[2] \n" "vmlal.s16 q12, d28, d0[3] \n"// sum3 = (a00-a07) * k30 "vmlal.s16 q13, d29, d0[3] \n" "vmlal.s16 q6, d30, d1[0] \n"// sum0 += (a10-a17) * k01 "vmlal.s16 q7, d31, d1[0] \n" "vmlal.s16 q8, d30, d1[1] \n"// sum1 += (a10-a17) * k11 "vmlal.s16 q9, d31, d1[1] \n" "vmlal.s16 q10, d30, d1[2] \n"// sum2 += (a10-a17) * k21 "vmlal.s16 q11, d31, d1[2] \n" "vmlal.s16 q12, d30, d1[3] \n"// sum3 += (a10-a17) * k31 "vmlal.s16 q13, d31, d1[3] \n" "vmlal.s16 q6, d8, d2[0] \n"// sum0 += (a20-a27) * k02 "vmlal.s16 q7, d9, d2[0] \n" "vmlal.s16 q8, d8, d2[1] \n"// sum1 += (a20-a27) * k12 "vmlal.s16 q9, d9, d2[1] \n" "vmlal.s16 q10, d8, d2[2] \n"// sum2 += (a20-a27) * k22 "vmlal.s16 q11, d9, d2[2] \n" "vmlal.s16 q12, d8, d2[3] \n"// sum3 += (a20-a27) * k32 "vmlal.s16 q13, d9, d2[3] \n" "vmlal.s16 q6, d10, d3[0] \n"// sum0 += (a30-a37) * k03 "vmlal.s16 q7, d11, d3[0] \n" "vmlal.s16 q8, d10, d3[1] \n"// sum1 += (a30-a37) * k13 "vmlal.s16 q9, d11, d3[1] \n" "vmlal.s16 q10, d10, d3[2] \n"// sum2 += (a30-a37) * k23 "vmlal.s16 q11, d11, d3[2] \n" "vmlal.s16 q12, d10, d3[3] \n"// sum3 += (a30-a37) * k33 "vmlal.s16 q13, d11, d3[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "vmlal.s16 q8, d2, d0[1] \n"// sum1 += (a00-a07) * k10 "vmlal.s16 q9, d3, d0[1] \n" "vmlal.s16 q10, d2, d0[2] \n"// sum2 += (a00-a07) * k20 "vmlal.s16 q11, d3, d0[2] \n" "vmlal.s16 q12, d2, d0[3] \n"// sum3 += (a00-a07) * k30 "vmlal.s16 q13, d3, d0[3] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[0] \n" "vmul.f32 q8, q8, %e17[1] \n" "vmul.f32 q9, q9, %e17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q14 \n" "vadd.f32 q8, q8, q15 \n" "vadd.f32 q9, q9, q15 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" // sum1 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %e18[1] \n" "vmul.f32 q1, q9, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.8 {d16}, [%1]! \n" // sum2 // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" "vcvt.f32.s32 q11, q11 \n" "vcvt.f32.s32 q12, q12 \n" "vcvt.f32.s32 q13, q13 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %f17[0] \n" "vmul.f32 q11, q11, %f17[0] \n" "vmul.f32 q12, q12, %f17[1] \n" "vmul.f32 q13, q13, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, q4 \n" "vadd.f32 q11, q11, q4 \n" "vadd.f32 q12, q12, q5 \n" "vadd.f32 q13, q13, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %f18[0] \n" "vmul.f32 q1, q11, %f18[0] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d20, q0 \n" "vqmovn.s32 d21, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d20, q10 \n" // save top_s8 "vst1.8 {d20}, [%2]! \n" // sum3 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q12, %f18[1] \n" "vmul.f32 q1, q13, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d24, q0 \n" "vqmovn.s32 d25, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d24, q12 \n" // save top_s8 "vst1.8 {d24}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13" ,"q14" ,"q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum0_4 = 0; int sum0_5 = 0; int sum0_6 = 0; int sum0_7 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum1_4 = 0; int sum1_5 = 0; int sum1_6 = 0; int sum1_7 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum2_4 = 0; int sum2_5 = 0; int sum2_6 = 0; int sum2_7 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; int sum3_4 = 0; int sum3_5 = 0; int sum3_6 = 0; int sum3_7 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum0_4 += tmpptr[4] * kptr[0]; sum0_5 += tmpptr[5] * kptr[0]; sum0_6 += tmpptr[6] * kptr[0]; sum0_7 += tmpptr[7] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum1_4 += tmpptr[4] * kptr[1]; sum1_5 += tmpptr[5] * kptr[1]; sum1_6 += tmpptr[6] * kptr[1]; sum1_7 += tmpptr[7] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum2_4 += tmpptr[4] * kptr[2]; sum2_5 += tmpptr[5] * kptr[2]; sum2_6 += tmpptr[6] * kptr[2]; sum2_7 += tmpptr[7] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; sum3_4 += tmpptr[4] * kptr[3]; sum3_5 += tmpptr[5] * kptr[3]; sum3_6 += tmpptr[6] * kptr[3]; sum3_7 += tmpptr[7] * kptr[3]; tmpptr += 8; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr0[4] = sum0_4; outptr0[5] = sum0_5; outptr0[6] = sum0_6; outptr0[7] = sum0_7; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr1[4] = sum1_4; outptr1[5] = sum1_5; outptr1[6] = sum1_6; outptr1[7] = sum1_7; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr2[4] = sum2_4; outptr2[5] = sum2_5; outptr2[6] = sum2_6; outptr2[7] = sum2_7; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr3[4] = sum3_4; outptr3[5] = sum3_5; outptr3[6] = sum3_6; outptr3[7] = sum3_7; outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "vmov.s32 q8, #0 \n" "vmov.s32 q9, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d28-d29}, [%4]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q15, d29 \n"// a20-a23,a30-a33 "vmovl.s8 q14, d28 \n"// a00-a04,a10-a14 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d28, d0[0] \n"// sum0 = (a00-a03) * k00 "vmlal.s16 q7, d28, d0[1] \n"// sum1 = (a00-a03) * k10 "vmlal.s16 q8, d28, d0[2] \n"// sum2 = (a00-a03) * k20 "vmlal.s16 q9, d28, d0[3] \n"// sum3 = (a00-a03) * k30 "vmlal.s16 q6, d29, d1[0] \n"// sum0 += (a10-a13) * k01 "vmlal.s16 q7, d29, d1[1] \n"// sum1 += (a10-a13) * k11 "vmlal.s16 q8, d29, d1[2] \n"// sum2 += (a10-a13) * k21 "vmlal.s16 q9, d29, d1[3] \n"// sum3 += (a10-a13) * k31 "vmlal.s16 q6, d30, d2[0] \n"// sum0 += (a20-a23) * k02 "vmlal.s16 q7, d30, d2[1] \n"// sum1 += (a20-a23) * k12 "vmlal.s16 q8, d30, d2[2] \n"// sum2 += (a20-a23) * k22 "vmlal.s16 q9, d30, d2[3] \n"// sum3 += (a20-a23) * k32 "vmlal.s16 q6, d31, d3[0] \n"// sum0 += (a30-a33) * k03 "vmlal.s16 q7, d31, d3[1] \n"// sum1 += (a30-a33) * k13 "vmlal.s16 q8, d31, d3[2] \n"// sum2 += (a30-a33) * k23 "vmlal.s16 q9, d31, d3[3] \n"// sum3 += (a30-a33) * k33 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #4 \n" "add %5, #4 \n" "vmlal.s16 q6, d2, d0[0] \n"// sum0 += (a00-a03) * k00 "vmlal.s16 q7, d2, d0[1] \n"// sum1 += (a00-a03) * k10 "vmlal.s16 q8, d2, d0[2] \n"// sum2 += (a00-a03) * k20 "vmlal.s16 q9, d2, d0[3] \n"// sum3 += (a00-a03) * k30 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory "vdup.f32 q14, %13 \n" // bias "vdup.f32 q15, %14 \n" // bias "vdup.f32 q4, %15 \n" // bias "vdup.f32 q5, %16 \n" // bias // sum0-1 // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" "vcvt.f32.s32 q8, q8 \n" "vcvt.f32.s32 q9, q9 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q6, q6, %e17[0] \n" "vmul.f32 q7, q7, %e17[1] \n" "vmul.f32 q8, q8, %f17[0] \n" "vmul.f32 q9, q9, %f17[1] \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q15 \n" "vadd.f32 q8, q8, q4 \n" "vadd.f32 q9, q9, q5 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %e18[0] \n" "vmul.f32 q1, q7, %e18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.s32 {d12[0]}, [%0]! \n" "vst1.s32 {d12[1]}, [%1]! \n" // sum1-2 // top_f32 = top_f32 * scale_out "vmul.f32 q0, q8, %f18[0] \n" "vmul.f32 q1, q9, %f18[1] \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d16, q0 \n" "vqmovn.s32 d17, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d16, q8 \n" // save top_s8 "vst1.s32 {d16[0]}, [%2]! \n" "vst1.s32 {d16[1]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "r"(bias0), // %13 "r"(bias1), // %14 "r"(bias2), // %15 "r"(bias3), // %16 "w"(_scale_in03), // %17 "w"(_scale_out03) // %18 : "cc", "memory", "r4", "q0", "q1", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #else int sum0_0 = 0; int sum0_1 = 0; int sum0_2 = 0; int sum0_3 = 0; int sum1_0 = 0; int sum1_1 = 0; int sum1_2 = 0; int sum1_3 = 0; int sum2_0 = 0; int sum2_1 = 0; int sum2_2 = 0; int sum2_3 = 0; int sum3_0 = 0; int sum3_1 = 0; int sum3_2 = 0; int sum3_3 = 0; for (int q=0; q<inch; q++) { sum0_0 += tmpptr[0] * kptr[0]; sum0_1 += tmpptr[1] * kptr[0]; sum0_2 += tmpptr[2] * kptr[0]; sum0_3 += tmpptr[3] * kptr[0]; sum1_0 += tmpptr[0] * kptr[1]; sum1_1 += tmpptr[1] * kptr[1]; sum1_2 += tmpptr[2] * kptr[1]; sum1_3 += tmpptr[3] * kptr[1]; sum2_0 += tmpptr[0] * kptr[2]; sum2_1 += tmpptr[1] * kptr[2]; sum2_2 += tmpptr[2] * kptr[2]; sum2_3 += tmpptr[3] * kptr[2]; sum3_0 += tmpptr[0] * kptr[3]; sum3_1 += tmpptr[1] * kptr[3]; sum3_2 += tmpptr[2] * kptr[3]; sum3_3 += tmpptr[3] * kptr[3]; tmpptr += 4; kptr += 4; } outptr0[0] = sum0_0; outptr0[1] = sum0_1; outptr0[2] = sum0_2; outptr0[3] = sum0_3; outptr1[0] = sum1_0; outptr1[1] = sum1_1; outptr1[2] = sum1_2; outptr1[3] = sum1_3; outptr2[0] = sum2_0; outptr2[1] = sum2_1; outptr2[2] = sum2_2; outptr2[3] = sum2_3; outptr3[0] = sum3_0; outptr3[1] = sum3_1; outptr3[2] = sum3_2; outptr3[3] = sum3_3; outptr0 += 4; outptr1 += 4; outptr2 += 4; outptr3 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4); #if __ARM_NEON asm volatile( // inch loop "veor q6, q6, q6 \n" "veor q7, q7, q7 \n" "veor q8, q8, q8 \n" "veor q9, q9, q9 \n" "vmov.s32 q10, #0 \n" "lsr r4, %12, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%4, #128] \n" "vld1.s8 {d4}, [%4] \n"// tmpr a00,a10,a20,a30 a(inch)(data) "add %4, #4 \n" "vmovl.s8 q2, d4 \n"// a00,a10,a20,a30 "vld1.s8 {d0-d1}, [%5]! \n"// kptr k00-k30,k01-k31,k02-k32,k03-k33 k(outch)(inch) "vmovl.s8 q1, d1 \n"// k02-k32,k03-k33 "vmovl.s8 q0, d0 \n"// k00-k30,k01-k31 "vmlal.s16 q6, d0, d4[0] \n"// (k00-k30) * a00 "vmlal.s16 q7, d1, d4[1] \n"// (k01-k31) * a10 "vmlal.s16 q8, d2, d4[2] \n"// (k02-k32) * a20 "vmlal.s16 q9, d3, d4[3] \n"// (k03-k33) * a30 "subs r4, r4, #1 \n" "bne 0b \n"// end for "vadd.s32 q6, q6, q7 \n" "vadd.s32 q9, q9, q8 \n" "vadd.s32 q10, q6, q9 \n" "1: \n" // remain loop "and r4, %12, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%4] \n"// tmpr a00 a(inch)(data) "vld1.s8 {d0}, [%5] \n"// kptr k00-k30 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %4, #1 \n" "add %5, #4 \n" "vmlal.s16 q10, d0, d2[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q10, q10 \n" // top_f32 = top_f32 * scale_int "vmul.f32 q10, q10, %q14 \n" // top_f32 = top_f32 + bias "vadd.f32 q10, q10, %q13 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q10, %q15 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12[0]}, [%0]! \n" "vst1.8 {d12[1]}, [%1]! \n" "vst1.8 {d12[2]}, [%2]! \n" "vst1.8 {d12[3]}, [%3]! \n" : "=r"(outptr0), // %0 "=r"(outptr1), // %1 "=r"(outptr2), // %2 "=r"(outptr3), // %3 "=r"(tmpptr), // %4 "=r"(kptr) // %5 : "0"(outptr0), "1"(outptr1), "2"(outptr2), "3"(outptr3), "4"(tmpptr), "5"(kptr), "r"(inch), // %12 "w"(_bias03), // %13 "w"(_scale_in03), // %14 "w"(_scale_out03) // %15 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[0] * kptr[1]; sum2 += tmpptr[0] * kptr[2]; sum3 += tmpptr[0] * kptr[3]; tmpptr++; kptr += 4; } outptr0[0] = sum0; outptr1[0] = sum1; outptr2[0] = sum2; outptr3[0] = sum3; outptr0++; outptr1++; outptr2++; outptr3++; #endif // __ARM_NEON } } remain_outch_start += nn_outch << 2; #pragma omp parallel for num_threads(opt.num_threads) for (int p=remain_outch_start; p<outch; p++) { Mat out0 = top_blob.channel(p); signed char* outptr0 = out0; const float bias0 = bias ? bias[p] : 0.f; const float scale_requant_in = scales_requant[2*p]; const float scale_requant_out = scales_requant[2*p+1]; #if __ARM_NEON float32x4_t _bias0 = vdupq_n_f32(bias0); float32x4_t _scale_in = vdupq_n_f32(scale_requant_in); float32x4_t _scale_out = vdupq_n_f32(scale_requant_out); #endif // __ARM_NEON int i = 0; for (; i+7<size; i+=8) { const signed char* tmpptr = tmp.channel(i/8); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "vmov.s32 q7, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%1, #128] \n" "vld1.s8 {d4-d7}, [%1]! \n"// tmpr a00-a07,a10-a17,a20-a27,a30-a37 a(inch)(data) "vmovl.s8 q5, d7 \n"// a30-a37 "vmovl.s8 q4, d6 \n"// a20-a27 "vmovl.s8 q3, d5 \n"// a10-a17 "vmovl.s8 q2, d4 \n"// a00-a07 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d5, d0[0] \n" "vmlal.s16 q6, d6, d0[1] \n"// (a10-a17) * k01 "vmlal.s16 q7, d7, d0[1] \n" "vmlal.s16 q6, d8, d0[2] \n"// (a20-a27) * k02 "vmlal.s16 q7, d9, d0[2] \n" "vmlal.s16 q6, d10, d0[3] \n"// (a30-a37) * k03 "vmlal.s16 q7, d11, d0[3] \n" "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1]! \n"// tmpr a00-a07 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a07) * k00 "vmlal.s16 q7, d3, d0[0] \n" "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" "vcvt.f32.s32 q7, q7 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" "vmul.f32 q7, q7, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" "vadd.f32 q7, q7, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" "vmul.f32 q1, q7, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" "vcvtr.s32.f32 s4, s4 \n" "vcvtr.s32.f32 s5, s5 \n" "vcvtr.s32.f32 s6, s6 \n" "vcvtr.s32.f32 s7, s7 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" "vqmovn.s32 d13, q1 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" // save top_s8 "vst1.8 {d12}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; int sum4 = 0; int sum5 = 0; int sum6 = 0; int sum7 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; sum4 += tmpptr[4] * kptr[0]; sum5 += tmpptr[5] * kptr[0]; sum6 += tmpptr[6] * kptr[0]; sum7 += tmpptr[7] * kptr[0]; tmpptr += 8; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0[4] = sum4; outptr0[5] = sum5; outptr0[6] = sum6; outptr0[7] = sum7; outptr0 += 8; #endif // __ARM_NEON } for (; i+3<size; i+=4) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4); const signed char* kptr = kernel.channel(p/4 + p%4); #if __ARM_NEON asm volatile( // inch loop "vmov.s32 q6, #0 \n" "lsr r4, %6, #2 \n"// r4 = nn = inch >> 2 "cmp r4, #0 \n" "beq 1f \n" "0: \n"// for(; nn != 0; nn--) "pld [%2, #128] \n" "vld1.s8 {d4-d5}, [%1]! \n"// tmpr a00-a03,a10-a13,a20-a23,a30-a33 a(inch)(data) "vmovl.s8 q3, d5 \n"// a20-a23,a30-a33 "vmovl.s8 q2, d4 \n"// a00-a03,a10-a13 "vld1.s8 {d0}, [%2] \n"// kptr k00,k01,k02,k03 k(outch)(inch) "vmovl.s8 q0, d0 \n"// k00,k01,k02,k03 "add %2, #4 \n" "vmlal.s16 q6, d4, d0[0] \n"// (a00-a03) * k00 "vmlal.s16 q6, d5, d0[1] \n"// (a10-a13) * k01 "vmlal.s16 q6, d6, d0[2] \n"// (a20-a23) * k02 "vmlal.s16 q6, d7, d0[3] \n"// (a30-a33) * k03 "subs r4, r4, #1 \n" "bne 0b \n"// end for "1: \n" // remain loop "and r4, %6, #3 \n"// r4 = remain = inch & 3 "cmp r4, #0 \n" "beq 3f \n" "2: \n"// for(; remain != 0; remain--) "vld1.s8 {d2}, [%1] \n"// tmpr a00-a03 a(inch)(data) "vld1.s8 {d0}, [%2] \n"// kptr k00 k(outch)(inch) "vmovl.s8 q1, d2 \n" "vmovl.s8 q0, d0 \n" "add %1, #4 \n" "add %2, #1 \n" "vmlal.s16 q6, d2, d0[0] \n"// (a00-a03) * k00 "subs r4, r4, #1 \n" "bne 2b \n" "3: \n"// store the result to memory // top_s32 -> top_f32 "vcvt.f32.s32 q6, q6 \n" // top_f32 = top_f32 * scale_in "vmul.f32 q6, q6, %q8 \n" // top_f32 = top_f32 + bias "vadd.f32 q6, q6, %q7 \n" // top_f32 = top_f32 * scale_out "vmul.f32 q0, q6, %q9 \n" // top_f32 -> top_s32 "vcvtr.s32.f32 s0, s0 \n" "vcvtr.s32.f32 s1, s1 \n" "vcvtr.s32.f32 s2, s2 \n" "vcvtr.s32.f32 s3, s3 \n" // top_s32 -> top_s16 "vqmovn.s32 d12, q0 \n" // top_s16 -> top_s8 "vqmovn.s16 d12, q6 \n" "vst1.s32 {d12[0]}, [%0]! \n" : "=r"(outptr0), // %0 "=r"(tmpptr), // %1 "=r"(kptr) // %2 : "0"(outptr0), "1"(tmpptr), "2"(kptr), "r"(inch), // %6 "w"(_bias0), // %7 "w"(_scale_in), // %8 "w"(_scale_out) // %9 : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6" ); #else int sum0 = 0; int sum1 = 0; int sum2 = 0; int sum3 = 0; for (int q=0; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; sum1 += tmpptr[1] * kptr[0]; sum2 += tmpptr[2] * kptr[0]; sum3 += tmpptr[3] * kptr[0]; tmpptr += 4; kptr++; } outptr0[0] = sum0; outptr0[1] = sum1; outptr0[2] = sum2; outptr0[3] = sum3; outptr0 += 4; #endif // __ARM_NEON } for (; i<size; i++) { const signed char* tmpptr = tmp.channel(i/8 + (i%8)/4 + i%4); const signed char* kptr = kernel.channel(p/4 + p%4); int q = 0; int sum0 = 0; for (; q<inch; q++) { sum0 += tmpptr[0] * kptr[0]; tmpptr++; kptr++; } outptr0[0] = sum0; outptr0++; } } } #endif
convolution_1x1_packn.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2021 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 conv1x1s1_sgemm_packn_rvv(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; const int size = w * h; Mat bottom_im2col = bottom_blob; bottom_im2col.w = size; bottom_im2col.h = 1; im2col_sgemm_packn_rvv(bottom_im2col, top_blob, kernel, _bias, opt); } static void conv1x1s2_packn_rvv(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { const int packn = csrr_vlenb() / 4; const word_type vl = vsetvl_e32m1(packn); int w = bottom_blob.w; int channels = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; const int tailstep = (w - 2 * outw + w) * packn; Mat bottom_blob_shrinked; bottom_blob_shrinked.create(outw, outh, channels, elemsize, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < channels; p++) { const float* r0 = bottom_blob.channel(p); float* outptr = bottom_blob_shrinked.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { vfloat32m1_t _val = vle32_v_f32m1(r0, vl); vse32_v_f32m1(outptr, _val, vl); r0 += packn * 2; outptr += packn; } r0 += tailstep; } } conv1x1s1_sgemm_packn_rvv(bottom_blob_shrinked, top_blob, kernel, _bias, opt); }
detach_nested_task.c
// RUN: %libomp-compile-and-run // Checked gcc 10.1 still does not support detach clause on task construct. // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8, gcc-9, gcc-10 // gcc 11 introduced detach clause, but gomp interface in libomp has no support // XFAIL: gcc-11, gcc-12 // clang supports detach clause since version 11. // UNSUPPORTED: clang-10, clang-9, clang-8, clang-7 // icc compiler does not support detach clause. // UNSUPPORTED: icc // The outer detachable task creates multiple child tasks with dependencies // when the last inner task incremented ret, the task calls omp_fulfill_event // to release the outer task. #include <omp.h> #include <stdio.h> int *buf; int foo(int n) { int ret = 0; for (int i = 0; i < n; ++i) { omp_event_handle_t event; #pragma omp task detach(event) firstprivate(i,n) shared(ret) { for (int j = 0; j < n; ++j) { #pragma omp task firstprivate(event,i,j,n) shared(ret) default(none) depend(out:ret) { //printf("Task %i, %i: %i\n", i, j, omp_get_thread_num()); #pragma omp atomic ret++; #if _OPENMP if (j == n-1) { //printf("Task %i, %i: omp_fulfill_event()\n", i, j); omp_fulfill_event(event); } #endif } } } } // the taskwait only guarantees the outer tasks to complete. #pragma omp taskwait return ret; } int main() { int ret; #pragma omp parallel #pragma omp master { ret = foo(8); } printf("%i\n", ret); //CHECK: 64 return 0; }
GB_unaryop__abs_uint8_int64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_uint8_int64 // op(A') function: GB_tran__abs_uint8_int64 // C type: uint8_t // A type: int64_t // cast: uint8_t cij = (uint8_t) aij // unaryop: cij = aij #define GB_ATYPE \ int64_t #define GB_CTYPE \ uint8_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ 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_ABS || GxB_NO_UINT8 || GxB_NO_INT64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_uint8_int64 ( uint8_t *restrict Cx, const int64_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_uint8_int64 ( GrB_Matrix C, const GrB_Matrix A, int64_t **Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
mri-q.c
/*************************************************************************** * * (C) Copyright 2007 The Board of Trustees of the * University of Illinois * All Rights Reserved * ***************************************************************************/ /*************************************************************************** * * This benchmark was adapted to run on GPUs with OpenMP 4.0 pragmas * and OpenCL driver implemented in gpuclang 2.0 (based on clang 3.5) * * Marcio M Pereira <mpereira@ic.unicamp.br> * ***************************************************************************/ /* * C code for creating the Q data structure for fast convolution-based * Hessian multiplication for arbitrary k-space trajectories. * * Inputs: * kx - VECTOR of kx values, same length as ky and kz * ky - VECTOR of ky values, same length as kx and kz * kz - VECTOR of kz values, same length as kx and ky * x - VECTOR of x values, same length as y and z * y - VECTOR of y values, same length as x and z * z - VECTOR of z values, same length as x and y * phi - VECTOR of the Fourier transform of the spatial basis * function, evaluated at [kx, ky, kz]. Same length as kx, ky, and kz. */ /* * === NOTE === * * The Polyhedral optmizations restricts the class of loops it can manipulate * to sequences of imperfectly nested loops with particular constraints on the * loop bound and array subscript expressions. * * To allow this optimization we fixed the problem size with __STATIC__ tag * comment this tag to use original version. * * Recommended gpuclang options: * -O2 -lm -ffast-math -opt-poly-all */ #ifndef __STATIC__ #define __STATIC__ #endif #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <sys/time.h> #ifdef __APPLE__ #include <sys/malloc.h> #include <machine/endian.h> #else #include <endian.h> #include <malloc.h> #endif #if __BYTE_ORDER != __LITTLE_ENDIAN # error "File I/O is not implemented for this system: wrong endianness." #endif #include "../../common/parboil.h" #include "../../common/polybenchUtilFuncts.h" #define ERROR_THRESHOLD 0.5 #define GPU_DEVICE 1 #define PI 3.1415926535897932384626433832795029f #define PIx2 6.2831853071795864769252867665590058f #define MIN(X,Y) ((X) < (Y) ? (X) : (Y)) #ifdef __STATIC__ // Define statically the problem size #define NK 2048 // K_ELEMS_PER_GRID #define NX 262144 #else int NK, NX; #endif double t_start, t_end, t_start_GPU, t_end_GPU; float *Qr_GPU, *Qi_GPU; /* Q signal (complex) */ float *Qr_CPU, *Qi_CPU; /* Q signal (complex) */ typedef float DATA_TYPE; struct kValues { float Kx; float Ky; float Kz; float PhiMag; }; void ComputePhiMagCPU(float* phiR, float* phiI, float* phiMag) { int indexK = 0; for (indexK = 0; indexK < NK; indexK++) { float real = phiR[indexK]; float imag = phiI[indexK]; phiMag[indexK] = real*real + imag*imag; } } void ComputeQGPU(struct kValues *kVals, float* x, float* y, float* z, float *Qr, float *Qi) { int indexK, indexX; #pragma omp target device(1) #pragma omp target map(to: kVals[:NK], x[:NX], y[:NX], z[:NX]) map(tofrom: Qr[:NX], Qi[:NX]) for (indexK = 0; indexK < NK; indexK++) { #pragma omp parallel for for (indexX = 0; indexX < NX; indexX++) { float expArg = PIx2 * (kVals[indexK].Kx * x[indexX] + kVals[indexK].Ky * y[indexX] + kVals[indexK].Kz * z[indexX]); float cosArg = cos(expArg); float sinArg = sin(expArg); float phi = kVals[indexK].PhiMag; Qr[indexX] += phi * cosArg; Qi[indexX] += phi * sinArg; } } } void ComputeQCPU(struct kValues *kVals, float* x, float* y, float* z, float *Qr, float *Qi) { int indexK, indexX; for (indexK = 0; indexK < NK; indexK++) { for (indexX = 0; indexX < NX; indexX++) { float expArg = PIx2 * (kVals[indexK].Kx * x[indexX] + kVals[indexK].Ky * y[indexX] + kVals[indexK].Kz * z[indexX]); float cosArg = cos(expArg); float sinArg = sin(expArg); float phi = kVals[indexK].PhiMag; Qr[indexX] += phi * cosArg; Qi[indexX] += phi * sinArg; } } } void createDataStructsCPU(float** phiMag, float** Qr, float** Qi) { *phiMag = (float* ) malloc(NK * sizeof(float)); *Qr = (float*) malloc(NX * sizeof (float)); memset((void *)*Qr, 0, NX * sizeof(float)); *Qi = (float*) malloc(NX * sizeof (float)); memset((void *)*Qi, 0, NX * sizeof(float)); } void inputData(char* fName, int* _numK, int* _numX, float** kx, float** ky, float** kz, float** x, float** y, float** z, float** phiR, float** phiI) { int numK, numX; FILE* fid = fopen(fName, "r"); if (fid == NULL) { fprintf(stderr, "Cannot open input file\n"); exit(-1); } fread (&numK, sizeof (int), 1, fid); *_numK = numK; fread (&numX, sizeof (int), 1, fid); *_numX = numX; *kx = (float *) malloc(numK * sizeof (float)); fread (*kx, sizeof (float), numK, fid); *ky = (float *) malloc(numK * sizeof (float)); fread (*ky, sizeof (float), numK, fid); *kz = (float *) malloc(numK * sizeof (float)); fread (*kz, sizeof (float), numK, fid); *x = (float *) malloc(numX * sizeof (float)); fread (*x, sizeof (float), numX, fid); *y = (float *) malloc(numX * sizeof (float)); fread (*y, sizeof (float), numX, fid); *z = (float *) malloc(numX * sizeof (float)); fread (*z, sizeof (float), numX, fid); *phiR = (float *) malloc(numK * sizeof (float)); fread (*phiR, sizeof (float), numK, fid); *phiI = (float *) malloc(numK * sizeof (float)); fread (*phiI, sizeof (float), numK, fid); fclose (fid); } void compareResults(DATA_TYPE *A, DATA_TYPE *A_GPU, DATA_TYPE *B, DATA_TYPE *B_GPU) { int i,fail=0; for (i=0; i < NX; i++) { if (percentDiff(A[i], A_GPU[i]) > ERROR_THRESHOLD) { fail++; } } for (i=0; i < NX; i++) { if (percentDiff(B[i], B_GPU[i]) > ERROR_THRESHOLD) { fail++; } } // print results printf(">>\n Non-Matching CPU-GPU Outputs Beyond Error Threshold of %4.2f%s: %d\n", ERROR_THRESHOLD, "%", fail); } double mriqGPU(int argc, char *argv[]) { int numX, numK; /* Number of X and K values */ int original_numK; /* Number of K values in input file */ float *kx, *ky, *kz; /* K trajectory (3D vectors) */ float *x, *y, *z; /* X coordinates (3D vectors) */ float *phiR, *phiI; /* Phi values (complex) */ float *phiMag; /* Magnitude of Phi */ struct kValues* kVals; struct pb_Parameters *params; /* Read command line */ params = pb_ReadParameters(&argc, argv); if ((params->inpFiles[0] == NULL) || (params->inpFiles[1] != NULL)) { fprintf(stderr, "Expecting one input filename\n"); exit(-1); } /* Read in data */ fprintf(stdout, "<< Reading data ... "); inputData(params->inpFiles[0], &original_numK, &numX, &kx, &ky, &kz, &x, &y, &z, &phiR, &phiI); /* Reduce the number of k-space samples if a number is given * on the command line */ if (argc < 2) numK = original_numK; else { int inputK; char *end; inputK = strtol(argv[1], &end, 10); if (end == argv[1]) { fprintf(stderr, "Expecting an integer parameter\n"); exit(-1); } numK = MIN(inputK, original_numK); } #ifndef __STATIC__ NK = numK; NX = numX; #endif /* Create CPU data structures */ createDataStructsCPU(&phiMag, &Qr_GPU, &Qi_GPU); ComputePhiMagCPU(phiR, phiI, phiMag); kVals = (struct kValues*)calloc(numK, sizeof (struct kValues)); int k; for (k = 0; k < numK; k++) { kVals[k].Kx = kx[k]; kVals[k].Ky = ky[k]; kVals[k].Kz = kz[k]; kVals[k].PhiMag = phiMag[k]; } fprintf(stdout, ">>\n<< Start computation on GPU... "); t_start_GPU = rtclock(); ComputeQGPU(kVals, x, y, z, Qr_GPU, Qi_GPU); t_end_GPU = rtclock(); free (kx); free (ky); free (kz); free (x); free (y); free (z); free (phiR); free (phiI); free (phiMag); free (kVals); return t_end_GPU - t_start_GPU; } double mriqCPU(int argc, char *argv[]) { int numX, numK; /* Number of X and K values */ int original_numK; /* Number of K values in input file */ float *kx, *ky, *kz; /* K trajectory (3D vectors) */ float *x, *y, *z; /* X coordinates (3D vectors) */ float *phiR, *phiI; /* Phi values (complex) */ float *phiMag; /* Magnitude of Phi */ struct kValues* kVals; struct pb_Parameters *params; /* Read command line */ params = pb_ReadParameters(&argc, argv); if ((params->inpFiles[0] == NULL) || (params->inpFiles[1] != NULL)) { fprintf(stderr, "Expecting one input filename\n"); exit(-1); } /* Read in data */ inputData(params->inpFiles[0], &original_numK, &numX, &kx, &ky, &kz, &x, &y, &z, &phiR, &phiI); /* Reduce the number of k-space samples if a number is given * on the command line */ if (argc < 2) numK = original_numK; else { int inputK; char *end; inputK = strtol(argv[1], &end, 10); if (end == argv[1]) { fprintf(stderr, "Expecting an integer parameter\n"); exit(-1); } numK = MIN(inputK, original_numK); } #ifndef __STATIC__ NK = numK; NX = numX; #endif /* Create CPU data structures */ createDataStructsCPU(&phiMag, &Qr_CPU, &Qi_CPU); ComputePhiMagCPU(phiR, phiI, phiMag); kVals = (struct kValues*)calloc(numK, sizeof (struct kValues)); int k; for (k = 0; k < numK; k++) { kVals[k].Kx = kx[k]; kVals[k].Ky = ky[k]; kVals[k].Kz = kz[k]; kVals[k].PhiMag = phiMag[k]; } fprintf(stdout, "\n<< Start computation on CPU... "); t_start = rtclock(); ComputeQCPU(kVals, x, y, z, Qr_CPU, Qi_CPU); t_end = rtclock(); free (kx); free (ky); free (kz); free (x); free (y); free (z); free (phiR); free (phiI); free (phiMag); free (kVals); return t_end - t_start; } int main (int argc, char *argv[]) { double t_GPU, t_CPU; fprintf(stdout, "<< Creating the Q data structure for fast convolution-based\n"); fprintf(stdout, " Hessian multiplication for arbitrary k-space trajectories.>>\n"); fprintf(stdout, "<< Elements per Grid: 2048 >>\n\n"); fprintf(stdout, " for (indexK = 0; indexK < 2048; indexK++) \n"); fprintf(stdout, " for (indexX = 0; indexX < 262144; indexX++) { \n"); fprintf(stdout, " float expArg = PIx2 * (kVals[indexK].Kx * x[indexX] +\n"); fprintf(stdout, " kVals[indexK].Ky * y[indexX] + \n"); fprintf(stdout, " kVals[indexK].Kz * z[indexX]);\n"); fprintf(stdout, " float cosArg = cos(expArg);\n"); fprintf(stdout, " float sinArg = sin(expArg);\n"); fprintf(stdout, " float phi = kVals[indexK].PhiMag;\n"); fprintf(stdout, " Qr[indexX] += phi * cosArg;\n"); fprintf(stdout, " Qi[indexX] += phi * sinArg;\n"); fprintf(stdout, " } \n\n"); t_GPU = mriqGPU(argc, argv); fprintf(stdout, ">>\n GPU Runtime: %0.6lfs\n", t_GPU); t_CPU = mriqCPU(argc, argv); fprintf(stdout, ">>\n CPU Runtime: %0.6lfs\n", t_CPU); fprintf(stdout, "\n<< Comparing Results..."); compareResults(Qr_CPU, Qr_GPU, Qi_CPU, Qi_GPU); free(Qr_GPU); free(Qi_GPU); free(Qr_CPU); free(Qi_CPU); return 0; }
GB_binop__bget_uint64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_uint64) // A.*B function (eWiseMult): GB (_AemultB_08__bget_uint64) // A.*B function (eWiseMult): GB (_AemultB_02__bget_uint64) // A.*B function (eWiseMult): GB (_AemultB_04__bget_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_uint64) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__bget_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_uint64) // C=scalar+B GB (_bind1st__bget_uint64) // C=scalar+B' GB (_bind1st_tran__bget_uint64) // C=A+scalar GB (_bind2nd__bget_uint64) // C=A'+scalar GB (_bind2nd_tran__bget_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = GB_BITGET (aij, bij, uint64_t, 64) #define GB_ATYPE \ uint64_t #define GB_BTYPE \ uint64_t #define GB_CTYPE \ uint64_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) \ uint64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_BITGET (x, y, uint64_t, 64) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_UINT64 || GxB_NO_BGET_UINT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__bget_uint64) ( 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__bget_uint64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__bget_uint64) ( 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 uint64_t uint64_t bwork = (*((uint64_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 uint64_t *restrict Cx = (uint64_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 uint64_t *restrict Cx = (uint64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_uint64) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool 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__bget_uint64) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bget_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__bget_uint64) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bget_uint64) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__bget_uint64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t x = (*((uint64_t *) x_input)) ; uint64_t *Bx = (uint64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITGET (x, bij, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_uint64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint64_t *Cx = (uint64_t *) Cx_output ; uint64_t *Ax = (uint64_t *) Ax_input ; uint64_t y = (*((uint64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint64_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITGET (aij, y, uint64_t, 64) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, uint64_t, 64) ; \ } GrB_Info GB (_bind1st_tran__bget_uint64) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t x = (*((const uint64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (aij, y, uint64_t, 64) ; \ } GrB_Info GB (_bind2nd_tran__bget_uint64) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
serial_tree_learner.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #define LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #include <LightGBM/dataset.h> #include <LightGBM/tree.h> #include <LightGBM/tree_learner.h> #include <LightGBM/cuda/vector_cudahost.h> #include <LightGBM/utils/array_args.h> #include <LightGBM/utils/json11.h> #include <LightGBM/utils/random.h> #include <string> #include <cmath> #include <cstdio> #include <memory> #include <random> #include <vector> #include "col_sampler.hpp" #include "data_partition.hpp" #include "feature_histogram.hpp" #include "leaf_splits.hpp" #include "monotone_constraints.hpp" #include "split_info.hpp" #ifdef USE_GPU // Use 4KBytes aligned allocator for ordered gradients and ordered hessians when GPU is enabled. // This is necessary to pin the two arrays in memory and make transferring faster. #include <boost/align/aligned_allocator.hpp> #endif namespace LightGBM { using json11::Json; /*! \brief forward declaration */ class CostEfficientGradientBoosting; /*! * \brief Used for learning a tree by single machine */ class SerialTreeLearner: public TreeLearner { public: friend CostEfficientGradientBoosting; explicit SerialTreeLearner(const Config* config); ~SerialTreeLearner(); void Init(const Dataset* train_data, bool is_constant_hessian) override; void ResetTrainingData(const Dataset* train_data, bool is_constant_hessian) override { ResetTrainingDataInner(train_data, is_constant_hessian, true); } void ResetIsConstantHessian(bool is_constant_hessian) override { share_state_->is_constant_hessian = is_constant_hessian; } virtual void ResetTrainingDataInner(const Dataset* train_data, bool is_constant_hessian, bool reset_multi_val_bin); void ResetConfig(const Config* config) override; inline void SetForcedSplit(const Json* forced_split_json) override { if (forced_split_json != nullptr && !forced_split_json->is_null()) { forced_split_json_ = forced_split_json; } else { forced_split_json_ = nullptr; } } Tree* Train(const score_t* gradients, const score_t *hessians) override; Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override; Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred, const score_t* gradients, const score_t* hessians) override; void SetBaggingData(const Dataset* subset, const data_size_t* used_indices, data_size_t num_data) override { if (subset == nullptr) { data_partition_->SetUsedDataIndices(used_indices, num_data); share_state_->is_use_subrow = false; } else { ResetTrainingDataInner(subset, share_state_->is_constant_hessian, false); share_state_->is_use_subrow = true; share_state_->is_subrow_copied = false; share_state_->bagging_use_indices = used_indices; share_state_->bagging_indices_cnt = num_data; } } void AddPredictionToScore(const Tree* tree, double* out_score) const override { if (tree->num_leaves() <= 1) { return; } CHECK_LE(tree->num_leaves(), data_partition_->num_leaves()); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < tree->num_leaves(); ++i) { double output = static_cast<double>(tree->LeafOutput(i)); data_size_t cnt_leaf_data = 0; auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); for (data_size_t j = 0; j < cnt_leaf_data; ++j) { out_score[tmp_idx[j]] += output; } } } void RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter, data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const override; /*! \brief Get output of parent node, used for path smoothing */ double GetParentOutput(const Tree* tree, const LeafSplits* leaf_splits) const; protected: void ComputeBestSplitForFeature(FeatureHistogram* histogram_array_, int feature_index, int real_fidx, int8_t is_feature_used, int num_data, const LeafSplits* leaf_splits, SplitInfo* best_split, double parent_output); void GetShareStates(const Dataset* dataset, bool is_constant_hessian, bool is_first_time); void RecomputeBestSplitForLeaf(int leaf, SplitInfo* split); /*! * \brief Some initial works before training */ virtual void BeforeTrain(); /*! * \brief Some initial works before FindBestSplit */ virtual bool BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf); virtual void FindBestSplits(const Tree* tree); virtual void ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract, const Tree*); /*! * \brief Partition tree and data according best split. * \param tree Current tree, will be splitted on this function. * \param best_leaf The index of leaf that will be splitted. * \param left_leaf The index of left leaf after splitted. * \param right_leaf The index of right leaf after splitted. */ inline virtual void Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf) { SplitInner(tree, best_leaf, left_leaf, right_leaf, true); } void SplitInner(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf, bool update_cnt); /* Force splits with forced_split_json dict and then return num splits forced.*/ int32_t ForceSplits(Tree* tree, int* left_leaf, int* right_leaf, int* cur_depth); /*! * \brief Get the number of data in a leaf * \param leaf_idx The index of leaf * \return The number of data in the leaf_idx leaf */ inline virtual data_size_t GetGlobalDataCountInLeaf(int leaf_idx) const; /*! \brief number of data */ data_size_t num_data_; /*! \brief number of features */ int num_features_; /*! \brief training data */ const Dataset* train_data_; /*! \brief gradients of current iteration */ const score_t* gradients_; /*! \brief hessians of current iteration */ const score_t* hessians_; /*! \brief training data partition on leaves */ std::unique_ptr<DataPartition> data_partition_; /*! \brief pointer to histograms array of parent of current leaves */ FeatureHistogram* parent_leaf_histogram_array_; /*! \brief pointer to histograms array of smaller leaf */ FeatureHistogram* smaller_leaf_histogram_array_; /*! \brief pointer to histograms array of larger leaf */ FeatureHistogram* larger_leaf_histogram_array_; /*! \brief store best split points for all leaves */ std::vector<SplitInfo> best_split_per_leaf_; /*! \brief store best split per feature for all leaves */ std::vector<SplitInfo> splits_per_leaf_; /*! \brief stores minimum and maximum constraints for each leaf */ std::unique_ptr<LeafConstraintsBase> constraints_; /*! \brief stores best thresholds for all feature for smaller leaf */ std::unique_ptr<LeafSplits> smaller_leaf_splits_; /*! \brief stores best thresholds for all feature for larger leaf */ std::unique_ptr<LeafSplits> larger_leaf_splits_; #ifdef USE_GPU /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_; #elif USE_CUDA /*! \brief gradients of current iteration, ordered for cache optimized */ std::vector<score_t, CHAllocator<score_t>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized */ std::vector<score_t, CHAllocator<score_t>> ordered_hessians_; #else /*! \brief gradients of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_; #endif /*! \brief used to cache historical histogram to speed up*/ HistogramPool histogram_pool_; /*! \brief config of tree learner*/ const Config* config_; ColSampler col_sampler_; const Json* forced_split_json_; std::unique_ptr<TrainingShareStates> share_state_; std::unique_ptr<CostEfficientGradientBoosting> cegb_; }; inline data_size_t SerialTreeLearner::GetGlobalDataCountInLeaf(int leaf_idx) const { if (leaf_idx >= 0) { return data_partition_->leaf_count(leaf_idx); } else { return 0; } } } // namespace LightGBM #endif // LightGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_
module_bl_mynn_boulac_length_impl.h
#ifndef __MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_H__ #define __MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_H__ // File version granularity. #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_VERSION_MAJOR #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_VERSION_MAJOR 1 #endif #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_VERSION_MINOR #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_VERSION_MINOR 0 #endif #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_PATCH_VERSION #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_PATCH_VERSION 0 #endif #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_CREATE_DATE #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_CREATE_DATE "Date: 15-11-2016 , Time: 11:54 AM GMT+2" #endif // Set this value to successful build date/time. #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_BUILD_DATE #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_BUILD_DATE "" #endif #ifndef MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_AUTHOR #define MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_AUTHOR "Name: Bernard Gingold , e-mail: beniekg@gmail.com" #endif #include "module_bl_mynn_F90_iface.h" #include "PhysLib_Config.h" #include "std_headers.h" namespace wrf_phys_wrappers { namespace module_bl_mynn { template<typename R32 = float, typename I32 = int > struct Wrap_Boulac_Length { /************************************ Constructors and Destructor. *************************************/ /* @Purpose: Default Constructor - explicitly default. */ Wrap_Boulac_Length() = default; /* @Purpose: 1st 'main' Constructor which purpose is to allocate and initialize scalar and array members. Array members are zero-filled. Caller must later initialize input arrays to correct physical state. */ Wrap_Boulac_Length(_In_ const I32 kts, _In_ const I32 kte) : m_kts{ kts }, m_kte{ kte }, m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qtke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb2{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } { if (0 >= (m_kte - m_kts)) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Invalid array size 1st Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Lower range value m_kts: " << m_kts << "\n"; std::cerr << "Upper range value m_kte: " << m_kte << "\n"; std::cerr << "Range value difference: " << m_kte - m_kts << "\n"; std::cerr << "Cannot recover --> calling exit(-1)!!\n"; std::exit(-1); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_zw)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 1st Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_zw)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { (&this->m_zw)[idx][i] = 0.f; } } const int top = m_kte + 1; (&this->m_zw)[0][top] = 0.f; #else // You must not #undef 'USE_AUTO_VECTORIZATION' macro!! #if defined (USE_AUTO_VECTORIZATION) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { (&this->m_zw)[idx][i] = 0.f; } } const int top = m_kte + 1; (&this->m_zw)[0][top] = 0.f; #endif #endif } /* @Purpose: 2nd 'main' Constructor which purpose is to allocate and initialize scalar and array members. Array output members are zero-filled. Caller must pass initialized input arrays to correct physical state. */ Wrap_Boulac_Length(_In_ const I32 kts, _In_ const I32 kte, _In_ R32* __restrict const zw, _In_ R32* __restrict const dz, _In_ R32* __restrict const qtke, _In_ R32* __restrict const theta) : m_kts{ kts }, m_kte{ kte }, m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qtke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb2{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } { if (0 >= (m_kte - m_kts)) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Invalid array size 2nd Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Lower range value m_kts: " << m_kts << "\n"; std::cerr << "Upper range value m_kte: " << m_kte << "\n"; std::cerr << "Range value difference: " << m_kte - m_kts << "\n"; std::cerr << "Cannot recover --> calling exit(-1)!!\n"; std::exit(-1); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_zw)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_zw)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } if (zw == NULL || dz == NULL || qtke == NULL || theta == NULL ) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in 2nd Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "One or more caller's arrays contains invalid pointer!!\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int i = m_kts; i != m_kte; ++i) { m_zw[i] = zw[i]; m_dz[i] = dz[i]; m_qtke[i] = qtke[i]; m_theta[i] = theta[i]; m_lb1[i] = 0.f; m_lb2[i] = 0.f; } const int top = m_kte + 1; m_zw[top] = zw[top]; #else #if defined (USE_AUTO_VECTORIZATION) #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { m_zw[i] = zw[i]; m_dz[i] = dz[i]; m_qtke[i] = qtke[i]; m_theta[i] = theta[i]; m_lb1[i] = 0.f; m_lb2[i] = 0.f; } const int top = m_kte + 1; m_zw[top] = zw[top]; #endif #endif } /* @Purpose: Copy Constructor implements deep copy semantics. */ Wrap_Boulac_Length(_In_ const Wrap_Boulac_Length &x) : m_kts{ x.m_kts }, m_kte{ x.m_kte }, m_zw{ reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)), align32B)) }, m_dz{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_qtke{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_theta{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb1{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) }, m_lb2{ reinterpret_cast<R32*>(_mm_malloc((m_kte * sizeof(R32)), align32B)) } { for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_zw)[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy-Ctor: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << (&this->m_zw)[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { (&this->m_zw)[idx][i] = (&x.m_zw)[idx][i]; } } const int top = m_kte + 1; (&this->m_zw)[0][top] = (&x.m_zw)[0][top]; #else #if defined (USE_AUTO_VECTORIZATION) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { (&this->m_zw)[idx][i] = (&x.m_zw)[idx][i]; } } const int top = m_kte + 1; (&this->m_zw)[0][top] = (&x.m_zw)[0][top]; #endif #endif } /* @Purpose: Move Constructor implements shallow copy semantics. */ Wrap_Boulac_Length(_In_ Wrap_Boulac_Length &&x) : m_kts{ x.m_kts }, m_kte{ x.m_kte }{ for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_zw)[i] = (&x.m_zw)[i]; } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&x.m_zw)[i] = NULL; } x.m_kts = 0; x.m_kte = 0; } /* @Purpose: Class Destructor. */ ~Wrap_Boulac_Length() { for (int i{ 0 }; i != this->m_totArrays; ++i) { if ((&this->m_zw)[i]) { _mm_free((&this->m_zw)[i]); } } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_zw)[i] = NULL; } m_kts = 0; m_kte = 0; } /* @Purpose: Copy-assign Operator implements deep copy semantics. */ Wrap_Boulac_Length & operator=(_In_ const Wrap_Boulac_Length &x) { if (this == &x) return (*this); m_kts = x.m_kts; m_kte = x.m_kte; constexpr int ntPtrs1D{6}; R32 *tPtrs1D[ntPtrs1D] = {}; for (int i{ 0 }; i != this->m_totArrays; ++i) { tPtrs1D[i] = reinterpret_cast<R32*>(_mm_malloc(((m_kte + 1) * sizeof(R32)),align32B)); } for (int i{ 0 }; i != this->m_totArrays; ++i) { if (tPtrs1D[i] == NULL) { std::cerr << "[" << __DATE__ << ":" << __TIME__ << "]" << "FATAL ERROR: Memory allocation failure in Copy Operator: 'Wrap_Boulac_Length'!!\n"; std::cerr << "at " << __FILE__ << ":" << __LINE__ << "(" << std::hex << "0x" << __FUNCTIONW__ << ")" << "\n"; std::cerr << "***** ERROR-DETAILS ***** \n"; std::cerr << "Failure detected at index: " << i << " heap address: " << std::hex << "0x" << tPtrs1D[i] << "\n"; std::cerr << "Cannot recover, hence on first failure occurrence --> calling exit(-1)!!\n"; std::exit(-1); } } #if defined (USE_ICL_OPENMP) && \ OPENMP_CURR_VER >= 40 #pragma omp parallel for if(m_kte >= (1 << 16)) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { tPtrs1D[idx][i] = (&x.m_zw)[idx][i]; } } const int top = m_kte + 1; tPtrs1D[0][top] = (&x.m_zw)[0][top]; for(int i {0}; i != this->m_totArrays; ++i) { _mm_free((&this->m_zw)[i]); } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_zw)[i] = tPtrs1D[i]; } return (*this); #else #if defined (USE_AUTO_VECTORIZATION) for (int idx = 0; idx != this->m_totArrays; ++idx) { #pragma ivdep #pragma simd #pragma unroll(UNROLL_4X) for (int i = m_kts; i != m_kte; ++i) { tPtrs1D[idx][i] = (&x.m_zw)[idx][i]; } } const int top = m_kte + 1; tPtrs1D[0][top] = (&x.m_zw)[0][top]; for (int i{ 0 }; i != this->m_totArrays; ++i) { _mm_free((&this->m_zw)[i]); } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_zw)[i] = tPtrs1D[i]; } return (*this); #endif #endif } /* @Purpose: Move-assign Operator implements shallow copy semantics. */ Wrap_Boulac_Length & operator=(_In_ Wrap_Boulac_Length &&x) { if (this == &x) return (*this); m_kts = x.m_kts; m_kte = x.m_kte; for (int i{ 0 }; i != this->m_totArrays; ++i) { _mm_free((&this->m_zw)[i]); } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&this->m_zw)[i] = (&x.m_zw)[i]; } for (int i{ 0 }; i != this->m_totArrays; ++i) { (&x.m_zw)[i] = NULL; } x.m_kts = 0; x.m_kte = 0; return (*this); } /* @Purpose: Call Fortran 90 'BOULAC_LENGTH' subroutine. */ void Call_Boulac_Length() { MODULE_BL_MYNN_mp_BOULAC_LENGTH(&this->m_kts, &this->m_kte, &this->m_zw[0], &this->m_dz[0], &this->m_qtke[0], &this->m_theta[0], &this->m_lb1[0], &this->m_lb2[0]); } /* @Purpose: Member variables. */ // Scalars - Input. I32 m_kts; I32 m_kte; // Arrays 1D - Input. _Field_size_(m_kte + 1) R32* __restrict m_zw; _Field_size_(m_kte) R32* __restrict m_dz; _Field_size_(m_kte) R32* __restrict m_qtke; _Field_size_(m_kte) R32* __restrict m_theta; // Arrays 1D - Output. _Field_size_(m_kte) R32* __restrict m_lb1; // the minimum of the length up and length down _Field_size_(m_kte) R32* __restrict m_lb2; // the average of the length up and length down static const int m_totArrays = 6; }; } } #endif /*__MODULE_BL_MYNN_BOULAC_LENGTH_IMPL_H__*/
vednnMaxPoolingForward.c
#include <stdint.h> #include "vednnMaxPoolingForward.h" #ifdef VEDNN_USE_OPENMP #include <stdint.h> #include <omp.h> extern int __vednn_omp_num_threads ; #endif static inline vednnError_t vednnMaxPoolingForward_wrapper( vednnMaxPoolForward_t pFunc, const vednnTensorParam_t *pParamIn, const void *pDataIn, const vednnTensorParam_t *pParamOut, void *pDataOut, const vednnPoolingParam_t *pParamPool ) { #ifdef VEDNN_USE_OPENMP if ( __vednn_omp_num_threads == 1 ) { return pFunc(pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; } else { vednnError_t rc = VEDNN_SUCCESS ; #pragma omp parallel reduction(|:rc) { int64_t nthreads = omp_get_num_threads() ; int64_t threadid = omp_get_thread_num() ; int64_t allBatch = pParamIn->batch ; int64_t nBatch = allBatch / nthreads ; int64_t remain = allBatch % nthreads ; int64_t batchBegin = nBatch * threadid + ( threadid < remain ? threadid : remain ) ; int64_t myBatch = nBatch + ( threadid < remain ? 1 : 0 ) ; if( myBatch == 0 ) { rc |= VEDNN_SUCCESS ; } else { vednnTensorParam_t _pParamIn = *pParamIn ; _pParamIn.batch = myBatch ; vednnTensorParam_t _pParamOut = *pParamOut ; _pParamOut.batch = myBatch ; float* _pDataIn = ((float *)pDataIn) + batchBegin * pParamIn->channel * pParamIn->height * pParamIn->width ; float* _pDataOut = ((float *)pDataOut) + batchBegin * pParamOut->channel * pParamOut->height * pParamOut->width ; rc |= pFunc(&_pParamIn, (void*)_pDataIn, &_pParamOut, (void*) _pDataOut, pParamPool) ; } } return rc ; } #else return pFunc(pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; #endif } /* ----------------------------------------------------------------------- */ vednnError_t vednnMaxPoolingForward( const vednnTensorParam_t *pParamIn, const void *pDataIn, const vednnTensorParam_t *pParamOut, void *pDataOut, const vednnPoolingParam_t *pParamPool ) { // [todo] add variations if( pParamPool->padHeight == 0 && pParamPool->padWidth == 0 && pParamPool->strideHeight == pParamPool->windowHeight && pParamPool->strideWidth == pParamPool->windowWidth && pParamOut->height*pParamPool->strideHeight <= pParamIn->height && pParamOut->width*pParamPool->strideWidth == pParamIn->width ) { if( pParamOut->width <= 128 ) { if( (pParamPool->windowWidth & 0x01) == 0 && (((uint64_t)pDataIn) & 0x07) == 0 ) { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingForward_regular_ww2X_owU128_ialigned, pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingForward_regular_owU128, pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; } } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingForward_regular, pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; } } else { return vednnMaxPoolingForward_wrapper( vednnMaxPoolingForward_default, pParamIn, pDataIn, pParamOut, pDataOut, pParamPool ) ; } }
test_utils.h
/* * Copyright (c) 2019, NVIDIA CORPORATION. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string> #include <sstream> #include <iostream> #include <iomanip> #include <algorithm> #include <limits> #include <utility> #include <cstdint> #include <cstdlib> #include <map> extern "C" { #include "mmio.h" } #include <cuda.h> #include <cuda_runtime.h> #include <cuda_profiler_api.h> #include <library_types.h> #include <thrust/host_vector.h> #include <thrust/adjacent_difference.h> #include <thrust/reduce.h> #include <thrust/functional.h> #include <thrust/device_vector.h> #include <thrust/sequence.h> #include <rmm_utils.h> #include "cugraph.h" #ifndef CUDA_RT_CALL #define CUDA_RT_CALL( call ) \ { \ cudaError_t cudaStatus = call; \ if ( cudaSuccess != cudaStatus ) { \ fprintf(stderr, "ERROR: CUDA RT call \"%s\" in line %d of file %s failed with %s (%d).\n", \ #call, __LINE__, __FILE__, cudaGetErrorString(cudaStatus), cudaStatus); \ } \ } #endif std::function<void(gdf_column*)> gdf_col_deleter = [](gdf_column* col){ if (col) { col->size = 0; if(col->data){ cudaStream_t stream{nullptr}; ALLOC_FREE_TRY(col->data, stream); } delete col; } }; using gdf_column_ptr = typename std::unique_ptr<gdf_column, decltype(gdf_col_deleter)>; std::function<void(gdf_graph*)> gdf_graph_deleter = [](gdf_graph* G){delete G;}; using gdf_graph_ptr = typename std::unique_ptr<gdf_graph,decltype(gdf_graph_deleter)>; std::string getFileName(const std::string& s) { char sep = '/'; #ifdef _WIN32 sep = '\\'; #endif size_t i = s.rfind(sep, s.length()); if (i != std::string::npos) { return(s.substr(i+1, s.length() - i)); } return(""); } template <typename T> void verbose_diff(std::vector<T> & v1, std::vector<T> & v2) { for (unsigned int i = 0; i < v1.size(); ++i) { if (v1[i] != v2[i]) { std::cout << "[" << i <<"] : " << v1[i] << " vs. "<< v2[i]<<std::endl; } } } template <typename T> int eq(std::vector<T> & v1, std::vector<T> & v2) { if (v1 == v2) return 0; else { verbose_diff(v1,v2); return 1; } } template <typename T> void printv(size_t n, T* vec, int offset) { thrust::device_ptr<T> dev_ptr(vec); std::cout.precision(15); std::cout << "sample size = "<< n << ", offset = "<< offset << std::endl; thrust::copy(dev_ptr+offset,dev_ptr+offset+n, std::ostream_iterator<T>(std::cout, " "));//Assume no RMM dependency; TODO: check / test (potential BUG !!!!!) std::cout << std::endl; } template <typename T> void random_vals(std::vector<T> & v) { srand(42); for (auto i = size_t{0}; i < v.size(); i++) v[i]=static_cast<T>(std::rand()%10); } template <typename T_ELEM> void ref_csr2csc (int m, int n, int nnz, const T_ELEM *csrVals, const int *csrRowptr, const int *csrColInd, T_ELEM *cscVals, int *cscRowind, int *cscColptr, int base=0){ int i,j, row, col, index; int * counters; T_ELEM val; /* early return */ if ((m <= 0) || (n <= 0) || (nnz <= 0)){ return; } /* build compressed column pointers */ memset(cscColptr, 0, (n+1)*sizeof(cscColptr[0])); cscColptr[0]=base; for (i=0; i<nnz; i++){ cscColptr[1+csrColInd[i]-base]++; } for(i=0; i<n; i++){ cscColptr[i+1]+=cscColptr[i]; } /* expand row indecis and copy them and values into csc arrays according to permutation */ counters = (int *)malloc(n*sizeof(counters[0])); memset(counters, 0, n*sizeof(counters[0])); for (i=0; i<m; i++){ for (j=csrRowptr[i]; j<csrRowptr[i+1]; j++){ row = i+base; col = csrColInd[j-base]; index=cscColptr[col-base]-base+counters[col-base]; counters[col-base]++; cscRowind[index]=row; if(csrVals!=NULL || cscVals!=NULL){ val = csrVals[j-base]; cscVals[index] = val; } } } free(counters); } template <typename T> int transition_matrix_cpu(int n, int e, int *csrRowPtrA, int *csrColIndA, T *weight, T* is_leaf) //omp_set_num_threads(4); //#pragma omp parallel { int j,row, row_size; //#pragma omp for for (row=0; row<n; row++) { row_size = csrRowPtrA[row+1] - csrRowPtrA[row]; if (row_size == 0) is_leaf[row]=1.0; else { is_leaf[row]=0.0; for (j=csrRowPtrA[row]; j<csrRowPtrA[row+1]; j++) weight[j] = 1.0/row_size; } } return 0; } template <typename T> void printCsrMatI(int m, int n, int nnz,std::vector<int> & csrRowPtr, std::vector<uint16_t> & csrColInd, std::vector<T> & csrVal) { std::vector<T> v(n); std::stringstream ss; ss.str(std::string()); ss << std::fixed; ss << std::setprecision(2); for (int i = 0; i < m; i++) { std::fill(v.begin(),v.end(),0); for (int j = csrRowPtr[i]; j < csrRowPtr[i+1]; j++) v[csrColInd[j]] = csrVal[j]; std::copy(v.begin(), v.end(), std::ostream_iterator<int>(ss, " ")); ss << "\n"; } ss << "\n"; std::cout<<ss.str(); } /// Read matrix properties from Matrix Market file /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param t (Output) MM_typecode with matrix properties. * @param m (Output) Number of matrix rows. * @param n (Output) Number of matrix columns. * @param nnz (Output) Number of non-zero matrix entries. * @return Zero if properties were read successfully. Otherwise * non-zero. */ template <typename IndexType_> int mm_properties(FILE * f, int tg, MM_typecode * t, IndexType_ * m, IndexType_ * n, IndexType_ * nnz) { // Read matrix properties from file int mint, nint, nnzint; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(*t) || !mm_is_coordinate(*t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&mint,&nint,&nnzint)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(*t) && !mm_is_real(*t) && !mm_is_integer(*t) && !mm_is_complex(*t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } *m = mint; *n = nint; *nnz = nnzint; // Find total number of non-zero entries if(tg && !mm_is_general(*t)) { // Non-diagonal entries should be counted twice IndexType_ nnzOld = *nnz; *nnz *= 2; // Diagonal entries should not be double-counted int i; int st; for(i=0; i<nnzOld; ++i) { // Read matrix entry IndexType_ row, col; double rval, ival; if (mm_is_pattern(*t)) st = fscanf(f, "%d %d\n", &row, &col); else if (mm_is_real(*t) || mm_is_integer(*t)) st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Check if entry is diagonal if(row == col) --(*nnz); } } return 0; } /// Read Matrix Market file and convert to COO format matrix /** Matrix Market file is assumed to be a sparse matrix in coordinate * format. * * @param f File stream for Matrix Market file. * @param tg Boolean indicating whether to convert matrix to general * format (from symmetric, Hermitian, or skew symmetric format). * @param nnz Number of non-zero matrix entries. * @param cooRowInd (Output) Row indices for COO matrix. Should have * at least nnz entries. * @param cooColInd (Output) Column indices for COO matrix. Should * have at least nnz entries. * @param cooRVal (Output) Real component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @param cooIVal (Output) Imaginary component of COO matrix * entries. Should have at least nnz entries. Ignored if null * pointer. * @return Zero if matrix was read successfully. Otherwise non-zero. */ template <typename IndexType_, typename ValueType_> int mm_to_coo(FILE *f, int tg, IndexType_ nnz, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal , ValueType_ * cooIVal) { // Read matrix properties from file MM_typecode t; int m, n, nnzOld; if(fseek(f,0,SEEK_SET)) { fprintf(stderr, "Error: could not set position in file\n"); return -1; } if(mm_read_banner(f,&t)) { fprintf(stderr, "Error: could not read Matrix Market file banner\n"); return -1; } if(!mm_is_matrix(t) || !mm_is_coordinate(t)) { fprintf(stderr, "Error: file does not contain matrix in coordinate format\n"); return -1; } if(mm_read_mtx_crd_size(f,&m,&n,&nnzOld)) { fprintf(stderr, "Error: could not read matrix dimensions\n"); return -1; } if(!mm_is_pattern(t) && !mm_is_real(t) && !mm_is_integer(t) && !mm_is_complex(t)) { fprintf(stderr, "Error: matrix entries are not valid type\n"); return -1; } // Add each matrix entry in file to COO format matrix IndexType_ i; // Entry index in Matrix Market file IndexType_ j = 0; // Entry index in COO format matrix for(i=0;i<nnzOld;++i) { // Read entry from file int row, col; double rval, ival; int st; if (mm_is_pattern(t)) { st = fscanf(f, "%d %d\n", &row, &col); rval = 1.0; ival = 0.0; } else if (mm_is_real(t) || mm_is_integer(t)) { st = fscanf(f, "%d %d %lg\n", &row, &col, &rval); ival = 0.0; } else // Complex matrix st = fscanf(f, "%d %d %lg %lg\n", &row, &col, &rval, &ival); if(ferror(f) || (st == EOF)) { fprintf(stderr, "Error: error %d reading Matrix Market file (entry %d)\n", st, i+1); return -1; } // Switch to 0-based indexing --row; --col; // Record entry cooRowInd[j] = row; cooColInd[j] = col; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; // Add symmetric complement of non-diagonal entries if(tg && !mm_is_general(t) && (row!=col)) { // Modify entry value if matrix is skew symmetric or Hermitian if(mm_is_skew(t)) { rval = -rval; ival = -ival; } else if(mm_is_hermitian(t)) { ival = -ival; } // Record entry cooRowInd[j] = col; cooColInd[j] = row; if(cooRVal != NULL) cooRVal[j] = rval; if(cooIVal != NULL) cooIVal[j] = ival; ++j; } } return 0; } /// Compare two tuples based on the element indexed by i class lesser_tuple { const int i; public: lesser_tuple(int _i) : i(_i) {} template<typename Tuple1, typename Tuple2> __host__ __device__ bool operator()(const Tuple1 t1, const Tuple2 t2) { switch(i) { case 0: return (thrust::get<0>(t1) == thrust::get<0>(t2) ? thrust::get<1>(t1) < thrust::get<1>(t2) : thrust::get<0>(t1) < thrust::get<0>(t2)); case 1: return (thrust::get<1>(t1) == thrust::get<1>(t2) ? thrust::get<0>(t1) < thrust::get<0>(t2) : thrust::get<1>(t1) < thrust::get<1>(t2)); default: return (thrust::get<0>(t1) == thrust::get<0>(t2) ? thrust::get<1>(t1) < thrust::get<1>(t2) : thrust::get<0>(t1) < thrust::get<0>(t2)); } } }; /// Sort entries in COO format matrix /** Sort is stable. * * @param nnz Number of non-zero matrix entries. * @param sort_by_row Boolean indicating whether matrix entries * will be sorted by row index or by column index. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component for COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component COO matrix entries. Ignored if * null pointer. */ template <typename IndexType_, typename ValueType_> void coo_sort(IndexType_ nnz, int sort_by_row, IndexType_ * cooRowInd, IndexType_ * cooColInd, ValueType_ * cooRVal, ValueType_ * cooIVal) { // Determine whether to sort by row or by column int i; if(sort_by_row == 0) i = 1; else i = 0; // Apply stable sort using namespace thrust; if((cooRVal==NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz)), lesser_tuple(i)); else if((cooRVal==NULL) && (cooIVal!=NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooIVal+nnz)), lesser_tuple(i)); else if((cooRVal!=NULL) && (cooIVal==NULL)) stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz,cooRVal+nnz)), lesser_tuple(i)); else stable_sort(make_zip_iterator(make_tuple(cooRowInd,cooColInd,cooRVal,cooIVal)), make_zip_iterator(make_tuple(cooRowInd+nnz,cooColInd+nnz, cooRVal+nnz,cooIVal+nnz)), lesser_tuple(i)); } template <typename IndexT> void coo2csr(std::vector<IndexT>& cooRowInd, //in: I[] (overwrite) const std::vector<IndexT>& cooColInd, //in: J[] std::vector<IndexT>& csrRowPtr, //out std::vector<IndexT>& csrColInd) //out { std::vector<std::pair<IndexT,IndexT> > items; for (auto i = size_t{0}; i < cooRowInd.size(); ++i) items.push_back(std::make_pair( cooRowInd[i], cooColInd[i])); //sort pairs std::sort(items.begin(), items.end(),[](const std::pair<IndexT,IndexT> &left, const std::pair<IndexT,IndexT> &right) {return left.first < right.first; }); for (auto i = size_t{0}; i < cooRowInd.size(); ++i) { cooRowInd[i]=items[i].first; // save the sorted rows to compress them later csrColInd[i]=items[i].second; // save the col idx, not sure if they are sorted for each row } // Count number of elements per row for(auto i=size_t{0}; i<cooRowInd.size(); ++i) ++(csrRowPtr[cooRowInd[i]+1]); // Compute cumulative sum to obtain row offsets/pointers for(auto i=size_t{0}; i<csrRowPtr.size()-1; ++i) csrRowPtr[i+1] += csrRowPtr[i]; } /// Compress sorted list of indices /** For use in converting COO format matrix to CSR or CSC format. * * @param n Maximum index. * @param nnz Number of non-zero matrix entries. * @param sortedIndices Sorted list of indices (COO format). * @param compressedIndices (Output) Compressed list of indices (CSR * or CSC format). Should have at least n+1 entries. */ template <typename IndexType_> void coo_compress(IndexType_ m, IndexType_ n, IndexType_ nnz, const IndexType_ * __restrict__ sortedIndices, IndexType_ * __restrict__ compressedIndices) { IndexType_ i; // Initialize everything to zero memset(compressedIndices, 0, (m+1)*sizeof(IndexType_)); // Count number of elements per row for(i=0; i<nnz; ++i) ++(compressedIndices[sortedIndices[i]+1]); // Compute cumulative sum to obtain row offsets/pointers for(i=0; i<m; ++i) compressedIndices[i+1] += compressedIndices[i]; } /// Convert COO format matrix to CSR format /** On output, matrix entries in COO format matrix will be sorted * (primarily by row index, secondarily by column index). * * @param m Number of matrix rows. * @param n Number of matrix columns. * @param nnz Number of non-zero matrix entries. * @param cooRowInd Row indices for COO matrix. * @param cooColInd Column indices for COO matrix. * @param cooRVal Real component of COO matrix entries. Ignored if * null pointer. * @param cooIVal Imaginary component of COO matrix entries. Ignored * if null pointer. * @param csrRowPtr Row pointers for CSR matrix. Should have at least * n+1 entries. * @param csrColInd Column indices for CSR matrix (identical to * output of cooColInd). Should have at least nnz entries. Ignored if * null pointer. * @param csrRVal Real component of CSR matrix entries (identical to * output of cooRVal). Should have at least nnz entries. Ignored if * null pointer. * @param csrIVal Imaginary component of CSR matrix entries * (identical to output of cooIVal). Should have at least nnz * entries. Ignored if null pointer. * @return Zero if matrix was converted successfully. Otherwise * non-zero. */ template <typename IndexType_, typename ValueType_> int coo_to_csr(IndexType_ m, IndexType_ n, IndexType_ nnz, IndexType_ * __restrict__ cooRowInd, IndexType_ * __restrict__ cooColInd, ValueType_ * __restrict__ cooRVal, ValueType_ * __restrict__ cooIVal, IndexType_ * __restrict__ csrRowPtr, IndexType_ * __restrict__ csrColInd, ValueType_ * __restrict__ csrRVal, ValueType_ * __restrict__ csrIVal) { // Convert COO to CSR matrix coo_sort(nnz, 0, cooRowInd, cooColInd, cooRVal, cooIVal); coo_sort(nnz, 1, cooRowInd, cooColInd, cooRVal, cooIVal); //coo_sort2<int,float>(m, nnz, cooRowInd, cooColInd); coo_compress(m, n, nnz, cooRowInd, csrRowPtr); // Copy arrays if(csrColInd!=NULL) memcpy(csrColInd, cooColInd, nnz*sizeof(IndexType_)); if((cooRVal!=NULL) && (csrRVal!=NULL)) memcpy(csrRVal, cooRVal, nnz*sizeof(ValueType_)); if((cooIVal!=NULL) && (csrIVal!=NULL)) memcpy(csrIVal, cooIVal, nnz*sizeof(ValueType_)); return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<float>& val ) { size_t is_read1; double* t_storage = new double[n]; is_read1 = fread(t_storage, sizeof(double), n, fpin); for (int i = 0; i < n; i++) { if (t_storage[i] == DBL_MAX) val[i] = FLT_MAX; else if (t_storage[i] == -DBL_MAX) val[i] = -FLT_MAX; else val[i] = static_cast<float>(t_storage[i]); } delete[] t_storage; if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } int read_binary_vector ( FILE* fpin, int n, std::vector<double>& val ) { size_t is_read1; is_read1 = fread(&val[0], sizeof(double), n, fpin); if (is_read1 != (size_t)n) { printf("%s", "I/O fail\n"); return 1; } return 0; } // Creates a gdf_column from a std::vector template <typename col_type> gdf_column_ptr create_gdf_column(std::vector<col_type> const & host_vector) { // Create a new instance of a gdf_column with a custom deleter that will free // the associated device memory when it eventually goes out of scope gdf_column_ptr the_column{new gdf_column, gdf_col_deleter}; // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaStream_t stream{nullptr}; ALLOC_TRY((void**)&(the_column->data), input_size_bytes, stream); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; return the_column; } // Creates a gdf_column from a std::vector template <typename col_type> void create_gdf_column(std::vector<col_type> const & host_vector, gdf_column * the_column) { // Allocate device storage for gdf_column and copy contents from host_vector const size_t input_size_bytes = host_vector.size() * sizeof(col_type); cudaStream_t stream{nullptr}; ALLOC_TRY((void**)&(the_column->data), input_size_bytes, stream); cudaMemcpy(the_column->data, host_vector.data(), input_size_bytes, cudaMemcpyHostToDevice); // Deduce the type and set the gdf_dtype accordingly gdf_dtype gdf_col_type; if(std::is_same<col_type,int8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,uint8_t>::value) gdf_col_type = GDF_INT8; else if(std::is_same<col_type,int16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,uint16_t>::value) gdf_col_type = GDF_INT16; else if(std::is_same<col_type,int32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,uint32_t>::value) gdf_col_type = GDF_INT32; else if(std::is_same<col_type,int64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,uint64_t>::value) gdf_col_type = GDF_INT64; else if(std::is_same<col_type,float>::value) gdf_col_type = GDF_FLOAT32; else if(std::is_same<col_type,double>::value) gdf_col_type = GDF_FLOAT64; // Fill the gdf_column members the_column->valid = nullptr; the_column->null_count = 0; the_column->size = host_vector.size(); the_column->dtype = gdf_col_type; gdf_dtype_extra_info extra_info; extra_info.time_unit = TIME_UNIT_NONE; the_column->dtype_info = extra_info; } void gdf_col_delete(gdf_column* col) { if (col) { col->size = 0; cudaStream_t stream{nullptr}; if(col->data) ALLOC_FREE_TRY(col->data, stream); #if 1 // If delete col is executed, the memory pointed by col is no longer valid and // can be used in another memory allocation, so executing col->data = nullptr // after delete col is dangerous, also, col = nullptr has no effect here (the // address is passed by value, for col = nullptr should work, the input // parameter should be gdf_column*& col (or alternatively, gdf_column** col and // *col = nullptr also work) col->data = nullptr; delete col; #else delete col; col->data = nullptr; col = nullptr; #endif } } template <typename col_type> bool gdf_column_equal(gdf_column* a, gdf_column* b) { if (a == nullptr || b == nullptr){ std::cout << "A given column is null!\n"; return false; } if (a->dtype != b->dtype){ std::cout << "Mismatched dtypes\n"; return false; } if (a->size != b->size){ std::cout << "Mismatched sizes: a=" << a->size << " b=" << b->size << "\n"; return false; } std::vector<col_type>a_h(a->size); std::vector<col_type>b_h(b->size); cudaMemcpy(&a_h[0], a->data, sizeof(col_type) * a->size, cudaMemcpyDefault); cudaMemcpy(&b_h[0], b->data, sizeof(col_type) * b->size, cudaMemcpyDefault); for (size_t i = 0; i < a_h.size(); i++) { if (a_h[i] != b_h[i]){ std::cout << "Elements at " << i << " differ: a=" << a_h[i] << " b=" << b_h[i] << "\n"; return false; } } return true; } template<typename idx_t> bool gdf_csr_equal(gdf_column* a_off, gdf_column* a_ind, gdf_column* b_off, gdf_column* b_ind) { if (a_off == nullptr || a_ind == nullptr || b_off == nullptr || b_ind == nullptr) { std::cout << "A given column is null!\n"; return false; } auto type = a_off->dtype; if (a_ind->dtype != type || b_off->dtype != type || b_ind->dtype != type) { std::cout << "Mismatched dtypes\n"; return false; } if (!gdf_column_equal<idx_t>(a_off, b_off)) { std::cout << "Offsets arrays do not match!\n"; return false; } if (a_ind->size != b_ind->size) { std::cout << "Size of indices arrays do not match\n"; return false; } // Compare the elements of each section of the indices, regardless of order std::vector<idx_t> a_off_h(a_off->size); std::vector<idx_t> a_ind_h(a_ind->size); std::vector<idx_t> b_ind_h(b_ind->size); cudaMemcpy(&a_off_h[0], a_off->data, a_off->size * sizeof(idx_t), cudaMemcpyDefault); cudaMemcpy(&a_ind_h[0], a_ind->data, a_ind->size * sizeof(idx_t), cudaMemcpyDefault); cudaMemcpy(&b_ind_h[0], b_ind->data, b_ind->size * sizeof(idx_t), cudaMemcpyDefault); auto numVerts = a_off_h.size() - 1; for (size_t vert = 0; vert < numVerts; vert++){ auto start = a_off_h[vert]; auto end = a_off_h[vert + 1]; std::set<idx_t> a_set; std::set<idx_t> b_set; for (int i = start; i < end; i++){ a_set.insert(a_ind_h[i]); b_set.insert(b_ind_h[i]); } if (a_set.size() != b_set.size()) { std::cout << "Vertex " << vert << " set sizes do not match!\n"; std::cout << "A Set: {"; for (auto it = a_set.begin(); it != a_set.end(); it++) std::cout << " " << *it; std::cout << "}\nB Set: {"; for (auto it = b_set.begin(); it != b_set.end(); it++) std::cout << " " << *it; std::cout << "}\n"; std::cout << "A list: {"; for (int i = start; i < end; i++) { std::cout << " " << a_ind_h[i]; } std::cout << "}\nB List: {"; for (int i = start; i < end; i++) { std::cout << " " << b_ind_h[i]; } std::cout << "}\n"; return false; } for (auto it = a_set.begin(); it != a_set.end(); it++) { if (b_set.count(*it) != 1) { std::cout << "A set contains " << *it << " B set does not!\n"; return false; } } } return true; } //////////////////////////////////////////////////////////////////////////////// // TODO: move this code to rapids-core //////////////////////////////////////////////////////////////////////////////// // Define RAPIDS_DATASET_ROOT_DIR using a preprocessor variable to // allow for a build to override the default. This is useful for // having different builds for specific default dataset locations. #ifndef RAPIDS_DATASET_ROOT_DIR #define RAPIDS_DATASET_ROOT_DIR "/datasets" #endif static const std::string& get_rapids_dataset_root_dir() { static std::string rdrd(""); // Env var always overrides the value of RAPIDS_DATASET_ROOT_DIR if (rdrd == "") { const char* envVar = std::getenv("RAPIDS_DATASET_ROOT_DIR"); rdrd = (envVar != NULL) ? envVar : RAPIDS_DATASET_ROOT_DIR; } return rdrd; }
CompositeKernels.h
#pragma once #include "CSRMatrix.h" #include "Parameters.h" float ComputeLaplacianAndInnerProduct(CSRMatrix& laplacianMatrix, const float (&u)[XDIM][YDIM][ZDIM], float (&Lu)[XDIM][YDIM][ZDIM]) { int N = laplacianMatrix.mSize; const auto rowOffsets = laplacianMatrix.GetRowOffsets(); const auto columnIndices = laplacianMatrix.GetColumnIndices(); const auto values = laplacianMatrix.GetValues(); float *y = &Lu[0][0][0]; const float *x = &u[0][0][0]; double result = 0.; #pragma omp parallel for reduction(+:result) for (int i = 0; i < N; i++) { y[i] = 0.; for (int k = rowOffsets[i]; k < rowOffsets[i+1]; k++) { const int j = columnIndices[k]; y[i] += values[k] * x[j]; } result += (double) x[i] * (double) y[i]; } return (float) result; }
CG.h
/** * This file contains (modified) code from the Eigen library. * Eigen License: * * Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr> * Copyright (C) 2007-2011 Benoit Jacob <jacob.benoit.1@gmail.com> * * This Source Code Form is subject to the terms of the Mozilla * Public License v. 2.0. If a copy of the MPL was not distributed * with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * * ====================== * * The modifications are part of the Eigen Recursive Matrix Extension (ERME). * ERME License: * * Copyright (c) 2019 Darius Rückert * Licensed under the MIT License. */ #pragma once #include "../Core.h" #include "../Core/ParallelHelper.h" #include "Cholesky.h" namespace Eigen::Recursive { template <typename _Scalar> class RecursiveDiagonalPreconditioner { typedef _Scalar Scalar; typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1> Vector; public: typedef typename Vector::StorageIndex StorageIndex; enum { ColsAtCompileTime = Eigen::Dynamic, MaxColsAtCompileTime = Eigen::Dynamic }; RecursiveDiagonalPreconditioner() : m_isInitialized(false) {} void resize(int N) { m_invdiag.resize(N); } template <typename MatType> explicit RecursiveDiagonalPreconditioner(const MatType& mat) : m_invdiag(mat.cols()) { compute(mat); } Eigen::Index rows() const { return m_invdiag.size(); } Eigen::Index cols() const { return m_invdiag.size(); } template <typename MatType> RecursiveDiagonalPreconditioner& analyzePattern(const MatType&) { return *this; } // Sparse Matrix Initialization template <typename Scalar, int options> // RecursiveDiagonalPreconditioner& factorize(const MatType& mat) RecursiveDiagonalPreconditioner& factorize(const SparseMatrix<Scalar, options>& mat) { using MatType = SparseMatrix<Scalar, options>; m_invdiag.resize(mat.cols()); for (int j = 0; j < mat.outerSize(); ++j) { typename MatType::InnerIterator it(mat, j); while (it && it.index() != j) ++it; if (it && it.index() == j) // m_invdiag(j) = Scalar(1)/it.value(); removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(inverseCholesky(it.value())); else // m_invdiag(j) = Scalar(1); removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(MultiplicativeNeutral<Scalar>::get()); } m_isInitialized = true; return *this; } // Dense Matrix Initialization template <typename MatType> RecursiveDiagonalPreconditioner& factorize(const MatType& mat) { m_invdiag.resize(mat.cols()); for (int j = 0; j < mat.outerSize(); ++j) { removeMatrixScalar(m_invdiag(j)) = removeMatrixScalar(inverseCholesky(mat(j, j))); } m_isInitialized = true; return *this; } template <typename T> RecursiveDiagonalPreconditioner& factorize(const Eigen::DiagonalMatrix<T, -1>& mat) { auto N = mat.rows(); if (m_invdiag.rows() != N) { std::terminate(); m_invdiag.resize(N); } #pragma omp for for (int j = 0; j < N; ++j) { m_invdiag(j) = inverseCholesky(mat.diagonal()(j)); } m_isInitialized = true; return *this; } template <typename MatType> RecursiveDiagonalPreconditioner& compute(const MatType& mat) { return factorize(mat); } /** \internal */ template <typename Rhs, typename Dest> void _solve_impl(const Rhs& b, Dest& x) const { // x = m_invdiag.array() * b.array(); #pragma omp for for (int i = 0; i < b.rows(); ++i) { x(i) = m_invdiag(i) * b(i); } } template <typename Rhs> inline const Eigen::Solve<RecursiveDiagonalPreconditioner, Rhs> solve(const Eigen::MatrixBase<Rhs>& b) const { eigen_assert(m_isInitialized && "DiagonalPreconditioner is not initialized."); eigen_assert(m_invdiag.size() == b.rows() && "DiagonalPreconditioner::solve(): invalid number of rows of the right hand side matrix b"); return Eigen::Solve<RecursiveDiagonalPreconditioner, Rhs>(*this, b.derived()); } Eigen::ComputationInfo info() { return Eigen::Success; } const auto& getDiagElement(int i) const { return m_invdiag(i); } Vector m_invdiag; protected: bool m_isInitialized; }; //#define RM_CG_DEBUG_OUTPUT /** * A conjugate gradient solver, which works for recursives matrices. * Solve: * A * x = b for x * * The matrix A is given as function (for example a lambda function). * This way we can implement an implicit cg solver, which does not construct the full matrix A. * * Example call: * * // Build preconditioner * RecursiveDiagonalPreconditioner<MatrixScalar<Block>> P; * Eigen::Index iters = 50; * Scalar tol = 1e-50; * P.compute(S); * * // Solve with explicit matrix S * DAType tmp(n); * recursive_conjugate_gradient( * [&](const DAType& v) { * tmp = S * v; * return tmp; * }, * ej, da, P, iters, tol); * */ template <typename MultFunction, typename Rhs, typename Dest, typename Preconditioner, typename SuperScalar> EIGEN_DONT_INLINE void recursive_conjugate_gradient(const MultFunction& applyA, const Rhs& rhs, Dest& x, const Preconditioner& precond, Eigen::Index& iters, SuperScalar& tol_error) { // Typedefs using namespace Eigen; using std::abs; using std::sqrt; typedef SuperScalar RealScalar; typedef SuperScalar Scalar; typedef Rhs VectorType; // Temp Vector variables Index n = rhs.rows(); #ifdef RM_CG_DEBUG_OUTPUT std::cout << "Starting recursive CG" << std::endl; std::cout << "Iterations: " << iters << std::endl; std::cout << "Tolerance: " << tol_error << std::endl; std::cout << "N: " << n << std::endl; #endif #if 0 // Create them locally VectorType z(n); VectorType p(n); #else // Use static variables so a repeated call with the same size doesn't allocate memory static thread_local VectorType z; static thread_local VectorType p; static thread_local VectorType residual; z.resize(n); p.resize(n); residual.resize(n); #endif RealScalar tol = tol_error; Index maxIters = iters; applyA(x, residual); residual = rhs - residual; RealScalar rhsNorm2 = squaredNorm(rhs); if (rhsNorm2 == 0) { x.setZero(); iters = 0; tol_error = 0; return; } RealScalar threshold = tol * tol * rhsNorm2; RealScalar residualNorm2 = squaredNorm(residual); #ifdef RM_CG_DEBUG_OUTPUT std::cout << "Initial residual: " << residualNorm2 << std::endl; #endif if (residualNorm2 < threshold) { iters = 0; tol_error = sqrt(residualNorm2 / rhsNorm2); return; } p = precond.solve(residual); // initial search direction // the square of the absolute value of r scaled by invM RealScalar absNew = dot(residual, p); #ifdef RM_CG_DEBUG_OUTPUT std::cout << "dot(r,p): " << absNew << std::endl; #endif Index i = 0; while (i < maxIters) { // std::cout << "CG Residual " << i << ": " << residualNorm2 << std::endl; applyA(p, z); // the amount we travel on dir Scalar alpha = absNew / dot(p, z); // update solution x += scalarMult(p, alpha); // update residual residual -= scalarMult(z, alpha); residualNorm2 = squaredNorm(residual); #ifdef RM_CG_DEBUG_OUTPUT std::cout << "Iteration: " << i << " Residual: " << residualNorm2 << " Alpha: " << alpha << std::endl; #endif if (residualNorm2 < threshold) break; z = precond.solve(residual); // approximately solve for "A z = residual" // std::cout << expand(p).transpose() << std::endl; RealScalar absOld = absNew; absNew = dot(residual, z); // update the absolute value of r RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction // std::cout << "absnew " << absNew << " beta " << beta << std::endl; p = z + scalarMult(p, beta); // update search direction i++; } tol_error = sqrt(residualNorm2 / rhsNorm2); iters = i; } template <typename T> struct alignas(64) CacheAlignedValues { T data; }; template <typename T> inline double accumulate(const T& v) { double d = 0; for (auto& v : v) { d += v.data; } return d; } // Multi threaded implementation template <typename MultFunction, typename Rhs, typename Dest, typename Preconditioner, typename SuperScalar> EIGEN_DONT_INLINE void recursive_conjugate_gradient_OMP(const MultFunction& applyA, const Rhs& rhs, Dest& x, const Preconditioner& precond, Eigen::Index& iters, SuperScalar& tol_error) { // Typedefs using namespace Eigen; using std::abs; using std::sqrt; typedef SuperScalar RealScalar; typedef SuperScalar Scalar; typedef Rhs VectorType; // Temp Vector variables Index n = rhs.rows(); // Use static variables so a repeated call with the same size doesn't allocate memory static VectorType z; static VectorType p; static VectorType residual; static std::vector<CacheAlignedValues<Scalar>> tmpResults1, tmpResults; #pragma omp single { z.resize(n); p.resize(n); residual.resize(n); tmpResults1.resize(omp_get_num_threads()); tmpResults.resize(omp_get_num_threads()); } int tid = omp_get_thread_num(); RealScalar tol = tol_error; Index maxIters = iters; applyA(x, residual); #pragma omp for for (int i = 0; i < n; ++i) { residual(i) = rhs(i) - residual(i); } // tmpResults[tid] = squaredNorm_omp(rhs); squaredNorm_omp_local(rhs, tmpResults[tid].data); RealScalar rhsNorm2 = accumulate(tmpResults); if (rhsNorm2 == 0) { // x.setZero(); #pragma omp for for (int i = 0; i < n; ++i) { x(i).get().setZero(); } iters = 0; tol_error = 0; maxIters = 0; } RealScalar threshold = tol * tol * rhsNorm2; squaredNorm_omp_local(residual, tmpResults1[tid].data); RealScalar residualNorm2 = accumulate(tmpResults1); // RealScalar residualNorm2 = squaredNorm(residual); if (residualNorm2 < threshold) { iters = 0; tol_error = sqrt(residualNorm2 / rhsNorm2); maxIters = 0; } p = precond.solve(residual); // initial search direction dot_omp_local(residual, p, tmpResults[tid].data); RealScalar absNew = accumulate(tmpResults); Index i = 0; while (i < maxIters) { // std::cout << "CG Residual " << i << ": " << residualNorm2 << std::endl; applyA(p, z); dot_omp_local(p, z, tmpResults1[tid].data); Scalar dotpz = accumulate(tmpResults1); Scalar alpha = absNew / dotpz; #pragma omp for for (int i = 0; i < n; ++i) { // the amount we travel on dir // update solution x(i) += p(i) * alpha; // update residual residual(i) -= z(i) * alpha; } squaredNorm_omp_local(residual, tmpResults[tid].data); residualNorm2 = accumulate(tmpResults); if (residualNorm2 < threshold) break; z = precond.solve(residual); // approximately solve for "A z = residual" RealScalar absOld = absNew; dot_omp_local(residual, z, tmpResults[tid].data); absNew = accumulate(tmpResults); RealScalar beta = absNew / absOld; // calculate the Gram-Schmidt value used to create the new search direction // std::cout << "absnew " << absNew << " beta " << beta << std::endl; #pragma omp for for (int i = 0; i < n; ++i) { p(i) = z(i) + p(i) * beta; // update search direction } i++; } tol_error = sqrt(residualNorm2 / rhsNorm2); iters = i; } // namespace Eigen::Recursive } // namespace Eigen::Recursive
taskloop_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -triple x86_64-unknown-unknown -verify %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -triple x86_64-unknown-unknown -verify %s -Wuninitialized void xxx(int argc) { int x; // expected-note {{initialize the variable 'x' to silence this warning}} #pragma omp taskloop for (int i = 0; i < 10; ++i) argc = x; // expected-warning {{variable 'x' is uninitialized when used here}} } // expected-error@+1 {{unexpected OpenMP directive '#pragma omp taskloop'}} #pragma omp taskloop // expected-error@+1 {{unexpected OpenMP directive '#pragma omp taskloop'}} #pragma omp taskloop foo void test_no_clause() { int i; #pragma omp taskloop for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp taskloop' must be a for loop}} #pragma omp taskloop ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp parallel #pragma omp taskloop for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} #pragma omp taskloop foo bar for (i = 0; i < 16; ++i) ; // expected-error@+1 {{directive '#pragma omp taskloop' cannot contain more than one 'nogroup' clause}} #pragma omp taskloop nogroup nogroup for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} #pragma omp taskloop; for (i = 0; i < 16; ++i) ; // expected-warning@+3 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} // expected-error@+2 {{unexpected OpenMP clause 'linear' in directive '#pragma omp taskloop'}} #pragma omp parallel #pragma omp taskloop linear(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} #pragma omp taskloop private(x); for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+1 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} #pragma omp taskloop, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_collapse() { int i; #pragma omp parallel // expected-error@+1 {{expected '('}} #pragma omp taskloop collapse for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp taskloop collapse( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop collapse() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp taskloop collapse(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp taskloop collapse(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-warning@+2 {{extra tokens at the end of '#pragma omp taskloop' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp taskloop collapse 4) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel #pragma omp taskloop collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); #pragma omp parallel // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp taskloop collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp taskloop', but found only 1}} #pragma omp parallel // expected-error@+1 {{integer constant expression}} #pragma omp taskloop collapse(2.5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{integer constant expression}} #pragma omp taskloop collapse(foo()) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp taskloop collapse(-5) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp taskloop collapse(0) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp taskloop collapse(5 - 5) for (i = 0; i < 16; ++i) ; } void test_private() { int i; #pragma omp parallel // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp taskloop private( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp taskloop private(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp taskloop private(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop private() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop private(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp taskloop private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp taskloop private(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_lastprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp taskloop lastprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp taskloop lastprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp taskloop lastprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop lastprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop lastprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp taskloop lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp taskloop lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_firstprivate() { int i; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp taskloop firstprivate( for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp taskloop firstprivate(, for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 2 {{expected expression}} #pragma omp taskloop firstprivate(, ) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop firstprivate() for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected expression}} #pragma omp taskloop firstprivate(int) for (i = 0; i < 16; ++i) ; #pragma omp parallel // expected-error@+1 {{expected variable name}} #pragma omp taskloop firstprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp parallel #pragma omp taskloop lastprivate(x) firstprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop lastprivate(x, y) firstprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp parallel #pragma omp taskloop lastprivate(x, y, z) firstprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp taskloop for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } #pragma omp parallel // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp taskloop for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-warning@+2 {{OpenMP loop iteration variable cannot have more than 64 bits size and will be narrowed}} #pragma omp taskloop for (__int128 ii = 0; ii < 10; ii++) { c[ii] = a[ii] + b[ii]; } }
pdf_fmt.c
/** * Copyright (C) 2006 Henning Norén * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * Re-factored for JtR by Dhiru Kholia during June, 2011 for GSoC. * * References: * * http://www.adobe.com/devnet/pdf/pdf_reference.html * http://www.cs.cmu.edu/~dst/Adobe/Gallery/anon21jul01-pdf-encryption.txt * http://www.novapdf.com/kb/pdf-example-files-created-with-with-novapdf-138.html * * TODO: add support for detecting AESV2 and AESV3 encrypted documents * lacking "trailer dictionary" to pdfparser.c */ #undef MEM_FREE #include <string.h> #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #include "misc.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 64 #endif #endif #include "pdfcrack.h" #include "pdfparser.h" #define FORMAT_LABEL "PDF" #define FORMAT_NAME "" #define ALGORITHM_NAME "MD5 RC4 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1000 #define PLAINTEXT_LENGTH 32 #define BINARY_SIZE 0 #define SALT_SIZE sizeof(struct custom_salt) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #if defined (_OPENMP) static int omp_t = 1; #endif static struct custom_salt *cur_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *cracked; static int any_cracked; static size_t cracked_size; static struct fmt_tests pdf_tests[] = { {"$pdf$Standard*badad1e86442699427116d3e5d5271bc80a27814fc5e80f815efeef839354c5f*289ece9b5ce451a5d7064693dab3badf101112131415161718191a1b1c1d1e1f*16*34b1b6e593787af681a9b63fa8bf563b*1*1*0*1*4*128*-4*3*2", "test"}, {"$pdf$Standard*d83a8ab680f144dfb2ff2334c206a6060779e007701ab881767f961aecda7984*a5ed4de7e078cb75dfdcd63e8da7a25800000000000000000000000000000000*16*06a7f710cf8dfafbd394540d40984ae2*1*1*0*1*4*128*-1028*3*2", "July2099"}, {"$pdf$Standard*2446dd5ed2e18b3ce1ac9b56733226018e3f5c2639051eb1c9b2b215b30bc820*fa3af175d761963c8449ee7015b7770800000000000000000000000000000000*16*12a4da1abe6b7a1ceb84610bad87236d*1*1*0*1*4*128*-1028*3*2", "WHATwhatWHERE?"}, {"$pdf$Standard*6a80a547b8b8b7636fcc5b322f1c63ce4b670c9b01f2aace09e48d85e1f19f83*e64eb62fc46be66e33571d50a29b464100000000000000000000000000000000*16*14a8c53ffa4a79b3ed9421ef15618420*1*1*0*1*4*128*-1028*3*2", "38r285a9"}, {NULL} }; static void init(struct fmt_main *self) { #if defined (_OPENMP) omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc_tiny(sizeof(*saved_key) * self->params.max_keys_per_crypt, MEM_ALIGN_WORD); any_cracked = 0; cracked_size = sizeof(*cracked) * self->params.max_keys_per_crypt; cracked = mem_calloc_tiny(cracked_size, MEM_ALIGN_WORD); } static int ishex(char *q) { while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q; } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *ptr, *keeptr; int res; if (strncmp(ciphertext, "$pdf$Standard*", 14)) return 0; if (!(ctcopy = strdup(ciphertext))) return 0; keeptr = ctcopy; ctcopy += 14; if (!(ptr = strtok(ctcopy, "*"))) /* o_string */ goto error; if (!ishex(ptr)) goto error; if (!(ptr = strtok(NULL, "*"))) /* u_string */ goto error; if (!ishex(ptr)) goto error; if (!(ptr = strtok(NULL, "*"))) /* fileIDLen */ goto error; if (strncmp(ptr, "16", 2)) goto error; if (!(ptr = strtok(NULL, "*"))) /* fileID */ goto error; if (!ishex(ptr)) goto error; if (!(ptr = strtok(NULL, "*"))) /* encryptMetaData */ goto error; res = atoi(ptr); if (res != 0 && res != 1) goto error; if (!(ptr = strtok(NULL, "*"))) /* work_with_user */ goto error; res = atoi(ptr); if (res != 0 && res != 1) goto error; if (!(ptr = strtok(NULL, "*"))) /* have_userpassword */ goto error; res = atoi(ptr); if (res != 0 && res != 1) goto error; if (!(ptr = strtok(NULL, "*"))) /* version_major */ goto error; if (!(ptr = strtok(NULL, "*"))) /* version_minor */ goto error; if (!(ptr = strtok(NULL, "*"))) /* length */ goto error; if (!(ptr = strtok(NULL, "*"))) /* permissions */ goto error; if (!(ptr = strtok(NULL, "*"))) /* revision */ goto error; if (!(ptr = strtok(NULL, "*"))) /* version */ goto error; MEM_FREE(keeptr); return 1; error: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static struct custom_salt cs; ctcopy += 5; /* skip over "$pdf$" marker */ memset(cs.encKeyWorkSpace, 0, 128); /* restore serialized data */ strncpy(cs.e.s_handler, strtok(ctcopy, "*"), 32); p = strtok(NULL, "*"); for (i = 0; i < 32; i++) cs.e.o_string[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); for (i = 0; i < 32; i++) cs.e.u_string[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); cs.e.fileIDLen = atoi(p); p = strtok(NULL, "*"); for (i = 0; i < cs.e.fileIDLen; i++) cs.e.fileID[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); cs.e.encryptMetaData = atoi(p); p = strtok(NULL, "*"); cs.e.work_with_user = atoi(p); p = strtok(NULL, "*"); cs.e.have_userpassword = atoi(p); p = strtok(NULL, "*"); cs.e.version_major = atoi(p); p = strtok(NULL, "*"); cs.e.version_minor = atoi(p); p = strtok(NULL, "*"); cs.e.length = atoi(p); p = strtok(NULL, "*"); cs.e.permissions = atoi(p); p = strtok(NULL, "*"); cs.e.revision = atoi(p); p = strtok(NULL, "*"); cs.e.version = atoi(p); if (cs.e.have_userpassword) cs.userpassword = (unsigned char *)strtok(NULL, "*"); else cs.userpassword = NULL; cs.knownPassword = false; MEM_FREE(keeptr); /* try to initialize the cracking-engine */ if (!initPDFCrack(&cs)) { fprintf(stderr, "Wrong userpassword, '%s'\n", cs.userpassword); exit(-1); } return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; loadPDFCrack(cur_salt); } static void pdf_set_key(char *key, int index) { int saved_len = strlen(key); if (saved_len > PLAINTEXT_LENGTH) saved_len = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, saved_len); saved_key[index][saved_len] = 0; } static char *get_key(int index) { return saved_key[index]; } static void crypt_all(int count) { int index = 0; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index++) #endif { /* do the actual crunching */ cracked[index] = runCrack(saved_key[index], cur_salt); if(cracked[index] == 1) #ifdef _OPENMP #pragma omp critical #endif any_cracked = 1; } } 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 cracked[index]; } struct fmt_main fmt_pdf = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, DEFAULT_ALIGN, SALT_SIZE, DEFAULT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, pdf_tests }, { init, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, set_salt, pdf_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } };
GB_binop__le_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__le_bool // A.*B function (eWiseMult): GB_AemultB__le_bool // A*D function (colscale): GB_AxD__le_bool // D*A function (rowscale): GB_DxB__le_bool // C+=B function (dense accum): GB_Cdense_accumB__le_bool // C+=b function (dense accum): GB_Cdense_accumb__le_bool // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__le_bool // C=scalar+B GB_bind1st__le_bool // C=scalar+B' GB_bind1st_tran__le_bool // C=A+scalar GB_bind2nd__le_bool // C=A'+scalar GB_bind2nd_tran__le_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_LE || GxB_NO_BOOL || GxB_NO_LE_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__le_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__le_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__le_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__le_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__le_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__le_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__le_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__le_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__le_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__le_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__le_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
test_core.c
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (c) 2012 RELIC Authors * * This file is part of RELIC. RELIC is legal property of its developers, * whose names are not listed here. Please refer to the COPYRIGHT file * for contact information. * * RELIC is free software; you can redistribute it and/or modify it under the * terms of the version 2.1 (or later) of the GNU Lesser General Public License * as published by the Free Software Foundation; or version 2.0 of the Apache * License as published by the Apache Software Foundation. See the LICENSE files * for more details. * * RELIC 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 LICENSE files for more details. * * You should have received a copy of the GNU Lesser General Public or the * Apache License along with RELIC. If not, see <https://www.gnu.org/licenses/> * or <https://www.apache.org/licenses/>. */ /** * @file * * Tests for configuration management. * * @ingroup test */ #include <stdio.h> #include "relic.h" #include "relic_test.h" #if MULTI == PTHREAD void *master(void *ptr) { int *code = (int *)ptr; core_init(); RLC_THROW(ERR_NO_MEMORY); if (err_get_code() != RLC_ERR) { *code = RLC_ERR; } else { *code = RLC_OK; } core_clean(); return NULL; } void *tester(void *ptr) { int *code = (int *)ptr; core_init(); if (err_get_code() != RLC_OK) { *code = RLC_ERR; } else { *code = RLC_OK; } core_clean(); return NULL; } #endif int main(void) { int code = RLC_ERR; /* Initialize library with default configuration. */ if (core_init() != RLC_OK) { core_clean(); return 1; } util_banner("Tests for the CORE module:\n", 0); TEST_ONCE("the library context is consistent") { TEST_ASSERT(core_get() != NULL, end); } TEST_END; TEST_ONCE("switching the library context is correct") { ctx_t new_ctx, *old_ctx; /* Backup the old context. */ old_ctx = core_get(); /* Switch the library context. */ core_set(&new_ctx); /* Reinitialize library with new context. */ core_init(); /* Run function to manipulate the library context. */ RLC_THROW(ERR_NO_MEMORY); core_set(old_ctx); TEST_ASSERT(err_get_code() == RLC_OK, end); core_set(&new_ctx); TEST_ASSERT(err_get_code() == RLC_ERR, end); /* Now we need to finalize the new context. */ core_clean(); /* And restore the original context. */ core_set(old_ctx); } TEST_END; code = RLC_OK; #if MULTI == OPENMP TEST_ONCE("library context is thread-safe") { omp_set_num_threads(CORES); #pragma omp parallel shared(code) { if (omp_get_thread_num() == 0) { RLC_THROW(ERR_NO_MEMORY); if (err_get_code() != RLC_ERR) { code = RLC_ERR; } } else { core_init(); if (err_get_code() != RLC_OK) { code = RLC_ERR; } core_clean(); } } TEST_ASSERT(code == RLC_OK, end); core_init(); #pragma omp parallel copyin(core_ctx) shared(code) { if (core_get() == NULL) { code = RLC_ERR; } } TEST_ASSERT(code == RLC_OK, end); core_clean(); } TEST_END; #endif #if MULTI == PTHREAD TEST_ONCE("library context is thread-safe") { pthread_t thread[CORES]; int result[CORES] = { RLC_OK }; for (int i = 0; i < CORES; i++) { if (i == 0) { if (pthread_create(&(thread[0]), NULL, master, &(result[0]))) { code = RLC_ERR; } } else { if (pthread_create(&(thread[i]), NULL, tester, &(result[i]))) { code = RLC_ERR; } } if (result[i] != RLC_OK) { code = RLC_ERR; } } for (int i = 0; i < CORES; i++) { if (pthread_join(thread[i], NULL)) { code = RLC_ERR; } } TEST_ASSERT(code == RLC_OK, end); } TEST_END; #endif util_banner("All tests have passed.\n", 0); end: core_clean(); return code; }
watchpoint_support.c
// // WatchPointDriver.cpp // // // Created by Milind Chabbi on 2/21/17. // // #if !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #include <asm/unistd.h> #include <errno.h> #include <fcntl.h> #include <linux/hw_breakpoint.h> #include <linux/perf_event.h> #include <linux/kernel.h> #include <signal.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <ucontext.h> #include <unistd.h> #include <sys/mman.h> #include <stdint.h> #include <stdbool.h> #include <stdlib.h> #include <math.h> #include <assert.h> #include <strings.h> #include <asm/prctl.h> #include <sys/prctl.h> #include "common.h" #include <hpcrun/main.h> #include <hpcrun/hpcrun_options.h> #include <hpcrun/write_data.h> #include <hpcrun/safe-sampling.h> #include <hpcrun/hpcrun_stats.h> #include <hpcrun/memory/mmap.h> #include <hpcrun/cct/cct.h> #include <hpcrun/metrics.h> #include <hpcrun/sample_event.h> #include <hpcrun/sample_sources_registered.h> #include <hpcrun/thread_data.h> #include <hpcrun/trace.h> #include <hpcrun/env.h> #include <lush/lush-backtrace.h> #include <messages/messages.h> #include <utilities/tokenize.h> #include <utilities/arch/context-pc.h> #include <unwind/common/unwind.h> #include "watchpoint_support.h" #include <unwind/x86-family/x86-misc.h> #if ADAMANT_USED #include <adm_init_fini.h> #endif #include "matrix.h" //extern int init_adamant; //#define CHANGE_THRESHOLD 100 __thread int wait_threshold = 0; extern __thread sample_count; extern int used_wp_count; extern MonitoredNodeStruct_t MonitoredNode; extern int profiling_mode; #define REUSE_HISTO 1 //#define MAX_WP_SLOTS (5) #define IS_ALIGNED(address, alignment) (! ((size_t)(address) & (alignment-1))) #define ADDRESSES_OVERLAP(addr1, len1, addr2, len2) (((addr1)+(len1) > (addr2)) && ((addr2)+(len2) > (addr1) )) //#define CACHE_LINE_SIZE (64) //#define ALT_STACK_SZ (4 * SIGSTKSZ) #define ALT_STACK_SZ ((1L<<20) > 4 * SIGSTKSZ? (1L<<20): 4* SIGSTKSZ) //#define TEST #ifdef TEST #define EMSG(...) fprintf(stderr, __VA_ARGS__) #define hpcrun_abort() abort() #define hpcrun_safe_exit() (1) #define hpcrun_safe_enter() (1) #define hpcrun_context_pc(context) (0) #define get_previous_instruction(ip, pip) (0) #define get_mem_access_length_and_type(a, b, c) (0) #endif #if defined(PERF_EVENT_IOC_UPDATE_BREAKPOINT) #define FAST_BP_IOC_FLAG (PERF_EVENT_IOC_UPDATE_BREAKPOINT) #elif defined(PERF_EVENT_IOC_MODIFY_ATTRIBUTES) #define FAST_BP_IOC_FLAG (PERF_EVENT_IOC_MODIFY_ATTRIBUTES) #else #endif #define CHECK(x) ({int err = (x); \ if (err) { \ EMSG("%s: Failed with %d on line %d of file %s\n", strerror(errno), err, __LINE__, __FILE__); \ monitor_real_abort(); }\ err;}) #define HANDLE_ERROR_IF_ANY(val, expected, errstr) {if (val != expected) {perror(errstr); abort();}} #define SAMPLES_POST_FULL_RESET_VAL (1) #define MAX_THREAD_SIZE 503 WPConfig_t wpConfig; extern int event_type; int global_thread_count; int dynamic_global_thread_count; //const WatchPointInfo_t dummyWPInfo = {.sample = {}, .startTime =0, .fileHandle= -1, .isActive= false, .mmapBuffer=0}; //const struct DUMMY_WATCHPOINT dummyWP[MAX_WP_SLOTS]; typedef enum WP_CLIENT_ID{ WP_DEADSPY, WP_REDSPY, WP_LOADSPY, WP_REUSE, WP_REUSETRACKER, WP_TEMPORAL_REUSE, WP_SPATIAL_REUSE, WP_FALSE_SHARING, WP_COMDETECTIVE, WP_ALL_SHARING, WP_TRUE_SHARING, WP_IPC_FALSE_SHARING, WP_IPC_TRUE_SHARING, WP_IPC_ALL_SHARING, WP_MAX_CLIENTS }WP_CLIENT_ID; // Data structure that is given by clients to set a WP typedef struct ThreadData{ int lbrDummyFD __attribute__((aligned(CACHE_LINE_SZ))); stack_t ss; void * fs_reg_val; void * gs_reg_val; uint64_t samplePostFull; uint64_t numWatchpointArmingAttempt[MAX_WP_SLOTS]; pid_t os_tid; long numWatchpointTriggers; long numActiveWatchpointTriggers; long numWatchpointImpreciseIP; long numWatchpointImpreciseAddressArbitraryLength; long numWatchpointImpreciseAddress8ByteLength; long numSampleTriggeringWatchpoints; long numWatchpointDropped; long numInsaneIP; struct drand48_data randBuffer; WatchPointInfo_t watchPointArray[MAX_WP_SLOTS]; WatchPointUpCall_t fptr; volatile uint64_t counter[MAX_WP_SLOTS]; char dummy[CACHE_LINE_SZ]; } ThreadData_t; typedef struct threadDataTableStruct{ struct ThreadData hashTable[MAX_THREAD_SIZE]; //struct SharedData * hashTable; } ThreadDataTable_t; ThreadDataTable_t threadDataTable; int globalWPIsUsers[MAX_WP_SLOTS]; int L3GlobalWPIsUsers[4][MAX_WP_SLOTS]; uint64_t numWatchpointArmingAttempt[MAX_WP_SLOTS]; globalReuseTable_t globalReuseWPs; globalReuseTable_t globalStoreReuseWPs; globalReuseTable_t globalL3ReuseWPs[4]; typedef struct FdData { int fd; int tid; pid_t os_tid; } FdData_t; typedef struct fdDataTableStruct{ volatile uint64_t counter __attribute__((aligned(64))); struct FdData hashTable[503]; //struct SharedData * hashTable; } FdDataTable_t; FdDataTable_t fdDataTable = {.counter = 0}; //extern uint64_t GetWeightedMetricDiff(cct_node_t * ctxtNode, int pebsMetricId, double proportion); int fdDataInsert(int fd, pid_t os_tid, int tid) { int idx = fd % 503; //printf("fd: %d is inserted to index: %d\n", fd, idx); fdDataTable.hashTable[idx].fd = fd; fdDataTable.hashTable[idx].os_tid = os_tid; fdDataTable.hashTable[idx].tid = tid; return idx; } FdData_t fdDataGet(int fd) { int idx = fd % 503; return fdDataTable.hashTable[idx]; } static __thread ThreadData_t tData; __thread uint64_t create_wp_count = 0; __thread uint64_t arm_wp_count = 0; __thread uint64_t sub_wp_count1 = 0; __thread uint64_t sub_wp_count2 = 0; __thread uint64_t sub_wp_count3 = 0; __thread uint64_t overlap_count = 0; __thread uint64_t none_available_count = 0; __thread uint64_t wp_count = 0; __thread uint64_t wp_count1 = 0; __thread uint64_t wp_count2 = 0; __thread uint64_t wp_active = 0; __thread uint64_t wp_dropped = 0; bool IsAltStackAddress(void *addr){ if((addr >= tData.ss.ss_sp) && (addr < tData.ss.ss_sp + tData.ss.ss_size)) return true; return false; } bool IsFSorGS(void * addr) { if (tData.fs_reg_val == (void *) -1) { syscall(SYS_arch_prctl, ARCH_GET_FS, &tData.fs_reg_val); syscall(SYS_arch_prctl, ARCH_GET_GS, &tData.gs_reg_val); } // 4096 smallest one page size if ( (tData.fs_reg_val <= addr) && (addr < tData.fs_reg_val + 4096)) return true; if ( (tData.gs_reg_val <= addr) && (addr < tData.gs_reg_val + 4096)) return true; return false; } /********* OS SUPPORT ****************/ // perf-util.h has it //static long perf_event_open(struct perf_event_attr *hw_event, pid_t pid, int cpu, int group_fd, unsigned long flags) { // return syscall(__NR_perf_event_open, hw_event, pid, cpu, group_fd, flags); //} static inline void EnableWatchpoint(int fd) { // Start the event CHECK(ioctl(fd, PERF_EVENT_IOC_ENABLE, 0)); } static inline void DisableWatchpoint(WatchPointInfo_t *wpi) { // Stop the event assert(wpi->fileHandle != -1); CHECK(ioctl(wpi->fileHandle, PERF_EVENT_IOC_DISABLE, 0)); wpi->isActive = false; } static void * MAPWPMBuffer(int fd){ void * buf = mmap(0, 2 * wpConfig.pgsz, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if (buf == MAP_FAILED) { fprintf(stderr, "Failed to mmap : %s\n", strerror(errno)); EMSG("Failed to mmap : %s\n", strerror(errno)); monitor_real_abort(); } return buf; } static void UNMAPWPMBuffer(void * buf){ CHECK(munmap(buf, 2 * wpConfig.pgsz)); } static int OnWatchPoint(int signum, siginfo_t *info, void *context); __attribute__((constructor)) static void InitConfig(){ /*if(!init_adamant) { init_adamant = 1;*/ //adm_initialize(); //} tData.fptr = NULL; volatile int dummyWP[MAX_WP_SLOTS]; wpConfig.isLBREnabled = true; struct perf_event_attr peLBR = { .type = PERF_TYPE_BREAKPOINT, .size = sizeof(struct perf_event_attr), .bp_type = HW_BREAKPOINT_W, .bp_len = HW_BREAKPOINT_LEN_1, .bp_addr = (uintptr_t)&dummyWP[0], .sample_period = 1, .precise_ip = 0 /* arbitraty skid */, .sample_type = 0, .exclude_user = 0, .exclude_kernel = 1, .exclude_hv = 1, .disabled = 0, /* enabled */ }; int fd = perf_event_open(&peLBR, 0, -1, -1 /*group*/, 0); if (fd != -1) { wpConfig.isLBREnabled = true; } else { wpConfig.isLBREnabled = false; } CHECK(close(fd)); #if defined(FAST_BP_IOC_FLAG) wpConfig.isWPModifyEnabled = true; #else wpConfig.isWPModifyEnabled = false; #endif //wpConfig.signalDelivered = SIGTRAP; //wpConfig.signalDelivered = SIGIO; //wpConfig.signalDelivered = SIGUSR1; wpConfig.signalDelivered = SIGRTMIN + 3; // Setup the signal handler sigset_t block_mask; sigfillset(&block_mask); // Set a signal handler for SIGUSR1 struct sigaction sa1 = { .sa_sigaction = OnWatchPoint, .sa_mask = block_mask, .sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER | SA_ONSTACK }; if(monitor_sigaction(wpConfig.signalDelivered, OnWatchPoint, 0 /*flags*/, &sa1) == -1) { fprintf(stderr, "Failed to set WHICH_SIG handler: %s\n", strerror(errno)); monitor_real_abort(); } wpConfig.pgsz = sysconf(_SC_PAGESIZE); // identify max WP supported by the architecture //fprintf(stderr, "watchpoints are created\n"); volatile int wpHandles[MAX_WP_SLOTS]; int i = 0; for(; i < MAX_WP_SLOTS; i++){ struct perf_event_attr pe = { .type = PERF_TYPE_BREAKPOINT, .size = sizeof(struct perf_event_attr), .bp_type = HW_BREAKPOINT_W, .bp_len = HW_BREAKPOINT_LEN_1, .bp_addr = (uintptr_t)&dummyWP[i], .sample_period = 1, .precise_ip = 0 /* arbitraty skid */, .sample_type = 0, .exclude_user = 0, .exclude_kernel = 1, .exclude_hv = 1, .disabled = 0, /* enabled */ }; wpHandles[i] = perf_event_open(&pe, 0, -1, -1 /*group*/, 0); if (wpHandles[i] == -1) { break; } } if(i == 0) { fprintf(stderr, "Cannot create a single watch point\n"); monitor_real_abort(); } for (int j = 0 ; j < i; j ++) { CHECK(close(wpHandles[j])); } int custom_wp_size = atoi(getenv(WATCHPOINT_SIZE)); if(custom_wp_size < i) wpConfig.maxWP = custom_wp_size; else wpConfig.maxWP = i; fprintf(stderr, "wpConfig.maxWP: %d\n", wpConfig.maxWP); //fprintf(stderr, "custom_wp_size is %d\n", custom_wp_size); // Should we get the floating point type in an access? wpConfig.getFloatType = false; // Get the replacement scheme char * replacementScheme = getenv("HPCRUN_WP_REPLACEMENT_SCHEME"); if(replacementScheme){ if(0 == strcasecmp(replacementScheme, "AUTO")) { wpConfig.replacementPolicy = AUTO; } if (0 == strcasecmp(replacementScheme, "OLDEST")) { wpConfig.replacementPolicy = OLDEST; } if (0 == strcasecmp(replacementScheme, "NEWEST")) { wpConfig.replacementPolicy = NEWEST; } else { // default; wpConfig.replacementPolicy = AUTO; } } else { // default; wpConfig.replacementPolicy = AUTO; } //fprintf(stderr, "InitConfig is called\n"); // Should we fix IP off by one? char * fixIP = getenv("HPCRUN_WP_DONT_FIX_IP"); if(fixIP){ if(0 == strcasecmp(fixIP, "1")) { wpConfig.dontFixIP = true; } if (0 == strcasecmp(fixIP, "true")) { wpConfig.dontFixIP = true; } else { // default; wpConfig.dontFixIP = false; } } else { // default; wpConfig.dontFixIP = false; } // Should we get the address in a WP trigger? char * disassembleWPAddress = getenv("HPCRUN_WP_DONT_DISASSEMBLE_TRIGGER_ADDRESS"); if(disassembleWPAddress){ if(0 == strcasecmp(disassembleWPAddress, "1")) { wpConfig.dontDisassembleWPAddress = true; } if (0 == strcasecmp(disassembleWPAddress, "true")) { wpConfig.dontDisassembleWPAddress = true; } else { // default; wpConfig.dontDisassembleWPAddress = false; } } else { // default; wpConfig.dontDisassembleWPAddress = false; } char * cachelineInvalidation = getenv("HPCRUN_WP_CACHELINE_INVALIDATION"); if(cachelineInvalidation){ if(0 == strcasecmp(cachelineInvalidation, "1")) { wpConfig.cachelineInvalidation = true; } if (0 == strcasecmp(cachelineInvalidation, "true")) { wpConfig.cachelineInvalidation = true; } else { // default; wpConfig.cachelineInvalidation = false; } } else { // default; wpConfig.cachelineInvalidation = false; } for(int i = 0; i < 503; i++) { for(int j = 0; j < MAX_WP_SLOTS; j++) { threadDataTable.hashTable[i].counter[j] = 0; } threadDataTable.hashTable[i].os_tid = -1; } for(int i = 0; i < MAX_WP_SLOTS; i++) { globalWPIsUsers[i] = -1; numWatchpointArmingAttempt[i] = SAMPLES_POST_FULL_RESET_VAL; globalReuseWPs.table[i].tid = -1; globalReuseWPs.table[i].monitored_tid = -1; globalReuseWPs.table[i].time = -1; globalStoreReuseWPs.table[i].is_rar = false; //globalReuseWPs.table[i].trap_just_happened = false; globalReuseWPs.table[i].active = false; globalReuseWPs.table[i].sharedActive = false; //globalReuseWPs.table[i].first_coherence_miss = false; globalReuseWPs.table[i].counter = 0; globalReuseWPs.table[i].node_id = -1; //globalReuseWPs.table[i].sampleCountInNode = 0; globalStoreReuseWPs.table[i].active = false; //globalStoreReuseWPs.table[i].first_coherence_miss = false; //globalStoreReuseWPs.table[i].trap_just_happened = false; globalStoreReuseWPs.table[i].counter = 0; } globalReuseWPs.counter = 0; MonitoredNode.timestamp = 0; MonitoredNode.trap_timestamp = 0; MonitoredNode.self_trap = false; MonitoredNode.counter = 0; MonitoredNode.tid = -1; } void RedSpyWPConfigOverride(void *v){ wpConfig.getFloatType = true; } void LoadSpyWPConfigOverride(void *v){ wpConfig.getFloatType = true; } void FalseSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void ComDetectiveWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void ReuseWPConfigOverride(void *v){ // dont fix IP //wpConfig.dontFixIP = true; //wpConfig.dontDisassembleWPAddress = true; //wpConfig.isLBREnabled = false; //jqswang fprintf(stderr, "ReuseWPConfigOverride is called\n"); wpConfig.replacementPolicy = RDX; //wpConfig.replacementPolicy = OLDEST; } void TrueSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void AllSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void IPCFalseSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void IPCTrueSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void IPCAllSharingWPConfigOverride(void *v){ // replacement policy is OLDEST forced. wpConfig.replacementPolicy = OLDEST; } void TemporalReuseWPConfigOverride(void *v){ // dont fix IP wpConfig.dontFixIP = true; wpConfig.dontDisassembleWPAddress = true; } void SpatialReuseWPConfigOverride(void *v){ // dont fix IP wpConfig.dontFixIP = true; wpConfig.dontDisassembleWPAddress = true; } static void CreateWatchPoint(WatchPointInfo_t * wpi, SampleData_t * sampleData, bool modify) { // Perf event settings create_wp_count++; struct perf_event_attr pe = { .type = PERF_TYPE_BREAKPOINT, .size = sizeof(struct perf_event_attr), // .bp_type = HW_BREAKPOINT_W, // .bp_len = HW_BREAKPOINT_LEN_4, .sample_period = 1, .precise_ip = wpConfig.isLBREnabled? 2 /*precise_ip 0 skid*/ : 0 /* arbitraty skid */, .sample_type = (PERF_SAMPLE_IP), .exclude_user = 0, .exclude_kernel = 1, .exclude_hv = 1, .disabled = 0, /* enabled */ }; switch (sampleData->wpLength) { case 1: pe.bp_len = HW_BREAKPOINT_LEN_1; break; case 2: pe.bp_len = HW_BREAKPOINT_LEN_2; break; case 4: pe.bp_len = HW_BREAKPOINT_LEN_4; break; case 8: pe.bp_len = HW_BREAKPOINT_LEN_8; break; default: EMSG("Unsupported .bp_len %d: %s\n", wpi->sample.wpLength,strerror(errno)); monitor_real_abort(); } pe.bp_addr = (uintptr_t)sampleData->va; switch (sampleData->type) { case WP_READ: pe.bp_type = HW_BREAKPOINT_R; break; case WP_WRITE: pe.bp_type = HW_BREAKPOINT_W; break; default: pe.bp_type = HW_BREAKPOINT_W | HW_BREAKPOINT_R; } //fprintf(stderr, "pe.bp_len: %d, pe.bp_addr: %lx\n", pe.bp_len, pe.bp_addr); #if defined(FAST_BP_IOC_FLAG) if(modify) { // modification assert(wpi->fileHandle != -1); assert(wpi->mmapBuffer != 0); //DisableWatchpoint(wpi); //fprintf(stderr, "watchpoint is created with FAST_BP_IOC_FLAG\n"); //create_wp_count++; CHECK(ioctl(wpi->fileHandle, FAST_BP_IOC_FLAG, (unsigned long) (&pe))); //if(wpi->isActive == false) { //EnableWatchpoint(wpi->fileHandle); //} } else #endif { //create_wp_count++; // fresh creation // Create the perf_event for this thread on all CPUs with no event group //fprintf(stderr, "watchpoint is created with perf_event_open\n"); int perf_fd = perf_event_open(&pe, 0, -1, -1 /*group*/, 0); if (perf_fd == -1) { EMSG("Failed to open perf event file: %s\n",strerror(errno)); monitor_real_abort(); } // Set the perf_event file to async mode CHECK(fcntl(perf_fd, F_SETFL, fcntl(perf_fd, F_GETFL, 0) | O_ASYNC)); // Tell the file to send a signal when an event occurs CHECK(fcntl(perf_fd, F_SETSIG, wpConfig.signalDelivered)); // Deliver the signal to this thread struct f_owner_ex fown_ex; fown_ex.type = F_OWNER_TID; fown_ex.pid = syscall(__NR_gettid);//gettid(); int ret = fcntl(perf_fd, F_SETOWN_EX, &fown_ex); if (ret == -1){ EMSG("Failed to set the owner of the perf event file: %s\n", strerror(errno)); return; } // CHECK(fcntl(perf_fd, F_SETOWN, gettid())); wpi->fileHandle = perf_fd; // mmap the file if lbr is enabled if(wpConfig.isLBREnabled) { wpi->mmapBuffer = MAPWPMBuffer(perf_fd); } } wp_active++; wpi->isActive = true; wpi->va = (void *) pe.bp_addr; wpi->sample = *sampleData; wpi->startTime = rdtsc(); wpi->bulletinBoardTimestamp = sampleData->bulletinBoardTimestamp; } static void CreateWatchPointShared(WatchPointInfo_t * wpi, SampleData_t * sampleData, int tid, bool modify) { // Perf event settings create_wp_count++; struct perf_event_attr pe = { .type = PERF_TYPE_BREAKPOINT, .size = sizeof(struct perf_event_attr), // .bp_type = HW_BREAKPOINT_W, // .bp_len = HW_BREAKPOINT_LEN_4, .sample_period = 1, .precise_ip = wpConfig.isLBREnabled? 2 /*precise_ip 0 skid*/ : 0 /* arbitraty skid */, .sample_type = (PERF_SAMPLE_IP), .exclude_user = 0, .exclude_kernel = 1, .exclude_hv = 1, .disabled = 0, /* enabled */ }; switch (sampleData->wpLength) { case 1: pe.bp_len = HW_BREAKPOINT_LEN_1; break; case 2: pe.bp_len = HW_BREAKPOINT_LEN_2; break; case 4: pe.bp_len = HW_BREAKPOINT_LEN_4; break; case 8: pe.bp_len = HW_BREAKPOINT_LEN_8; break; default: EMSG("Unsupported .bp_len %d: %s\n", wpi->sample.wpLength,strerror(errno)); fprintf(stderr, "error: Unsupported .bp_len %d: %s\n", wpi->sample.wpLength,strerror(errno)); monitor_real_abort(); } pe.bp_addr = (uintptr_t)sampleData->va; switch (sampleData->type) { case WP_READ: pe.bp_type = HW_BREAKPOINT_R; break; case WP_WRITE: pe.bp_type = HW_BREAKPOINT_W; break; default: pe.bp_type = HW_BREAKPOINT_W | HW_BREAKPOINT_R; } #if defined(FAST_BP_IOC_FLAG) if(modify) { assert(wpi->fileHandle != -1); assert(wpi->mmapBuffer != 0); //fprintf(stderr, "this region is reached\n"); CHECK(ioctl(wpi->fileHandle, FAST_BP_IOC_FLAG, (unsigned long) (&pe))); } else #endif if (threadDataTable.hashTable[tid].os_tid != -1) { int perf_fd = perf_event_open(&pe, threadDataTable.hashTable[tid].os_tid, -1, -1, 0); if (perf_fd == -1) { EMSG("Failed to open perf event file: %s\n",strerror(errno)); return; } // Set the perf_event file to async mode CHECK(fcntl(perf_fd, F_SETFL, fcntl(perf_fd, F_GETFL, 0) | O_ASYNC)); // Tell the file to send a signal when an event occurs CHECK(fcntl(perf_fd, F_SETSIG, wpConfig.signalDelivered)); // Deliver the signal to this thread struct f_owner_ex fown_ex; fown_ex.type = F_OWNER_TID; fown_ex.pid = threadDataTable.hashTable[tid].os_tid; //gettid(); int ret = fcntl(perf_fd, F_SETOWN_EX, &fown_ex); if (ret == -1){ EMSG("Failed to set the owner of the perf event file: %s\n", strerror(errno)); return; } // CHECK(fcntl(perf_fd, F_SETOWN, gettid())); wpi->fileHandle = perf_fd; // insert to perf_fd - tid table here // mmap the file if lbr is enabled if(wpConfig.isLBREnabled) { //fprintf(stderr, "mmapBuffer is initialized\n"); wpi->mmapBuffer = MAPWPMBuffer(perf_fd); } //fprintf(stderr, "perf_event_open has been used successfully\n"); int idx = fdDataInsert(perf_fd, threadDataTable.hashTable[tid].os_tid, tid); } wp_active++; wpi->isActive = true; wpi->va = (void *) pe.bp_addr; wpi->sample = *sampleData; wpi->startTime = rdtsc(); } /* create a dummy PERF_TYPE_HARDWARE event that will never fire */ static void CreateDummyHardwareEvent(void) { // Perf event settings struct perf_event_attr pe = { .type = PERF_TYPE_HARDWARE, .size = sizeof(struct perf_event_attr), .config = PERF_COUNT_HW_CACHE_MISSES, .sample_period = 0x7fffffffffffffff, /* some insanely large sample period */ .precise_ip = 2, .sample_type = PERF_SAMPLE_BRANCH_STACK, .exclude_user = 0, .exclude_kernel = 1, .exclude_hv = 1, .branch_sample_type = PERF_SAMPLE_BRANCH_ANY, }; // Create the perf_event for this thread on all CPUs with no event group int perf_fd = perf_event_open(&pe, 0, -1, -1, 0); if (perf_fd == -1) { EMSG("Failed to open perf event file: %s\n", strerror(errno)); monitor_real_abort(); } tData.lbrDummyFD = perf_fd; } static void CloseDummyHardwareEvent(int perf_fd){ CHECK(close(perf_fd)); } /*********** Client interfaces *******/ static void DisArm(WatchPointInfo_t * wpi){ // assert(wpi->isActive); assert(wpi->fileHandle != -1); if(wpi->mmapBuffer) UNMAPWPMBuffer(wpi->mmapBuffer); wpi->mmapBuffer = 0; CHECK(close(wpi->fileHandle)); wpi->fileHandle = -1; wpi->isActive = false; } static bool ArmWatchPoint(WatchPointInfo_t * wpi, SampleData_t * sampleData) { // if WP modification is suppoted use it //void * cacheLineBaseAddress = (void *) ((uint64_t)((size_t)sampleData->va) & (~(64-1))); arm_wp_count++; if(wpConfig.isWPModifyEnabled){ // Does not matter whether it was active or not. // If it was not active, enable it. if(wpi->fileHandle != -1) { CreateWatchPoint(wpi, sampleData, true); return true; } } // disable the old WP if active if(wpi->isActive) { DisArm(wpi); } CreateWatchPoint(wpi, sampleData, false); return true; } static bool ArmWatchPointShared(WatchPointInfo_t * wpi, SampleData_t * sampleData, int tid) { arm_wp_count++; if(wpConfig.isWPModifyEnabled){ // Does not matter whether it was active or not. // If it was not active, enable it. if((wpi->fileHandle != -1) && (sampleData->first_accessing_tid == wpi->sample.first_accessing_tid)) { //fprintf(stderr, "CreateWatchPointShared is entered with modify by thread %d in thread %d\n", TD_GET(core_profile_trace_data.id), tid); CreateWatchPointShared(wpi, sampleData, tid, true); return true; } } if(wpi->fileHandle != -1) { DisArm(wpi); } //fprintf(stderr, "CreateWatchPointShared is entered without modify\n"); //fprintf(stderr, "CreateWatchPointShared is entered with modify by thread %d in thread %d without modify\n", TD_GET(core_profile_trace_data.id), tid); CreateWatchPointShared(wpi, sampleData, tid, false); return true; } // Per thread initialization void WatchpointThreadInit(WatchPointUpCall_t func){ //global_thread_count++; //dynamic_global_thread_count++; tData.ss.ss_sp = malloc(ALT_STACK_SZ); if (tData.ss.ss_sp == NULL){ EMSG("Failed to malloc ALT_STACK_SZ"); monitor_real_abort(); } tData.ss.ss_size = ALT_STACK_SZ; tData.ss.ss_flags = 0; if (sigaltstack(&tData.ss, NULL) == -1){ EMSG("Failed sigaltstack"); monitor_real_abort(); } tData.lbrDummyFD = -1; tData.fptr = func; tData.fs_reg_val = (void*)-1; tData.gs_reg_val = (void*)-1; srand48_r(time(NULL), &tData.randBuffer); tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; tData.numWatchpointTriggers = 0; tData.numWatchpointImpreciseIP = 0; tData.numWatchpointImpreciseAddressArbitraryLength = 0; tData.numWatchpointImpreciseAddress8ByteLength = 0; tData.numWatchpointDropped = 0; tData.numSampleTriggeringWatchpoints = 0; tData.numInsaneIP = 0; for (int i=0; i<wpConfig.maxWP; i++) { tData.watchPointArray[i].isActive = false; tData.watchPointArray[i].fileHandle = -1; tData.watchPointArray[i].startTime = 0; tData.numWatchpointArmingAttempt[i] = SAMPLES_POST_FULL_RESET_VAL; } //if LBR is supported create a dummy PERF_TYPE_HARDWARE for Linux workaround if(wpConfig.isLBREnabled) { CreateDummyHardwareEvent(); } #ifdef REUSE_HISTO int me = TD_GET(core_profile_trace_data.id); tData.os_tid = syscall(__NR_gettid); //gettid(); for(int i = 0; i < MAX_WP_SLOTS; i++) tData.counter[i] = 0; //if((event_type == WP_REUSE_MT) || (event_type == WP_MT_REUSE)) threadDataTable.hashTable[me] = tData; #endif } void WatchpointThreadTerminate(){ int me = TD_GET(core_profile_trace_data.id); dynamic_global_thread_count--; ThreadData_t threadData; if(event_type == WP_REUSETRACKER) { // before int location = -1; for(int j = 0; j < wpConfig.maxWP; j++) { if(me == globalReuseWPs.table[j].monitored_tid) { globalReuseWPs.table[j].monitored_tid = -1; break; } } for(int j = 0; j < wpConfig.maxWP; j++) { if(me == globalWPIsUsers[j]) { location = j; break; } } if(location != -1) { while(1) { uint64_t theCounter = globalReuseWPs.counter; if((theCounter & 1) == 0) { if(__sync_bool_compare_and_swap(&globalReuseWPs.counter, theCounter, theCounter+1)) { globalWPIsUsers[location] = -1; globalReuseWPs.table[location].tid = -1; used_wp_count--; if(MonitoredNode.tid == me) MonitoredNode.tid = -1; //fprintf(stderr, "WP number %d is released by thread %d\n", location, me); // after globalReuseWPs.counter++; break; } } } } // after threadDataTable.hashTable[me].os_tid = -1; threadData = threadDataTable.hashTable[me]; for (int i = 0; i < wpConfig.maxWP; i++) { if(threadDataTable.hashTable[me].watchPointArray[i].fileHandle != -1) { DisArm(&threadDataTable.hashTable[me].watchPointArray[i]); } } if(threadData.lbrDummyFD != -1) { CloseDummyHardwareEvent(threadDataTable.hashTable[me].lbrDummyFD); threadDataTable.hashTable[me].lbrDummyFD = -1; } threadDataTable.hashTable[me].fs_reg_val = (void*)-1; threadDataTable.hashTable[me].gs_reg_val = (void*)-1; } else { for (int i = 0; i < wpConfig.maxWP; i++) { if(tData.watchPointArray[i].fileHandle != -1) { DisArm(&tData.watchPointArray[i]); } } if(tData.lbrDummyFD != -1) { CloseDummyHardwareEvent(tData.lbrDummyFD); tData.lbrDummyFD = -1; } tData.fs_reg_val = (void*)-1; tData.gs_reg_val = (void*)-1; } //fprintf(stderr, "tData.numWatchpointTriggers: %ld\n", tData.numWatchpointTriggers); //fprintf(stderr, "tData.numActiveWatchpointTriggers: %ld\n", tData.numActiveWatchpointTriggers); hpcrun_stats_num_watchpoints_triggered_inc(tData.numWatchpointTriggers); hpcrun_stats_num_watchpoints_imprecise_inc(tData.numWatchpointImpreciseIP); hpcrun_stats_num_watchpoints_imprecise_address_inc(tData.numWatchpointImpreciseAddressArbitraryLength); hpcrun_stats_num_watchpoints_imprecise_address_8_byte_inc(tData.numWatchpointImpreciseAddress8ByteLength); hpcrun_stats_num_insane_ip_inc(tData.numInsaneIP); hpcrun_stats_num_watchpoints_dropped_inc(tData.numWatchpointDropped); hpcrun_stats_num_sample_triggering_watchpoints_inc(tData.numSampleTriggeringWatchpoints); #if 0 tData.ss.ss_flags = SS_DISABLE; if (sigaltstack(&tData.ss, NULL) == -1){ EMSG("Failed sigaltstack WatchpointThreadTerminate"); // no need to abort , just leak the memory // monitor_real_abort(); } else { if(tData.ss.ss_sp) free(tData.ss.ss_sp); } #endif } bool ArmWatchPointProb(int * location, uint64_t sampleTime, int me) { double probabilityToReplace = 1.0/((double)numWatchpointArmingAttempt[*location]); double randValue; drand48_r(&tData.randBuffer, &randValue); if((randValue <= probabilityToReplace) /*|| (profiling_mode == L3 && probabilityToReplace <= 0.001)*/) { /*if(profiling_mode == L3 && probabilityToReplace <= 0.001) fprintf(stderr, "reset that is special to L3 profiling");*/ numWatchpointArmingAttempt[*location]++; //fprintf(stderr, "watchpoint is armed randValue: %0.2lf and probabilityToReplace: %0.2lf, denominator: %d, location: %d, arming thread: %d\n", randValue, probabilityToReplace, numWatchpointArmingAttempt[*location]-1, *location, TD_GET(core_profile_trace_data.id)); globalReuseWPs.table[*location].active = true; globalReuseWPs.table[*location].sharedActive = true; //globalReuseWPs.table[*location].first_coherence_miss = true; globalReuseWPs.table[*location].time = sampleTime; globalReuseWPs.table[*location].monitored_tid = me; globalReuseWPs.table[*location].self_trap = true; globalReuseWPs.table[*location].is_rar = false; globalReuseWPs.table[*location].inc = 0; globalReuseWPs.table[*location].rd = 0; return true; } else { //fprintf(stderr, "thread %d fails to arm location %d while a wp armed by %d is still monitored, randValue: %0.2lf, probabilityToReplace:%0.2lf\n", me, *location, globalReuseWPs.table[*location].monitored_tid, randValue, probabilityToReplace); } //fprintf(stderr, "watchpoint is not armed randValue: %0.2lf and probabilityToReplace: %0.2lf, denominator: %d, location: %d, arming thread: %d\n", randValue, probabilityToReplace, numWatchpointArmingAttempt[*location], *location, TD_GET(core_profile_trace_data.id)); /*if(globalReuseWPs.table[*location].monitored_tid != globalReuseWPs.table[*location].tid) fprintf(stderr, "owner tid is different from monitored tid and watchpoint arming is not allowed\n");*/ numWatchpointArmingAttempt[*location]++; return false; } // Finds a victim slot to set a new WP static VictimType GetVictim(int * location, ReplacementPolicy policy){ // If any WP slot is inactive, return it; for(int i = 0; i < wpConfig.maxWP; i++){ if(!tData.watchPointArray[i].isActive) { *location = i; //fprintf(stderr, "empty slot found in watchpoint %d by thread %d, tData.numWatchpointArmingAttempt[0]: %ld, tData.numWatchpointArmingAttempt[1]: %ld, tData.numWatchpointArmingAttempt[2]: %ld, tData.numWatchpointArmingAttempt[3]: %ld, tData.watchPointArray[0].isActive: %d, tData.watchPointArray[1].isActive: %d, tData.watchPointArray[2].isActive: %d, tData.watchPointArray[3].isActive: %d\n", i, TD_GET(core_profile_trace_data.id), tData.numWatchpointArmingAttempt[0], tData.numWatchpointArmingAttempt[1], tData.numWatchpointArmingAttempt[2], tData.numWatchpointArmingAttempt[3], tData.watchPointArray[0].isActive, tData.watchPointArray[1].isActive, tData.watchPointArray[2].isActive, tData.watchPointArray[3].isActive); if(policy == RDX) { for(int j = 0; j < wpConfig.maxWP; j++){ if(tData.watchPointArray[j].isActive || (i == j)){ tData.numWatchpointArmingAttempt[j]++; } } } //fprintf(stderr, "after empty slot found in watchpoint %d by thread %d, tData.numWatchpointArmingAttempt[0]: %ld, tData.numWatchpointArmingAttempt[1]: %ld, tData.numWatchpointArmingAttempt[2]: %ld, tData.numWatchpointArmingAttempt[3]: %ld, tData.watchPointArray[0].isActive: %d, tData.watchPointArray[1].isActive: %d, tData.watchPointArray[2].isActive: %d, tData.watchPointArray[3].isActive: %d\n", i, TD_GET(core_profile_trace_data.id), tData.numWatchpointArmingAttempt[0], tData.numWatchpointArmingAttempt[1], tData.numWatchpointArmingAttempt[2], tData.numWatchpointArmingAttempt[3], tData.watchPointArray[0].isActive, tData.watchPointArray[1].isActive, tData.watchPointArray[2].isActive, tData.watchPointArray[3].isActive); return EMPTY_SLOT; } } switch (policy) { case AUTO:{ //fprintf(stderr, "replacement policy is AUTO\n"); // Equal probability for any data access // Randomly pick a slot to victimize. long int tmpVal; lrand48_r(&tData.randBuffer, &tmpVal); int rSlot = tmpVal % wpConfig.maxWP; *location = rSlot; // if it is the first sample after full, use wpConfig.maxWP/(wpConfig.maxWP+1) probability to replace. // if it is the second sample after full, use wpConfig.maxWP/(wpConfig.maxWP+2) probability to replace. // if it is the third sample after full, use wpConfig.maxWP/(wpConfig.maxWP+3) probability replace. double probabilityToReplace = wpConfig.maxWP/((double)wpConfig.maxWP+tData.samplePostFull); double randValue; drand48_r(&tData.randBuffer, &randValue); // update tData.samplePostFull //fprintf(stderr, "thread id: %d, tData.samplePostFull: %ld\n", TD_GET(core_profile_trace_data.id), tData.samplePostFull); tData.samplePostFull++; //fprintf(stderr, "thread id: %d, tData.samplePostFull: %ld\n", TD_GET(core_profile_trace_data.id), tData.samplePostFull); //fprintf(stderr, "probabilityToReplace: %0.2lf\n", probabilityToReplace); if(/*randValue <= probabilityToReplace*/ 1) { return NON_EMPTY_SLOT; } // this is an indication not to replace, but if the client chooses to force, they can return NONE_AVAILABLE; } break; case NEWEST:{ // Always replace the newest //fprintf(stderr, "replacement policy is NEWEST\n"); int64_t newestTime = 0; for(int i = 0; i < wpConfig.maxWP; i++){ if(newestTime < tData.watchPointArray[i].startTime) { *location = i; newestTime = tData.watchPointArray[i].startTime; } } return NON_EMPTY_SLOT; } break; case OLDEST:{ // Always replace the oldest //fprintf(stderr, "replacement policy is OLDEST\n"); int64_t oldestTime = INT64_MAX; for(int i = 0; i < wpConfig.maxWP; i++){ if(oldestTime > tData.watchPointArray[i].startTime) { *location = i; oldestTime = tData.watchPointArray[i].startTime; } } return NON_EMPTY_SLOT; } break; case EMPTY_SLOT_ONLY:{ return NONE_AVAILABLE; } break; case RDX:{ // make a random sequence of watchpoints to visit // before int indices[wpConfig.maxWP]; for (int i = 0; i < wpConfig.maxWP; i++) { indices[i] = i; } //fprintf(stderr, "in thread %d, before indices[0]: %d, indices[1]: %d, indices[2]: %d, indices[3]: %d\n", TD_GET(core_profile_trace_data.id), indices[0], indices[1], indices[2], indices[3]); int wp_index = wpConfig.maxWP; while (wp_index) { long int tmpVal; lrand48_r(&tData.randBuffer, &tmpVal); int index = tmpVal % wp_index; wp_index--; int swap = indices[index]; indices[index] = indices[wp_index]; indices[wp_index] = swap; } //fprintf(stderr, "in thread %d, after indices[0]: %d, indices[1]: %d, indices[2]: %d, indices[3]: %d\n", TD_GET(core_profile_trace_data.id), indices[0], indices[1], indices[2], indices[3]); // after // visit each watchpoint according to the sequence for(int i = 0; i < wpConfig.maxWP; i++) { int idx = indices[i]; double probabilityToReplace = 1.0/((double)tData.numWatchpointArmingAttempt[idx]); double randValue; drand48_r(&tData.randBuffer, &randValue); //fprintf(stderr, "i: %d, idx: %d, denominator: %ld, probability: %0.4lf\n", i, idx, tData.numWatchpointArmingAttempt[idx], probabilityToReplace); if(randValue <= probabilityToReplace /* 1 */) { *location = idx; //fprintf(stderr, "arming watchpoint at i: %d and probability: %0.4lf\n", i, probabilityToReplace); for(int j = 0; j < wpConfig.maxWP; j++){ tData.numWatchpointArmingAttempt[j]++; } return NON_EMPTY_SLOT; } } for(int i = 0; i < wpConfig.maxWP; i++) { tData.numWatchpointArmingAttempt[i]++; } return NONE_AVAILABLE; } break; default: return NONE_AVAILABLE; } // No unarmed WP slot found. } static inline void rmb(void) { asm volatile("lfence":::"memory"); } static void ConsumeAllRingBufferData(void *mbuf) { struct perf_event_mmap_page *hdr = (struct perf_event_mmap_page *)mbuf; unsigned long tail; size_t avail_sz; size_t pgmsk = wpConfig.pgsz - 1; /* * data points to beginning of buffer payload */ void * data = ((void *)hdr) + wpConfig.pgsz; /* * position of tail within the buffer payload */ tail = hdr->data_tail & pgmsk; /* * size of what is available * * data_head, data_tail never wrap around */ avail_sz = hdr->data_head - hdr->data_tail; rmb(); #if 0 if(avail_sz == 0 ) EMSG("\n avail_sz = %d\n", avail_sz); else EMSG("\n EEavail_sz = %d\n", avail_sz); #endif // reset tail to head hdr->data_tail = hdr->data_head; } static int ReadMampBuffer(void *mbuf, void *buf, size_t sz) { //fprintf(stderr, "in ReadMampBuffer\n"); struct perf_event_mmap_page *hdr = (struct perf_event_mmap_page *)mbuf; //fprintf(stderr, "in ReadMampBuffer 6\n"); void *data; unsigned long tail; size_t avail_sz, m, c; size_t pgmsk = wpConfig.pgsz - 1; if(hdr == NULL) return -1; /* * data points to beginning of buffer payload */ data = ((void *)hdr) + wpConfig.pgsz; /* * position of tail within the buffer payload */ //fprintf(stderr, "in ReadMampBuffer 7\n"); tail = hdr->data_tail & pgmsk; /* * size of what is available * * data_head, data_tail never wrap around */ //fprintf(stderr, "in ReadMampBuffer 5\n"); avail_sz = hdr->data_head - hdr->data_tail; if (sz > avail_sz) { //printf("\n sz > avail_sz: sz = %lu, avail_sz = %lu\n", sz, avail_sz); rmb(); return -1; } /* From perf_event_open() manpage */ rmb(); /* * sz <= avail_sz, we can satisfy the request */ /* * c = size till end of buffer * * buffer payload size is necessarily * a power of two, so we can do: */ c = pgmsk + 1 - tail; /* * min with requested size */ m = c < sz ? c : sz; //fprintf(stderr, "in ReadMampBuffer 4\n"); /* copy beginning */ memcpy(buf, data + tail, m); /* * copy wrapped around leftover */ //fprintf(stderr, "in ReadMampBuffer 3\n"); if (sz > m) memcpy(buf + m, data, sz - m); //fprintf(stderr, "in ReadMampBuffer 2\n"); hdr->data_tail += sz; return 0; } void SkipBuffer(struct perf_event_mmap_page *hdr, size_t sz){ if ((hdr->data_tail + sz) > hdr->data_head) sz = hdr->data_head - hdr->data_tail; rmb(); hdr->data_tail += sz; } static inline bool IsPCSane(void * contextPC, void *possiblePC){ if( (possiblePC==0) || ((possiblePC > contextPC) || (contextPC-possiblePC > 15))){ return false; } return true; } double ProportionOfWatchpointAmongOthersSharingTheSameContext(WatchPointInfo_t *wpi){ #if 0 int share = 0; for(int i = 0; i < wpConfig.maxWP; i++) { if(tData.watchPointArray[i].isActive && tData.watchPointArray[i].sample.node == wpi->sample.node) { share ++; } } assert(share > 0); return 1.0/share; #else return 1.0; #endif } static inline void * GetPatchedIP(void * contextIP) { void * patchedIP; void * excludeList[MAX_WP_SLOTS] = {0}; int numExcludes = 0; for(int idx = 0; idx < wpConfig.maxWP; idx++){ if(tData.watchPointArray[idx].isActive) { excludeList[numExcludes]=tData.watchPointArray[idx].va; numExcludes++; } } get_previous_instruction(contextIP, &patchedIP, excludeList, numExcludes); return patchedIP; } static inline void * GetPatchedIPShared(void * contextIP, int me) { //fprintf(stderr, "in GetPatchedIPShared\n"); ThreadData_t threadData = threadDataTable.hashTable[me]; void * patchedIP; void * excludeList[MAX_WP_SLOTS] = {0}; int numExcludes = 0; for(int idx = 0; idx < wpConfig.maxWP; idx++){ if(threadData.watchPointArray[idx].isActive) { excludeList[numExcludes]=threadData.watchPointArray[idx].va; numExcludes++; } } get_previous_instruction(contextIP, &patchedIP, excludeList, numExcludes); return patchedIP; } // Gather all useful data when a WP triggers static bool CollectWatchPointTriggerInfo(WatchPointInfo_t * wpi, WatchPointTrigger_t *wpt, void * context){ //struct perf_event_mmap_page * b = wpi->mmapBuffer; struct perf_event_header hdr; //fprintf(stderr, "in CollectWatchPointTriggerInfo\n"); if (ReadMampBuffer(wpi->mmapBuffer, &hdr, sizeof(struct perf_event_header)) < 0) { EMSG("Failed to ReadMampBuffer: %s\n", strerror(errno)); monitor_real_abort(); } //fprintf(stderr, "in CollectWatchPointTriggerInfo 1\n"); switch(hdr.type) { case PERF_RECORD_SAMPLE: assert (hdr.type & PERF_SAMPLE_IP); void * contextIP = hpcrun_context_pc(context); void * preciseIP = (void *)-1; void * patchedIP = (void *)-1; void * reliableIP = (void *)-1; void * addr = (void *)-1; if (hdr.type & PERF_SAMPLE_IP){ if (ReadMampBuffer(wpi->mmapBuffer, &preciseIP, sizeof(uint64_t)) < 0) { EMSG("Failed to ReadMampBuffer: %s\n", strerror(errno)); monitor_real_abort(); } if(! (hdr.misc & PERF_RECORD_MISC_EXACT_IP)){ //EMSG("PERF_SAMPLE_IP imprecise\n"); tData.numWatchpointImpreciseIP ++; if(wpConfig.dontFixIP == false) { patchedIP = GetPatchedIP(contextIP); if(!IsPCSane(contextIP, patchedIP)) { //EMSG("get_previous_instruction failed \n"); tData.numInsaneIP ++; goto ErrExit; } reliableIP = patchedIP; } else { // Fake as requested by Xu for reuse clients reliableIP = contextIP-1; } //EMSG("PERF_SAMPLE_IP imprecise: %p patched to %p in WP handler\n", tmpIP, patchedIP); } else { #if 0 // Precise PC can be far away in jump/call instructions. // Ensure the "precise" PC is within one instruction from context pc if(!IsPCSane(contextIP, preciseIP)) { tData.numInsaneIP ++; //EMSG("get_previous_instruction failed \n"); goto ErrExit; } #endif reliableIP = preciseIP; //if(! ((ip <= tmpIP) && (tmpIP-ip < 20))) ConsumeAllRingBufferData(wpi->mmapBuffer); //assert( (ip <= tmpIP) && (tmpIP-ip < 20)); } } else { // Should happen only for wpConfig.isLBREnabled==false assert(wpConfig.isLBREnabled==false); // Fall back to old scheme of disassembling and capturing the info if(wpConfig.dontFixIP == false) { patchedIP = GetPatchedIP(contextIP); if(!IsPCSane(contextIP, patchedIP)) { tData.numInsaneIP ++; //EMSG("PERF_SAMPLE_IP imprecise: %p failed to patch in WP handler, WP dropped\n", tmpIP); goto ErrExit; } reliableIP = patchedIP; }else { // Fake as requested by Xu for reuse clients reliableIP = contextIP-1; } } wpt->pc = reliableIP; if(wpConfig.dontDisassembleWPAddress == false){ FloatType * floatType = wpConfig.getFloatType? &wpt->floatType : 0; if(false == get_mem_access_length_and_type_address(wpt->pc, (uint32_t*) &(wpt->accessLength), &(wpt->accessType), floatType, context, &addr)){ //EMSG("WP triggered on a non Load/Store add = %p\n", wpt->pc); goto ErrExit; } if (wpt->accessLength == 0) { //EMSG("WP triggered 0 access length! at pc=%p\n", wpt->pc); goto ErrExit; } void * patchedAddr = (void *)-1; // Stack affecting addresses will be off by 8 // Some instructions affect the address computing register: mov (%rax),%eax // Hence, if the addresses do NOT overlap, merely use the Sample address! if(false == ADDRESSES_OVERLAP(addr, wpt->accessLength, wpi->va, wpi->sample.wpLength)) { if ((wpt->accessLength == sizeof(void *)) && (wpt->accessLength == wpi->sample.wpLength) && (((addr - wpi->va) == sizeof(void *)) || ((wpi->va - addr) == sizeof(void *)))) tData.numWatchpointImpreciseAddress8ByteLength ++; else tData.numWatchpointImpreciseAddressArbitraryLength ++; tData.numWatchpointImpreciseAddressArbitraryLength ++; patchedAddr = wpi->va; } else { patchedAddr = addr; } wpt->va = patchedAddr; } else { wpt->va = (void *)-1; } wpt->ctxt = context; // We must cleanup the mmap buffer if there is any data left ConsumeAllRingBufferData(wpi->mmapBuffer); return true; case PERF_RECORD_EXIT: EMSG("PERF_RECORD_EXIT sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_LOST: EMSG("PERF_RECORD_LOST sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_THROTTLE: EMSG("PERF_RECORD_THROTTLE sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_UNTHROTTLE: EMSG("PERF_RECORD_UNTHROTTLE sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; default: EMSG("unknown sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; } ErrExit: // We must cleanup the mmap buffer if there is any data left ConsumeAllRingBufferData(wpi->mmapBuffer); return false; } static bool CollectWatchPointTriggerInfoShared(WatchPointInfo_t * wpi, WatchPointTrigger_t *wpt, void * context, int me){ //struct perf_event_mmap_page * b = wpi->mmapBuffer; struct perf_event_header hdr; //fprintf(stderr, "in CollectWatchPointTriggerInfoShared in thread %d\n", me); if (wpi->mmapBuffer == 0) goto ErrExit2; if (ReadMampBuffer(wpi->mmapBuffer, &hdr, sizeof(struct perf_event_header)) < 0) { EMSG("Failed to ReadMampBuffer: %s\n", strerror(errno)); //fprintf(stderr, "error: Failed to ReadMampBuffer: %s\n", strerror(errno)); //monitor_real_abort(); goto ErrExit2; } //fprintf(stderr, "in CollectWatchPointTriggerInfo 1\n"); switch(hdr.type) { case PERF_RECORD_SAMPLE: assert (hdr.type & PERF_SAMPLE_IP); void * contextIP = hpcrun_context_pc(context); void * preciseIP = (void *)-1; void * patchedIP = (void *)-1; void * reliableIP = (void *)-1; void * addr = (void *)-1; if (hdr.type & PERF_SAMPLE_IP){ if (ReadMampBuffer(wpi->mmapBuffer, &preciseIP, sizeof(uint64_t)) < 0) { EMSG("Failed to ReadMampBuffer: %s\n", strerror(errno)); //fprintf(stderr, "error: Failed to ReadMampBuffer: %s\n", strerror(errno)); //monitor_real_abort(); goto ErrExit2; } if(! (hdr.misc & PERF_RECORD_MISC_EXACT_IP)){ //EMSG("PERF_SAMPLE_IP imprecise\n"); threadDataTable.hashTable[me].numWatchpointImpreciseIP ++; if(wpConfig.dontFixIP == false) { patchedIP = GetPatchedIPShared(contextIP, me); if(!IsPCSane(contextIP, patchedIP)) { //EMSG("get_previous_instruction failed \n"); threadDataTable.hashTable[me].numInsaneIP ++; goto ErrExit; } reliableIP = patchedIP; } else { // Fake as requested by Xu for reuse clients reliableIP = contextIP-1; } //EMSG("PERF_SAMPLE_IP imprecise: %p patched to %p in WP handler\n", tmpIP, patchedIP); } else { #if 0 // Precise PC can be far away in jump/call instructions. // Ensure the "precise" PC is within one instruction from context pc if(!IsPCSane(contextIP, preciseIP)) { tData.numInsaneIP ++; //EMSG("get_previous_instruction failed \n"); goto ErrExit; } #endif reliableIP = preciseIP; //if(! ((ip <= tmpIP) && (tmpIP-ip < 20))) ConsumeAllRingBufferData(wpi->mmapBuffer); //assert( (ip <= tmpIP) && (tmpIP-ip < 20)); } } else { // Should happen only for wpConfig.isLBREnabled==false assert(wpConfig.isLBREnabled==false); // Fall back to old scheme of disassembling and capturing the info if(wpConfig.dontFixIP == false) { fprintf(stderr, "wpConfig.dontFixIP is false\n"); patchedIP = GetPatchedIPShared(contextIP, me); if(!IsPCSane(contextIP, patchedIP)) { threadDataTable.hashTable[me].numInsaneIP ++; //EMSG("PERF_SAMPLE_IP imprecise: %p failed to patch in WP handler, WP dropped\n", tmpIP); goto ErrExit; } reliableIP = patchedIP; }else { fprintf(stderr, "wpConfig.dontFixIP is true\n"); // Fake as requested by Xu for reuse clients reliableIP = contextIP-1; } } wpt->pc = reliableIP; if(wpConfig.dontDisassembleWPAddress == false){ //fprintf(stderr, "wpConfig.dontDisassembleWPAddress is false\n"); FloatType * floatType = wpConfig.getFloatType? &wpt->floatType : 0; if(false == get_mem_access_length_and_type_address(wpt->pc, (uint32_t*) &(wpt->accessLength), &(wpt->accessType), floatType, context, &addr)){ //EMSG("WP triggered on a non Load/Store add = %p\n", wpt->pc); goto ErrExit; } if (wpt->accessLength == 0) { //EMSG("WP triggered 0 access length! at pc=%p\n", wpt->pc); goto ErrExit; } void * patchedAddr = (void *)-1; // Stack affecting addresses will be off by 8 // Some instructions affect the address computing register: mov (%rax),%eax // Hence, if the addresses do NOT overlap, merely use the Sample address! if(false == ADDRESSES_OVERLAP(addr, wpt->accessLength, wpi->va, wpi->sample.wpLength)) { if ((wpt->accessLength == sizeof(void *)) && (wpt->accessLength == wpi->sample.wpLength) && (((addr - wpi->va) == sizeof(void *)) || ((wpi->va - addr) == sizeof(void *)))) threadDataTable.hashTable[me].numWatchpointImpreciseAddress8ByteLength ++; else threadDataTable.hashTable[me].numWatchpointImpreciseAddressArbitraryLength ++; threadDataTable.hashTable[me].numWatchpointImpreciseAddressArbitraryLength ++; patchedAddr = wpi->va; } else { patchedAddr = addr; } wpt->va = patchedAddr; } else { wpt->va = (void *)-1; } wpt->ctxt = context; // We must cleanup the mmap buffer if there is any data left ConsumeAllRingBufferData(wpi->mmapBuffer); return true; case PERF_RECORD_EXIT: EMSG("PERF_RECORD_EXIT sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_LOST: EMSG("PERF_RECORD_LOST sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_THROTTLE: EMSG("PERF_RECORD_THROTTLE sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; case PERF_RECORD_UNTHROTTLE: EMSG("PERF_RECORD_UNTHROTTLE sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; default: EMSG("unknown sample type %d sz=%d\n", hdr.type, hdr.size); //SkipBuffer(wpi->mmapBuffer , hdr.size - sizeof(hdr)); goto ErrExit; } ErrExit: // We must cleanup the mmap buffer if there is any data left ConsumeAllRingBufferData(wpi->mmapBuffer); ErrExit2: return false; } void DisableWatchpointWrapper(WatchPointInfo_t *wpi){ if(wpConfig.isWPModifyEnabled) { DisableWatchpoint(wpi); } else { DisArm(wpi); } } WatchPointInfo_t * getWPI (int me, int location) { return &threadDataTable.hashTable[me].watchPointArray[location]; } static int OnWatchPoint(int signum, siginfo_t *info, void *context){ //volatile int x; //fprintf(stderr, "OnWatchPoint=%p\n", &x); //printf("OnWatchPoint is executed\n"); // Disable HPCRUN sampling // if the trap is already in hpcrun, return // If the interrupt came from inside our code, then drop the sample // and return and avoid any MSG. //fprintf(stderr, "in OnWatchpoint\n"); linux_perf_events_pause(); wp_count++; void* pc = hpcrun_context_pc(context); if (!hpcrun_safe_enter_async(pc)) { linux_perf_events_resume(); return 0; } wp_count1++; if(event_type == WP_REUSETRACKER) { tData.numWatchpointTriggers++; int location = -1; FdData_t fdData = fdDataGet(info->si_fd); int me = fdData.tid; for(int i = 0; i < wpConfig.maxWP; i++) { if(threadDataTable.hashTable[me].watchPointArray[i].isActive && (info->si_fd == threadDataTable.hashTable[me].watchPointArray[i].fileHandle)) { location = i; //theCounter = threadDataTable.hashTable[me].counter; //fprintf(stderr, "trap due to access in thread %d armed by %d is handled by thread %d WP location is found in %d\n", me, threadDataTable.hashTable[me].watchPointArray[i].sample.first_accessing_tid, TD_GET(core_profile_trace_data.id), location); break; } } if(location == -1) { EMSG("\n WP trigger did not match any known active WP\n"); //monitor_real_abort(); hpcrun_safe_exit(); linux_perf_events_resume(); //fprintf(stderr, "WP trigger did not match any known active WP\n"); return 0; } uint64_t theCounter = threadDataTable.hashTable[me].counter[location]; if((theCounter & 1) == 0) { if(__sync_bool_compare_and_swap(&threadDataTable.hashTable[me].counter[location], theCounter, theCounter+1)){ WatchPointTrigger_t wpt; WPTriggerActionType retVal; WatchPointInfo_t *wpi = &threadDataTable.hashTable[me].watchPointArray[location]; bool handle_flag =false; switch (wpi->sample.preWPAction) { case DISABLE_WP: //fprintf(stderr, "in DISABLE_WP\n"); DisableWatchpointWrapper(wpi); //fprintf(stderr, "location %d is opened by trap\n", location); break; default: //fprintf(stderr, "aborted here\n"); assert(0 && "NYI"); threadDataTable.hashTable[me].counter[location]++; monitor_real_abort(); break; } //fprintf(stderr, "watchpoint trap happens\n"); if( false == CollectWatchPointTriggerInfoShared(wpi, &wpt, context, me)) { tData.numWatchpointDropped++; retVal = DISABLE_WP; // disable if unable to collect any info. } else { wpt.location = location; retVal = tData.fptr(wpi, 0, wpt.accessLength, &wpt); } switch (retVal) { case DISABLE_WP: { if(wpi->isActive){ DisableWatchpointWrapper(wpi); } // Reset per WP probability //wpi->samplePostFull = SAMPLES_POST_FULL_RESET_VAL; tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; threadDataTable.hashTable[me].numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; /*if(wpi->sample.L1Sample) { uint64_t theCounter = globalReuseWPs.table[location].counter; if((theCounter & 1) == 0) { if(__sync_bool_compare_and_swap(&globalReuseWPs.table[location].counter, theCounter, theCounter+1)) { if(globalReuseWPs.table[location].active) { globalReuseWPs.table[location].active = false; } globalReuseWPs.table[location].counter++; } } if(threadDataTable.hashTable[me].watchPointArray[location].sample.first_accessing_tid == me) { numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; //fprintf(stderr, "reservoir sampling counter in location %d is reset by thread %d\n", location, me); } }*/ } break; case ALREADY_DISABLED: { // Already disabled, perhaps in pre-WP action //assert(wpi->isActive == false); tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; threadDataTable.hashTable[me].numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; /*if(wpi->sample.L1Sample) { uint64_t theCounter = globalReuseWPs.table[location].counter; if((theCounter & 1) == 0) { if(__sync_bool_compare_and_swap(&globalReuseWPs.table[location].counter, theCounter, theCounter+1)) { if(globalReuseWPs.table[location].active) { numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; globalReuseWPs.table[location].active = false; //fprintf(stderr, "location %d has been disabled by thread %d\n", location, me); } globalReuseWPs.table[location].counter++; } } if(globalReuseWPs.table[location].tid == me) { if (sample_count > wait_threshold) { globalWPIsUsers[location] = -1; globalReuseWPs.table[location].tid = -1; //uint64_t sampleCountDiff = GetWeightedMetricDiff(wpi->sample.node, wpi->sample.sampledMetricId, 1.0); //globalReuseWPs.table[location].residueSampleCountInPrevThread = GetWeightedMetricDiff(wpi->sample.node, wpi->sample.sampledMetricId, 1.0); //fprintf(stderr, "residueSampleCountInPrevThread is assigned with %ld in thread %d\n", sampleCountDiff, me); //wait_threshold = sample_count + CHANGE_THRESHOLD; used_wp_count--; //fprintf(stderr, "WP number %d is released by thread %d, sample_count: %d, wait_threshold: %d\n", location, me, sample_count, wait_threshold); } numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; //fprintf(stderr, "reservoir sampling counter in location %d is reset by thread %d\n", location, me); } }*/ } break; default: // Retain the state break; } threadDataTable.hashTable[me].counter[location]++; } } } else { // start from here //linux_perf_events_pause(); tData.numWatchpointTriggers++; //fprintf(stderr, " numWatchpointTriggers = %lu, \n", tData.numWatchpointTriggers); //find which watchpoint fired int location = -1; for(int i = 0 ; i < wpConfig.maxWP; i++) { if((tData.watchPointArray[i].isActive) && (info->si_fd == tData.watchPointArray[i].fileHandle)) { location = i; break; } } //fprintf(stderr, "in OnWatchpoint at this point\n"); // Ensure it is an active WP if(location == -1) { // before for(int i = 0 ; i < wpConfig.maxWP; i++) { //if((tData.watchPointArray[i].isActive) && (info->si_fd == tData.watchPointArray[i].fileHandle)) { //location = i; //break; //fprintf(stderr, "tData.watchPointArray[%d].isActive = %d and info->si_fd = %d and tData.watchPointArray[%d].fileHandle = %d monitored address: %lx\n", i, tData.watchPointArray[i].isActive, info->si_fd, i, tData.watchPointArray[i].fileHandle, (long) tData.watchPointArray[i].va); //} } // after EMSG("\n WP trigger did not match any known active WP\n"); //monitor_real_abort(); hpcrun_safe_exit(); linux_perf_events_resume(); //fprintf("\n WP trigger did not match any known active WP\n"); return 0; } wp_count2++; WatchPointTrigger_t wpt; WPTriggerActionType retVal; WatchPointInfo_t *wpi = &tData.watchPointArray[location]; // Perform Pre watchpoint action switch (wpi->sample.preWPAction) { case DISABLE_WP: DisableWatchpointWrapper(wpi); break; case DISABLE_ALL_WP: for(int i = 0; i < wpConfig.maxWP; i++) { if(tData.watchPointArray[i].isActive){ DisableWatchpointWrapper(&tData.watchPointArray[i]); } } break; default: assert(0 && "NYI"); monitor_real_abort(); break; } //fprintf(stderr, "in OnWatchpoint at that point\n"); if( false == CollectWatchPointTriggerInfo(wpi, &wpt, context)) { //fprintf(stderr, "in OnWatchpoint at that point 3!!!!\n"); tData.numWatchpointDropped++; retVal = DISABLE_WP; // disable if unable to collect any info. wp_dropped++; } else { //fprintf(stderr, "in OnWatchpoint at that point 1!!!!\n"); tData.numActiveWatchpointTriggers++; retVal = tData.fptr(wpi, 0, wpt.accessLength/* invalid*/, &wpt); //fprintf(stderr, "in OnWatchpoint at that point 2!!!!\n"); } //fprintf(stderr, "in OnWatchpoint at that point !!!\n"); // Let the client take action. switch (retVal) { case DISABLE_WP: { if(wpi->isActive){ DisableWatchpointWrapper(wpi); } //reset to tData.samplePostFull tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; //tData.numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; //fprintf(stderr, "tData.samplePostFull is reset in DISABLE_WP in thread %d\n", TD_GET(core_profile_trace_data.id)); } break; case DISABLE_ALL_WP: { for(int i = 0; i < wpConfig.maxWP; i++) { if(tData.watchPointArray[i].isActive){ DisableWatchpointWrapper(&tData.watchPointArray[i]); } } //reset to tData.samplePostFull to SAMPLES_POST_FULL_RESET_VAL tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; //tData.numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; //fprintf(stderr, "tData.samplePostFull is reset in DISABLE_ALL_WP in thread %d\n", TD_GET(core_profile_trace_data.id)); } break; case ALREADY_DISABLED: { // Already disabled, perhaps in pre-WP action assert(wpi->isActive == false); tData.samplePostFull = SAMPLES_POST_FULL_RESET_VAL; if (wpConfig.replacementPolicy == RDX) { tData.numWatchpointArmingAttempt[location] = SAMPLES_POST_FULL_RESET_VAL; //fprintf(stderr, "watchpoint %d is reset due to trap\n", location); } //fprintf(stderr, "tData.samplePostFull is reset in ALREADY_DISABLED in thread %d\n", TD_GET(core_profile_trace_data.id)); } break; case RETAIN_WP: { // resurrect this wp if(!wpi->isActive){ EnableWatchpoint(wpi->fileHandle); wpi->isActive = true; } } break; default: // Retain the state break; } } // hpcrun_all_sources_start(); //linux_perf_events_resume(); hpcrun_safe_exit(); linux_perf_events_resume(); return 0; } static bool ValidateWPData(SampleData_t * sampleData){ // Check alignment #if defined(__x86_64__) || defined(__amd64__) || defined(__x86_64) || defined(__amd64) switch (sampleData->wpLength) { case 0: EMSG("\nValidateWPData: 0 length WP never allowed"); monitor_real_abort(); case 1: case 2: case 4: case 8: if(IS_ALIGNED(sampleData->va, sampleData->wpLength)) return true; // unaligned else return false; break; default: EMSG("Unsuppported WP length %d", sampleData->wpLength); monitor_real_abort(); return false; // unsupported alignment } #else #error "unknown architecture" #endif } static bool IsOveralpped(SampleData_t * sampleData){ // Is a WP with the same/overlapping address active? for (int i = 0; i < wpConfig.maxWP; i++) { if(tData.watchPointArray[i].isActive){ if(ADDRESSES_OVERLAP(tData.watchPointArray[i].sample.va, tData.watchPointArray[i].sample.wpLength, sampleData->va, sampleData->wpLength)){ //fprintf(stderr, "address %lx and address %lx overlap\n", tData.watchPointArray[i].sample.va, sampleData->va); overlap_count++; return true; } } } return false; } void CaptureValue(SampleData_t * sampleData, WatchPointInfo_t * wpi){ void * valLoc = & (wpi->value[0]); switch(sampleData->wpLength) { default: // force 1 length case 1: *((uint8_t*)valLoc) = *(uint8_t*)(sampleData->va); break; case 2: *((uint16_t*)valLoc) = *(uint16_t*)(sampleData->va); break; case 4: *((uint32_t*)valLoc) = *(uint32_t*)(sampleData->va); break; case 8: *((uint64_t*)valLoc) = *(uint64_t*)(sampleData->va); break; } } bool SubscribeWatchpoint(SampleData_t * sampleData, OverwritePolicy overwritePolicy, bool captureValue){ sub_wp_count1++; if(ValidateWPData(sampleData) == false) { return false; } //sub_wp_count2++; if(IsOveralpped(sampleData)){ return false; // drop the sample if it overlaps an existing address } sub_wp_count2++; // No overlap, look for a victim slot int victimLocation = -1; // Find a slot to install WP VictimType r = GetVictim(&victimLocation, wpConfig.replacementPolicy); sub_wp_count3++; if(r != NONE_AVAILABLE) { // VV IMP: Capture value before arming the WP. if(captureValue) { CaptureValue(sampleData, &tData.watchPointArray[victimLocation]); } // I know the error case that we have captured the value but ArmWatchPoint fails. // I am not handling that corner case because ArmWatchPoint() will fail with a monitor_real_abort(). //printf("and this region\n"); //printf("arming watchpoints\n"); //fprintf(stderr, "watchpoint is armed\n"); if(ArmWatchPoint(&tData.watchPointArray[victimLocation], sampleData) == false){ //LOG to hpcrun log EMSG("ArmWatchPoint failed for address %p", sampleData->va); return false; } return true; } none_available_count++; return false; } bool SubscribeWatchpointShared(SampleData_t * sampleData, OverwritePolicy overwritePolicy, bool captureValue, int me, int location){ sub_wp_count1++; if(ValidateWPData(sampleData) == false) { return false; } if(sampleData->L3StoreUse && (TD_GET(core_profile_trace_data.id) == me)) { if(captureValue) { CaptureValue(sampleData, &threadDataTable.hashTable[me].watchPointArray[location]); } //fprintf(stderr, "Thread %d is arming thread %d in location %d\n", TD_GET(core_profile_trace_data.id), me, location); if(ArmWatchPointShared(&threadDataTable.hashTable[me].watchPointArray[location] , sampleData, me) == false){ //LOG to hpcrun log EMSG("ArmWatchPoint failed for address %p", sampleData->va); return false; } return true; } else if(threadDataTable.hashTable[me].os_tid != -1) { uint64_t theCounter = threadDataTable.hashTable[me].counter[location]; if((theCounter & 1) == 0) { if(__sync_bool_compare_and_swap(&threadDataTable.hashTable[me].counter[location], theCounter, theCounter+1)){ if(captureValue) { CaptureValue(sampleData, &threadDataTable.hashTable[me].watchPointArray[location]); } //fprintf(stderr, "Thread %d is arming thread %d in location %d\n", TD_GET(core_profile_trace_data.id), me, location); if(ArmWatchPointShared(&threadDataTable.hashTable[me].watchPointArray[location] , sampleData, me) == false){ //LOG to hpcrun log EMSG("ArmWatchPoint failed for address %p", sampleData->va); threadDataTable.hashTable[me].counter[location]++; return false; } threadDataTable.hashTable[me].counter[location]++; return true; } } } return false; } bool SubscribeWatchpointWithStoreTime(SampleData_t * sampleData, OverwritePolicy overwritePolicy, bool captureValue, uint64_t curTime){ if(ValidateWPData(sampleData) == false) { return false; } if(IsOveralpped(sampleData)){ return false; // drop the sample if it overlaps an existing address } // No overlap, look for a victim slot int victimLocation = -1; // Find a slot to install WP VictimType r = GetVictim(&victimLocation, wpConfig.replacementPolicy); if(r != NONE_AVAILABLE) { // VV IMP: Capture value before arming the WP. if(captureValue) { CaptureValue(sampleData, &tData.watchPointArray[victimLocation]); } // I know the error case that we have captured the value but ArmWatchPoint fails. // I am not handling that corner case because ArmWatchPoint() will fail with a monitor_real_abort(). //printf("and this region\n"); //printf("arming watchpoints\n"); if((curTime - tData.watchPointArray[victimLocation].sample.bulletinBoardTimestamp) > tData.watchPointArray[victimLocation].sample.expirationPeriod) { //printf("watchpoints are armed on address %lx, length: %d\n", sampleData->va, sampleData->accessLength); if(ArmWatchPoint(&tData.watchPointArray[victimLocation], sampleData) == false){ //LOG to hpcrun log EMSG("ArmWatchPoint failed for address %p", sampleData->va); return false; } } /*else { printf("watchpoints are not armed because they are still new\n"); }*/ return true; } return false; } bool SubscribeWatchpointWithTime(SampleData_t * sampleData, OverwritePolicy overwritePolicy, bool captureValue, uint64_t curTime, uint64_t lastTime){ if(ValidateWPData(sampleData) == false) { return false; } if(IsOveralpped(sampleData)){ return false; // drop the sample if it overlaps an existing address } // No overlap, look for a victim slot int victimLocation = -1; // Find a slot to install WP VictimType r = GetVictim(&victimLocation, wpConfig.replacementPolicy); if(r != NONE_AVAILABLE) { // VV IMP: Capture value before arming the WP. if(captureValue) { CaptureValue(sampleData, &tData.watchPointArray[victimLocation]); } // I know the error case that we have captured the value but ArmWatchPoint fails. // I am not handling that corner case because ArmWatchPoint() will fail with a monitor_real_abort(). //printf("and this region\n"); //printf("arming watchpoints\n"); if((sampleData->bulletinBoardTimestamp - tData.watchPointArray[victimLocation].bulletinBoardTimestamp) > (curTime - lastTime)) { //printf("watchpoints are armed on address %lx, length: %d\n", sampleData->va, sampleData->accessLength); if(ArmWatchPoint(&tData.watchPointArray[victimLocation], sampleData) == false){ //LOG to hpcrun log EMSG("ArmWatchPoint failed for address %p", sampleData->va); return false; } } /*else { printf("watchpoints are not armed because they are still new\n"); }*/ return true; } return false; } #ifdef TEST #include<omp.h> __thread volatile int cnt; WPUpCallTRetType Test1UpCall(WatchPointInfo_t * wp, WatchPointTrigger_t * wt) { printf("\n Test1UpCall %p\n", wt->va); if(wpConfig.isLBREnabled) assert(wp->sample.va == wt->va); cnt ++; return DISABLE; } void TestBasic(){ tData.fptr = Test1UpCall; sigset_t block_mask; sigemptyset (&block_mask); // Set a signal handler for SIGUSR1 struct sigaction sa1 = { .sa_sigaction = OnWatchPoint, // .sa_mask = block_mask, .sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER }; if(sigaction(wpConfig.signalDelivered, &sa1, NULL) == -1) { fprintf(stderr, "Failed to set WHICH_SIG handler: %s\n", strerror(errno)); monitor_real_abort(); } WatchpointThreadInit(); int N = 10000; volatile int dummyWPLocation[10000]; cnt = 0; for(int i = 0 ; i < N; i++) { SampleData_t s = {.va = &dummyWPLocation[i], .wpLength = sizeof(int), .type = WP_WRITE}; SubscribeWatchpoint(&s, AUTO); } for(int i = 0 ; i < N; i++) { dummyWPLocation[i]++; } printf("\n cnt = %d\n", cnt); assert(cnt == wpConfig.maxWP); WatchpointThreadTerminate(); } int main() { printf("\n Test 1: single threaded"); while(1) { #pragma omp parallel { TestBasic(); } } return 0; } #endif
GB_unop__acosh_fp32_fp32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__acosh_fp32_fp32) // op(A') function: GB (_unop_tran__acosh_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = acoshf (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 = acoshf (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] = acoshf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ACOSH || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__acosh_fp32_fp32) ( float *Cx, // Cx and Ax may be aliased const float *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { float aij = Ax [p] ; float z = aij ; Cx [p] = acoshf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; float aij = Ax [p] ; float z = aij ; Cx [p] = acoshf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__acosh_fp32_fp32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__isge_uint32.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__isge_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__isge_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__isge_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__isge_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_uint32) // A*D function (colscale): GB (_AxD__isge_uint32) // D*A function (rowscale): GB (_DxB__isge_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__isge_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__isge_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_uint32) // C=scalar+B GB (_bind1st__isge_uint32) // C=scalar+B' GB (_bind1st_tran__isge_uint32) // C=A+scalar GB (_bind2nd__isge_uint32) // C=A'+scalar GB (_bind2nd_tran__isge_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_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) \ uint32_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) \ uint32_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) \ 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 = (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_ISGE || GxB_NO_UINT32 || GxB_NO_ISGE_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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__isge_uint32) ( 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__isge_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__isge_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 uint32_t uint32_t bwork = (*((uint32_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__isge_uint32) ( 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 uint32_t *restrict Cx = (uint32_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__isge_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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 } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_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 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_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__isge_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__isge_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__isge_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__isge_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__isge_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)) ; 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__isge_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 ; 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__isge_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__isge_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_binop__bset_uint16.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__bset_uint16) // A.*B function (eWiseMult): GB (_AemultB_01__bset_uint16) // A.*B function (eWiseMult): GB (_AemultB_02__bset_uint16) // A.*B function (eWiseMult): GB (_AemultB_03__bset_uint16) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bset_uint16) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bset_uint16) // C+=b function (dense accum): GB (_Cdense_accumb__bset_uint16) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bset_uint16) // C=scalar+B GB (_bind1st__bset_uint16) // C=scalar+B' GB (_bind1st_tran__bset_uint16) // C=A+scalar GB (_bind2nd__bset_uint16) // C=A'+scalar GB (_bind2nd_tran__bset_uint16) // C type: uint16_t // A type: uint16_t // B,b type: uint16_t // BinaryOp: cij = GB_BITSET (aij, bij, uint16_t, 16) #define GB_ATYPE \ uint16_t #define GB_BTYPE \ uint16_t #define GB_CTYPE \ uint16_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) \ uint16_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint16_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint16_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_BITSET (x, y, uint16_t, 16) ; // 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_BSET || GxB_NO_UINT16 || GxB_NO_BSET_UINT16) //------------------------------------------------------------------------------ // 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__bset_uint16) ( 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__bset_uint16) ( 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__bset_uint16) ( 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 uint16_t uint16_t bwork = (*((uint16_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 uint16_t *restrict Cx = (uint16_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 uint16_t *restrict Cx = (uint16_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bset_uint16) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__bset_uint16) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__bset_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__bset_uint16) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__bset_uint16) ( 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__bset_uint16) ( 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 uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t x = (*((uint16_t *) x_input)) ; uint16_t *Bx = (uint16_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 ; uint16_t bij = GBX (Bx, p, false) ; Cx [p] = GB_BITSET (x, bij, uint16_t, 16) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bset_uint16) ( 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 ; uint16_t *Cx = (uint16_t *) Cx_output ; uint16_t *Ax = (uint16_t *) Ax_input ; uint16_t y = (*((uint16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint16_t aij = GBX (Ax, p, false) ; Cx [p] = GB_BITSET (aij, y, uint16_t, 16) ; } 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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITSET (x, aij, uint16_t, 16) ; \ } GrB_Info GB (_bind1st_tran__bset_uint16) ( 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 \ uint16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint16_t x = (*((const uint16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint16_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) \ { \ uint16_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITSET (aij, y, uint16_t, 16) ; \ } GrB_Info GB (_bind2nd_tran__bset_uint16) ( 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 uint16_t y = (*((const uint16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
elemwise_binary_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2016 by Contributors * \file elemwise_binary_op.h * \brief Function definition of elementwise binary operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #include <mxnet/operator_util.h> #include <mxnet/op_attr_types.h> #include <vector> #include <string> #include <utility> #include <typeinfo> #include <algorithm> #include "../mxnet_op.h" #include "../mshadow_op.h" #include "../../engine/openmp.h" #include "elemwise_unary_op.h" #include "../../common/utils.h" #include "./init_op.h" #include "../operator_common.h" namespace mxnet { namespace op { /*! Gather binary operator functions into ElemwiseBinaryOp class */ class ElemwiseBinaryOp : public OpBase { public: /*! \brief For sparse, assume missing rvalue is 0 */ template<typename OP, int Req> struct MissingRValueOp { typedef OP Operation; template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *lhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(lhs[i], DType(0))); } }; /*! \brief For sparse, assume missing lvalue is 0 */ template<typename OP, int Req> struct MissingLValueOp { typedef OP Operation; template<typename DType> MSHADOW_XINLINE static void Map(int i, DType *out, const DType *rhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(DType(0), rhs[i])); } }; private: /*! * \brief CSR operation requires temp space */ enum ResourceRequestType { kTempSpace }; /*! * \brief Fill contiguous dense output rows with value computed from 0 lhs and 0 rhs input * CPU-Only version */ template<typename DType, typename OP, typename xpu> static inline size_t FillDense(mshadow::Stream<xpu> *s, const size_t idx_l, const size_t idx_r, const OpReqType req, mshadow::Tensor<xpu, 2, DType> *out, const size_t iter_out) { const int index_out_min = static_cast<int>(std::min(idx_l, idx_r)); if (static_cast<size_t>(index_out_min) > iter_out) { const DType zero_input_val = OP::Map(DType(0), DType(0)); #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (int i = static_cast<int>(iter_out); i < index_out_min; ++i) { Fill<false>(s, (*out)[i], req, zero_input_val); } } return static_cast<size_t>(index_out_min); // MSVC wants OMP loops to always use 'int' } static inline bool IsSameArray(const NDArray& a1, const NDArray& a2) { return a1.var() == a2.var(); } public: /*! \brief Minimum of three */ static MSHADOW_XINLINE size_t minthree(const size_t a, const size_t b, const size_t c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } private: template<typename LOP, typename ROP> static void BackwardUseNone_(const nnvm::NodeAttrs &attrs, mshadow::Stream<cpu>* s, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { using namespace mxnet_op; const int size = static_cast<int>((outputs[0].Size() + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes); const DType *ograd_dptr = inputs[0].dptr<DType>(); if (std::is_same<LOP, mshadow_op::identity>::value && req[0] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[0].dptr<DType>()); } else if (req[0] != kNullOp) { DType *lgrad_dptr = outputs[0].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { Kernel<mxnet_op::op_with_req<LOP, Req>, cpu>::Launch(s, size, lgrad_dptr, ograd_dptr); }); } if (std::is_same<ROP, mshadow_op::identity>::value && req[1] == kWriteInplace) { CHECK_EQ(ograd_dptr, outputs[1].dptr<DType>()); } else if (req[1] != kNullOp) { DType *rgrad_dptr = outputs[1].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { Kernel<mxnet_op::op_with_req<ROP, Req>, cpu>::Launch(s, size, rgrad_dptr, ograd_dptr); }); } }); } template<typename LOP, typename ROP> static void BackwardUseIn_(const nnvm::NodeAttrs &attrs, mshadow::Stream<cpu>* s, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { DCHECK_EQ(outputs.size(), 2U); DCHECK_EQ(inputs.size(), 3U); const DType *ograd_dptr = inputs[0].dptr<DType>(); const DType *lhs_dptr = inputs[1].dptr<DType>(); const DType *rhs_dptr = inputs[2].dptr<DType>(); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { const int size = static_cast<int>( (outputs[0].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * lgrad_dptr = outputs[0].dptr<DType>(); mxnet_op::Kernel< mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<LOP>, Req>, cpu>::Launch( s, size, lgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr); }); MXNET_ASSIGN_REQ_SWITCH(req[1], Req, { const int size = static_cast<int>( (outputs[1].Size() + mxnet_op::DataType<DType>::kLanes - 1) / mxnet_op::DataType<DType>::kLanes); DType * rgrad_dptr = outputs[1].dptr<DType>(); mxnet_op::Kernel< mxnet_op::op_with_req<mxnet_op::backward_grad_tuned<ROP>, Req>, cpu>::Launch( s, size, rgrad_dptr, ograd_dptr, lhs_dptr, rhs_dptr); }); }); } template< typename xpu, typename LOP, typename ROP, bool in0_ok_dense = false, bool in1_ok_dense = false, bool in2_ok_dense = false, typename BackupCompute> static inline void RspRspOpBackward(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs, BackupCompute backup_compute) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); // lhs grad if (req[0] != kNullOp) { // RspRspOp can handle dense outputs so long as OP(0, 0) == 0 RspRspOp<LOP>( s, attrs, ctx, inputs[1], inputs[2], req[0], outputs[0], false, false, false, false); // lhs in-place RspRspOp<op::mshadow_op::mul>( s, attrs, ctx, outputs[0], inputs[0], req[0], outputs[0], false, false, true, false); } // rhs grad if (req[1] != kNullOp) { RspRspOp<ROP>( s, attrs, ctx, inputs[1], inputs[2], req[1], outputs[1], false, false, false, false); // rhs in-place RspRspOp<op::mshadow_op::mul>( s, attrs, ctx, inputs[0], outputs[1], req[1], outputs[1], false, false, true, false); } } public: /*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */ template<typename OP> static void RspRspOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, bool lhs_may_be_dense, bool rhs_may_be_dense, bool allow_inplace, bool scatter); /*! \brief Binary op handling for lhr/rhs: RspDns, RspRsp, DnsRsp, or RspRsp->Dns result */ template<typename OP> static void RspRspOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, bool lhs_may_be_dense, bool rhs_may_be_dense, bool allow_inplace, bool scatter); /*! \brief CSR -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void CsrCsrOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output); /*! \brief CSR -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void CsrCsrOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void DnsCsrDnsOp(mshadow::Stream<cpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename OP> static void DnsCsrDnsOp(mshadow::Stream<gpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- CSR binary operator for non-canonical NDArray */ template<typename xpu, typename OP> static void DnsCsrCsrOp(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); /*! \brief DNS -op- RSP binary operator for non-canonical NDArray */ template<typename xpu, typename OP> static void DnsRspDnsOp(mshadow::Stream<xpu> *s, const nnvm::NodeAttrs &attrs, const OpContext &ctx, const NDArray &lhs, const NDArray &rhs, OpReqType req, const NDArray &output, const bool reverse); public: /*! * \brief Rsp-op-Rsp operation which produces a dense result * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool SparseSparseWithDenseResult(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs); /*! * \brief Allow one of the binary inputs to be dense and still produce a sparse output. * Typically used for sparse * dense = sparse. * Note: for csr, it dispatches to fallback other than csr, csr -> csr * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool PreferSparseStorageType(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { using namespace common; CHECK_EQ(in_attrs->size(), 2U) << " in operator " << attrs.name; CHECK_EQ(out_attrs->size(), 1U) << " in operator " << attrs.name; const auto& lhs_stype = in_attrs->at(0); const auto& rhs_stype = in_attrs->at(1); auto& out_stype = out_attrs->at(0); bool dispatched = false; const bool invalid_ctx = dev_mask != mshadow::cpu::kDevMask; const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback : DispatchMode::kFComputeEx; if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) { // dns, dns -> dns dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } if (!dispatched && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) { // rsp, rsp -> rsp dispatched = storage_type_assign(&out_stype, kRowSparseStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ContainsOnlyStorage(*in_attrs, kCSRStorage)) { // csr, csr -> csr dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage))) { // rsp, dns -> rsp // dns, rsp -> rsp dispatched = storage_type_assign(&out_stype, kRowSparseStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage))) { // csr, dns -> csr // dns, csr -> csr dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched) { dispatched = dispatch_fallback(out_attrs, dispatch_mode); } return dispatched; } /*! * \brief Allow one of the inputs to be dense and produce a dense output, * for rsp inputs only support when both inputs are rsp type. * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ template<bool cpu_only, bool rsp, bool csr> static bool PreferDenseStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs) { using namespace common; CHECK_EQ(in_attrs->size(), 2); CHECK_EQ(out_attrs->size(), 1); const auto lhs_stype = (*in_attrs)[0]; const auto rhs_stype = (*in_attrs)[1]; bool dispatched = false; const bool invalid_ctx = cpu_only && dev_mask != mshadow::cpu::kDevMask; const auto dispatch_ex = invalid_ctx ? DispatchMode::kFComputeFallback : DispatchMode::kFComputeEx; if (!dispatched && ContainsOnlyStorage(*in_attrs, kDefaultStorage)) { // dns, dns ... -> dns dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } if (!dispatched && rsp && ContainsOnlyStorage(*in_attrs, kRowSparseStorage)) { // rsp, rsp, ... -> rsp dispatched = storage_type_assign(out_attrs, kRowSparseStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched && csr && ContainsOnlyStorage(*in_attrs, kCSRStorage)) { // csr, csr, ... -> csr dispatched = storage_type_assign(out_attrs, kCSRStorage, dispatch_mode, dispatch_ex); } if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage) || (lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage))) { // dense, csr -> dense / csr, dense -> dense dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched && ((lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage) || (lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage))) { // dense, rsp -> dense / rsp, dense -> dense dispatched = storage_type_assign(out_attrs, kDefaultStorage, dispatch_mode, DispatchMode::kFComputeEx); } if (!dispatched) { dispatch_fallback(out_attrs, dispatch_mode); } return true; } /*! * \brief Backward pass computing input gradient using forward inputs * \param attrs Attributes * \param dev_mask Device mask * \param dispatch_mode Dispatch Mode * \param in_attrs Input storage attributes * \param out_attrs Output storage attributes * \return true if handled */ static bool BackwardUseInStorageType(const nnvm::NodeAttrs& attrs, int dev_mask, DispatchMode* dispatch_mode, std::vector<int> *in_attrs, std::vector<int> *out_attrs); template<typename xpu, typename OP> static void ComputeInt(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MXNET_INT_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void Compute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); if (outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "Operator " << attrs.op->name << " does not support boolean type"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void MixedUnaryBackwardUseInCompute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); if (mxnet::common::is_int(outputs[0].type_flag_) || outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "gradient computation of operator " << attrs.op->name << " for " << mshadow::dtype_string(outputs[0].type_flag_) << " type is not supported"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void MixedUnaryBackwardUseInOutCompute(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 1U); if (mxnet::common::is_int(outputs[0].type_flag_) || outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "gradient computation of operator " << attrs.op->name << " for " << mshadow::dtype_string(outputs[0].type_flag_) << " type is not supported"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[2].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[2].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void ComputeWithBool(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template<typename xpu, typename OP> static void ComputeLogic(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, { MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[1].type_flag_, EType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch(s, size, outputs[0].dptr<bool>(), inputs[0].dptr<DType>(), inputs[1].dptr<EType>()); } }); }); }); } template<typename xpu, typename OP> static void ComputeEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace common; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] == kNullOp) return; const auto lhs_stype = inputs[0].storage_type(); const auto rhs_stype = inputs[1].storage_type(); const auto out_stype = outputs[0].storage_type(); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); if ((ContainsOnlyStorage(inputs, kRowSparseStorage)) && (out_stype == kRowSparseStorage || out_stype == kDefaultStorage)) { // rsp, rsp -> rsp // rsp, rsp -> dns RspRspOp<OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], false, false, false, false); } else if (ContainsOnlyStorage(inputs, kCSRStorage) && out_stype == kCSRStorage) { // csr, csr -> csr CsrCsrOp<OP>(s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0]); } else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) && out_stype == kDefaultStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kCSRStorage); DnsCsrDnsOp<OP>(s, attrs, ctx, dns, csr, req[0], outputs[0], reverse); } else if (((lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) && out_stype == kDefaultStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kRowSparseStorage); const NDArray& rsp = (reverse)? inputs[0] : inputs[1]; DnsRspDnsOp<xpu, OP>(s, attrs, ctx, dns, rsp, req[0], outputs[0], reverse); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } /*! \brief ComputeEx allowing dense lvalue and/or rvalue */ template<typename xpu, typename OP, bool lhs_may_be_dense, bool rhs_may_be_dense> static void ComputeDnsLRValueEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(inputs.size(), 2); CHECK_EQ(outputs.size(), 1); if (req[0] == kNullOp) return; const auto lhs_stype = inputs[0].storage_type(); const auto rhs_stype = inputs[1].storage_type(); const auto out_stype = outputs[0].storage_type(); if ((out_stype == kRowSparseStorage || out_stype == kDefaultStorage) && ((lhs_stype == kRowSparseStorage && rhs_stype == kRowSparseStorage) || (lhs_stype == kRowSparseStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kRowSparseStorage)) && lhs_may_be_dense && rhs_may_be_dense) { // rsp, rsp -> rsp // rsp, rsp -> dns // rsp, dns -> rsp // dns, rsp -> rsp // More than once dense not allowed (this will be checked in RspRspOp): // rsp, dns -> dns <-- NOT ALLOWED // dns, rsp -> dns <-- NOT ALLOWED mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); RspRspOp<OP>( s, attrs, ctx, inputs[0], inputs[1], req[0], outputs[0], lhs_may_be_dense, rhs_may_be_dense, false, false); } else if (lhs_stype == kCSRStorage && rhs_stype == kCSRStorage) { ComputeEx<xpu, OP>(attrs, ctx, inputs, req, outputs); } else if (((lhs_stype == kCSRStorage && rhs_stype == kDefaultStorage) || (lhs_stype == kDefaultStorage && rhs_stype == kCSRStorage)) && out_stype == kCSRStorage) { const NDArray& dns = (lhs_stype == kDefaultStorage)? inputs[0] : inputs[1]; const NDArray& csr = (lhs_stype == kCSRStorage)? inputs[0] : inputs[1]; const bool reverse = (lhs_stype == kCSRStorage); DnsCsrCsrOp<xpu, OP>(attrs, ctx, dns, csr, req[0], outputs[0], reverse); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNone(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); BackwardUseNone_<LOP, ROP>(attrs, s, inputs, req, outputs); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseNoneEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { CHECK_EQ(inputs.size(), 1U); // output grad CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad const auto in_stype = inputs[0].storage_type(); const auto lhs_stype = outputs[0].storage_type(); const auto rhs_stype = outputs[1].storage_type(); // lhs grad if (req[0] != kNullOp) { if (in_stype == lhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { CHECK_EQ(outputs[0].storage_type(), in_stype); // rsp -> rsp, _. op requires 0-input returns 0-output DCHECK_LT(std::fabs(static_cast<float>(LOP::Map(0))), 1e-5f); UnaryOp::ComputeEx<xpu, LOP>(attrs, ctx, inputs, req, {outputs[0]}); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } // rhs grad if (req[1] != kNullOp) { if (in_stype == rhs_stype && (in_stype == kRowSparseStorage || in_stype == kCSRStorage)) { CHECK_EQ(outputs[0].storage_type(), in_stype); // rsp -> _, rsp. op requires 0-input returns 0-output DCHECK_LT(std::fabs(static_cast<float>(ROP::Map(0))), 1e-5f); UnaryOp::ComputeEx<xpu, ROP>(attrs, ctx, inputs, req, {outputs[1]}); } else { LogUnimplementedOp(attrs, ctx, inputs, req, outputs); } } } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseIn(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<TBlob> &inputs, const std::vector<OpReqType> &req, const std::vector<TBlob> &outputs) { mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); BackwardUseIn_<LOP, ROP>(attrs, s, inputs, req, outputs); } template<typename xpu, typename LOP, typename ROP> static inline void BackwardUseInEx(const nnvm::NodeAttrs &attrs, const OpContext &ctx, const std::vector<NDArray> &inputs, const std::vector<OpReqType> &req, const std::vector<NDArray> &outputs) { using namespace common; CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 2U); // lhs input grad, rhs input grad const auto lhs_grad_stype = outputs[0].storage_type(); const auto rhs_grad_stype = outputs[1].storage_type(); if (ContainsOnlyStorage(inputs, kRowSparseStorage) && (lhs_grad_stype == kDefaultStorage || lhs_grad_stype == kRowSparseStorage) && (rhs_grad_stype == kDefaultStorage || rhs_grad_stype == kRowSparseStorage)) { // rsp, rsp, rsp -> [dns, rsp], [dns, rsp] RspRspOpBackward<xpu, LOP, ROP, false, false, false>( attrs, ctx, inputs, req, outputs, BackwardUseIn<xpu, LOP, ROP>); } else { LOG(FATAL) << "Not Implemented"; } } }; // class ElemwiseBinaryOp /*! \brief Binary launch */ #define MXNET_OPERATOR_REGISTER_BINARY(name) \ NNVM_REGISTER_OP(name) \ .set_num_inputs(2) \ .set_num_outputs(1) \ .set_attr<nnvm::FListInputNames>("FListInputNames", \ [](const NodeAttrs& attrs) { \ return std::vector<std::string>{"lhs", "rhs"}; \ }) \ .set_attr<mxnet::FInferShape>("FInferShape", ElemwiseShape<2, 1>) \ .set_attr<nnvm::FInferType>("FInferType", ElemwiseType<2, 1>) \ .set_attr<nnvm::FInplaceOption>("FInplaceOption", \ [](const NodeAttrs& attrs){ \ return std::vector<std::pair<int, int> >{{0, 0}, {1, 0}}; \ }) \ .add_argument("lhs", "NDArray-or-Symbol", "first input") \ .add_argument("rhs", "NDArray-or-Symbol", "second input") /*! \brief Binary launch, with FComputeEx for csr and rsp available */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseStorageType<2, 1, true, true, true>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) /*! \brief Binary launch, with FComputeEx for csr and rsp available. when inputs contain both sparse and dense, sparse output is preferred. */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PS(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::PreferSparseStorageType) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) /*! \brief Binary launch, dense result * FInferStorageType attr is not set using this macro. * By default DefaultStorageType is used. */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_DR(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::SparseSparseWithDenseResult) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) /*! \brief Binary launch, with FComputeEx for prefer dense */ #define MXNET_OPERATOR_REGISTER_BINARY_WITH_SPARSE_CPU_PD(__name$, __kernel$) \ MXNET_OPERATOR_REGISTER_BINARY(__name$) \ .set_attr<FInferStorageType>("FInferStorageType", \ ElemwiseBinaryOp::PreferDenseStorageType<true, true, true>) \ .set_attr<FCompute>("FCompute<cpu>", ElemwiseBinaryOp::Compute<cpu, __kernel$>) \ .set_attr<FComputeEx>("FComputeEx<cpu>", ElemwiseBinaryOp::ComputeEx<cpu, __kernel$>) \ .set_attr<FResourceRequest>("FResourceRequest", /* For Sparse CSR */ \ [](const NodeAttrs& attrs) { \ return std::vector<ResourceRequest>{ResourceRequest::kTempSpace};}) #if MXNET_USE_CUDA struct ElemwiseBinaryRTCCompute { std::string OP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct ElemwiseBinaryRTCBwdUseNone { std::string LOP; std::string ROP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; struct ElemwiseBinaryRTCBwdUseIn { std::string LOP; std::string ROP; void operator()(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs); }; #endif } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_
dropout-inl.h
/*! * Copyright (c) 2015 by Contributors * \file dropout-inl.h * \brief * \author Bing Xu */ #ifndef MXNET_OPERATOR_DROPOUT_INL_H_ #define MXNET_OPERATOR_DROPOUT_INL_H_ #include <dmlc/logging.h> #include <dmlc/parameter.h> #include <mxnet/operator.h> #include <map> #include <vector> #include <string> #include <utility> #include <algorithm> #include "./operator_common.h" #include "./mshadow_op.h" #if defined(USE_STATIC_MKL) && defined(_OPENMP) #include <omp.h> #include <sched.h> #include <mkl_vml_functions.h> #include <mkl_vsl.h> #endif // USE_MKL && _OPENMP namespace dropout { enum DropoutOpInputs {kData}; enum DropoutOpOutputs {kOut, kMask}; enum DropoutOpForwardResource {kRandom}; } // namespace dropout namespace mxnet { namespace op { #if defined(USE_STATIC_MKL) && defined(_OPENMP) static void bernoulli_generate(int n, double p, int* r) { int seed = 17 + rand_r() % 4096; int nthr = omp_get_max_threads(); # pragma omp parallel num_threads(nthr) { const int ithr = omp_get_thread_num(); const int avg_amount = (n + nthr - 1) / nthr; const int my_offset = ithr * avg_amount; const int my_amount = std::min(my_offset + avg_amount, n) - my_offset; if (my_amount > 0) { VSLStreamStatePtr stream; vslNewStream(&stream, VSL_BRNG_MCG31, seed); vslSkipAheadStream(stream, my_offset); viRngBernoulli(VSL_RNG_METHOD_BERNOULLI_ICDF, stream, my_amount, r + my_offset, p); vslDeleteStream(&stream); } } } #endif // USE_MKL && _OPENMP struct DropoutParam : public dmlc::Parameter<DropoutParam> { float p; DMLC_DECLARE_PARAMETER(DropoutParam) { DMLC_DECLARE_FIELD(p).set_default(0.5) .set_range(0, 1) .describe("Fraction of the input that gets dropped out at training time"); } }; // struct DropoutParam template<typename xpu, typename DType> class DropoutOp : public Operator { public: explicit DropoutOp(DropoutParam param) { this->pkeep_ = 1.0f - param.p; } virtual void Forward(const OpContext &ctx, const std::vector<TBlob> &in_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &out_data, const std::vector<TBlob> &aux_states) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(in_data.size(), 1); if (ctx.is_train) { CHECK_EQ(out_data.size(), 2); } Stream<xpu> *s = ctx.get_stream<xpu>(); Tensor<xpu, 2, DType> data = in_data[dropout::kData].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> out = out_data[dropout::kOut].FlatTo2D<xpu, DType>(s); if (ctx.is_train) { Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s); #if defined(USE_STATIC_MKL) && defined(_OPENMP) DType* outptr = out.dptr_; DType* dataptr = data.dptr_; int* maskptr = reinterpret_cast<int*>(mask.dptr_); int count = mask.shape_[0]*mask.shape_[1]; bernoulli_generate(count, this->pkeep_, maskptr); #pragma omp parallel for for (int i = 0; i < count; ++i) { outptr[i] = dataptr[i] * maskptr[i]; } #else Random<xpu> *prnd = ctx.requested[dropout::kRandom].get_random<xpu, real_t>(s); mask = tcast<DType>(F<mshadow_op::threshold>( prnd->uniform(mask.shape_), pkeep_) * (1.0f / pkeep_)); Assign(out, req[dropout::kOut], data * mask); #endif // USE_MKL && _OPENMP } else { Assign(out, req[dropout::kOut], F<mshadow_op::identity>(data)); } } virtual void Backward(const OpContext &ctx, const std::vector<TBlob> &out_grad, const std::vector<TBlob> &in_data, const std::vector<TBlob> &out_data, const std::vector<OpReqType> &req, const std::vector<TBlob> &in_grad, const std::vector<TBlob> &aux_states) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(out_grad.size(), 1); CHECK_EQ(in_grad.size(), 1); Stream<xpu> *s = ctx.get_stream<xpu>(); Tensor<xpu, 2, DType> grad = out_grad[dropout::kOut].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> mask = out_data[dropout::kMask].FlatTo2D<xpu, DType>(s); Tensor<xpu, 2, DType> gdata = in_grad[dropout::kData].FlatTo2D<xpu, DType>(s); #if defined(USE_STATIC_MKL) && defined(_OPENMP) DType* ingradptr = gdata.dptr_; DType* outgradptr = grad.dptr_; int* maskptr = reinterpret_cast<int*>(mask.dptr_); int count = mask.shape_[0]*mask.shape_[1]; #pragma omp parallel for for (int i = 0; i < count; ++i) { ingradptr[i] = outgradptr[i] * maskptr[i]; } #else // USE_MKL && _OPENMP Assign(gdata, req[dropout::kData], grad * mask); #endif // USE_MKL && _OPENMP } private: real_t pkeep_; }; // class DropoutOp template<typename xpu> Operator *CreateOp(DropoutParam param, int dtype); #if DMLC_USE_CXX11 class DropoutProp : public OperatorProperty { public: void Init(const std::vector<std::pair<std::string, std::string> >& kwargs) override { param_.Init(kwargs); } std::map<std::string, std::string> GetParams() const override { return param_.__DICT__(); } bool InferShape(std::vector<TShape> *in_shape, std::vector<TShape> *out_shape, std::vector<TShape> *aux_shape) const override { using namespace mshadow; CHECK_EQ(in_shape->size(), 1); const TShape &dshape = in_shape->at(0); if (dshape.ndim() == 0) return false; out_shape->clear(); out_shape->push_back(dshape); out_shape->push_back(dshape); return true; } bool InferType(std::vector<int> *in_type, std::vector<int> *out_type, std::vector<int> *aux_type) const override { CHECK_EQ(in_type->size(), 1); int dtype = in_type->at(0); if (dtype == -1) { LOG(FATAL) << "input type to dropout is not specified."; return false; } size_t nout = this->ListOutputs().size(); out_type->clear(); for (size_t i = 0; i < nout; ++i) out_type->push_back(dtype); return true; } OperatorProperty* Copy() const override { auto ptr = new DropoutProp(); ptr->param_ = param_; return ptr; } std::string TypeString() const override { return "Dropout"; } std::vector<int> DeclareBackwardDependency( const std::vector<int> &out_grad, const std::vector<int> &in_data, const std::vector<int> &out_data) const override { return {out_grad[dropout::kOut], out_data[dropout::kMask]}; } std::vector<std::pair<int, void*> > BackwardInplaceOption( const std::vector<int> &out_grad, const std::vector<int> &in_data, const std::vector<int> &out_data, const std::vector<void*> &in_grad) const override { return {{out_grad[dropout::kOut], in_grad[dropout::kData]}}; } std::vector<std::pair<int, void*> > ForwardInplaceOption( const std::vector<int> &in_data, const std::vector<void*> &out_data) const override { return {{in_data[dropout::kData], out_data[dropout::kOut]}}; } std::vector<ResourceRequest> ForwardResource( const std::vector<TShape> &in_shape) const override { return {ResourceRequest::kRandom}; } int NumVisibleOutputs() const override { return 1; } int NumOutputs() const override { return 2; } std::vector<std::string> ListOutputs() const override { return {"output", "mask"}; } Operator* CreateOperator(Context ctx) const override { LOG(FATAL) << "Not Implemented"; return NULL; } Operator* CreateOperatorEx(Context ctx, std::vector<TShape> *in_shape, std::vector<int> *in_type) const override; private: DropoutParam param_; }; // class DropoutProp #endif // DMLC_USE_CXX11 } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_DROPOUT_INL_H_
convolutiondepthwise_5x5_pack8.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. static void convdw5x5s1_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const float* k0 = kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); const float* r3 = img0.row(3); const float* r4 = img0.row(4); int i = 0; for (; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _k00 = _mm256_loadu_ps(k0); __m256 _k01 = _mm256_loadu_ps(k0 + 8); __m256 _k02 = _mm256_loadu_ps(k0 + 16); __m256 _k03 = _mm256_loadu_ps(k0 + 24); __m256 _k04 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _k10 = _mm256_loadu_ps(k0); __m256 _k11 = _mm256_loadu_ps(k0 + 8); __m256 _k12 = _mm256_loadu_ps(k0 + 16); __m256 _k13 = _mm256_loadu_ps(k0 + 24); __m256 _k14 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r24 = _mm256_loadu_ps(r2 + 32); __m256 _k20 = _mm256_loadu_ps(k0); __m256 _k21 = _mm256_loadu_ps(k0 + 8); __m256 _k22 = _mm256_loadu_ps(k0 + 16); __m256 _k23 = _mm256_loadu_ps(k0 + 24); __m256 _k24 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k23, _r23, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k24, _r24, _sum0); __m256 _r30 = _mm256_loadu_ps(r3); __m256 _r31 = _mm256_loadu_ps(r3 + 8); __m256 _r32 = _mm256_loadu_ps(r3 + 16); __m256 _r33 = _mm256_loadu_ps(r3 + 24); __m256 _r34 = _mm256_loadu_ps(r3 + 32); __m256 _k30 = _mm256_loadu_ps(k0); __m256 _k31 = _mm256_loadu_ps(k0 + 8); __m256 _k32 = _mm256_loadu_ps(k0 + 16); __m256 _k33 = _mm256_loadu_ps(k0 + 24); __m256 _k34 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k30, _r30, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k31, _r31, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k32, _r32, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k33, _r33, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k34, _r34, _sum0); __m256 _r40 = _mm256_loadu_ps(r4); __m256 _r41 = _mm256_loadu_ps(r4 + 8); __m256 _r42 = _mm256_loadu_ps(r4 + 16); __m256 _r43 = _mm256_loadu_ps(r4 + 24); __m256 _r44 = _mm256_loadu_ps(r4 + 32); __m256 _k40 = _mm256_loadu_ps(k0); __m256 _k41 = _mm256_loadu_ps(k0 + 8); __m256 _k42 = _mm256_loadu_ps(k0 + 16); __m256 _k43 = _mm256_loadu_ps(k0 + 24); __m256 _k44 = _mm256_loadu_ps(k0 + 32); k0 -= 160; _sum0 = _mm256_comp_fmadd_ps(_k40, _r40, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k41, _r41, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k42, _r42, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k43, _r43, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k44, _r44, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 8; r1 += 8; r2 += 8; r3 += 8; r4 += 8; outptr0 += 8; } r0 += 4 * 8; r1 += 4 * 8; r2 += 4 * 8; r3 += 4 * 8; r4 += 4 * 8; } } } static void convdw5x5s2_pack8_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { int w = bottom_blob.w; int outw = top_blob.w; int outh = top_blob.h; const int group = bottom_blob.c; const int tailstep = (w - 2 * outw + w) * 8; const float* bias = _bias; #pragma omp parallel for num_threads(opt.num_threads) for (int g = 0; g < group; g++) { Mat out = top_blob.channel(g); __m256 _bias0 = bias ? _mm256_loadu_ps((const float*)bias + g * 8) : _mm256_set1_ps(0.f); const float* k0 = kernel.row(g); float* outptr0 = out.row(0); const Mat img0 = bottom_blob.channel(g); const float* r0 = img0.row(0); const float* r1 = img0.row(1); const float* r2 = img0.row(2); const float* r3 = img0.row(3); const float* r4 = img0.row(4); int i = 0; for (; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m256 _sum0 = _bias0; __m256 _r00 = _mm256_loadu_ps(r0); __m256 _r01 = _mm256_loadu_ps(r0 + 8); __m256 _r02 = _mm256_loadu_ps(r0 + 16); __m256 _r03 = _mm256_loadu_ps(r0 + 24); __m256 _r04 = _mm256_loadu_ps(r0 + 32); __m256 _k00 = _mm256_loadu_ps(k0); __m256 _k01 = _mm256_loadu_ps(k0 + 8); __m256 _k02 = _mm256_loadu_ps(k0 + 16); __m256 _k03 = _mm256_loadu_ps(k0 + 24); __m256 _k04 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k00, _r00, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k01, _r01, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k02, _r02, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k03, _r03, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k04, _r04, _sum0); __m256 _r10 = _mm256_loadu_ps(r1); __m256 _r11 = _mm256_loadu_ps(r1 + 8); __m256 _r12 = _mm256_loadu_ps(r1 + 16); __m256 _r13 = _mm256_loadu_ps(r1 + 24); __m256 _r14 = _mm256_loadu_ps(r1 + 32); __m256 _k10 = _mm256_loadu_ps(k0); __m256 _k11 = _mm256_loadu_ps(k0 + 8); __m256 _k12 = _mm256_loadu_ps(k0 + 16); __m256 _k13 = _mm256_loadu_ps(k0 + 24); __m256 _k14 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k10, _r10, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k11, _r11, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k12, _r12, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k13, _r13, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k14, _r14, _sum0); __m256 _r20 = _mm256_loadu_ps(r2); __m256 _r21 = _mm256_loadu_ps(r2 + 8); __m256 _r22 = _mm256_loadu_ps(r2 + 16); __m256 _r23 = _mm256_loadu_ps(r2 + 24); __m256 _r24 = _mm256_loadu_ps(r2 + 32); __m256 _k20 = _mm256_loadu_ps(k0); __m256 _k21 = _mm256_loadu_ps(k0 + 8); __m256 _k22 = _mm256_loadu_ps(k0 + 16); __m256 _k23 = _mm256_loadu_ps(k0 + 24); __m256 _k24 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k20, _r20, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k21, _r21, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k22, _r22, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k23, _r23, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k24, _r24, _sum0); __m256 _r30 = _mm256_loadu_ps(r3); __m256 _r31 = _mm256_loadu_ps(r3 + 8); __m256 _r32 = _mm256_loadu_ps(r3 + 16); __m256 _r33 = _mm256_loadu_ps(r3 + 24); __m256 _r34 = _mm256_loadu_ps(r3 + 32); __m256 _k30 = _mm256_loadu_ps(k0); __m256 _k31 = _mm256_loadu_ps(k0 + 8); __m256 _k32 = _mm256_loadu_ps(k0 + 16); __m256 _k33 = _mm256_loadu_ps(k0 + 24); __m256 _k34 = _mm256_loadu_ps(k0 + 32); k0 += 40; _sum0 = _mm256_comp_fmadd_ps(_k30, _r30, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k31, _r31, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k32, _r32, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k33, _r33, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k34, _r34, _sum0); __m256 _r40 = _mm256_loadu_ps(r4); __m256 _r41 = _mm256_loadu_ps(r4 + 8); __m256 _r42 = _mm256_loadu_ps(r4 + 16); __m256 _r43 = _mm256_loadu_ps(r4 + 24); __m256 _r44 = _mm256_loadu_ps(r4 + 32); __m256 _k40 = _mm256_loadu_ps(k0); __m256 _k41 = _mm256_loadu_ps(k0 + 8); __m256 _k42 = _mm256_loadu_ps(k0 + 16); __m256 _k43 = _mm256_loadu_ps(k0 + 24); __m256 _k44 = _mm256_loadu_ps(k0 + 32); k0 -= 160; _sum0 = _mm256_comp_fmadd_ps(_k40, _r40, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k41, _r41, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k42, _r42, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k43, _r43, _sum0); _sum0 = _mm256_comp_fmadd_ps(_k44, _r44, _sum0); _mm256_storeu_ps(outptr0, _sum0); r0 += 16; r1 += 16; r2 += 16; r3 += 16; r4 += 16; outptr0 += 8; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; r4 += tailstep; } } }
elect_energy_avx2.c
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <math.h> #include <immintrin.h> /* gcc -o evec1 elect_energy_vec_01.c -O4 -lm -fopenmp -march=native */ int main(int argc, char **argv) { struct timespec ts_start, ts_end; float time_total; int i, j, m, ix, iy, iz; int n = 60; /* number of atoms per side */ int n_charges = n * n * n; /* total number of charges */ float a = 0.5; /* Lattice constant */ long v_element_count = 0; long v_count = 0; float tmp_vec[4][8] __attribute__((aligned(32))); double Energy = 0.0; __m256 *X, *Y, *Z, *Q; __m256 tmpQ[8], tmpX[8], tmpY[8], tmpZ[8]; __m256 r_vec, result, vcps, diff[8], mask[8]; /* We need an extra block of 8 floats when n_charges is not a multiple of 8 */ X = aligned_alloc(32, (n_charges) * sizeof(float)); Y = aligned_alloc(32, (n_charges) * sizeof(float)); Z = aligned_alloc(32, (n_charges) * sizeof(float)); Q = aligned_alloc(32, (n_charges) * sizeof(float)); srand(111); /* Seed random numbers generator */ /* Initialize X,Y,Z,Q arrays with 256-bit long vectors */ float tmp_add[8] __attribute__((aligned(32))); for (ix = 0; ix < n; ix++) for (iy = 0; iy < n; iy++) for (iz = 0; iz < n; iz++) { tmp_vec[0][v_element_count] = ix * a; tmp_vec[1][v_element_count] = iy * a; tmp_vec[2][v_element_count] = iz * a; tmp_vec[3][v_element_count] = 10 * ((double)random() / (double)RAND_MAX - 0.5); /* charges */ v_element_count++; /* when 8 elements are computed pack them into _m256 vectors */ if (v_element_count == 8) { X[v_count] = _mm256_set_ps( tmp_vec[0][7], tmp_vec[0][6], tmp_vec[0][5], tmp_vec[0][4], tmp_vec[0][3], tmp_vec[0][2], tmp_vec[0][1], tmp_vec[0][0]); Y[v_count] = _mm256_set_ps( tmp_vec[1][7], tmp_vec[1][6], tmp_vec[1][5], tmp_vec[1][4], tmp_vec[1][3], tmp_vec[1][2], tmp_vec[1][1], tmp_vec[1][0]); Z[v_count] = _mm256_set_ps( tmp_vec[2][7], tmp_vec[2][6], tmp_vec[2][5], tmp_vec[2][4], tmp_vec[2][3], tmp_vec[2][2], tmp_vec[2][1], tmp_vec[2][0]); Q[v_count] = _mm256_set_ps( tmp_vec[3][7], tmp_vec[3][6], tmp_vec[3][5], tmp_vec[3][4], tmp_vec[3][3], tmp_vec[3][2], tmp_vec[3][1], tmp_vec[3][0]); v_count++; v_element_count = 0; memset(tmp_vec, 0, 32 * sizeof(float)); } } /* Treat the remainder. The last vector is padded with zeros */ if (v_element_count != 0) { for (float v = n * a * 2; v_element_count < 8; v_element_count++, v += 1) { tmp_vec[0][v_element_count] = v; tmp_vec[1][v_element_count] = 0.0; tmp_vec[2][v_element_count] = 0.0; tmp_vec[3][v_element_count] = 0.0; } X[v_count] = _mm256_set_ps( tmp_vec[0][7], tmp_vec[0][6], tmp_vec[0][5], tmp_vec[0][4], tmp_vec[0][3], tmp_vec[0][2], tmp_vec[0][1], tmp_vec[0][0]); Y[v_count] = _mm256_set_ps( tmp_vec[1][7], tmp_vec[1][6], tmp_vec[1][5], tmp_vec[1][4], tmp_vec[1][3], tmp_vec[1][2], tmp_vec[1][1], tmp_vec[1][0]); Z[v_count] = _mm256_set_ps( tmp_vec[2][7], tmp_vec[2][6], tmp_vec[2][5], tmp_vec[2][4], tmp_vec[2][3], tmp_vec[2][2], tmp_vec[2][1], tmp_vec[2][0]); Q[v_count] = _mm256_set_ps( tmp_vec[3][7], tmp_vec[3][6], tmp_vec[3][5], tmp_vec[3][4], tmp_vec[3][3], tmp_vec[3][2], tmp_vec[3][1], tmp_vec[3][0]); v_count++; } /* mask upper triangular elements */ mask[0] = (__m256)_mm256_set_epi32(-1, -1, -1, -1, -1, -1, -1, 0); mask[1] = (__m256)_mm256_set_epi32(-1, -1, -1, -1, -1, -1, 0, 0); mask[2] = (__m256)_mm256_set_epi32(-1, -1, -1, -1, -1, 0, 0, 0); mask[3] = (__m256)_mm256_set_epi32(-1, -1, -1, -1, 0, 0, 0, 0); mask[4] = (__m256)_mm256_set_epi32(-1, -1, -1, 0, 0, 0, 0, 0); mask[5] = (__m256)_mm256_set_epi32(-1, -1, 0, 0, 0, 0, 0, 0); mask[6] = (__m256)_mm256_set_epi32(-1, 0, 0, 0, 0, 0, 0, 0); mask[7] = (__m256)_mm256_set_epi32(0, 0, 0, 0, 0, 0, 0, 0); clock_gettime(CLOCK_MONOTONIC, &ts_start); #pragma omp parallel for private(tmpQ, tmpX, tmpY, tmpZ, i, j, m, diff, r_vec, vcps, tmp_add, result) reduction(+ \ : Energy) schedule(dynamic) for (i = 0; i < v_count; i++) { tmpQ[0] = _mm256_broadcast_ss(&Q[i][0]); tmpQ[1] = _mm256_broadcast_ss(&Q[i][1]); tmpQ[2] = _mm256_broadcast_ss(&Q[i][2]); tmpQ[3] = _mm256_broadcast_ss(&Q[i][3]); tmpQ[4] = _mm256_broadcast_ss(&Q[i][4]); tmpQ[5] = _mm256_broadcast_ss(&Q[i][5]); tmpQ[6] = _mm256_broadcast_ss(&Q[i][6]); tmpQ[7] = _mm256_broadcast_ss(&Q[i][7]); tmpX[0] = _mm256_broadcast_ss(&X[i][0]); tmpX[1] = _mm256_broadcast_ss(&X[i][1]); tmpX[2] = _mm256_broadcast_ss(&X[i][2]); tmpX[3] = _mm256_broadcast_ss(&X[i][3]); tmpX[4] = _mm256_broadcast_ss(&X[i][4]); tmpX[5] = _mm256_broadcast_ss(&X[i][5]); tmpX[6] = _mm256_broadcast_ss(&X[i][6]); tmpX[7] = _mm256_broadcast_ss(&X[i][7]); tmpY[0] = _mm256_broadcast_ss(&Y[i][0]); tmpY[1] = _mm256_broadcast_ss(&Y[i][1]); tmpY[2] = _mm256_broadcast_ss(&Y[i][2]); tmpY[3] = _mm256_broadcast_ss(&Y[i][3]); tmpY[4] = _mm256_broadcast_ss(&Y[i][4]); tmpY[5] = _mm256_broadcast_ss(&Y[i][5]); tmpY[6] = _mm256_broadcast_ss(&Y[i][6]); tmpY[7] = _mm256_broadcast_ss(&Y[i][7]); tmpZ[0] = _mm256_broadcast_ss(&Z[i][0]); tmpZ[1] = _mm256_broadcast_ss(&Z[i][1]); tmpZ[2] = _mm256_broadcast_ss(&Z[i][2]); tmpZ[3] = _mm256_broadcast_ss(&Z[i][3]); tmpZ[4] = _mm256_broadcast_ss(&Z[i][4]); tmpZ[5] = _mm256_broadcast_ss(&Z[i][5]); tmpZ[6] = _mm256_broadcast_ss(&Z[i][6]); tmpZ[7] = _mm256_broadcast_ss(&Z[i][7]); /* Accumulate coupling between all lower triangular elements of the diagonal 8x8 blocks */ vcps = _mm256_setzero_ps(); for (m = 0; m < 8; m++) { /* dx,dy,dz */ diff[0] = _mm256_sub_ps(tmpX[m], X[i]); diff[1] = _mm256_sub_ps(tmpY[m], Y[i]); diff[2] = _mm256_sub_ps(tmpZ[m], Z[i]); /* dx*dx + dy*dy + dz*dz */ r_vec = _mm256_fmadd_ps(diff[0], diff[0], _mm256_setzero_ps()); r_vec = _mm256_fmadd_ps(diff[1], diff[1], r_vec); r_vec = _mm256_fmadd_ps(diff[2], diff[2], r_vec); /* distance^-1 */ r_vec = _mm256_rsqrt_ps(r_vec); /* Q[m]*Q[i]*distance^-1 */ result = _mm256_mul_ps(tmpQ[m], Q[i]); result = _mm256_mul_ps(result, r_vec); result = _mm256_and_ps(mask[m], result); vcps = _mm256_add_ps(vcps, result); } /* transfer vcps to double precision accumulator VC */ _mm256_store_ps(tmp_add, vcps); Energy += tmp_add[0] + tmp_add[1] + tmp_add[2] + tmp_add[3] + tmp_add[4] + tmp_add[5] + tmp_add[6] + tmp_add[7]; /* Accumulate coupling between all elemnts of lower triangular 8x8 blocks */ for (j = i + 1; j < v_count; j++) { vcps = _mm256_setzero_ps(); for (m = 0; m < 8; m++) { diff[0] = _mm256_sub_ps(tmpX[m], X[j]); diff[1] = _mm256_sub_ps(tmpY[m], Y[j]); diff[2] = _mm256_sub_ps(tmpZ[m], Z[j]); r_vec = _mm256_fmadd_ps(diff[0], diff[0], _mm256_setzero_ps()); r_vec = _mm256_fmadd_ps(diff[1], diff[1], r_vec); r_vec = _mm256_fmadd_ps(diff[2], diff[2], r_vec); r_vec = _mm256_rsqrt_ps(r_vec); result = _mm256_mul_ps(tmpQ[m], Q[j]); vcps = _mm256_fmadd_ps(result, r_vec, vcps); } _mm256_store_ps(tmp_add, vcps); Energy += tmp_add[0] + tmp_add[1] + tmp_add[2] + tmp_add[3] + tmp_add[4] + tmp_add[5] + tmp_add[6] + tmp_add[7]; } } clock_gettime(CLOCK_MONOTONIC, &ts_end); time_total = (ts_end.tv_sec - ts_start.tv_sec) * 1e9 + (ts_end.tv_nsec - ts_start.tv_nsec); printf("\nTotal time is %f ms, Energy is %.3f\n", time_total / 1e6, Energy * 1e-4); printf("%i\n", v_count); }
statistic.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS TTTTT AAA TTTTT IIIII SSSSS TTTTT IIIII CCCC % % SS T A A T I SS T I C % % SSS T AAAAA T I SSS T I C % % SS T A A T I SS T I C % % SSSSS T A A T IIIII SSSSS T IIIII CCCC % % % % % % MagickCore Image Statistical 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/accelerate-private.h" #include "MagickCore/animate.h" #include "MagickCore/artifact.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/compress.h" #include "MagickCore/constitute.h" #include "MagickCore/display.h" #include "MagickCore/draw.h" #include "MagickCore/enhance.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/gem-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/image-private.h" #include "MagickCore/magic.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/module.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/paint.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/profile.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/random_.h" #include "MagickCore/random-private.h" #include "MagickCore/resource_.h" #include "MagickCore/segment.h" #include "MagickCore/semaphore.h" #include "MagickCore/signature-private.h" #include "MagickCore/statistic.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/timer.h" #include "MagickCore/utility.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E v a l u a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EvaluateImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the EvaluateImage method is: % % MagickBooleanType EvaluateImage(Image *image, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % MagickBooleanType EvaluateImages(Image *images, % const MagickEvaluateOperator op,const double value, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A channel op. % % o value: A value value. % % o exception: return any errors or warnings in this structure. % */ typedef struct _PixelChannels { double channel[CompositePixelChannel]; } PixelChannels; static PixelChannels **DestroyPixelThreadSet(PixelChannels **pixels) { register ssize_t i; assert(pixels != (PixelChannels **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixels[i] != (PixelChannels *) NULL) pixels[i]=(PixelChannels *) RelinquishMagickMemory(pixels[i]); pixels=(PixelChannels **) RelinquishMagickMemory(pixels); return(pixels); } static PixelChannels **AcquirePixelThreadSet(const Image *image) { PixelChannels **pixels; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixels=(PixelChannels **) AcquireQuantumMemory(number_threads, sizeof(*pixels)); if (pixels == (PixelChannels **) NULL) return((PixelChannels **) NULL); (void) ResetMagickMemory(pixels,0,number_threads*sizeof(*pixels)); for (i=0; i < (ssize_t) number_threads; i++) { register ssize_t j; pixels[i]=(PixelChannels *) AcquireQuantumMemory(image->columns, sizeof(**pixels)); if (pixels[i] == (PixelChannels *) NULL) return(DestroyPixelThreadSet(pixels)); for (j=0; j < (ssize_t) image->columns; j++) { register ssize_t k; for (k=0; k < MaxPixelChannels; k++) pixels[i][j].channel[k]=0.0; } } return(pixels); } static inline double EvaluateMax(const double x,const double y) { if (x > y) return(x); return(y); } #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static int IntensityCompare(const void *x,const void *y) { const PixelChannels *color_1, *color_2; double distance; register ssize_t i; color_1=(const PixelChannels *) x; color_2=(const PixelChannels *) y; distance=0.0; for (i=0; i < MaxPixelChannels; i++) distance+=color_1->channel[i]-(double) color_2->channel[i]; return(distance < 0 ? -1 : distance > 0 ? 1 : 0); } #if defined(__cplusplus) || defined(c_plusplus) } #endif static double ApplyEvaluateOperator(RandomInfo *random_info,const Quantum pixel, const MagickEvaluateOperator op,const double value) { double result; result=0.0; switch (op) { case UndefinedEvaluateOperator: break; case AbsEvaluateOperator: { result=(double) fabs((double) (pixel+value)); break; } case AddEvaluateOperator: { result=(double) (pixel+value); break; } case AddModulusEvaluateOperator: { /* This returns a 'floored modulus' of the addition which is a positive result. It differs from % or fmod() that returns a 'truncated modulus' result, where floor() is replaced by trunc() and could return a negative result (which is clipped). */ result=pixel+value; result-=(QuantumRange+1.0)*floor((double) result/(QuantumRange+1.0)); break; } case AndEvaluateOperator: { result=(double) ((size_t) pixel & (size_t) (value+0.5)); break; } case CosineEvaluateOperator: { result=(double) (QuantumRange*(0.5*cos((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case DivideEvaluateOperator: { result=pixel/(value == 0.0 ? 1.0 : value); break; } case ExponentialEvaluateOperator: { result=(double) (QuantumRange*exp((double) (value*QuantumScale*pixel))); break; } case GaussianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, GaussianNoise,value); break; } case ImpulseNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,ImpulseNoise, value); break; } case LaplacianNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, LaplacianNoise,value); break; } case LeftShiftEvaluateOperator: { result=(double) ((size_t) pixel << (size_t) (value+0.5)); break; } case LogEvaluateOperator: { if ((QuantumScale*pixel) >= MagickEpsilon) result=(double) (QuantumRange*log((double) (QuantumScale*value*pixel+ 1.0))/log((double) (value+1.0))); break; } case MaxEvaluateOperator: { result=(double) EvaluateMax((double) pixel,value); break; } case MeanEvaluateOperator: { result=(double) (pixel+value); break; } case MedianEvaluateOperator: { result=(double) (pixel+value); break; } case MinEvaluateOperator: { result=(double) MagickMin((double) pixel,value); break; } case MultiplicativeNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel, MultiplicativeGaussianNoise,value); break; } case MultiplyEvaluateOperator: { result=(double) (value*pixel); break; } case OrEvaluateOperator: { result=(double) ((size_t) pixel | (size_t) (value+0.5)); break; } case PoissonNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,PoissonNoise, value); break; } case PowEvaluateOperator: { result=(double) (QuantumRange*pow((double) (QuantumScale*pixel),(double) value)); break; } case RightShiftEvaluateOperator: { result=(double) ((size_t) pixel >> (size_t) (value+0.5)); break; } case RootMeanSquareEvaluateOperator: { result=(double) (pixel*pixel+value); break; } case SetEvaluateOperator: { result=value; break; } case SineEvaluateOperator: { result=(double) (QuantumRange*(0.5*sin((double) (2.0*MagickPI* QuantumScale*pixel*value))+0.5)); break; } case SubtractEvaluateOperator: { result=(double) (pixel-value); break; } case SumEvaluateOperator: { result=(double) (pixel+value); break; } case ThresholdEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : QuantumRange); break; } case ThresholdBlackEvaluateOperator: { result=(double) (((double) pixel <= value) ? 0 : pixel); break; } case ThresholdWhiteEvaluateOperator: { result=(double) (((double) pixel > value) ? QuantumRange : pixel); break; } case UniformNoiseEvaluateOperator: { result=(double) GenerateDifferentialNoise(random_info,pixel,UniformNoise, value); break; } case XorEvaluateOperator: { result=(double) ((size_t) pixel ^ (size_t) (value+0.5)); break; } } return(result); } MagickExport Image *EvaluateImages(const Image *images, const MagickEvaluateOperator op,ExceptionInfo *exception) { #define EvaluateImageTag "Evaluate/Image" CacheView *evaluate_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict evaluate_pixels; RandomInfo **magick_restrict random_info; size_t number_images; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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=CloneImage(images,images->columns,images->rows,MagickTrue, exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); evaluate_pixels=AcquirePixelThreadSet(images); if (evaluate_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Evaluate image pixels. */ status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); evaluate_view=AcquireAuthenticCacheView(image,exception); if (op == MedianEvaluateOperator) { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t j, k; for (j=0; j < (ssize_t) number_images; j++) for (k=0; k < MaxPixelChannels; k++) evaluate_pixel[j].channel[k]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; register ssize_t i; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,x,y,1,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); PixelTrait traits = GetPixelChannelTraits(next,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[j].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),op, evaluate_pixel[j].channel[i]); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } qsort((void *) evaluate_pixel,number_images,sizeof(*evaluate_pixel), IntensityCompare); for (k=0; k < (ssize_t) GetPixelChannels(image); k++) q[k]=ClampToQuantum(evaluate_pixel[j/2].channel[k]); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } else { #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,images,image->rows,key == ~0UL) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *evaluate_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(evaluate_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } evaluate_pixel=evaluate_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) evaluate_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { p+=GetPixelChannels(next); continue; } for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait evaluate_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (evaluate_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; evaluate_pixel[x].channel[i]=ApplyEvaluateOperator( random_info[id],GetPixelChannel(image,channel,p),j == 0 ? AddEvaluateOperator : op,evaluate_pixel[x].channel[i]); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; switch (op) { case MeanEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]/=(double) number_images; break; } case MultiplyEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { register ssize_t j; for (j=0; j < (ssize_t) (number_images-1); j++) evaluate_pixel[x].channel[i]*=QuantumScale; } break; } case RootMeanSquareEvaluateOperator: { for (i=0; i < (ssize_t) GetPixelChannels(image); i++) evaluate_pixel[x].channel[i]=sqrt(evaluate_pixel[x].channel[i]/ number_images); break; } default: break; } } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(evaluate_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(evaluate_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_EvaluateImages) #endif proceed=SetImageProgress(images,EvaluateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } } evaluate_view=DestroyCacheView(evaluate_view); evaluate_pixels=DestroyPixelThreadSet(evaluate_pixels); random_info=DestroyRandomInfoThreadSet(random_info); if (status == MagickFalse) image=DestroyImage(image); return(image); } MagickExport MagickBooleanType EvaluateImage(Image *image, const MagickEvaluateOperator op,const double value,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; RandomInfo **magick_restrict random_info; ssize_t y; #if defined(MAGICKCORE_OPENMP_SUPPORT) unsigned long key; #endif 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 (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; random_info=AcquireRandomInfoThreadSet(); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) key=GetRandomSecretKey(random_info[0]); #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,key == ~0UL) #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 result; register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if (((traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,q) <= (QuantumRange/2))) continue; if ((traits & UpdatePixelTrait) == 0) continue; result=ApplyEvaluateOperator(random_info[id],q[i],op,value); if (op == MeanEvaluateOperator) result/=2.0; q[i]=ClampToQuantum(result); } 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 critical (MagickCore_EvaluateImage) #endif proceed=SetImageProgress(image,EvaluateImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F u n c t i o n I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % FunctionImage() applies a value to the image with an arithmetic, relational, % or logical operator to an image. Use these operations to lighten or darken % an image, to increase or decrease contrast in an image, or to produce the % "negative" of an image. % % The format of the FunctionImage method is: % % MagickBooleanType FunctionImage(Image *image, % const MagickFunction function,const ssize_t number_parameters, % const double *parameters,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o function: A channel function. % % o parameters: one or more parameters. % % o exception: return any errors or warnings in this structure. % */ static Quantum ApplyFunction(Quantum pixel,const MagickFunction function, const size_t number_parameters,const double *parameters, ExceptionInfo *exception) { double result; register ssize_t i; (void) exception; result=0.0; switch (function) { case PolynomialFunction: { /* Polynomial: polynomial constants, highest to lowest order (e.g. c0*x^3+ c1*x^2+c2*x+c3). */ result=0.0; for (i=0; i < (ssize_t) number_parameters; i++) result=result*QuantumScale*pixel+parameters[i]; result*=QuantumRange; break; } case SinusoidFunction: { double amplitude, bias, frequency, phase; /* Sinusoid: frequency, phase, amplitude, bias. */ frequency=(number_parameters >= 1) ? parameters[0] : 1.0; phase=(number_parameters >= 2) ? parameters[1] : 0.0; amplitude=(number_parameters >= 3) ? parameters[2] : 0.5; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (QuantumRange*(amplitude*sin((double) (2.0* MagickPI*(frequency*QuantumScale*pixel+phase/360.0)))+bias)); break; } case ArcsinFunction: { double bias, center, range, width; /* Arcsin (peged at range limits for invalid results): width, center, range, and bias. */ width=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=2.0/width*(QuantumScale*pixel-center); if ( result <= -1.0 ) result=bias-range/2.0; else if (result >= 1.0) result=bias+range/2.0; else result=(double) (range/MagickPI*asin((double) result)+bias); result*=QuantumRange; break; } case ArctanFunction: { double center, bias, range, slope; /* Arctan: slope, center, range, and bias. */ slope=(number_parameters >= 1) ? parameters[0] : 1.0; center=(number_parameters >= 2) ? parameters[1] : 0.5; range=(number_parameters >= 3) ? parameters[2] : 1.0; bias=(number_parameters >= 4) ? parameters[3] : 0.5; result=(double) (MagickPI*slope*(QuantumScale*pixel-center)); result=(double) (QuantumRange*(range/MagickPI*atan((double) result)+bias)); break; } case UndefinedFunction: break; } return(ClampToQuantum(result)); } MagickExport MagickBooleanType FunctionImage(Image *image, const MagickFunction function,const size_t number_parameters, const double *parameters,ExceptionInfo *exception) { #define FunctionImageTag "Function/Image " CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) if (AccelerateFunctionImage(image,function,number_parameters,parameters, exception) != MagickFalse) return(MagickTrue); #endif if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_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 ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyFunction(q[i],function,number_parameters,parameters, exception); } 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 critical (MagickCore_FunctionImage) #endif proceed=SetImageProgress(image,FunctionImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E n t r o p y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageEntropy() returns the entropy of one or more image channels. % % The format of the GetImageEntropy method is: % % MagickBooleanType GetImageEntropy(const Image *image,double *entropy, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o entropy: the average entropy of the selected channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageEntropy(const Image *image, double *entropy,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *entropy=channel_statistics[CompositePixelChannel].entropy; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtrema() returns the extrema of one or more image channels. % % The format of the GetImageExtrema method is: % % MagickBooleanType GetImageExtrema(const Image *image,size_t *minima, % size_t *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageExtrema(const Image *image, size_t *minima,size_t *maxima,ExceptionInfo *exception) { double max, min; MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=GetImageRange(image,&min,&max,exception); *minima=(size_t) ceil(min-0.5); *maxima=(size_t) floor(max+0.5); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e K u r t o s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageKurtosis() returns the kurtosis and skewness of one or more image % channels. % % The format of the GetImageKurtosis method is: % % MagickBooleanType GetImageKurtosis(const Image *image,double *kurtosis, % double *skewness,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o kurtosis: the kurtosis of the channel. % % o skewness: the skewness of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageKurtosis(const Image *image, double *kurtosis,double *skewness,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *kurtosis=channel_statistics[CompositePixelChannel].kurtosis; *skewness=channel_statistics[CompositePixelChannel].skewness; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M e a n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMean() returns the mean and standard deviation of one or more image % channels. % % The format of the GetImageMean method is: % % MagickBooleanType GetImageMean(const Image *image,double *mean, % double *standard_deviation,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mean: the average value in the channel. % % o standard_deviation: the standard deviation of the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageMean(const Image *image,double *mean, double *standard_deviation,ExceptionInfo *exception) { ChannelStatistics *channel_statistics; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_statistics=GetImageStatistics(image,exception); if (channel_statistics == (ChannelStatistics *) NULL) return(MagickFalse); *mean=channel_statistics[CompositePixelChannel].mean; *standard_deviation= channel_statistics[CompositePixelChannel].standard_deviation; channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e M o m e n t s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageMoments() returns the normalized moments of one or more image % channels. % % The format of the GetImageMoments method is: % % ChannelMoments *GetImageMoments(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. % */ static size_t GetImageChannels(const Image *image) { register ssize_t i; size_t channels; channels=0; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; channels++; } return((size_t) (channels == 0 ? 1 : channels)); } MagickExport ChannelMoments *GetImageMoments(const Image *image, ExceptionInfo *exception) { #define MaxNumberImageMoments 8 CacheView *image_view; ChannelMoments *channel_moments; double M00[MaxPixelChannels+1], M01[MaxPixelChannels+1], M02[MaxPixelChannels+1], M03[MaxPixelChannels+1], M10[MaxPixelChannels+1], M11[MaxPixelChannels+1], M12[MaxPixelChannels+1], M20[MaxPixelChannels+1], M21[MaxPixelChannels+1], M22[MaxPixelChannels+1], M30[MaxPixelChannels+1]; PointInfo centroid[MaxPixelChannels+1]; ssize_t channel, y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); channel_moments=(ChannelMoments *) AcquireQuantumMemory(MaxPixelChannels+1, sizeof(*channel_moments)); if (channel_moments == (ChannelMoments *) NULL) return(channel_moments); (void) ResetMagickMemory(channel_moments,0,(MaxPixelChannels+1)* sizeof(*channel_moments)); (void) ResetMagickMemory(centroid,0,sizeof(centroid)); (void) ResetMagickMemory(M00,0,sizeof(M00)); (void) ResetMagickMemory(M01,0,sizeof(M01)); (void) ResetMagickMemory(M02,0,sizeof(M02)); (void) ResetMagickMemory(M03,0,sizeof(M03)); (void) ResetMagickMemory(M10,0,sizeof(M10)); (void) ResetMagickMemory(M11,0,sizeof(M11)); (void) ResetMagickMemory(M12,0,sizeof(M12)); (void) ResetMagickMemory(M20,0,sizeof(M20)); (void) ResetMagickMemory(M21,0,sizeof(M21)); (void) ResetMagickMemory(M22,0,sizeof(M22)); (void) ResetMagickMemory(M30,0,sizeof(M30)); image_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute center of mass (centroid). */ 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++) { register ssize_t i; 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); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M00[channel]+=QuantumScale*p[i]; M00[MaxPixelChannels]+=QuantumScale*p[i]; M10[channel]+=x*QuantumScale*p[i]; M10[MaxPixelChannels]+=x*QuantumScale*p[i]; M01[channel]+=y*QuantumScale*p[i]; M01[MaxPixelChannels]+=y*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute center of mass (centroid). */ if (M00[channel] < MagickEpsilon) { M00[channel]+=MagickEpsilon; centroid[channel].x=(double) image->columns/2.0; centroid[channel].y=(double) image->rows/2.0; continue; } M00[channel]+=MagickEpsilon; centroid[channel].x=M10[channel]/M00[channel]; centroid[channel].y=M01[channel]/M00[channel]; } for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute the image moments. */ 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++) { register ssize_t i; 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); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; M11[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M11[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* QuantumScale*p[i]; M20[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M20[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* QuantumScale*p[i]; M02[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M02[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* QuantumScale*p[i]; M21[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M21[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[channel]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M12[MaxPixelChannels]+=(x-centroid[channel].x)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M22[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M22[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (y-centroid[channel].y)*(y-centroid[channel].y)*QuantumScale*p[i]; M30[channel]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M30[MaxPixelChannels]+=(x-centroid[channel].x)*(x-centroid[channel].x)* (x-centroid[channel].x)*QuantumScale*p[i]; M03[channel]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; M03[MaxPixelChannels]+=(y-centroid[channel].y)*(y-centroid[channel].y)* (y-centroid[channel].y)*QuantumScale*p[i]; } p+=GetPixelChannels(image); } } M00[MaxPixelChannels]/=GetImageChannels(image); M01[MaxPixelChannels]/=GetImageChannels(image); M02[MaxPixelChannels]/=GetImageChannels(image); M03[MaxPixelChannels]/=GetImageChannels(image); M10[MaxPixelChannels]/=GetImageChannels(image); M11[MaxPixelChannels]/=GetImageChannels(image); M12[MaxPixelChannels]/=GetImageChannels(image); M20[MaxPixelChannels]/=GetImageChannels(image); M21[MaxPixelChannels]/=GetImageChannels(image); M22[MaxPixelChannels]/=GetImageChannels(image); M30[MaxPixelChannels]/=GetImageChannels(image); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute elliptical angle, major and minor axes, eccentricity, & intensity. */ channel_moments[channel].centroid=centroid[channel]; channel_moments[channel].ellipse_axis.x=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])+sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_axis.y=sqrt((2.0/M00[channel])* ((M20[channel]+M02[channel])-sqrt(4.0*M11[channel]*M11[channel]+ (M20[channel]-M02[channel])*(M20[channel]-M02[channel])))); channel_moments[channel].ellipse_angle=RadiansToDegrees(0.5*atan(2.0* M11[channel]/(M20[channel]-M02[channel]+MagickEpsilon))); if (fabs(M11[channel]) < MagickEpsilon) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } else if (M11[channel] < 0.0) { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=180.0; } else { if (fabs(M20[channel]-M02[channel]) < MagickEpsilon) channel_moments[channel].ellipse_angle+=0.0; else if ((M20[channel]-M02[channel]) < 0.0) channel_moments[channel].ellipse_angle+=90.0; else channel_moments[channel].ellipse_angle+=0.0; } channel_moments[channel].ellipse_eccentricity=sqrt(1.0-( channel_moments[channel].ellipse_axis.y/ (channel_moments[channel].ellipse_axis.x+MagickEpsilon))); channel_moments[channel].ellipse_intensity=M00[channel]/ (MagickPI*channel_moments[channel].ellipse_axis.x* channel_moments[channel].ellipse_axis.y+MagickEpsilon); } for (channel=0; channel <= MaxPixelChannels; channel++) { /* Normalize image moments. */ M10[channel]=0.0; M01[channel]=0.0; M11[channel]/=pow(M00[channel],1.0+(1.0+1.0)/2.0); M20[channel]/=pow(M00[channel],1.0+(2.0+0.0)/2.0); M02[channel]/=pow(M00[channel],1.0+(0.0+2.0)/2.0); M21[channel]/=pow(M00[channel],1.0+(2.0+1.0)/2.0); M12[channel]/=pow(M00[channel],1.0+(1.0+2.0)/2.0); M22[channel]/=pow(M00[channel],1.0+(2.0+2.0)/2.0); M30[channel]/=pow(M00[channel],1.0+(3.0+0.0)/2.0); M03[channel]/=pow(M00[channel],1.0+(0.0+3.0)/2.0); M00[channel]=1.0; } image_view=DestroyCacheView(image_view); for (channel=0; channel <= MaxPixelChannels; channel++) { /* Compute Hu invariant moments. */ channel_moments[channel].invariant[0]=M20[channel]+M02[channel]; channel_moments[channel].invariant[1]=(M20[channel]-M02[channel])* (M20[channel]-M02[channel])+4.0*M11[channel]*M11[channel]; channel_moments[channel].invariant[2]=(M30[channel]-3.0*M12[channel])* (M30[channel]-3.0*M12[channel])+(3.0*M21[channel]-M03[channel])* (3.0*M21[channel]-M03[channel]); channel_moments[channel].invariant[3]=(M30[channel]+M12[channel])* (M30[channel]+M12[channel])+(M21[channel]+M03[channel])* (M21[channel]+M03[channel]); channel_moments[channel].invariant[4]=(M30[channel]-3.0*M12[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))+(3.0*M21[channel]-M03[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[5]=(M20[channel]-M02[channel])* ((M30[channel]+M12[channel])*(M30[channel]+M12[channel])- (M21[channel]+M03[channel])*(M21[channel]+M03[channel]))+ 4.0*M11[channel]*(M30[channel]+M12[channel])*(M21[channel]+M03[channel]); channel_moments[channel].invariant[6]=(3.0*M21[channel]-M03[channel])* (M30[channel]+M12[channel])*((M30[channel]+M12[channel])* (M30[channel]+M12[channel])-3.0*(M21[channel]+M03[channel])* (M21[channel]+M03[channel]))-(M30[channel]-3*M12[channel])* (M21[channel]+M03[channel])*(3.0*(M30[channel]+M12[channel])* (M30[channel]+M12[channel])-(M21[channel]+M03[channel])* (M21[channel]+M03[channel])); channel_moments[channel].invariant[7]=M11[channel]*((M30[channel]+ M12[channel])*(M30[channel]+M12[channel])-(M03[channel]+M21[channel])* (M03[channel]+M21[channel]))-(M20[channel]-M02[channel])* (M30[channel]+M12[channel])*(M03[channel]+M21[channel]); } if (y < (ssize_t) image->rows) channel_moments=(ChannelMoments *) RelinquishMagickMemory(channel_moments); return(channel_moments); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e C h a n n e l P e r c e p t u a l H a s h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePerceptualHash() returns the perceptual hash of one or more % image channels. % % The format of the GetImagePerceptualHash method is: % % ChannelPerceptualHash *GetImagePerceptualHash(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. % */ static inline double MagickLog10(const double x) { #define Log10Epsilon (1.0e-11) if (fabs(x) < Log10Epsilon) return(log10(Log10Epsilon)); return(log10(fabs(x))); } MagickExport ChannelPerceptualHash *GetImagePerceptualHash(const Image *image, ExceptionInfo *exception) { ChannelPerceptualHash *perceptual_hash; char *colorspaces, *q; const char *artifact; MagickBooleanType status; register char *p; register ssize_t i; perceptual_hash=(ChannelPerceptualHash *) AcquireQuantumMemory( MaxPixelChannels+1UL,sizeof(*perceptual_hash)); if (perceptual_hash == (ChannelPerceptualHash *) NULL) return((ChannelPerceptualHash *) NULL); artifact=GetImageArtifact(image,"phash:colorspaces"); if (artifact != NULL) colorspaces=AcquireString(artifact); else colorspaces=AcquireString("sRGB,HCLp"); perceptual_hash[0].number_colorspaces=0; perceptual_hash[0].number_channels=0; q=colorspaces; for (i=0; (p=StringToken(",",&q)) != (char *) NULL; i++) { ChannelMoments *moments; Image *hash_image; size_t j; ssize_t channel, colorspace; if (i >= MaximumNumberOfPerceptualColorspaces) break; colorspace=ParseCommandOption(MagickColorspaceOptions,MagickFalse,p); if (colorspace < 0) break; perceptual_hash[0].colorspace[i]=(ColorspaceType) colorspace; hash_image=BlurImage(image,0.0,1.0,exception); if (hash_image == (Image *) NULL) break; hash_image->depth=8; status=TransformImageColorspace(hash_image,(ColorspaceType) colorspace, exception); if (status == MagickFalse) break; moments=GetImageMoments(hash_image,exception); perceptual_hash[0].number_colorspaces++; perceptual_hash[0].number_channels+=GetImageChannels(hash_image); hash_image=DestroyImage(hash_image); if (moments == (ChannelMoments *) NULL) break; for (channel=0; channel <= MaxPixelChannels; channel++) for (j=0; j < MaximumNumberOfImageMoments; j++) perceptual_hash[channel].phash[i][j]= (-MagickLog10(moments[channel].invariant[j])); moments=(ChannelMoments *) RelinquishMagickMemory(moments); } colorspaces=DestroyString(colorspaces); return(perceptual_hash); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e R a n g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageRange() returns the range of one or more image channels. % % The format of the GetImageRange method is: % % MagickBooleanType GetImageRange(const Image *image,double *minima, % double *maxima,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o minima: the minimum value in the channel. % % o maxima: the maximum value in the channel. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetImageRange(const Image *image,double *minima, double *maxima,ExceptionInfo *exception) { CacheView *image_view; MagickBooleanType initialize, status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; initialize=MagickTrue; *maxima=0.0; *minima=0.0; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status,initialize) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { double row_maxima = 0.0, row_minima = 0.0; MagickBooleanType row_initialize; register const Quantum *magick_restrict p; register ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } row_initialize=MagickTrue; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; 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); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (row_initialize != MagickFalse) { row_minima=(double) p[i]; row_maxima=(double) p[i]; row_initialize=MagickFalse; } else { if ((double) p[i] < row_minima) row_minima=(double) p[i]; if ((double) p[i] > row_maxima) row_maxima=(double) p[i]; } } p+=GetPixelChannels(image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_GetImageRange) #endif { if (initialize != MagickFalse) { *minima=row_minima; *maxima=row_maxima; initialize=MagickFalse; } else { if (row_minima < *minima) *minima=row_minima; if (row_maxima > *maxima) *maxima=row_maxima; } } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t I m a g e S t a t i s t i c s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageStatistics() returns statistics for each channel in the image. The % statistics include the channel depth, its minima, maxima, mean, standard % deviation, kurtosis and skewness. You can access the red channel mean, for % example, like this: % % channel_statistics=GetImageStatistics(image,exception); % red_mean=channel_statistics[RedPixelChannel].mean; % % Use MagickRelinquishMemory() to free the statistics buffer. % % The format of the GetImageStatistics method is: % % ChannelStatistics *GetImageStatistics(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 ChannelStatistics *GetImageStatistics(const Image *image, ExceptionInfo *exception) { ChannelStatistics *channel_statistics; double area, *histogram, standard_deviation; MagickStatusType status; QuantumAny range; register ssize_t i; size_t depth; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); histogram=(double *) AcquireQuantumMemory(MaxMap+1UL,GetPixelChannels(image)* sizeof(*histogram)); channel_statistics=(ChannelStatistics *) AcquireQuantumMemory( MaxPixelChannels+1,sizeof(*channel_statistics)); if ((channel_statistics == (ChannelStatistics *) NULL) || (histogram == (double *) NULL)) { if (histogram != (double *) NULL) histogram=(double *) RelinquishMagickMemory(histogram); if (channel_statistics != (ChannelStatistics *) NULL) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } (void) ResetMagickMemory(channel_statistics,0,(MaxPixelChannels+1)* sizeof(*channel_statistics)); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { channel_statistics[i].depth=1; channel_statistics[i].maxima=(-MagickMaximumValue); channel_statistics[i].minima=MagickMaximumValue; } (void) ResetMagickMemory(histogram,0,(MaxMap+1)*GetPixelChannels(image)* sizeof(*histogram)); for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; /* Compute pixel statistics. */ p=GetVirtualPixels(image,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; 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); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; if (channel_statistics[channel].depth != MAGICKCORE_QUANTUM_DEPTH) { depth=channel_statistics[channel].depth; range=GetQuantumRange(depth); status=p[i] != ScaleAnyToQuantum(ScaleQuantumToAny(p[i],range), range) ? MagickTrue : MagickFalse; if (status != MagickFalse) { channel_statistics[channel].depth++; i--; continue; } } if ((double) p[i] < channel_statistics[channel].minima) channel_statistics[channel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[channel].maxima) channel_statistics[channel].maxima=(double) p[i]; channel_statistics[channel].sum+=p[i]; channel_statistics[channel].sum_squared+=(double) p[i]*p[i]; channel_statistics[channel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[channel].sum_fourth_power+=(double) p[i]*p[i]*p[i]* p[i]; channel_statistics[channel].area++; if ((double) p[i] < channel_statistics[CompositePixelChannel].minima) channel_statistics[CompositePixelChannel].minima=(double) p[i]; if ((double) p[i] > channel_statistics[CompositePixelChannel].maxima) channel_statistics[CompositePixelChannel].maxima=(double) p[i]; histogram[GetPixelChannels(image)*ScaleQuantumToMap( ClampToQuantum((double) p[i]))+i]++; channel_statistics[CompositePixelChannel].sum+=(double) p[i]; channel_statistics[CompositePixelChannel].sum_squared+=(double) p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_cubed+=(double) p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].sum_fourth_power+=(double) p[i]*p[i]*p[i]*p[i]; channel_statistics[CompositePixelChannel].area++; } p+=GetPixelChannels(image); } } for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Normalize pixel statistics. */ area=PerceptibleReciprocal(channel_statistics[i].area); channel_statistics[i].sum*=area; channel_statistics[i].sum_squared*=area; channel_statistics[i].sum_cubed*=area; channel_statistics[i].sum_fourth_power*=area; channel_statistics[i].mean=channel_statistics[i].sum; channel_statistics[i].variance=channel_statistics[i].sum_squared; standard_deviation=sqrt(channel_statistics[i].variance- (channel_statistics[i].mean*channel_statistics[i].mean)); standard_deviation=sqrt(PerceptibleReciprocal(channel_statistics[i].area- 1.0)*channel_statistics[i].area*standard_deviation*standard_deviation); channel_statistics[i].standard_deviation=standard_deviation; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { double number_bins; register ssize_t j; /* Compute pixel entropy. */ PixelChannel channel = GetPixelChannelChannel(image,i); number_bins=0.0; for (j=0; j <= (ssize_t) MaxMap; j++) if (histogram[GetPixelChannels(image)*j+i] > 0.0) number_bins++; area=PerceptibleReciprocal(channel_statistics[channel].area); for (j=0; j <= (ssize_t) MaxMap; j++) { double count; count=area*histogram[GetPixelChannels(image)*j+i]; if (number_bins > MagickEpsilon) { channel_statistics[channel].entropy+=-count*MagickLog10(count)/ MagickLog10(number_bins); channel_statistics[CompositePixelChannel].entropy+=-count* MagickLog10(count)/MagickLog10(number_bins)/ GetPixelChannels(image); } } } histogram=(double *) RelinquishMagickMemory(histogram); for (i=0; i <= (ssize_t) MaxPixelChannels; i++) { /* Compute kurtosis & skewness statistics. */ standard_deviation=PerceptibleReciprocal( channel_statistics[i].standard_deviation); channel_statistics[i].skewness=(channel_statistics[i].sum_cubed-3.0* channel_statistics[i].mean*channel_statistics[i].sum_squared+2.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation); channel_statistics[i].kurtosis=(channel_statistics[i].sum_fourth_power-4.0* channel_statistics[i].mean*channel_statistics[i].sum_cubed+6.0* channel_statistics[i].mean*channel_statistics[i].mean* channel_statistics[i].sum_squared-3.0*channel_statistics[i].mean* channel_statistics[i].mean*1.0*channel_statistics[i].mean* channel_statistics[i].mean)*(standard_deviation*standard_deviation* standard_deviation*standard_deviation)-3.0; } if (y < (ssize_t) image->rows) channel_statistics=(ChannelStatistics *) RelinquishMagickMemory( channel_statistics); return(channel_statistics); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P o l y n o m i a l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PolynomialImage() returns a new image where each pixel is the sum of the % pixels in the image sequence after applying its corresponding terms % (coefficient and degree pairs). % % The format of the PolynomialImage method is: % % Image *PolynomialImage(const Image *images,const size_t number_terms, % const double *terms,ExceptionInfo *exception) % % A description of each parameter follows: % % o images: the image sequence. % % o number_terms: the number of terms in the list. The actual list length % is 2 x number_terms + 1 (the constant). % % o terms: the list of polynomial coefficients and degree pairs and a % constant. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *PolynomialImage(const Image *images, const size_t number_terms,const double *terms,ExceptionInfo *exception) { #define PolynomialImageTag "Polynomial/Image" CacheView *polynomial_view; Image *image; MagickBooleanType status; MagickOffsetType progress; PixelChannels **magick_restrict polynomial_pixels; size_t number_images; ssize_t y; 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=CloneImage(images,images->columns,images->rows,MagickTrue, exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImage(image); return((Image *) NULL); } number_images=GetImageListLength(images); polynomial_pixels=AcquirePixelThreadSet(images); if (polynomial_pixels == (PixelChannels **) NULL) { image=DestroyImage(image); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",images->filename); return((Image *) NULL); } /* Polynomial image pixels. */ status=MagickTrue; progress=0; polynomial_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { CacheView *image_view; const Image *next; const int id = GetOpenMPThreadId(); register ssize_t i, x; register PixelChannels *polynomial_pixel; register Quantum *magick_restrict q; ssize_t j; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(polynomial_view,0,y,image->columns,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } polynomial_pixel=polynomial_pixels[id]; for (j=0; j < (ssize_t) image->columns; j++) for (i=0; i < MaxPixelChannels; i++) polynomial_pixel[j].channel[i]=0.0; next=images; for (j=0; j < (ssize_t) number_images; j++) { register const Quantum *p; if (j >= (ssize_t) number_terms) continue; image_view=AcquireVirtualCacheView(next,exception); p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { image_view=DestroyCacheView(image_view); break; } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(next,p) <= (QuantumRange/2)) { p+=GetPixelChannels(next); continue; } for (i=0; i < (ssize_t) GetPixelChannels(next); i++) { MagickRealType coefficient, degree; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(next,channel); PixelTrait polynomial_traits=GetPixelChannelTraits(image,channel); if ((traits == UndefinedPixelTrait) || (polynomial_traits == UndefinedPixelTrait)) continue; if ((traits & UpdatePixelTrait) == 0) continue; coefficient=(MagickRealType) terms[2*j]; degree=(MagickRealType) terms[(j << 1)+1]; polynomial_pixel[x].channel[i]+=coefficient* pow(QuantumScale*GetPixelChannel(image,channel,p),degree); } p+=GetPixelChannels(next); } image_view=DestroyCacheView(image_view); next=GetNextImageInList(next); } for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; if (GetPixelWriteMask(image,q) <= (QuantumRange/2)) { q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(QuantumRange*polynomial_pixel[x].channel[i]); } q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(polynomial_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_PolynomialImages) #endif proceed=SetImageProgress(images,PolynomialImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } polynomial_view=DestroyCacheView(polynomial_view); polynomial_pixels=DestroyPixelThreadSet(polynomial_pixels); if (status == MagickFalse) image=DestroyImage(image); return(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S t a t i s t i c I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % StatisticImage() makes each pixel the min / max / median / mode / etc. of % the neighborhood of the specified width and height. % % The format of the StatisticImage method is: % % Image *StatisticImage(const Image *image,const StatisticType type, % const size_t width,const size_t height,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o type: the statistic type (median, mode, etc.). % % o width: the width of the pixel neighborhood. % % o height: the height of the pixel neighborhood. % % o exception: return any errors or warnings in this structure. % */ typedef struct _SkipNode { size_t next[9], count, signature; } SkipNode; typedef struct _SkipList { ssize_t level; SkipNode *nodes; } SkipList; typedef struct _PixelList { size_t length, seed; SkipList skip_list; size_t signature; } PixelList; static PixelList *DestroyPixelList(PixelList *pixel_list) { if (pixel_list == (PixelList *) NULL) return((PixelList *) NULL); if (pixel_list->skip_list.nodes != (SkipNode *) NULL) pixel_list->skip_list.nodes=(SkipNode *) RelinquishAlignedMemory( pixel_list->skip_list.nodes); pixel_list=(PixelList *) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList **DestroyPixelListThreadSet(PixelList **pixel_list) { register ssize_t i; assert(pixel_list != (PixelList **) NULL); for (i=0; i < (ssize_t) GetMagickResourceLimit(ThreadResource); i++) if (pixel_list[i] != (PixelList *) NULL) pixel_list[i]=DestroyPixelList(pixel_list[i]); pixel_list=(PixelList **) RelinquishMagickMemory(pixel_list); return(pixel_list); } static PixelList *AcquirePixelList(const size_t width,const size_t height) { PixelList *pixel_list; pixel_list=(PixelList *) AcquireMagickMemory(sizeof(*pixel_list)); if (pixel_list == (PixelList *) NULL) return(pixel_list); (void) ResetMagickMemory((void *) pixel_list,0,sizeof(*pixel_list)); pixel_list->length=width*height; pixel_list->skip_list.nodes=(SkipNode *) AcquireAlignedMemory(65537UL, sizeof(*pixel_list->skip_list.nodes)); if (pixel_list->skip_list.nodes == (SkipNode *) NULL) return(DestroyPixelList(pixel_list)); (void) ResetMagickMemory(pixel_list->skip_list.nodes,0,65537UL* sizeof(*pixel_list->skip_list.nodes)); pixel_list->signature=MagickCoreSignature; return(pixel_list); } static PixelList **AcquirePixelListThreadSet(const size_t width, const size_t height) { PixelList **pixel_list; register ssize_t i; size_t number_threads; number_threads=(size_t) GetMagickResourceLimit(ThreadResource); pixel_list=(PixelList **) AcquireQuantumMemory(number_threads, sizeof(*pixel_list)); if (pixel_list == (PixelList **) NULL) return((PixelList **) NULL); (void) ResetMagickMemory(pixel_list,0,number_threads*sizeof(*pixel_list)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_list[i]=AcquirePixelList(width,height); if (pixel_list[i] == (PixelList *) NULL) return(DestroyPixelListThreadSet(pixel_list)); } return(pixel_list); } static void AddNodePixelList(PixelList *pixel_list,const size_t color) { register SkipList *p; register ssize_t level; size_t search, update[9]; /* Initialize the node. */ p=(&pixel_list->skip_list); p->nodes[color].signature=pixel_list->signature; p->nodes[color].count=1; /* Determine where it belongs in the list. */ search=65536UL; for (level=p->level; level >= 0; level--) { while (p->nodes[search].next[level] < color) search=p->nodes[search].next[level]; update[level]=search; } /* Generate a pseudo-random level for this node. */ for (level=0; ; level++) { pixel_list->seed=(pixel_list->seed*42893621L)+1L; if ((pixel_list->seed & 0x300) != 0x300) break; } if (level > 8) level=8; if (level > (p->level+2)) level=p->level+2; /* If we're raising the list's level, link back to the root node. */ while (level > p->level) { p->level++; update[p->level]=65536UL; } /* Link the node into the skip-list. */ do { p->nodes[color].next[level]=p->nodes[update[level]].next[level]; p->nodes[update[level]].next[level]=color; } while (level-- > 0); } static inline void GetMaximumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, maximum; ssize_t count; /* Find the maximum value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; maximum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color > maximum) maximum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) maximum); } static inline void GetMeanPixelList(PixelList *pixel_list,Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the mean value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sum); } static inline void GetMedianPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color; ssize_t count; /* Find the median value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; do { color=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetMinimumPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, minimum; ssize_t count; /* Find the minimum value for each of the color. */ p=(&pixel_list->skip_list); count=0; color=65536UL; minimum=p->nodes[color].next[0]; do { color=p->nodes[color].next[0]; if (color < minimum) minimum=color; count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) minimum); } static inline void GetModePixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, max_count, mode; ssize_t count; /* Make each pixel the 'predominant color' of the specified neighborhood. */ p=(&pixel_list->skip_list); color=65536L; mode=color; max_count=p->nodes[mode].count; count=0; do { color=p->nodes[color].next[0]; if (p->nodes[color].count > max_count) { mode=color; max_count=p->nodes[mode].count; } count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); *pixel=ScaleShortToQuantum((unsigned short) mode); } static inline void GetNonpeakPixelList(PixelList *pixel_list,Quantum *pixel) { register SkipList *p; size_t color, next, previous; ssize_t count; /* Finds the non peak value for each of the colors. */ p=(&pixel_list->skip_list); color=65536L; next=p->nodes[color].next[0]; count=0; do { previous=color; color=next; next=p->nodes[color].next[0]; count+=p->nodes[color].count; } while (count <= (ssize_t) (pixel_list->length >> 1)); if ((previous == 65536UL) && (next != 65536UL)) color=next; else if ((previous != 65536UL) && (next == 65536UL)) color=previous; *pixel=ScaleShortToQuantum((unsigned short) color); } static inline void GetRootMeanSquarePixelList(PixelList *pixel_list, Quantum *pixel) { double sum; register SkipList *p; size_t color; ssize_t count; /* Find the root mean square value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; do { color=p->nodes[color].next[0]; sum+=(double) (p->nodes[color].count*color*color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum)); } static inline void GetStandardDeviationPixelList(PixelList *pixel_list, Quantum *pixel) { double sum, sum_squared; register SkipList *p; size_t color; ssize_t count; /* Find the standard-deviation value for each of the color. */ p=(&pixel_list->skip_list); color=65536L; count=0; sum=0.0; sum_squared=0.0; do { register ssize_t i; color=p->nodes[color].next[0]; sum+=(double) p->nodes[color].count*color; for (i=0; i < (ssize_t) p->nodes[color].count; i++) sum_squared+=((double) color)*((double) color); count+=p->nodes[color].count; } while (count < (ssize_t) pixel_list->length); sum/=pixel_list->length; sum_squared/=pixel_list->length; *pixel=ScaleShortToQuantum((unsigned short) sqrt(sum_squared-(sum*sum))); } static inline void InsertPixelList(const Quantum pixel,PixelList *pixel_list) { size_t signature; unsigned short index; index=ScaleQuantumToShort(pixel); signature=pixel_list->skip_list.nodes[index].signature; if (signature == pixel_list->signature) { pixel_list->skip_list.nodes[index].count++; return; } AddNodePixelList(pixel_list,index); } static void ResetPixelList(PixelList *pixel_list) { int level; register SkipNode *root; register SkipList *p; /* Reset the skip-list. */ p=(&pixel_list->skip_list); root=p->nodes+65536UL; p->level=0; for (level=0; level < 9; level++) root->next[level]=65536UL; pixel_list->seed=pixel_list->signature++; } MagickExport Image *StatisticImage(const Image *image,const StatisticType type, const size_t width,const size_t height,ExceptionInfo *exception) { #define StatisticImageTag "Statistic/Image" CacheView *image_view, *statistic_view; Image *statistic_image; MagickBooleanType status; MagickOffsetType progress; PixelList **magick_restrict pixel_list; ssize_t center, y; /* Initialize statistics image attributes. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); statistic_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (statistic_image == (Image *) NULL) return((Image *) NULL); status=SetImageStorageClass(statistic_image,DirectClass,exception); if (status == MagickFalse) { statistic_image=DestroyImage(statistic_image); return((Image *) NULL); } pixel_list=AcquirePixelListThreadSet(MagickMax(width,1),MagickMax(height,1)); if (pixel_list == (PixelList **) NULL) { statistic_image=DestroyImage(statistic_image); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } /* Make each pixel the min / max / median / mode / etc. of the neighborhood. */ center=(ssize_t) GetPixelChannels(image)*(image->columns+MagickMax(width,1))* (MagickMax(height,1)/2L)+GetPixelChannels(image)*(MagickMax(width,1)/2L); status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); statistic_view=AcquireAuthenticCacheView(statistic_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,statistic_image,statistic_image->rows,1) #endif for (y=0; y < (ssize_t) statistic_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,-((ssize_t) MagickMax(width,1)/2L),y- (ssize_t) (MagickMax(height,1)/2L),image->columns+MagickMax(width,1), MagickMax(height,1),exception); q=QueueCacheViewAuthenticPixels(statistic_view,0,y,statistic_image->columns, 1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) statistic_image->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { Quantum pixel; register const Quantum *magick_restrict pixels; register ssize_t u; ssize_t v; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait statistic_traits=GetPixelChannelTraits(statistic_image, channel); if ((traits == UndefinedPixelTrait) || (statistic_traits == UndefinedPixelTrait)) continue; if (((statistic_traits & CopyPixelTrait) != 0) || (GetPixelWriteMask(image,p) <= (QuantumRange/2))) { SetPixelChannel(statistic_image,channel,p[center+i],q); continue; } if ((statistic_traits & UpdatePixelTrait) == 0) continue; pixels=p; ResetPixelList(pixel_list[id]); for (v=0; v < (ssize_t) MagickMax(height,1); v++) { for (u=0; u < (ssize_t) MagickMax(width,1); u++) { InsertPixelList(pixels[i],pixel_list[id]); pixels+=GetPixelChannels(image); } pixels+=GetPixelChannels(image)*image->columns; } switch (type) { case GradientStatistic: { double maximum, minimum; GetMinimumPixelList(pixel_list[id],&pixel); minimum=(double) pixel; GetMaximumPixelList(pixel_list[id],&pixel); maximum=(double) pixel; pixel=ClampToQuantum(MagickAbsoluteValue(maximum-minimum)); break; } case MaximumStatistic: { GetMaximumPixelList(pixel_list[id],&pixel); break; } case MeanStatistic: { GetMeanPixelList(pixel_list[id],&pixel); break; } case MedianStatistic: default: { GetMedianPixelList(pixel_list[id],&pixel); break; } case MinimumStatistic: { GetMinimumPixelList(pixel_list[id],&pixel); break; } case ModeStatistic: { GetModePixelList(pixel_list[id],&pixel); break; } case NonpeakStatistic: { GetNonpeakPixelList(pixel_list[id],&pixel); break; } case RootMeanSquareStatistic: { GetRootMeanSquarePixelList(pixel_list[id],&pixel); break; } case StandardDeviationStatistic: { GetStandardDeviationPixelList(pixel_list[id],&pixel); break; } } SetPixelChannel(statistic_image,channel,pixel,q); } p+=GetPixelChannels(image); q+=GetPixelChannels(statistic_image); } if (SyncCacheViewAuthenticPixels(statistic_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_StatisticImage) #endif proceed=SetImageProgress(image,StatisticImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } statistic_view=DestroyCacheView(statistic_view); image_view=DestroyCacheView(image_view); pixel_list=DestroyPixelListThreadSet(pixel_list); if (status == MagickFalse) statistic_image=DestroyImage(statistic_image); return(statistic_image); }
flush.c
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s // REQUIRES: ompt // GCC generates code that does not call the runtime for the flush construct // XFAIL: gcc #include "callback.h" #include <omp.h> int main() { #pragma omp parallel num_threads(2) { int tid = omp_get_thread_num(); #pragma omp flush print_current_address(1); } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_flush' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_flush: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: current_address=[[RETURN_ADDRESS]] // // CHECK: {{^}}[[THREAD_ID:[0-9]+]]: ompt_event_flush: codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]] // CHECK: {{^}}[[THREAD_ID:[0-9]+]]: current_address=[[RETURN_ADDRESS]] return 0; }
ten_tusscher_2004_epi_S2_11.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S2_11.h" GET_CELL_MODEL_DATA(init_cell_model_data) { assert(cell_model); if(get_initial_v) cell_model->initial_v = INITIAL_V; if(get_neq) cell_model->number_of_ode_equations = NEQ; } //TODO: this should be called only once for the whole mesh, like in the GPU code SET_ODE_INITIAL_CONDITIONS_CPU(set_model_initial_conditions_cpu) { // Default initial conditions /* sv[0] = INITIAL_V; // V; millivolt sv[1] = 0.f; //M sv[2] = 0.75; //H sv[3] = 0.75f; //J sv[4] = 0.f; //Xr1 sv[5] = 1.f; //Xr2 sv[6] = 0.f; //Xs sv[7] = 1.f; //S sv[8] = 0.f; //R sv[9] = 0.f; //D sv[10] = 1.f; //F sv[11] = 1.f; //FCa sv[12] = 1.f; //G sv[13] = 0.0002; //Cai sv[14] = 0.2f; //CaSR sv[15] = 11.6f; //Nai sv[16] = 138.3f; //Ki */ // Elnaz's steady-state initial conditions real sv_sst[]={-86.5878770431026,0.00128467644044377,0.780190776060102,0.780031768712007,0.000174269347293292,0.485294334096334,0.00293619530930145,0.999998354577283,1.92718333358183e-08,1.88612615371809e-05,0.999770487779485,1.00715530958520,0.999996174757918,4.37641258651731e-05,0.481810864796698,10.5215306150078,139.090426708925}; for (uint32_t i = 0; i < NEQ; i++) sv[i] = sv_sst[i]; } SOLVE_MODEL_ODES_CPU(solve_model_odes_cpu) { uint32_t sv_id; int i; #pragma omp parallel for private(sv_id) for (i = 0; i < num_cells_to_solve; i++) { if(cells_to_solve) sv_id = cells_to_solve[i]; else sv_id = i; for (int j = 0; j < num_steps; ++j) { solve_model_ode_cpu(dt, sv + (sv_id * NEQ), stim_currents[i]); } } } void solve_model_ode_cpu(real dt, real *sv, real stim_current) { assert(sv); real rY[NEQ], rDY[NEQ]; for(int i = 0; i < NEQ; i++) rY[i] = sv[i]; RHS_cpu(rY, rDY, stim_current, dt); for(int i = 0; i < NEQ; i++) sv[i] = rDY[i]; } void RHS_cpu(const real *sv, real *rDY_, real stim_current, real dt) { // State variables real svolt = sv[0]; real sm = sv[1]; real sh = sv[2]; real sj = sv[3]; real sxr1 = sv[4]; real sxr2 = sv[5]; real sxs = sv[6]; real ss = sv[7]; real sr = sv[8]; real sd = sv[9]; real sf = sv[10]; real sfca = sv[11]; real sg = sv[12]; real Cai = sv[13]; real CaSR = sv[14]; real Nai = sv[15]; real Ki = sv[16]; //External concentrations real Ko=5.4; real Cao=2.0; real Nao=140.0; //Intracellular volumes real Vc=0.016404; real Vsr=0.001094; //Calcium dynamics real Bufc=0.15f; real Kbufc=0.001f; real Bufsr=10.f; real Kbufsr=0.3f; real taufca=2.f; real taug=2.f; real Vmaxup=0.000425f; real Kup=0.00025f; //Constants const real R = 8314.472f; const real F = 96485.3415f; const real T =310.0f; real RTONF =(R*T)/F; //Cellular capacitance real CAPACITANCE=0.185; //Parameters for currents //Parameters for IKr real Gkr=0.096; //Parameters for Iks real pKNa=0.03; ///#ifdef EPI real Gks=0.245; ///#endif ///#ifdef ENDO /// real Gks=0.245; ///#endif ///#ifdef MCELL /// real Gks=0.062; ///#endif //Parameters for Ik1 real GK1=5.405; //Parameters for Ito //#ifdef EPI real Gto=0.294; //#endif // #ifdef ENDO // real Gto=0.073; //#endif //#ifdef MCELL // real Gto=0.294; ///#endif //Parameters for INa real GNa=14.838; //Parameters for IbNa real GbNa=0.00029; //Parameters for INaK real KmK=1.0; real KmNa=40.0; real knak=1.362; //Parameters for ICaL real GCaL=0.000175; //Parameters for IbCa real GbCa=0.000592; //Parameters for INaCa real knaca=1000; real KmNai=87.5; real KmCa=1.38; real ksat=0.1; real n=0.35; //Parameters for IpCa real GpCa=0.825; real KpCa=0.0005; //Parameters for IpK; real GpK=0.0146; real parameters []={14.4067656911232,0.000251423214660846,0.000138644400006808,0.000171348168255836,0.271363539920663,0.152533735596316,0.167802952974848,4.50982141647208,0.0182925907891570,1.32742805103830,1087.64330176885,0.000521118477931967,0.130358693810526,0.0198787620687159,0.00477679600041959,4.82656795411010e-05}; GNa=parameters[0]; GbNa=parameters[1]; GCaL=parameters[2]; GbCa=parameters[3]; Gto=parameters[4]; Gkr=parameters[5]; Gks=parameters[6]; GK1=parameters[7]; GpK=parameters[8]; knak=parameters[9]; knaca=parameters[10]; Vmaxup=parameters[11]; GpCa=parameters[12]; real arel=parameters[13]; real crel=parameters[14]; real Vleak=parameters[15]; real IKr; real IKs; real IK1; real Ito; real INa; real IbNa; real ICaL; real IbCa; real INaCa; real IpCa; real IpK; real INaK; real Irel; real Ileak; real dNai; real dKi; real dCai; real dCaSR; real A; // real BufferFactorc; // real BufferFactorsr; real SERCA; real Caisquare; real CaSRsquare; real CaCurrent; real CaSRCurrent; real fcaold; real gold; real Ek; real Ena; real Eks; real Eca; real CaCSQN; real bjsr; real cjsr; real CaBuf; real bc; real cc; real Ak1; real Bk1; real rec_iK1; real rec_ipK; real rec_iNaK; real AM; real BM; real AH_1; real BH_1; real AH_2; real BH_2; real AJ_1; real BJ_1; real AJ_2; real BJ_2; real M_INF; real H_INF; real J_INF; real TAU_M; real TAU_H; real TAU_J; real axr1; real bxr1; real axr2; real bxr2; real Xr1_INF; real Xr2_INF; real TAU_Xr1; real TAU_Xr2; real Axs; real Bxs; real Xs_INF; real TAU_Xs; real R_INF; real TAU_R; real S_INF; real TAU_S; real Ad; real Bd; real Cd; real TAU_D; real D_INF; real TAU_F; real F_INF; real FCa_INF; real G_INF; real inverseVcF2=1/(2*Vc*F); real inverseVcF=1./(Vc*F); real Kupsquare=Kup*Kup; // real BufcKbufc=Bufc*Kbufc; // real Kbufcsquare=Kbufc*Kbufc; // real Kbufc2=2*Kbufc; // real BufsrKbufsr=Bufsr*Kbufsr; // const real Kbufsrsquare=Kbufsr*Kbufsr; // const real Kbufsr2=2*Kbufsr; const real exptaufca=exp(-dt/taufca); const real exptaug=exp(-dt/taug); real sItot; //Needed to compute currents Ek=RTONF*(log((Ko/Ki))); Ena=RTONF*(log((Nao/Nai))); Eks=RTONF*(log((Ko+pKNa*Nao)/(Ki+pKNa*Nai))); Eca=0.5*RTONF*(log((Cao/Cai))); Ak1=0.1/(1.+exp(0.06*(svolt-Ek-200))); Bk1=(3.*exp(0.0002*(svolt-Ek+100))+ exp(0.1*(svolt-Ek-10)))/(1.+exp(-0.5*(svolt-Ek))); rec_iK1=Ak1/(Ak1+Bk1); rec_iNaK=(1./(1.+0.1245*exp(-0.1*svolt*F/(R*T))+0.0353*exp(-svolt*F/(R*T)))); rec_ipK=1./(1.+exp((25-svolt)/5.98)); //Compute currents INa=GNa*sm*sm*sm*sh*sj*(svolt-Ena); ICaL=GCaL*sd*sf*sfca*4*svolt*(F*F/(R*T))* (exp(2*svolt*F/(R*T))*Cai-0.341*Cao)/(exp(2*svolt*F/(R*T))-1.); Ito=Gto*sr*ss*(svolt-Ek); IKr=Gkr*sqrt(Ko/5.4)*sxr1*sxr2*(svolt-Ek); IKs=Gks*sxs*sxs*(svolt-Eks); IK1=GK1*rec_iK1*(svolt-Ek); INaCa=knaca*(1./(KmNai*KmNai*KmNai+Nao*Nao*Nao))*(1./(KmCa+Cao))* (1./(1+ksat*exp((n-1)*svolt*F/(R*T))))* (exp(n*svolt*F/(R*T))*Nai*Nai*Nai*Cao- exp((n-1)*svolt*F/(R*T))*Nao*Nao*Nao*Cai*2.5); INaK=knak*(Ko/(Ko+KmK))*(Nai/(Nai+KmNa))*rec_iNaK; IpCa=GpCa*Cai/(KpCa+Cai); IpK=GpK*rec_ipK*(svolt-Ek); IbNa=GbNa*(svolt-Ena); IbCa=GbCa*(svolt-Eca); //Determine total current (sItot) = IKr + IKs + IK1 + Ito + INa + IbNa + ICaL + IbCa + INaK + INaCa + IpCa + IpK + stim_current; //update concentrations Caisquare=Cai*Cai; CaSRsquare=CaSR*CaSR; CaCurrent=-(ICaL+IbCa+IpCa-2.0f*INaCa)*inverseVcF2*CAPACITANCE; ///A=0.016464f*CaSRsquare/(0.0625f+CaSRsquare)+0.008232f; A=arel*CaSRsquare/(0.0625f+CaSRsquare)+crel; Irel=A*sd*sg; ///Ileak=0.00008f*(CaSR-Cai); Ileak=Vleak*(CaSR-Cai); SERCA=Vmaxup/(1.f+(Kupsquare/Caisquare)); CaSRCurrent=SERCA-Irel-Ileak; CaCSQN=Bufsr*CaSR/(CaSR+Kbufsr); dCaSR=dt*(Vc/Vsr)*CaSRCurrent; bjsr=Bufsr-CaCSQN-dCaSR-CaSR+Kbufsr; cjsr=Kbufsr*(CaCSQN+dCaSR+CaSR); CaSR=(sqrt(bjsr*bjsr+4.*cjsr)-bjsr)/2.; CaBuf=Bufc*Cai/(Cai+Kbufc); dCai=dt*(CaCurrent-CaSRCurrent); bc=Bufc-CaBuf-dCai-Cai+Kbufc; cc=Kbufc*(CaBuf+dCai+Cai); Cai=(sqrt(bc*bc+4*cc)-bc)/2; dNai=-(INa+IbNa+3*INaK+3*INaCa)*inverseVcF*CAPACITANCE; Nai+=dt*dNai; dKi=-(stim_current+IK1+Ito+IKr+IKs-2*INaK+IpK)*inverseVcF*CAPACITANCE; Ki+=dt*dKi; //compute steady state values and time constants AM=1./(1.+exp((-60.-svolt)/5.)); BM=0.1/(1.+exp((svolt+35.)/5.))+0.10/(1.+exp((svolt-50.)/200.)); TAU_M=AM*BM; M_INF=1./((1.+exp((-56.86-svolt)/9.03))*(1.+exp((-56.86-svolt)/9.03))); if (svolt>=-40.) { AH_1=0.; BH_1=(0.77/(0.13*(1.+exp(-(svolt+10.66)/11.1)))); TAU_H= 1.0/(AH_1+BH_1); } else { AH_2=(0.057*exp(-(svolt+80.)/6.8)); BH_2=(2.7*exp(0.079*svolt)+(3.1e5)*exp(0.3485*svolt)); TAU_H=1.0/(AH_2+BH_2); } H_INF=1./((1.+exp((svolt+71.55)/7.43))*(1.+exp((svolt+71.55)/7.43))); if(svolt>=-40.) { AJ_1=0.; BJ_1=(0.6*exp((0.057)*svolt)/(1.+exp(-0.1*(svolt+32.)))); TAU_J= 1.0/(AJ_1+BJ_1); } else { AJ_2=(((-2.5428e4)*exp(0.2444*svolt)-(6.948e-6)* exp(-0.04391*svolt))*(svolt+37.78)/ (1.+exp(0.311*(svolt+79.23)))); BJ_2=(0.02424*exp(-0.01052*svolt)/(1.+exp(-0.1378*(svolt+40.14)))); TAU_J= 1.0/(AJ_2+BJ_2); } J_INF=H_INF; Xr1_INF=1./(1.+exp((-26.-svolt)/7.)); axr1=450./(1.+exp((-45.-svolt)/10.)); bxr1=6./(1.+exp((svolt-(-30.))/11.5)); TAU_Xr1=axr1*bxr1; Xr2_INF=1./(1.+exp((svolt-(-88.))/24.)); axr2=3./(1.+exp((-60.-svolt)/20.)); bxr2=1.12/(1.+exp((svolt-60.)/20.)); TAU_Xr2=axr2*bxr2; Xs_INF=1./(1.+exp((-5.-svolt)/14.)); Axs=1100./(sqrt(1.+exp((-10.-svolt)/6))); Bxs=1./(1.+exp((svolt-60.)/20.)); TAU_Xs=Axs*Bxs; #ifdef EPI R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif #ifdef ENDO R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+28)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=1000.*exp(-(svolt+67)*(svolt+67)/1000.)+8.; #endif #ifdef MCELL R_INF=1./(1.+exp((20-svolt)/6.)); S_INF=1./(1.+exp((svolt+20)/5.)); TAU_R=9.5*exp(-(svolt+40.)*(svolt+40.)/1800.)+0.8; TAU_S=85.*exp(-(svolt+45.)*(svolt+45.)/320.)+5./(1.+exp((svolt-20.)/5.))+3.; #endif D_INF=1./(1.+exp((-5-svolt)/7.5)); Ad=1.4/(1.+exp((-35-svolt)/13))+0.25; Bd=1.4/(1.+exp((svolt+5)/5)); Cd=1./(1.+exp((50-svolt)/20)); TAU_D=Ad*Bd+Cd; F_INF=1./(1.+exp((svolt+20)/7)); TAU_F=1125*exp(-(svolt+27)*(svolt+27)/240)+80+165/(1.+exp((25-svolt)/10)); FCa_INF=(1./(1.+pow((Cai/0.000325),8))+ 0.1/(1.+exp((Cai-0.0005)/0.0001))+ 0.20/(1.+exp((Cai-0.00075)/0.0008))+ 0.23 )/1.46; if(Cai<0.00035) G_INF=1./(1.+pow((Cai/0.00035),6)); else G_INF=1./(1.+pow((Cai/0.00035),16)); //Update gates rDY_[1] = M_INF-(M_INF-sm)*exp(-dt/TAU_M); rDY_[2] = H_INF-(H_INF-sh)*exp(-dt/TAU_H); rDY_[3] = J_INF-(J_INF-sj)*exp(-dt/TAU_J); rDY_[4] = Xr1_INF-(Xr1_INF-sxr1)*exp(-dt/TAU_Xr1); rDY_[5] = Xr2_INF-(Xr2_INF-sxr2)*exp(-dt/TAU_Xr2); rDY_[6] = Xs_INF-(Xs_INF-sxs)*exp(-dt/TAU_Xs); rDY_[7] = S_INF-(S_INF-ss)*exp(-dt/TAU_S); rDY_[8] = R_INF-(R_INF-sr)*exp(-dt/TAU_R); rDY_[9] = D_INF-(D_INF-sd)*exp(-dt/TAU_D); rDY_[10] = F_INF-(F_INF-sf)*exp(-dt/TAU_F); fcaold= sfca; sfca = FCa_INF-(FCa_INF-sfca)*exptaufca; if(sfca>fcaold && (svolt)>-37.0) sfca = fcaold; gold = sg; sg = G_INF-(G_INF-sg)*exptaug; if(sg>gold && (svolt)>-37.0) sg=gold; //update voltage rDY_[0] = svolt + dt*(-sItot); rDY_[11] = sfca; rDY_[12] = sg; rDY_[13] = Cai; rDY_[14] = CaSR; rDY_[15] = Nai; rDY_[16] = Ki; }
GB_unaryop__identity_int16_uint8.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__identity_int16_uint8 // op(A') function: GB_tran__identity_int16_uint8 // C type: int16_t // A type: uint8_t // cast: int16_t cij = (int16_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint8_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, x) \ int16_t z = (int16_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_IDENTITY || GxB_NO_INT16 || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int16_uint8 ( int16_t *restrict Cx, const uint8_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int16_uint8 ( 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
GB_binop__fmod_fp32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_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__fmod_fp32 // A.*B function (eWiseMult): GB_AemultB__fmod_fp32 // A*D function (colscale): (none) // D*A function (rowscale): (node) // C+=B function (dense accum): GB_Cdense_accumB__fmod_fp32 // C+=b function (dense accum): GB_Cdense_accumb__fmod_fp32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__fmod_fp32 // C=scalar+B GB_bind1st__fmod_fp32 // C=scalar+B' GB_bind1st_tran__fmod_fp32 // C=A+scalar GB_bind2nd__fmod_fp32 // C=A'+scalar GB_bind2nd_tran__fmod_fp32 // C type: float // A type: float // B,b type: float // BinaryOp: cij = fmodf (aij, bij) #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, i, j) \ z = fmodf (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_FMOD || GxB_NO_FP32 || GxB_NO_FMOD_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__fmod_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__fmod_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__fmod_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 //------------------------------------------------------------------------------ #if 0 GrB_Info (none) ( 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 } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info (node) ( 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 } #endif //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__fmod_fp32 ( 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 *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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__fmod_fp32 ( 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 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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__fmod_fp32 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, 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++) { if (!GBB (Bb, p)) continue ; float bij = Bx [p] ; Cx [p] = fmodf (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__fmod_fp32 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, 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++) { if (!GBB (Ab, p)) continue ; float aij = Ax [p] ; Cx [p] = fmodf (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) \ { \ float aij = Ax [pA] ; \ Cx [pC] = fmodf (x, aij) ; \ } GrB_Info GB_bind1st_tran__fmod_fp32 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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 \ float #if GB_DISABLE return (GrB_NO_VALUE) ; #else float x = (*((const float *) x_input)) ; #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 typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ float aij = Ax [pA] ; \ Cx [pC] = fmodf (aij, y) ; \ } GrB_Info GB_bind2nd_tran__fmod_fp32 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
isogeometric_post_utility.h
// // Project Name: Kratos // Last Modified by: $Author: hbui $ // Date: $Date: 2013-10-12 $ // Revision: $Revision: 1.0 $ // // #if !defined(KRATOS_ISOGEOMETRIC_POST_UTILITY_H_INCLUDED ) #define KRATOS_ISOGEOMETRIC_POST_UTILITY_H_INCLUDED // System includes #include <string> #include <vector> #include <tuple> #include <iostream> // External includes #include <omp.h> #include "boost/progress.hpp" // Project includes #include "includes/define.h" #include "includes/model_part.h" #include "includes/node.h" #include "includes/element.h" #include "includes/properties.h" #include "utilities/openmp_utils.h" #include "custom_utilities/iga_define.h" #include "custom_utilities/isogeometric_utility.h" #define USE_TRIANGULATION_UTILS_FOR_TRIANGULATION #if defined(USE_TRIANGULATION_UTILS_FOR_TRIANGULATION) #include "custom_utilities/triangulation_utils.h" #elif defined(USE_CGAL_FOR_TRIANGULATION) && defined(ISOGEOMETRIC_APPLICATION_USE_CGAL) #include <CGAL/Exact_predicates_inexact_constructions_kernel.h> #include <CGAL/Exact_predicates_exact_constructions_kernel.h> #include <CGAL/Delaunay_triangulation_2.h> #include <CGAL/Triangulation_vertex_base_with_info_2.h> #endif namespace Kratos { ///@addtogroup IsogeometricApplication ///@{ ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** * Abstract class for all utility to export mesh from NURBS. Also to provide basic utility functions. */ class IsogeometricPostUtility : public IsogeometricUtility { public: ///@name Type Definitions ///@{ typedef typename ModelPart::NodesContainerType NodesArrayType; typedef typename ModelPart::ElementsContainerType ElementsArrayType; typedef typename ModelPart::ConditionsContainerType ConditionsArrayType; typedef typename Element::GeometryType GeometryType; typedef typename GeometryType::PointType NodeType; typedef typename NodeType::PointType PointType; typedef typename GeometryType::IntegrationPointsArrayType IntegrationPointsArrayType; typedef typename GeometryType::CoordinatesArrayType CoordinatesArrayType; typedef typename NodeType::DofsContainerType DofsContainerType; typedef std::size_t IndexType; /// Pointer definition of IsogeometricPostUtility KRATOS_CLASS_POINTER_DEFINITION(IsogeometricPostUtility); ///@} ///@name Life Cycle ///@{ /// Default constructor. IsogeometricPostUtility() { } /// Destructor. virtual ~IsogeometricPostUtility() { } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ /// Create a node for a model_part with a specific Id and transfer the values template<class TPatchType, typename TCoordinatesType, typename TIndexType> static typename NodeType::Pointer CreateNodeAndTransferValues(const TCoordinatesType& p_ref, const TPatchType& rPatch, ModelPart& r_model_part, const TIndexType& NodeCounter) { typename NodeType::Pointer pNewNode = CreateNode(p_ref, rPatch, r_model_part, NodeCounter); TransferValuesToNodes(*pNewNode, p_ref, rPatch); return pNewNode; } /// Create a node for a model_part with a specific Id template<class TPatchType, typename TCoordinatesType, typename TIndexType> static typename NodeType::Pointer CreateNode(const TCoordinatesType& p_ref, const TPatchType& rPatch, ModelPart& r_model_part, const TIndexType& NodeCounter) { typename TPatchType::ControlPointType p = rPatch.pControlPointGridFunction()->GetValue(p_ref); typename NodeType::Pointer pNewNode = r_model_part.CreateNewNode(NodeCounter, p.X(), p.Y(), p.Z()); return pNewNode; } /// Transfer the control values from patch to node /// The node has to be inside the patch template<class TPatchType> static void TransferValuesToNodes(NodeType& rNode, const TPatchType& rPatch) { typename TPatchType::Array1DGridFunctionType::ConstPointer pControlPointCoordinatesGridFunction = rPatch.pGetGridFunction(CONTROL_POINT_COORDINATES); typename TPatchType::Array1DGridFunctionType::DataType p_ref; pControlPointCoordinatesGridFunction->LocalCoordinates(rNode, p_ref); TransferValuesToNodes(rNode, p_ref, rPatch); } /// Transfer the control values from patch to node /// p_ref is the local coordinates of the node in patch template<class TPatchType, typename TCoordinatesType> static void TransferValuesToNodes(NodeType& rNode, const TCoordinatesType& p_ref, const TPatchType& rPatch) { typedef typename TPatchType::DoubleGridFunctionContainerType DoubleGridFunctionContainerType; typedef typename TPatchType::Array1DGridFunctionContainerType Array1DGridFunctionContainerType; typedef typename TPatchType::VectorGridFunctionContainerType VectorGridFunctionContainerType; // transfer the control values DoubleGridFunctionContainerType DoubleGridFunctions_ = rPatch.DoubleGridFunctions(); for (typename DoubleGridFunctionContainerType::const_iterator it_gf = DoubleGridFunctions_.begin(); it_gf != DoubleGridFunctions_.end(); ++it_gf) { typedef double DataType; typedef Variable<DataType> VariableType; const std::string& var_name = (*it_gf)->pControlGrid()->Name(); if (KratosComponents<VariableData>::Has(var_name)) { VariableType* pVariable = dynamic_cast<VariableType*>(&KratosComponents<VariableData>::Get(var_name)); DataType value = (*it_gf)->GetValue(p_ref); if (rNode.SolutionStepsDataHas(*pVariable)) rNode.GetSolutionStepValue(*pVariable) = value; } } Array1DGridFunctionContainerType Array1DGridFunctions_ = rPatch.Array1DGridFunctions(); for (typename Array1DGridFunctionContainerType::const_iterator it_gf = Array1DGridFunctions_.begin(); it_gf != Array1DGridFunctions_.end(); ++it_gf) { typedef array_1d<double, 3> DataType; typedef Variable<DataType> VariableType; const std::string& var_name = (*it_gf)->pControlGrid()->Name(); if (var_name == "CONTROL_POINT_COORDINATES") continue; if (KratosComponents<VariableData>::Has(var_name)) { VariableType* pVariable = dynamic_cast<VariableType*>(&KratosComponents<VariableData>::Get(var_name)); DataType value = (*it_gf)->GetValue(p_ref); if (rNode.SolutionStepsDataHas(*pVariable)) rNode.GetSolutionStepValue(*pVariable) = value; } } VectorGridFunctionContainerType VectorGridFunctions_ = rPatch.VectorGridFunctions(); for (typename VectorGridFunctionContainerType::const_iterator it_gf = VectorGridFunctions_.begin(); it_gf != VectorGridFunctions_.end(); ++it_gf) { typedef Vector DataType; typedef Variable<DataType> VariableType; const std::string& var_name = (*it_gf)->pControlGrid()->Name(); if (KratosComponents<VariableData>::Has(var_name)) { VariableType* pVariable = dynamic_cast<VariableType*>(&KratosComponents<VariableData>::Get(var_name)); DataType value = (*it_gf)->GetValue(p_ref); if (rNode.SolutionStepsDataHas(*pVariable)) rNode.GetSolutionStepValue(*pVariable) = value; } } } /// Transfer the control values from patch to Gauss points template<class TEntityType, typename TVariableType, class TPatchType> static void TransferValuesToGaussPoints(TEntityType& rElement, const TVariableType& rVariable, const TPatchType& rPatch, const ProcessInfo& rProcessInfo) { GeometryData::IntegrationMethod ThisIntegrationMethod = rElement.GetIntegrationMethod(); GeometryType& rGeometry = rElement.GetGeometry(); typename TPatchType::Array1DGridFunctionType::ConstPointer pControlPointCoordinatesGridFunction = rPatch.pGetGridFunction(CONTROL_POINT_COORDINATES); typename GridFunction<TPatchType::FESpaceType::Dim(), typename TVariableType::Type>::ConstPointer pGridFunc = rPatch.pGetGridFunction(rVariable); #ifdef ENABLE_BEZIER_GEOMETRY //initialize the geometry rGeometry.Initialize(ThisIntegrationMethod); #endif const IntegrationPointsArrayType& integration_points = rGeometry.IntegrationPoints(ThisIntegrationMethod); std::vector<typename TVariableType::Type> ValuesOnIntPoint(integration_points.size()); CoordinatesArrayType GlobalCoords; typename TPatchType::Array1DGridFunctionType::DataType p_ref; for (unsigned int PointNumber = 0; PointNumber < integration_points.size(); ++PointNumber) { rGeometry.GlobalCoordinates(GlobalCoords, integration_points[PointNumber]); typename TPatchType::Array1DGridFunctionType::ConstPointer pControlPointCoordinatesGridFunction = rPatch.pGetGridFunction(CONTROL_POINT_COORDINATES); pControlPointCoordinatesGridFunction->LocalCoordinates(GlobalCoords, p_ref); ValuesOnIntPoint[PointNumber] = pGridFunc->GetValue(p_ref); } #ifdef ENABLE_BEZIER_GEOMETRY // clean the geometry rGeometry.Clean(); #endif rElement.SetValueOnIntegrationPoints( rVariable, ValuesOnIntPoint, rProcessInfo); } /// Generate corner points for regular geometry template<int TDim, typename TCoordinatesType, typename TValueType> static void GenerateRegular(std::vector<TCoordinatesType>& points, const std::vector<TCoordinatesType>& cmin, const std::vector<TCoordinatesType>& cmax) { if (TDim == 2) { GenerateRectangle(points, cmin[0], cmax[0], cmin[1], cmax[1]); } else if (TDim == 3) { GenerateBox(points, cmin[0], cmax[0], cmin[1], cmax[1], cmin[2], cmax[2]); } else KRATOS_THROW_ERROR(std::logic_error, "Invalid dimension", TDim) } /// Generate a single rectangle. The 4 corner points are denoted as /// 4---3 /// | | /// 1---2 template<typename TCoordinatesType, typename TValueType> static void GenerateRectangle(std::vector<TCoordinatesType>& points, const TValueType& xmin, const TValueType& xmax, const TValueType& ymin, const TValueType& ymax) { points[0][0] = xmin; points[0][1] = ymin; // points[0][2] = 0.0; points[1][0] = xmax; points[1][1] = ymin; // points[1][2] = 0.0; points[2][0] = xmax; points[2][1] = ymax; // points[2][2] = 0.0; points[3][0] = xmin; points[3][1] = ymax; // points[3][2] = 0.0; } /// Generate the triangulation for a list of points in 3D /// The triangulation will be performed on the physical points with the information {cemter, normal, t1, t2} template<typename TCoordinatesType, typename TVectorType, typename TIndexType> static std::vector<std::vector<TIndexType> > GenerateTriangleGrid(const std::vector<TCoordinatesType>& points, const TVectorType& rCenter, const TVectorType& rNormal, const TVectorType& rTangent1, const TVectorType& rTangent2) { // create the 2D coordinates for points, in order to triangulate std::vector<double> XY; TCoordinatesType Projection; for (std::size_t i = 0; i < points.size(); ++i) { noalias(Projection) = points[i] - inner_prod(points[i] - rCenter, rNormal) * rNormal; XY.push_back(inner_prod(Projection - rCenter, rTangent1)); XY.push_back(inner_prod(Projection - rCenter, rTangent2)); } // std::cout << "XY:" << std::endl; // for (std::size_t i = 0; i < XY.size()/2; ++i) // std::cout << " " << XY[2*i] << " " << XY[2*i+1] << std::endl; // compute the triangulation typedef std::vector<std::vector<TIndexType> > connectivity_t; connectivity_t Connectivities; #if defined(USE_CGAL_FOR_TRIANGULATION) typedef CGAL::Exact_predicates_inexact_constructions_kernel Kernel; typedef CGAL::Triangulation_vertex_base_with_info_2<unsigned int, Kernel> Vb; typedef CGAL::Triangulation_data_structure_2<Vb> Tds; typedef CGAL::Delaunay_triangulation_2<Kernel, Tds> Delaunay; typedef Kernel::Point_2 Point2; std::vector< std::pair<Point2, unsigned int> > clipped_points; for(std::size_t i = 0; i < XY.size() / 2; ++i) { clipped_points.push_back( std::make_pair( Point2(XY[2*i], XY[2*i+1]), i ) ); } Delaunay triangulation; triangulation.insert(clipped_points.begin(), clipped_points.end()); for(Delaunay::Finite_faces_iterator fit = triangulation.finite_faces_begin(); fit != triangulation.finite_faces_end(); ++fit) { Delaunay::Face_handle face = fit; std::vector<unsigned int> con(3); con[0] = face->vertex(0)->info(); con[1] = face->vertex(1)->info(); con[2] = face->vertex(2)->info(); Connectivities.push_back(con); } #elif defined(USE_TRIANGULATION_UTILS_FOR_TRIANGULATION) TriangulationUtils tri_util; tri_util.ComputeDelaunayTriangulation(XY, Connectivities); #else // REMARK: a tool to perform triangulation is not defined. You must define it. KRATOS_THROW_ERROR(std::logic_error, "A triangulation method must be specialized", "") #endif return Connectivities; } /// Generate the triangulation for a list of points in 3D /// The triangulation will be performed on the physical points with the information {cemter, normal, t1, t2} /// The refinement is performed on the local points instead. template<typename TCoordinatesType, typename TVectorType, typename TIndexType> static std::pair<std::vector<TCoordinatesType>, std::vector<std::vector<TIndexType> > > GenerateTriangleGrid(const std::vector<TCoordinatesType>& physical_points, const TVectorType& rCenter, const TVectorType& rNormal, const TVectorType& rTangent1, const TVectorType& rTangent2, const std::vector<TCoordinatesType>& local_points, const TIndexType& offset, const std::size_t& nrefine) { // compute the triangulation typedef std::vector<std::vector<TIndexType> > connectivity_t; connectivity_t Connectivities = GenerateTriangleGrid<TCoordinatesType, TVectorType, TIndexType>(physical_points, rCenter, rNormal, rTangent1, rTangent2); // refine if needed std::vector<TCoordinatesType> new_points = local_points; for (std::size_t i = 0; i < nrefine; ++i) RefineTriangleGrid<TIndexType, TCoordinatesType>(new_points, Connectivities); // offset the connectivity for (std::size_t i = 0; i < Connectivities.size(); ++i) for (std::size_t j = 0; j < Connectivities[i].size(); ++j) Connectivities[i][j] += offset; return std::make_pair(new_points, Connectivities); } /// Generate the quadrilateral grid. The 4 corner points are denoted as /// 4---3 /// | | /// 1---2 template<typename TCoordinatesType, typename TIndexType> static std::pair<std::vector<TCoordinatesType>, std::vector<std::vector<TIndexType> > > GenerateQuadGrid(const TCoordinatesType& p1, const TCoordinatesType& p2, const TCoordinatesType& p3, const TCoordinatesType& p4, const TIndexType& starting_node_id, const std::size_t& num_div_1, const std::size_t& num_div_2) { TCoordinatesType p, pm, pn; std::vector<TCoordinatesType> points; std::vector<std::vector<TIndexType> > connectivities; double xi, eta; std::size_t i, j; for (i = 0; i <= num_div_1; ++i) { xi = ((double) i) / num_div_1; pm = p1 + xi*(p2 - p1); pn = p4 + xi*(p3 - p4); for (j = 0; j <= num_div_2; ++j) { eta = ((double) j) / num_div_2; p = pm + eta*(pn - pm); points.push_back(p); } } TIndexType n1, n2, n3, n4; for (i = 0; i < num_div_1; ++i) { for(j = 0; j < num_div_2; ++j) { n1 = starting_node_id + i * (num_div_2 + 1) + j; n2 = starting_node_id + i * (num_div_2 + 1) + j + 1; n3 = starting_node_id + (i + 1) * (num_div_2 + 1) + j; n4 = starting_node_id + (i + 1) * (num_div_2 + 1) + j + 1; connectivities.push_back(std::vector<std::size_t>{n1, n2, n4, n3}); } } return std::make_pair(points, connectivities); } /// Generate a single box. The 8 corner points are denoted as /// 4---3 8---7 /// | | --> | | /// 1---2 5---6 template<typename TCoordinatesType, typename TValueType> static void GenerateBox(std::vector<TCoordinatesType>& points, const TValueType& xmin, const TValueType& xmax, const TValueType& ymin, const TValueType& ymax, const TValueType& zmin, const TValueType& zmax) { points[0][0] = xmin; points[0][1] = ymin; points[0][2] = zmin; points[1][0] = xmax; points[1][1] = ymin; points[1][2] = zmin; points[2][0] = xmax; points[2][1] = ymax; points[2][2] = zmin; points[3][0] = xmin; points[3][1] = ymax; points[3][2] = zmin; points[4][0] = xmin; points[4][1] = ymin; points[4][2] = zmax; points[5][0] = xmax; points[5][1] = ymin; points[5][2] = zmax; points[6][0] = xmax; points[6][1] = ymax; points[6][2] = zmax; points[7][0] = xmin; points[7][1] = ymax; points[7][2] = zmax; } /// Generate the hexahedral grid. The 8 corner points are denoted as /// 4---3 8---7 /// | | --> | | /// 1---2 5---6 template<typename TCoordinatesType, typename TIndexType> static std::pair<std::vector<TCoordinatesType>, std::vector<std::vector<TIndexType> > > GenerateHexGrid(const TCoordinatesType& p1, const TCoordinatesType& p2, const TCoordinatesType& p3, const TCoordinatesType& p4, const TCoordinatesType& p5, const TCoordinatesType& p6, const TCoordinatesType& p7, const TCoordinatesType& p8, const TIndexType& starting_node_id, const std::size_t& num_div_1, const std::size_t& num_div_2, const std::size_t& num_div_3) { TCoordinatesType p, pm1, pn1, pm2, pn2, pq1, pq2; std::vector<TCoordinatesType> points; std::vector<std::vector<TIndexType> > connectivities; double xi, eta, zeta; std::size_t i, j, k; for (i = 0; i <= num_div_1; ++i) { xi = ((double) i) / num_div_1; pm1 = p1 + xi*(p2 - p1); pn1 = p4 + xi*(p3 - p4); pm2 = p5 + xi*(p6 - p5); pn2 = p8 + xi*(p7 - p8); for (j = 0; j <= num_div_2; ++j) { eta = ((double) j) / num_div_2; pq1 = pm1 + eta*(pn1 - pm1); pq2 = pm2 + eta*(pn2 - pm2); for (k = 0; k <= num_div_3; ++k) { zeta = ((double) k) / num_div_3; p = pq1 + zeta*(pq2-pq1); points.push_back(p); } } } // std::cout << "points:" << std::endl; // for (std::size_t i = 0; i < points.size(); ++i) // std::cout << " " << points[i] << std::endl; // std::cout << std::endl; TIndexType n1, n2, n3, n4, n5, n6, n7, n8; for (i = 0; i < num_div_1; ++i) { for (j = 0; j < num_div_2; ++j) { for (k = 0; k < num_div_3; ++k) { IndexType n1 = starting_node_id + (i * (num_div_2 + 1) + j) * (num_div_3 + 1) + k; IndexType n2 = starting_node_id + (i * (num_div_2 + 1) + j + 1) * (num_div_3 + 1) + k; IndexType n3 = starting_node_id + ((i + 1) * (num_div_2 + 1) + j) * (num_div_3 + 1) + k; IndexType n4 = starting_node_id + ((i + 1) * (num_div_2 + 1) + j + 1) * (num_div_3 + 1) + k; IndexType n5 = n1 + 1; IndexType n6 = n2 + 1; IndexType n7 = n3 + 1; IndexType n8 = n4 + 1; connectivities.push_back(std::vector<std::size_t>{n1, n2, n4, n3, n5, n6, n8, n7}); } } } // std::cout << "connectivities:" << std::endl; // for (std::size_t i = 0; i < connectivities.size(); ++i) // { // std::cout << " "; // for (std::size_t j = 0; j < connectivities[i].size(); ++j) // std::cout << " " << connectivities[i][j]; // std::cout << std::endl; // } // std::cout << std::endl; return std::make_pair(points, connectivities); } /// Refine a triangle grid by sub-divide a triangle into 4 sub-triangles. template<typename TIndexType = std::size_t, typename TCoordinatesType = std::vector<double>, typename TCoordinatesListType = std::vector<TCoordinatesType>, typename TConnectivityType = std::vector<TIndexType>, typename TConnectivityListType = std::vector<TConnectivityType> > static void RefineTriangleGrid(TCoordinatesListType& Points, TConnectivityListType& Connectivities) { std::size_t npoints = Points.size(); TIndexType last_id = static_cast<TIndexType>(npoints-1); // generate the new middle points typedef std::pair<TIndexType, TIndexType> key_t; std::map<key_t, TIndexType> map_corner_to_middle; key_t key1, key2; TIndexType n1, n2, n3; for (typename TConnectivityListType::iterator it = Connectivities.begin(); it != Connectivities.end(); ++it) { n1 = (*it)[0]; n2 = (*it)[1]; n3 = (*it)[2]; key1 = std::make_pair(n1, n2); key2 = std::make_pair(n2, n1); if (map_corner_to_middle.find(key1) == map_corner_to_middle.end()) { Points.push_back(0.5*(Points[n1] + Points[n2])); map_corner_to_middle[key1] = ++last_id; map_corner_to_middle[key2] = last_id; } key1 = std::make_pair(n2, n3); key2 = std::make_pair(n3, n2); if (map_corner_to_middle.find(key1) == map_corner_to_middle.end()) { Points.push_back(0.5*(Points[n2] + Points[n3])); map_corner_to_middle[key1] = ++last_id; map_corner_to_middle[key2] = last_id; } key1 = std::make_pair(n3, n1); key2 = std::make_pair(n1, n3); if (map_corner_to_middle.find(key1) == map_corner_to_middle.end()) { Points.push_back(0.5*(Points[n3] + Points[n1])); map_corner_to_middle[key1] = ++last_id; map_corner_to_middle[key2] = last_id; } } // generate new triangles TIndexType m1, m2, m3; TConnectivityListType Connectivities_old = Connectivities; Connectivities.clear(); for (typename TConnectivityListType::iterator it = Connectivities_old.begin(); it != Connectivities_old.end(); ++it) { n1 = (*it)[0]; n2 = (*it)[1]; n3 = (*it)[2]; m1 = map_corner_to_middle[std::make_pair(n1, n2)]; m2 = map_corner_to_middle[std::make_pair(n2, n3)]; m3 = map_corner_to_middle[std::make_pair(n3, n1)]; Connectivities.push_back(TConnectivityType{n1, m1, m3}); Connectivities.push_back(TConnectivityType{m1, n2, m2}); Connectivities.push_back(TConnectivityType{m1, m2, m3}); Connectivities.push_back(TConnectivityType{m2, n3, m3}); } } /// Find the entity of the same type in the list of entities template<class TEntityType, class TEntitiesContainerType> static TEntitiesContainerType FindEntities(TEntitiesContainerType& pEntities, TEntityType const& r_sample_entity) { TEntitiesContainerType pFoundEntities; for (typename TEntitiesContainerType::ptr_iterator it = pEntities.ptr_begin(); it != pEntities.ptr_end(); ++it) { if (typeid(*(*it)) == typeid(r_sample_entity)) if (typeid((*it)->GetGeometry()) == typeid(r_sample_entity.GetGeometry())) pFoundEntities.push_back(*it); } return pFoundEntities; } /// Create the entities based on the connectivities /// It is noted that the newly created entities are not added to the other model_part. User must do it manually. template<typename TConnectivityType, typename TEntityType, typename TEntitiesContainerType> static TEntitiesContainerType CreateEntities( const TConnectivityType& r_connectivities, ModelPart& r_model_part, TEntityType const& r_sample_entity, std::size_t& last_entity_id, Properties::Pointer pProperties, const std::string& NodeKey) { TEntitiesContainerType pNewEntities; typename TEntityType::NodesArrayType temp_entity_nodes; for (typename TConnectivityType::const_iterator it = r_connectivities.begin(); it != r_connectivities.end(); ++it) { temp_entity_nodes.clear(); for (typename TConnectivityType::value_type::const_iterator it2 = it->begin(); it2 != it->end(); ++it2) temp_entity_nodes.push_back(*(FindKey(r_model_part.Nodes(), *it2, NodeKey).base())); typename TEntityType::Pointer pNewEntity = r_sample_entity.Create(++last_entity_id, temp_entity_nodes, pProperties); pNewEntities.push_back(pNewEntity); } return pNewEntities; } /// Create a list of entities (element/condition) from a model_part to another model_part /// It is noted that the newly created entities are not added to the other model_part. User must do it manually. template<class TEntityType, class TEntitiesContainerType> static TEntitiesContainerType CreateEntities( TEntitiesContainerType& pEntities, ModelPart& r_other_model_part, TEntityType const& r_sample_entity, std::size_t& last_entity_id, Properties::Pointer pProperties, const bool& retain_prop_id = false) { // first collect all the nodes from the elements std::map<std::size_t, NodeType::Pointer> pNodes; for (typename TEntitiesContainerType::ptr_iterator it = pEntities.ptr_begin(); it != pEntities.ptr_end(); ++it) { for (std::size_t i = 0; i < (*it)->GetGeometry().size(); ++i) { pNodes[(*it)->GetGeometry()[i].Id()] = (*it)->GetGeometry().pGetPoint(i); } } // create the new nodes in the other model_part std::size_t last_node_id = GetLastNodeId(r_other_model_part); std::map<std::size_t, std::size_t> MapOldToNew; for (std::map<std::size_t, NodeType::Pointer>::iterator it = pNodes.begin(); it != pNodes.end(); ++it) { const PointType& rPoint = it->second->GetInitialPosition(); NodeType::Pointer pNewNode = r_other_model_part.CreateNewNode(++last_node_id, rPoint[0], rPoint[1], rPoint[2]); MapOldToNew[it->second->Id()] = last_node_id; } // create new elements in the other model_part const std::string NodeKey = std::string("Node"); typename TEntityType::NodesArrayType temp_entity_nodes; TEntitiesContainerType pNewEntities; for (typename TEntitiesContainerType::ptr_iterator it = pEntities.ptr_begin(); it != pEntities.ptr_end(); ++it) { temp_entity_nodes.clear(); for (std::size_t i = 0; i < (*it)->GetGeometry().size(); ++i) { std::size_t node_id = MapOldToNew[(*it)->GetGeometry()[i].Id()]; temp_entity_nodes.push_back(*(FindKey(r_other_model_part.Nodes(), node_id, NodeKey).base())); } if (!retain_prop_id) { pNewEntities.push_back(r_sample_entity.Create(++last_entity_id, temp_entity_nodes, pProperties)); } else { Properties::Pointer pNewProperties = r_other_model_part.pGetProperties((*it)->GetProperties().Id()); pNewEntities.push_back(r_sample_entity.Create(++last_entity_id, temp_entity_nodes, pNewProperties)); } } return pNewEntities; } // /// Create conditions/elements from the list of points. // /// The triangulation will be performed on the physical points with the information {cemter, normal, t1, t2} // /// The refinement is performed on the local points instead. // /// The point list will be triangulated before the conditions are created. // /// It is noted that the newly created entities are not added to the other model_part. User must do it manually. Nevertheless, the nodes are added to the model_part. // /// The new node will be created from last_node_id+1 // template<typename TPointType, typename TVectorType, class TEntityType, class TPointsContainerType, class TNodesContainerType, class TEntitiesContainerType> // static std::tuple<TPointsContainerType, TNodesContainerType, TEntitiesContainerType> CreateEntities( // const TPointsContainerType& physical_points, // const TVectorType& rCenter, // const TVectorType& rNormal, // const TVectorType& rTangent1, // const TVectorType& rTangent2, // const TPointsContainerType& local_points, // const std::size_t& nrefine, // ModelPart& r_model_part, // TEntityType const& r_sample_entity, // std::size_t& last_node_id, // std::size_t& last_entity_id, // Properties::Pointer pProperties) // { // // compute the triangulation // typedef unsigned int IndexType; // typedef std::vector<std::vector<IndexType> > connectivity_t; // connectivity_t Connectivities = GenerateTriangleGrid<TPointType, TVectorType, IndexType>(physical_points, rCenter, rNormal, rTangent1, rTangent2); // // refine if needed // TPointsContainerType new_points = local_points; // for (std::size_t i = 0; i < nrefine; ++i) // RefineTriangleGrid<unsigned int, TPointType>(new_points, Connectivities); // // offset the connectivity // for (std::size_t i = 0; i < Connectivities.size(); ++i) // for (std::size_t j = 0; j < Connectivities[i].size(); ++j) // Connectivities[i][j] += last_node_id+1; // // std::cout << "Connectivities:" << std::endl; // // for (std::size_t i = 0; i < Connectivities.size(); ++i) // // { // // std::cout << " " << i << ":"; // // for (std::size_t j = 0; j < Connectivities[i].size(); ++j) // // std::cout << " " << Connectivities[i][j]; // // std::cout << std::endl; // // } // // create the nodes // std::vector<std::size_t> map_con_to_mp(new_points.size()); // TNodesContainerType pNewNodes; // for (std::size_t i = 0; i < new_points.size(); ++i) // { // NodeType::Pointer pNewNode = r_model_part.CreateNewNode(++last_node_id, new_points[i][0], new_points[i][1], new_points[i][2]); // map_con_to_mp[i] = pNewNode->Id(); // pNewNodes.push_back(pNewNode); // } // // create the entities based on connectivity // const std::string NodeKey = std::string("Node"); // TEntitiesContainerType pNewEntities = CreateEntities<connectivity_t, TEntityType, TEntitiesContainerType>(Connectivities, r_model_part, // r_sample_entity, last_entity_id, pProperties, NodeKey); // return std::make_tuple(new_points, pNewNodes, pNewEntities); // } //**********AUXILIARY FUNCTION************************************************************** // Construct the matrix structure for high performance assembling // This subroutine shall only be used to construct the matrix structure for L2 projection // using in post-processing //****************************************************************************************** template<typename TElementType, typename TCompressedMatrixType, typename TElementsArrayType> static void ConstructL2MatrixStructure ( TCompressedMatrixType& A, TElementsArrayType& rElements, std::map<std::size_t, std::size_t> MapNodeIdToVec) { std::size_t equation_size = A.size1(); std::vector<std::vector<std::size_t> > indices(equation_size); typename TElementType::EquationIdVectorType ids; for(typename TElementsArrayType::iterator i_element = rElements.begin() ; i_element != rElements.end() ; ++i_element) { ids.resize((i_element)->GetGeometry().size()); for(unsigned int i = 0; i < (i_element)->GetGeometry().size(); ++i) ids[i] = MapNodeIdToVec[(i_element)->GetGeometry()[i].Id()]; for(std::size_t i = 0 ; i < ids.size() ; ++i) { if(ids[i] < equation_size) { std::vector<std::size_t>& row_indices = indices[ids[i]]; for(std::size_t j = 0 ; j < ids.size() ; ++j) { if(ids[j] < equation_size) AddUnique(row_indices, ids[j]); } } } } //allocating the memory needed int data_size = 0; for(std::size_t i = 0 ; i < indices.size() ; ++i) { data_size += indices[i].size(); } A.reserve(data_size, false); //filling with zero the matrix (creating the structure) #ifndef _OPENMP for(std::size_t i = 0 ; i < indices.size() ; ++i) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for(std::vector<std::size_t>::iterator it = row_indices.begin(); it != row_indices.end() ; ++it) { A.push_back(i, *it, 0.00); } row_indices.clear(); } #else int number_of_threads = omp_get_max_threads(); std::vector<unsigned int> matrix_partition; OpenMPUtils::CreatePartition(number_of_threads, indices.size(), matrix_partition); for( int k=0; k < number_of_threads; ++k ) { #pragma omp parallel if( omp_get_thread_num() == k ) { for( std::size_t i = matrix_partition[k]; i < matrix_partition[k+1]; i++ ) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for(std::vector<std::size_t>::iterator it = row_indices.begin(); it != row_indices.end() ; ++it) { A.push_back(i, *it, 0.00); } row_indices.clear(); } } } #endif } //**********AUXILIARY FUNCTION************************************************************** // Construct the matrix structure for high performance assembling // This subroutine shall only be used to construct the matrix structure for L2 projection // using in post-processing //****************************************************************************************** template<typename TElementType, typename TCompressedMatrixType, typename TElementsArrayType> static void ConstructL2MatrixStructure ( TCompressedMatrixType& A, TElementsArrayType& rElements) { std::size_t equation_size = A.size1(); std::vector<std::vector<std::size_t> > indices(equation_size); typename TElementType::EquationIdVectorType ids; for(typename TElementsArrayType::iterator i_element = rElements.begin() ; i_element != rElements.end() ; ++i_element) { ids.resize((i_element)->GetGeometry().size()); for(unsigned int i = 0; i < (i_element)->GetGeometry().size(); ++i) ids[i] = (i_element)->GetGeometry()[i].Id() - 1; for(std::size_t i = 0 ; i < ids.size() ; ++i) { if(ids[i] < equation_size) { std::vector<std::size_t>& row_indices = indices[ids[i]]; for(std::size_t j = 0 ; j < ids.size() ; ++j) { if(ids[j] < equation_size) AddUnique(row_indices, ids[j]); } } } } //allocating the memory needed int data_size = 0; for(std::size_t i = 0 ; i < indices.size() ; ++i) { data_size += indices[i].size(); } A.reserve(data_size, false); //filling with zero the matrix (creating the structure) #ifndef _OPENMP for(std::size_t i = 0 ; i < indices.size() ; i++) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for(std::vector<std::size_t>::iterator it= row_indices.begin(); it != row_indices.end() ; it++) { A.push_back(i, *it, 0.00); } row_indices.clear(); } #else int number_of_threads = omp_get_max_threads(); std::vector<unsigned int> matrix_partition; OpenMPUtils::CreatePartition(number_of_threads, indices.size(), matrix_partition); for( int k=0; k < number_of_threads; ++k ) { #pragma omp parallel if( omp_get_thread_num() == k ) { for( std::size_t i = matrix_partition[k]; i < matrix_partition[k+1]; i++ ) { std::vector<std::size_t>& row_indices = indices[i]; std::sort(row_indices.begin(), row_indices.end()); for(std::vector<std::size_t>::iterator it= row_indices.begin(); it != row_indices.end() ; it++) { A.push_back(i, *it, 0.00); } row_indices.clear(); } } } #endif } //**********AUXILIARY FUNCTION************************************************************** // Support function for ConstructMatrixStructure //****************************************************************************************** static inline void AddUnique(std::vector<std::size_t>& v, const std::size_t& candidate) { std::vector<std::size_t>::iterator i = v.begin(); std::vector<std::size_t>::iterator endit = v.end(); while ( i != endit && (*i) != candidate) { ++i; } if( i == endit ) { v.push_back(candidate); } } //**********AUXILIARY FUNCTION************************************************************** //****************************************************************************************** static inline double CoordinateScaling(const double& x, const int& Type) { if(Type == _NURBS_) { return x; } else if(Type == _BEZIER_) { return 2 * x - 1; } else return 0.0; } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const { std::stringstream buffer; buffer << "IsogeometricPostUtility"; return buffer.str(); } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const { rOStream << "IsogeometricPostUtility"; } /// Print object's data. virtual void PrintData(std::ostream& rOStream) const {} ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Un accessible methods ///@{ /// Assignment operator. IsogeometricPostUtility& operator=(IsogeometricPostUtility const& rOther) { return *this; } /// Copy constructor. IsogeometricPostUtility(IsogeometricPostUtility const& rOther) { } ///@} }; // Class IsogeometricPostUtility ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >>(std::istream& rIStream, IsogeometricPostUtility& rThis) { return rIStream; } /// output stream function inline std::ostream& operator <<(std::ostream& rOStream, const IsogeometricPostUtility& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} ///@} addtogroup block }// namespace Kratos. #endif // KRATOS_ISOGEOMETRIC_POST_UTILITY_H_INCLUDED
visualization.h
#pragma once #include <algorithm> #include <boost/archive/text_iarchive.hpp> #include <boost/serialization/vector.hpp> #include <fstream> #include <iostream> #include <iterator> #include <pcl/io/pcd_io.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/visualization/cloud_viewer.h> #include <vector> #include "omp.h" /** * Convert libfreenect data to Point Cloud Library format pcd */ template <typename PointT> class Freenect2Pcl { public: /** * Constructor of Freenect2Pcl object * @param[in] depthfile name of the depth file * @param[in] rgbfile name of the rgbfile */ Freenect2Pcl(std::string depthfile, std::string rgbfile) : _depthfile(depthfile), _rgbfile(rgbfile) { { std::ifstream ifs(_rgbfile); boost::archive::text_iarchive ia(ifs); ia &rgb; } { std::ifstream ifs(_depthfile); boost::archive::text_iarchive ia(ifs); ia &_depth; } } /** * Default Destructor */ ~Freenect2Pcl() {} /** * Template for point cloud conversion. Use this function to return a * pcd formatted point cloud. * @param[in] distance maximum distance to get from depth data * @param[in] colored boolean value to apply rgb data or not */ typename pcl::PointCloud<PointT>::Ptr getPointCloud(int distance, bool colored) { std::cerr << "Reading Point Cloud Data... "; int depth_width = 640; int depth_height = 480; // create the empty Pointcloud boost::shared_ptr<pcl::PointCloud<PointT>> cloud( new pcl::PointCloud<PointT>); // allow infinite values for points coordinates cloud->is_dense = false; // set camera parameters for kinect double focal_x_depth = 585.187492217609; // 5.9421434211923247e+02; double focal_y_depth = 585.308616340665; // 5.9104053696870778e+02; double center_x_depth = 322.714077555293; // 3.3930780975300314e+02; double center_y_depth = 248.626108676666; // 2.4273913761751615e+02; float bad_point = std::numeric_limits<float>::quiet_NaN(); #pragma omp parallel for for (unsigned int y = 0; y < depth_height; ++y) for (unsigned int x = 0; x < depth_width; ++x) { PointT ptout; uint16_t dz = _depth[y * depth_width + x]; if (abs(dz) < distance) { Eigen::Vector3d ptd((x - center_x_depth) * dz / focal_x_depth, (y - center_y_depth) * dz / focal_y_depth, dz); // assign output xyz ptout.x = ptd.x() * 0.001f; ptout.y = ptd.y() * 0.001f; ptout.z = ptd.z() * 0.001f; if (colored) { uint8_t r = rgb[(y * depth_width + x) * 3]; uint8_t g = rgb[(y * depth_width + x) * 3 + 1]; uint8_t b = rgb[(y * depth_width + x) * 3 + 2]; ptout.rgba = pcl::PointXYZRGB(r, g, b).rgba; // assign color } else ptout.rgba = pcl::PointXYZRGB(0, 0, 0).rgba; #pragma omp critical cloud->points.push_back(ptout); // assigns point to cloud } } cloud->height = 480; cloud->width = 640; std::cerr << "DONE!" << std::endl; return (cloud); } private: std::string _depthfile; std::string _rgbfile; std::vector<uint16_t> _depth; std::vector<uint8_t> rgb; };
PeptideIndexing.h
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2020. // // This software is released under a three-clause BSD license: // * 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 any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Chris Bielow $ // $Authors: Andreas Bertsch, Chris Bielow $ // -------------------------------------------------------------------------- #pragma once #include <OpenMS/ANALYSIS/ID/AhoCorasickAmbiguous.h> #include <OpenMS/CHEMISTRY/ProteaseDigestion.h> #include <OpenMS/CHEMISTRY/ProteaseDB.h> #include <OpenMS/CONCEPT/LogStream.h> #include <OpenMS/CONCEPT/ProgressLogger.h> #include <OpenMS/DATASTRUCTURES/DefaultParamHandler.h> #include <OpenMS/DATASTRUCTURES/FASTAContainer.h> #include <OpenMS/DATASTRUCTURES/ListUtils.h> #include <OpenMS/DATASTRUCTURES/StringUtils.h> #include <OpenMS/DATASTRUCTURES/SeqanIncludeWrapper.h> #include <OpenMS/FORMAT/FASTAFile.h> #include <OpenMS/KERNEL/StandardTypes.h> #include <OpenMS/METADATA/PeptideEvidence.h> #include <OpenMS/METADATA/PeptideIdentification.h> #include <OpenMS/METADATA/ProteinIdentification.h> #include <OpenMS/SYSTEM/StopWatch.h> #include <OpenMS/SYSTEM/SysInfo.h> #include <atomic> #include <algorithm> #include <fstream> namespace OpenMS { /** @brief Refreshes the protein references for all peptide hits in a vector of PeptideIdentifications and adds target/decoy information. All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy". For proteins the possible values are "target" and "decoy", depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string) as a suffix or prefix, respectively (see parameter @p prefix). For peptides, the possible values are "target", "decoy" and "target+decoy", depending on whether the peptide sequence is found only in target proteins, only in decoy proteins, or in both. The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool. (For FDR calculations, "target+decoy" peptide hits count as target hits.) @note Make sure that your protein names in the database contain a correctly formatted decoy string. This can be ensured by using @ref UTILS_DecoyDatabase. If the decoy identifier is not recognized successfully all proteins will be assumed to stem from the target-part of the query.<br> E.g., "sw|P33354_DECOY|YEHR_ECOLI Uncharacterized lipop..." is <b>invalid</b>, since the tool has no knowledge of how SwissProt entries are build up. A correct identifier could be "DECOY_sw|P33354|YEHR_ECOLI Uncharacterized li ..." or "sw|P33354|YEHR_ECOLI_DECOY Uncharacterized li", depending on whether you are using prefix or suffix annotation.<br> Some helpful target/decoy statistics will be reported when done. By default this tool will fail if an unmatched peptide occurs, i.e. if the database does not contain the corresponding protein. You can force it to return successfully in this case by setting @p '-unmatched_action' to accept or even remove those hits. Search engines (such as Mascot) will replace ambiguous amino acids ('B', 'J', 'Z' and 'X') in the protein database with unambiguous amino acids in the reported peptides, e.g. exchange 'X' with 'H'. This will cause such peptides to not be found by exactly matching their sequences to the protein database. However, we can recover these cases by using tolerant search for ambiguous amino acids in the protein sequence. This is done by default with up to four amino acids per peptide hit. If you only want exact matches, set @p aaa_max to zero (but expect that unmatched peptides might occur)! Leucine/Isoleucine: Further complications can arise due to the presence of the isobaric amino acids isoleucine ('I') and leucine ('L') in protein sequences. Since the two have the exact same chemical composition and mass, they generally cannot be distinguished by mass spectrometry. If a peptide containing 'I' was reported as a match for a spectrum, a peptide containing 'L' instead would be an equally good match (and vice versa). To account for this inherent ambiguity, setting the flag @p IL_equivalent causes 'I' and 'L' to be considered as indistinguishable.@n For example, if the sequence "PEPTIDE" (matching "Protein1") was identified as a search hit, but the database additionally contained "PEPTLDE" (matching "Protein2"), running PeptideIndexer with the @p IL_equivalent option would report both "Protein1" and "Protein2" as accessions for "PEPTIDE". (This is independent of ambiguous matching via @p aaa_max.) Additionally, setting this flag will convert all 'J's in any protein sequence to 'I'. This way, no tolerant search is required for 'J' (but is still possible for all the other ambiguous amino acids). If @p write_protein_sequences is requested and @p IL_equivalent is set as well, both the I/L-version and unmodified protein sequences need to be stored internally. This requires some extra memory, roughly equivalent to the size of the FASTA database file itself. Enzyme specificity: Once a peptide sequence is found in a protein sequence, this does <b>not</b> imply that the hit is valid! This is where enzyme specificity comes into play. By default, the enzyme and the specificity used during search is derived from metadata in the idXML files ('auto' setting). We make two exceptions to any specificity constraints: 1) for peptides starting at the second or third position of a protein are still considered N-terminally specific, since the residues can be cleaved off in vivo; X!Tandem reports these peptides. For example, the two peptides ABAR and LABAR would both match a protein starting with MLABAR. 2) adventitious cleavage at Asp|Pro (Aspartate/D | Proline/P) is allowed for all enzymes (as supported by X!Tandem), i.e. counts as a proper cleavage site (see http://www.thegpm.org/tandem/release.html). You can relax the requirements further by choosing <tt>semi-tryptic</tt> (only one of two "internal" termini must match requirements) or <tt>none</tt> (essentially allowing all hits, no matter their context). These settings should not be used (due to high risk of reporting false positives), unless the search engine was instructed to search peptides in the same way (but then the default 'auto' setting will do the correct thing). X!Tandem treats any occurence of 'X' as stop codon (and thus as cleavage site). The resulting peptide will be non- or semi-tryptic. Those hits will not be matched and need to be removed using @p '-unmatched_action' (do not use termini specificity to cheat around it! It adds more false hits!). The FASTA file should not contain duplicate protein accessions (since accessions are not validated) if a correct unique-matching annotation is important (target/decoy annotation is still correct). Threading: This tool support multiple threads (@p threads option) to speed up computation, at the cost of little extra memory. */ class OPENMS_DLLAPI PeptideIndexing : public DefaultParamHandler, public ProgressLogger { public: /// name of enzyme/specificity which signals that the enzyme/specificity should be taken from meta information static char const* const AUTO_MODE; /* = 'auto' */ /// Exit codes enum ExitCodes { EXECUTION_OK, DATABASE_EMPTY, PEPTIDE_IDS_EMPTY, ILLEGAL_PARAMETERS, UNEXPECTED_RESULT }; /// Action to take when peptide hits could not be matched enum class Unmatched { IS_ERROR, ///< throws an error (and returns no results) WARN, ///< skips annotation with target/decoy but returns with 'success' REMOVE, ///< removes unmatched hits entirely and returns with 'success' SIZE_OF_UNMATCHED }; static const std::array<std::string, (Size)Unmatched::SIZE_OF_UNMATCHED> names_of_unmatched; enum class MissingDecoy { IS_ERROR, WARN, SILENT, SIZE_OF_MISSING_DECOY }; static const std::array<std::string, (Size)MissingDecoy::SIZE_OF_MISSING_DECOY> names_of_missing_decoy; /// Default constructor PeptideIndexing(); /// Default destructor ~PeptideIndexing() override; /// forward for old interface and pyOpenMS; use run<T>() for more control inline ExitCodes run(std::vector<FASTAFile::FASTAEntry>& proteins, std::vector<ProteinIdentification>& prot_ids, std::vector<PeptideIdentification>& pep_ids) { FASTAContainer<TFI_Vector> protein_container(proteins); return run<TFI_Vector>(protein_container, prot_ids, pep_ids); } /** @brief Re-index peptide identifications honoring enzyme cutting rules, ambiguous amino acids and target/decoy hits. Template parameter 'T' can be either TFI_File or TFI_Vector. If the data is already available, use TFI_Vector and pass the vector. If the data is still in a FASTA file and its not needed afterwards for additional processing, use TFI_File and pass the filename. PeptideIndexer refreshes target/decoy information and mapping of peptides to proteins. The target/decoy information is crucial for the @ref TOPP_FalseDiscoveryRate tool. (For FDR calculations, "target+decoy" peptide hits count as target hits.) PeptideIndexer allows for ambiguous amino acids (B|J|Z|X) in the protein database, but not in the peptide sequences. For the latter only I/L can be treated as equivalent (see 'IL_equivalent' flag), but 'J' is not allowed. Enzyme cutting rules and partial specificity can be specified. Resulting protein hits appear in the order of the FASTA file, except for orphaned proteins, which will appear first with an empty target_decoy metavalue. Duplicate protein accessions & sequences will not raise a warning, but create multiple hits (PeptideIndexer scans over the FASTA file once for efficiency reasons, and thus might not see all accessions & sequences at once). All peptide and protein hits are annotated with target/decoy information, using the meta value "target_decoy". For proteins the possible values are "target" and "decoy", depending on whether the protein accession contains the decoy pattern (parameter @p decoy_string) as a suffix or prefix, respectively (see parameter @p prefix). Peptide hits are annotated with metavalue 'protein_references', and if matched to at least one protein also with metavalue 'target_decoy'. The possible values for 'target_decoy' are "target", "decoy" and "target+decoy", depending on whether the peptide sequence is found only in target proteins, only in decoy proteins, or in both. The metavalue is not present, if the peptide is unmatched. Runtime: PeptideIndexer is usually very fast (loading and storing the data takes the most time) and search speed can be further improved (linearly), but using more threads. Avoid allowing too many (>=4) ambiguous amino acids if your database contains long stretches of 'X' (exponential search space). @param proteins A list of proteins -- either read piecewise from a FASTA file or as existing vector of FASTAEntries. @param prot_ids Resulting protein identifications associated to pep_ids (will be re-written completely) @param pep_ids Peptide identifications which should be search within @p proteins and then linked to @p prot_ids @return Exit status codes. */ template<typename T> ExitCodes run(FASTAContainer<T>& proteins, std::vector<ProteinIdentification>& prot_ids, std::vector<PeptideIdentification>& pep_ids) { // no decoy string provided? try to deduce from data if (decoy_string_.empty()) { auto r = DecoyHelper::findDecoyString(proteins); proteins.reset(); if (!r.success) { r.is_prefix = true; r.name = "DECOY_"; OPENMS_LOG_WARN << "Unable to determine decoy string automatically (not enough decoys were detected)! Using default " << (r.is_prefix ? "prefix" : "suffix") << " decoy string '" << r.name << "'\n" << "If you think that this is incorrect, please provide a decoy_string and its position manually!" << std::endl; } prefix_ = r.is_prefix; decoy_string_ = r.name; // decoy string and position was extracted successfully OPENMS_LOG_INFO << "Using " << (prefix_ ? "prefix" : "suffix") << " decoy string '" << decoy_string_ << "'" << std::endl; } //--------------------------------------------------------------- // parsing parameters, correcting xtandem and MSGFPlus parameters //--------------------------------------------------------------- ProteaseDigestion enzyme; if (!enzyme_name_.empty() && (enzyme_name_.compare(AUTO_MODE) != 0)) { // use param (not empty, not 'auto') enzyme.setEnzyme(enzyme_name_); } else if (!prot_ids.empty() && prot_ids[0].getSearchParameters().digestion_enzyme.getName() != "unknown_enzyme") { // take from meta (this assumes all runs used the same enzyme) OPENMS_LOG_INFO << "Info: using '" << prot_ids[0].getSearchParameters().digestion_enzyme.getName() << "' as enzyme (obtained from idXML) for digestion." << std::endl; enzyme.setEnzyme(&prot_ids[0].getSearchParameters().digestion_enzyme); } else { // fallback OPENMS_LOG_WARN << "Warning: Enzyme name neither given nor deduceable from input. Defaulting to Trypsin!" << std::endl; enzyme.setEnzyme("Trypsin"); } bool xtandem_fix_parameters = false; bool msgfplus_fix_parameters = false; // determine if at least one search engine was xtandem or MSGFPlus to enable special rules for (const auto& prot_id : prot_ids) { String search_engine = prot_id.getOriginalSearchEngineName(); StringUtils::toUpper(search_engine); OPENMS_LOG_INFO << "Peptide identification engine: " << search_engine << std::endl; if (search_engine == "XTANDEM" || prot_id.getSearchParameters().metaValueExists("SE:XTandem")) { xtandem_fix_parameters = true; } if (search_engine == "MS-GF+" || search_engine == "MSGFPLUS" || prot_id.getSearchParameters().metaValueExists("SE:MS-GF+")) { msgfplus_fix_parameters = true; } } // including MSGFPlus -> Trypsin/P as enzyme if (msgfplus_fix_parameters && enzyme.getEnzymeName() == "Trypsin") { OPENMS_LOG_WARN << "MSGFPlus detected but enzyme cutting rules were set to Trypsin. Correcting to Trypsin/P to cope with special cutting rule in MSGFPlus." << std::endl; enzyme.setEnzyme("Trypsin/P"); } OPENMS_LOG_INFO << "Enzyme: " << enzyme.getEnzymeName() << std::endl; if (!enzyme_specificity_.empty() && (enzyme_specificity_.compare(AUTO_MODE) != 0)) { // use param (not empty and not 'auto') enzyme.setSpecificity(ProteaseDigestion::getSpecificityByName(enzyme_specificity_)); } else if (!prot_ids.empty() && prot_ids[0].getSearchParameters().enzyme_term_specificity != ProteaseDigestion::SPEC_UNKNOWN) { // deduce from data ('auto') enzyme.setSpecificity(prot_ids[0].getSearchParameters().enzyme_term_specificity); OPENMS_LOG_INFO << "Info: using '" << EnzymaticDigestion::NamesOfSpecificity[prot_ids[0].getSearchParameters().enzyme_term_specificity] << "' as enzyme specificity (obtained from idXML) for digestion." << std::endl; } else { // fallback OPENMS_LOG_WARN << "Warning: Enzyme specificity neither given nor present in the input file. Defaulting to 'full'!" << std::endl; enzyme.setSpecificity(ProteaseDigestion::SPEC_FULL); } //------------------------------------------------------------- // calculations //------------------------------------------------------------- // cache the first proteins const size_t PROTEIN_CACHE_SIZE = 4e5; // 400k should be enough for most DB's and is not too hard on memory either (~200 MB FASTA) this->startProgress(0, 1, "Load first DB chunk"); proteins.cacheChunk(PROTEIN_CACHE_SIZE); this->endProgress(); if (proteins.empty()) // we do not allow an empty database { OPENMS_LOG_ERROR << "Error: An empty database was provided. Mapping makes no sense. Aborting..." << std::endl; return DATABASE_EMPTY; } if (pep_ids.empty()) // Aho-Corasick requires non-empty input; but we allow this case, since the TOPP tool should not crash when encountering a bad raw file (with no PSMs) { OPENMS_LOG_WARN << "Warning: An empty set of peptide identifications was provided. Output will be empty as well." << std::endl; if (!keep_unreferenced_proteins_) { // delete only protein hits, not whole ID runs incl. meta data: for (std::vector<ProteinIdentification>::iterator it = prot_ids.begin(); it != prot_ids.end(); ++it) { it->getHits().clear(); } } return PEPTIDE_IDS_EMPTY; } FoundProteinFunctor func(enzyme, xtandem_fix_parameters); // store the matches Map<String, Size> acc_to_prot; // map: accessions --> FASTA protein index std::vector<bool> protein_is_decoy; // protein index -> is decoy? std::vector<std::string> protein_accessions; // protein index -> accession bool invalid_protein_sequence = false; // check for proteins with modifications, i.e. '[' or '(', and throw an exception { // new scope - forget data after search /* BUILD Peptide DB */ bool has_illegal_AAs(false); AhoCorasickAmbiguous::PeptideDB pep_DB; for (std::vector<PeptideIdentification>::const_iterator it1 = pep_ids.begin(); it1 != pep_ids.end(); ++it1) { //String run_id = it1->getIdentifier(); const std::vector<PeptideHit>& hits = it1->getHits(); for (std::vector<PeptideHit>::const_iterator it2 = hits.begin(); it2 != hits.end(); ++it2) { // // Warning: // do not skip over peptides here, since the results are iterated in the same way // String seq = it2->getSequence().toUnmodifiedString().remove('*'); // make a copy, i.e. do NOT change the peptide sequence! if (seqan::isAmbiguous(seqan::AAString(seq.c_str()))) { // do not quit here, to show the user all sequences .. only quit after loop OPENMS_LOG_ERROR << "Peptide sequence '" << it2->getSequence() << "' contains one or more ambiguous amino acids (B|J|Z|X).\n"; has_illegal_AAs = true; } if (IL_equivalent_) // convert L to I; { seq.substitute('L', 'I'); } appendValue(pep_DB, seq.c_str()); } } if (has_illegal_AAs) { OPENMS_LOG_ERROR << "One or more peptides contained illegal amino acids. This is not allowed!" << "\nPlease either remove the peptide or replace it with one of the unambiguous ones (while allowing for ambiguous AA's to match the protein)." << std::endl;; } OPENMS_LOG_INFO << "Mapping " << length(pep_DB) << " peptides to " << (proteins.size() == PROTEIN_CACHE_SIZE ? "? (unknown number of)" : String(proteins.size())) << " proteins." << std::endl; if (length(pep_DB) == 0) { // Aho-Corasick will crash if given empty needles as input OPENMS_LOG_WARN << "Warning: Peptide identifications have no hits inside! Output will be empty as well." << std::endl; return PEPTIDE_IDS_EMPTY; } /* Aho Corasick (fast) */ OPENMS_LOG_INFO << "Searching with up to " << aaa_max_ << " ambiguous amino acid(s) and " << mm_max_ << " mismatch(es)!" << std::endl; SysInfo::MemUsage mu; OPENMS_LOG_INFO << "Building trie ..."; StopWatch s; s.start(); AhoCorasickAmbiguous::FuzzyACPattern pattern; AhoCorasickAmbiguous::initPattern(pep_DB, aaa_max_, mm_max_, pattern); s.stop(); OPENMS_LOG_INFO << " done (" << int(s.getClockTime()) << "s)" << std::endl; s.reset(); uint16_t count_j_proteins(0); bool has_active_data = true; // becomes false if end of FASTA file is reached const std::string jumpX(aaa_max_ + mm_max_ + 1, 'X'); // jump over stretches of 'X' which cost a lot of time; +1 because AXXA is a valid hit for aaa_max == 2 (cannot split it) // use very large target value for progress if DB size is unknown (did not fit into first chunk) this->startProgress(0, proteins.size() == PROTEIN_CACHE_SIZE ? std::numeric_limits<SignedSize>::max() : proteins.size(), "Aho-Corasick"); std::atomic<int> progress_prots(0); #ifdef _OPENMP #pragma omp parallel #endif { FoundProteinFunctor func_threads(enzyme, xtandem_fix_parameters); Map<String, Size> acc_to_prot_thread; // map: accessions --> FASTA protein index AhoCorasickAmbiguous fuzzyAC; String prot; while (true) { #pragma omp barrier // all threads need to be here, since we are about to swap protein data #pragma omp single { DEBUG_ONLY std::cerr << " activating cache ...\n"; has_active_data = proteins.activateCache(); // swap in last cache protein_accessions.resize(proteins.getChunkOffset() + proteins.chunkSize()); } // implicit barrier here if (!has_active_data) break; // leave while-loop SignedSize prot_count = (SignedSize)proteins.chunkSize(); #pragma omp master { DEBUG_ONLY std::cerr << "Filling Protein Cache ..."; proteins.cacheChunk(PROTEIN_CACHE_SIZE); protein_is_decoy.resize(proteins.getChunkOffset() + prot_count); for (SignedSize i = 0; i < prot_count; ++i) { // do this in master only, to avoid false sharing const String& seq = proteins.chunkAt(i).identifier; protein_is_decoy[i + proteins.getChunkOffset()] = (prefix_ ? seq.hasPrefix(decoy_string_) : seq.hasSuffix(decoy_string_)); } DEBUG_ONLY std::cerr << " done" << std::endl; } DEBUG_ONLY std::cerr << " starting for loop \n"; // search all peptides in each protein #pragma omp for schedule(dynamic, 100) nowait for (SignedSize i = 0; i < prot_count; ++i) { ++progress_prots; // atomic if (omp_get_thread_num() == 0) { this->setProgress(progress_prots); } prot = proteins.chunkAt(i).sequence; prot.remove('*'); // check for invalid sequences with modifications if (prot.has('[') || prot.has('(')) { invalid_protein_sequence = true; // not omp-critical because its write-only // we cannot throw an exception here, since we'd need to catch it within the parallel region } // convert L/J to I; also replace 'J' in proteins if (IL_equivalent_) { prot.substitute('L', 'I'); prot.substitute('J', 'I'); } else { // warn if 'J' is found (it eats into aaa_max) if (prot.has('J')) { #pragma omp atomic ++count_j_proteins; } } Size prot_idx = i + proteins.getChunkOffset(); // test if protein was a hit Size hits_total = func_threads.filter_passed + func_threads.filter_rejected; // check if there are stretches of 'X' if (prot.has('X')) { // create chunks of the protein (splitting it at stretches of 'X..X') and feed them to AC one by one size_t offset = -1, start = 0; while ((offset = prot.find(jumpX, offset + 1)) != std::string::npos) { //std::cout << "found X..X at " << offset << " in protein " << proteins[i].identifier << "\n"; addHits_(fuzzyAC, pattern, pep_DB, prot.substr(start, offset + jumpX.size() - start), prot, prot_idx, (int)start, func_threads); // skip ahead while we encounter more X... while (offset + jumpX.size() < prot.size() && prot[offset + jumpX.size()] == 'X') ++offset; start = offset; //std::cout << " new start: " << start << "\n"; } // last chunk if (start < prot.size()) { addHits_(fuzzyAC, pattern, pep_DB, prot.substr(start), prot, prot_idx, (int)start, func_threads); } } else { addHits_(fuzzyAC, pattern, pep_DB, prot, prot, prot_idx, 0, func_threads); } // was protein found? if (hits_total < func_threads.filter_passed + func_threads.filter_rejected) { protein_accessions[prot_idx] = proteins.chunkAt(i).identifier; acc_to_prot_thread[protein_accessions[prot_idx]] = prot_idx; } } // end parallel FOR // join results again DEBUG_ONLY std::cerr << " critical now \n"; #ifdef _OPENMP #pragma omp critical(PeptideIndexer_joinAC) #endif { s.start(); // hits func.merge(func_threads); // accession -> index acc_to_prot.insert(acc_to_prot_thread.begin(), acc_to_prot_thread.end()); acc_to_prot_thread.clear(); s.stop(); } // OMP end critical } // end readChunk } // OMP end parallel this->endProgress(); std::cout << "Merge took: " << s.toString() << "\n"; mu.after(); std::cout << mu.delta("Aho-Corasick") << "\n\n"; OPENMS_LOG_INFO << "\nAho-Corasick done:\n found " << func.filter_passed << " hits for " << func.pep_to_prot.size() << " of " << length(pep_DB) << " peptides.\n"; // write some stats OPENMS_LOG_INFO << "Peptide hits passing enzyme filter: " << func.filter_passed << "\n" << " ... rejected by enzyme filter: " << func.filter_rejected << std::endl; if (count_j_proteins) { OPENMS_LOG_WARN << "PeptideIndexer found " << count_j_proteins << " protein sequences in your database containing the amino acid 'J'." << "To match 'J' in a protein, an ambiguous amino acid placeholder for I/L will be used.\n" << "This costs runtime and eats into the 'aaa_max' limit, leaving less opportunity for B/Z/X matches.\n" << "If you want 'J' to be treated as unambiguous, enable '-IL_equivalent'!" << std::endl; } } // end local scope // // do mapping // // index existing proteins Map<String, Size> runid_to_runidx; // identifier to index for (Size run_idx = 0; run_idx < prot_ids.size(); ++run_idx) { runid_to_runidx[prot_ids[run_idx].getIdentifier()] = run_idx; } // for peptides --> proteins Size stats_matched_unique(0); Size stats_matched_multi(0); Size stats_unmatched(0); // no match to DB Size stats_count_m_t(0); // match to Target DB Size stats_count_m_d(0); // match to Decoy DB Size stats_count_m_td(0); // match to T+D DB Map<Size, std::set<Size> > runidx_to_protidx; // in which protID do appear which proteins (according to mapped peptides) Size pep_idx(0); for (std::vector<PeptideIdentification>::iterator it1 = pep_ids.begin(); it1 != pep_ids.end(); ++it1) { // which ProteinIdentification does the peptide belong to? Size run_idx = runid_to_runidx[it1->getIdentifier()]; std::vector<PeptideHit>& hits = it1->getHits(); for (std::vector<PeptideHit>::iterator it_hit = hits.begin(); it_hit != hits.end(); /* no increase here! we might need to skip it; see below */) { // clear protein accessions it_hit->setPeptideEvidences(std::vector<PeptideEvidence>()); // // is this a decoy hit? // bool matches_target(false); bool matches_decoy(false); std::set<Size> prot_indices; /// protein hits of this peptide // add new protein references for (std::set<PeptideProteinMatchInformation>::const_iterator it_i = func.pep_to_prot[pep_idx].begin(); it_i != func.pep_to_prot[pep_idx].end(); ++it_i) { prot_indices.insert(it_i->protein_index); const String& accession = protein_accessions[it_i->protein_index]; PeptideEvidence pe(accession, it_i->position, it_i->position + (int)it_hit->getSequence().size() - 1, it_i->AABefore, it_i->AAAfter); it_hit->addPeptideEvidence(pe); runidx_to_protidx[run_idx].insert(it_i->protein_index); // fill protein hits if (protein_is_decoy[it_i->protein_index]) { matches_decoy = true; } else { matches_target = true; } } ++pep_idx; // next hit if (matches_decoy && matches_target) { it_hit->setMetaValue("target_decoy", "target+decoy"); ++stats_count_m_td; } else if (matches_target) { it_hit->setMetaValue("target_decoy", "target"); ++stats_count_m_t; } else if (matches_decoy) { it_hit->setMetaValue("target_decoy", "decoy"); ++stats_count_m_d; } // else: could match to no protein (i.e. both are false) //else ... // not required (handled below; see stats_unmatched); if (prot_indices.size() == 1) { it_hit->setMetaValue("protein_references", "unique"); ++stats_matched_unique; } else if (prot_indices.size() > 1) { it_hit->setMetaValue("protein_references", "non-unique"); ++stats_matched_multi; } else { ++stats_unmatched; if (stats_unmatched < 15) OPENMS_LOG_INFO << "Unmatched peptide: " << it_hit->getSequence() << "\n"; else if (stats_unmatched == 15) OPENMS_LOG_INFO << "Unmatched peptide: ...\n"; if (unmatched_action_ == Unmatched::REMOVE) { it_hit = hits.erase(it_hit); continue; // already points to the next hit } else { it_hit->setMetaValue("protein_references", "unmatched"); } } ++it_hit; // next hit } // all hits } // next PepID Size total_peptides = stats_count_m_t + stats_count_m_d + stats_count_m_td + stats_unmatched; OPENMS_LOG_INFO << "-----------------------------------\n"; OPENMS_LOG_INFO << "Peptide statistics\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " unmatched : " << stats_unmatched << " (" << stats_unmatched * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " target/decoy:\n"; OPENMS_LOG_INFO << " match to target DB only: " << stats_count_m_t << " (" << stats_count_m_t * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " match to decoy DB only : " << stats_count_m_d << " (" << stats_count_m_d * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << " match to both : " << stats_count_m_td << " (" << stats_count_m_td * 100 / total_peptides << " %)\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " mapping to proteins:\n"; OPENMS_LOG_INFO << " no match (to 0 protein) : " << stats_unmatched << "\n"; OPENMS_LOG_INFO << " unique match (to 1 protein) : " << stats_matched_unique << "\n"; OPENMS_LOG_INFO << " non-unique match (to >1 protein): " << stats_matched_multi << std::endl; /// for proteins --> peptides Size stats_matched_proteins(0), stats_matched_new_proteins(0), stats_orphaned_proteins(0), stats_proteins_target(0), stats_proteins_decoy(0); // all peptides contain the correct protein hit references, now update the protein hits for (Size run_idx = 0; run_idx < prot_ids.size(); ++run_idx) { std::set<Size> masterset = runidx_to_protidx[run_idx]; // all protein matches from above std::vector<ProteinHit>& phits = prot_ids[run_idx].getHits(); { // go through existing protein hits and count orphaned proteins (with no peptide hits) std::vector<ProteinHit> orphaned_hits; for (std::vector<ProteinHit>::iterator p_hit = phits.begin(); p_hit != phits.end(); ++p_hit) { const String& acc = p_hit->getAccession(); if (!acc_to_prot.has(acc)) // acc_to_prot only contains found proteins from current run { // old hit is orphaned ++stats_orphaned_proteins; if (keep_unreferenced_proteins_) { p_hit->setMetaValue("target_decoy", ""); orphaned_hits.push_back(*p_hit); } } } // only keep orphaned hits (if any) phits = orphaned_hits; } // add new protein hits FASTAFile::FASTAEntry fe; phits.reserve(phits.size() + masterset.size()); for (std::set<Size>::const_iterator it = masterset.begin(); it != masterset.end(); ++it) { ProteinHit hit; hit.setAccession(protein_accessions[*it]); if (write_protein_sequence_ || write_protein_description_) { proteins.readAt(fe, *it); if (write_protein_sequence_) { hit.setSequence(fe.sequence); } // no else, since sequence is empty by default if (write_protein_description_) { hit.setDescription(fe.description); } // no else, since description is empty by default } if (protein_is_decoy[*it]) { hit.setMetaValue("target_decoy", "decoy"); ++stats_proteins_decoy; } else { hit.setMetaValue("target_decoy", "target"); ++stats_proteins_target; } phits.push_back(hit); ++stats_matched_new_proteins; } stats_matched_proteins += phits.size(); } OPENMS_LOG_INFO << "-----------------------------------\n"; OPENMS_LOG_INFO << "Protein statistics\n"; OPENMS_LOG_INFO << "\n"; OPENMS_LOG_INFO << " total proteins searched: " << proteins.size() << "\n"; OPENMS_LOG_INFO << " matched proteins : " << stats_matched_proteins << " (" << stats_matched_new_proteins << " new)\n"; if (stats_matched_proteins) { // prevent Division-by-0 Exception OPENMS_LOG_INFO << " matched target proteins: " << stats_proteins_target << " (" << stats_proteins_target * 100 / stats_matched_proteins << " %)\n"; OPENMS_LOG_INFO << " matched decoy proteins : " << stats_proteins_decoy << " (" << stats_proteins_decoy * 100 / stats_matched_proteins << " %)\n"; } OPENMS_LOG_INFO << " orphaned proteins : " << stats_orphaned_proteins << (keep_unreferenced_proteins_ ? " (all kept)" : " (all removed)\n"); OPENMS_LOG_INFO << "-----------------------------------" << std::endl; /// exit if no peptides were matched to decoy bool has_error = false; if (invalid_protein_sequence) { OPENMS_LOG_ERROR << "Error: One or more protein sequences contained the characters '[' or '(', which are illegal in protein sequences." << "\nPeptide hits might be masked by these characters (which usually indicate presence of modifications).\n"; has_error = true; } if ((stats_count_m_d + stats_count_m_td) == 0) { String msg("No peptides were matched to the decoy portion of the database! Did you provide the correct concatenated database? Are your 'decoy_string' (=" + decoy_string_ + ") and 'decoy_string_position' (=" + std::string(param_.getValue("decoy_string_position")) + ") settings correct?"); if (missing_decoy_action_ == MissingDecoy::IS_ERROR) { OPENMS_LOG_ERROR << "Error: " << msg << "\nSet 'missing_decoy_action' to 'warn' if you are sure this is ok!\nAborting ..." << std::endl; has_error = true; } else if (missing_decoy_action_ == MissingDecoy::WARN) { OPENMS_LOG_WARN << "Warn: " << msg << "\nSet 'missing_decoy_action' to 'error' if you want to elevate this to an error!" << std::endl; } else // silent { } } if (stats_unmatched > 0) { OPENMS_LOG_ERROR << "PeptideIndexer found unmatched peptides, which could not be associated to a protein.\n"; if (unmatched_action_ == Unmatched::IS_ERROR) { OPENMS_LOG_ERROR << "Potential solutions:\n" << " - check your FASTA database is identical to the search DB (or use 'auto')\n" << " - set 'enzyme:specificity' and 'enzyme:name' to 'auto' to match the parameters of the search engine\n" << " - increase 'aaa_max' to allow more ambiguous amino acids\n" << " - as a last resort: use the 'unmatched_action' option to accept or even remove unmatched peptides\n" << " (note that unmatched peptides cannot be used for FDR calculation or quantification)\n"; has_error = true; } else if (unmatched_action_ == Unmatched::WARN) { OPENMS_LOG_ERROR << " Warning: " << stats_unmatched << " unmatched hits have been found, but were not removed!\n" << "These are not annotated with target/decoy information and might lead to issues with downstream tools (such as FDR).\n" << "Switch to '" << names_of_unmatched[(Size)Unmatched::REMOVE] << "' if you want to avoid these problems.\n"; } else if (unmatched_action_ == Unmatched::REMOVE) { OPENMS_LOG_ERROR << " Warning: " << stats_unmatched <<" unmatched hits have been removed!\n" << "Make sure that these hits are actually a violation of the cutting rules by inspecting the database!\n"; if (xtandem_fix_parameters) OPENMS_LOG_ERROR << "Since the results are from X!Tandem, this is probably ok (check anyways).\n"; } else { throw Exception::NotImplemented(__FILE__, __LINE__, OPENMS_PRETTY_FUNCTION); } } if (has_error) { OPENMS_LOG_ERROR << "Result files will be written, but PeptideIndexer will exit with an error code." << std::endl; return UNEXPECTED_RESULT; } return EXECUTION_OK; } const String& getDecoyString() const; bool isPrefix() const; protected: struct PeptideProteinMatchInformation { OpenMS::Size protein_index; //< index of the protein the peptide is contained in OpenMS::Int position; //< the position of the peptide in the protein char AABefore; //< the amino acid after the peptide in the protein char AAAfter; //< the amino acid before the peptide in the protein const std::tuple<const Size&, const Int&, const char&, const char&> tie() const { return std::tie(protein_index, position, AABefore, AAAfter); } bool operator<(const PeptideProteinMatchInformation& other) const { return tie() < other.tie(); } bool operator==(const PeptideProteinMatchInformation& other) const { return tie() == other.tie(); } }; struct FoundProteinFunctor { public: typedef std::map<OpenMS::Size, std::set<PeptideProteinMatchInformation> > MapType; MapType pep_to_prot; //< peptide index --> protein indices OpenMS::Size filter_passed; //< number of accepted hits (passing addHit() constraints) OpenMS::Size filter_rejected; //< number of rejected hits (not passing addHit()) private: ProteaseDigestion enzyme_; bool xtandem_; //< are we checking xtandem cleavage rules? public: explicit FoundProteinFunctor(const ProteaseDigestion& enzyme, bool xtandem) : pep_to_prot(), filter_passed(0), filter_rejected(0), enzyme_(enzyme), xtandem_(xtandem) { } void merge(FoundProteinFunctor& other) { if (pep_to_prot.empty()) { // first merge is easy pep_to_prot.swap(other.pep_to_prot); } else { for (FoundProteinFunctor::MapType::const_iterator it = other.pep_to_prot.begin(); it != other.pep_to_prot.end(); ++it) { // augment set this->pep_to_prot[it->first].insert(other.pep_to_prot[it->first].begin(), other.pep_to_prot[it->first].end()); } other.pep_to_prot.clear(); } // cheap members this->filter_passed += other.filter_passed; other.filter_passed = 0; this->filter_rejected += other.filter_rejected; other.filter_rejected = 0; } void addHit(const OpenMS::Size idx_pep, const OpenMS::Size idx_prot, const OpenMS::Size len_pep, const OpenMS::String& seq_prot, OpenMS::Int position) { //TODO we could read and double-check missed cleavages as well if (enzyme_.isValidProduct(seq_prot, position, len_pep, true, true, xtandem_)) { PeptideProteinMatchInformation match { idx_prot, position, (position == 0) ? PeptideEvidence::N_TERMINAL_AA : seq_prot[position - 1], (position + len_pep >= seq_prot.size()) ? PeptideEvidence::C_TERMINAL_AA : seq_prot[position + len_pep] }; pep_to_prot[idx_pep].insert(match); ++filter_passed; } else { //std::cerr << "REJECTED Peptide " << seq_pep << " with hit to protein " // << seq_prot << " at position " << position << std::endl; ++filter_rejected; } } }; inline void addHits_(AhoCorasickAmbiguous& fuzzyAC, const AhoCorasickAmbiguous::FuzzyACPattern& pattern, const AhoCorasickAmbiguous::PeptideDB& pep_DB, const String& prot, const String& full_prot, SignedSize idx_prot, Int offset, FoundProteinFunctor& func_threads) const { fuzzyAC.setProtein(prot); while (fuzzyAC.findNext(pattern)) { const seqan::Peptide& tmp_pep = pep_DB[fuzzyAC.getHitDBIndex()]; func_threads.addHit(fuzzyAC.getHitDBIndex(), idx_prot, length(tmp_pep), full_prot, fuzzyAC.getHitProteinPosition() + offset); } } void updateMembers_() override; String decoy_string_{}; bool prefix_{ false }; MissingDecoy missing_decoy_action_ = MissingDecoy::IS_ERROR; String enzyme_name_{}; String enzyme_specificity_{}; bool write_protein_sequence_{ false }; bool write_protein_description_{ false }; bool keep_unreferenced_proteins_{ false }; Unmatched unmatched_action_ = Unmatched::IS_ERROR; bool IL_equivalent_{ false }; Int aaa_max_{0}; Int mm_max_{0}; }; }
for_reduction.c
#include <stdio.h> #include <math.h> #include "omp_testsuite.h" int check_for_reduction (FILE * logFile) { int sum = 0; int known_sum; double dsum = 0; double dknown_sum; double dt = 0.5; /* base of geometric row for + and - test */ double rounding_error = 1.E-9; #define DOUBLE_DIGITS 20 /* dt^DOUBLE_DIGITS */ int diff; double ddiff; int product = 1; int known_product; #define MAX_FACTOR 10 #define KNOWN_PRODUCT 3628800 /* 10! */ int logic_and = 1; int logic_or = 0; int bit_and = 1; int bit_or = 0; int exclusiv_bit_or = 0; int logics[LOOPCOUNT]; int i; double dpt; int result = 0; dt = 1. / 3.; known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(+:sum) for (i = 1; i <= LOOPCOUNT; i++) { sum = sum + i; } } if (known_sum != sum) { result++; fprintf (logFile, "Error in sum with integers: Result was %d instead of %d.\n", sum, known_sum); } diff = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(-:diff) for (i = 1; i <= LOOPCOUNT; ++i) { diff = diff - i; } } if (diff != 0) { result++; fprintf (logFile, "Error in difference with integers: Result was %d instead of 0.\n", diff); } /* Tests for doubles */ dsum = 0; dpt = 1; for (i = 0; i < DOUBLE_DIGITS; ++i) { dpt *= dt; } dknown_sum = (1 - dpt) / (1 - dt); #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(+:dsum) for (i = 0; i < DOUBLE_DIGITS; ++i) { dsum += pow (dt, i); } } if (dsum != dknown_sum && (fabs (dsum - dknown_sum) > rounding_error)) { result++; fprintf (logFile, "\nError in sum with doubles: Result was %f instead of: %f (Difference: %E)\n", dsum, dknown_sum, dsum - dknown_sum); } dpt = 1; for (i = 0; i < DOUBLE_DIGITS; ++i) { dpt *= dt; } ddiff = (1 - dpt) / (1 - dt); #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(-:ddiff) for (i = 0; i < DOUBLE_DIGITS; ++i) { ddiff -= pow (dt, i); } } if (fabs (ddiff) > rounding_error) { result++; fprintf (logFile, "Error in Difference with doubles: Result was %E instead of 0.0\n", ddiff); } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(*:product) for (i = 1; i <= MAX_FACTOR; i++) { product *= i; } } known_product = KNOWN_PRODUCT; if (known_product != product) { result++; fprintf (logFile, "Error in Product with integers: Result was %d instead of %d\n", product, known_product); } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 1; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(&&:logic_and) for (i = 0; i < LOOPCOUNT; ++i) { logic_and = (logic_and && logics[i]); } } if (!logic_and) { result++; fprintf (logFile, "Error in logic AND part 1\n"); } logic_and = 1; logics[LOOPCOUNT / 2] = 0; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(&&:logic_and) for (i = 0; i < LOOPCOUNT; ++i) { logic_and = logic_and && logics[i]; } } if (logic_and) { result++; fprintf (logFile, "Error in logic AND part 2\n"); } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(||:logic_or) for (i = 0; i < LOOPCOUNT; ++i) { logic_or = logic_or || logics[i]; } } if (logic_or) { result++; fprintf (logFile, "Error in logic OR part 1\n"); } logic_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(||:logic_or) for (i = 0; i < LOOPCOUNT; ++i) { logic_or = logic_or || logics[i]; } } if (!logic_or) { result++; fprintf (logFile, "Error in logic OR part 2\n"); } for (i = 0; i < LOOPCOUNT; ++i) { logics[i] = 1; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(&:bit_and) for (i = 0; i < LOOPCOUNT; ++i) { bit_and = (bit_and & logics[i]); } } if (!bit_and) { result++; fprintf (logFile, "Error in BIT AND part 1\n"); } bit_and = 1; logics[LOOPCOUNT / 2] = 0; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(&:bit_and) for (i = 0; i < LOOPCOUNT; ++i) { bit_and = bit_and & logics[i]; } } if (bit_and) { result++; fprintf (logFile, "Error in BIT AND part 2\n"); } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(|:bit_or) for (i = 0; i < LOOPCOUNT; ++i) { bit_or = bit_or | logics[i]; } } if (bit_or) { result++; fprintf (logFile, "Error in BIT OR part 1\n"); } bit_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(|:bit_or) for (i = 0; i < LOOPCOUNT; ++i) { bit_or = bit_or | logics[i]; } } if (!bit_or) { result++; fprintf (logFile, "Error in BIT OR part 2\n"); } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(^:exclusiv_bit_or) for (i = 0; i < LOOPCOUNT; ++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } } if (exclusiv_bit_or) { result++; fprintf (logFile, "Error in EXCLUSIV BIT OR part 1\n"); } exclusiv_bit_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) reduction(^:exclusiv_bit_or) for (i = 0; i < LOOPCOUNT; ++i) { exclusiv_bit_or = exclusiv_bit_or ^ logics[i]; } } if (!exclusiv_bit_or) { result++; fprintf (logFile, "Error in EXCLUSIV BIT OR part 2\n"); } /*fprintf("\nResult:%d\n",result); */ return (result == 0); } int crosscheck_for_reduction (FILE * logFile) { int sum = 0; int known_sum; double dsum = 0; double dknown_sum; double dt = 0.5; /* base of geometric row for + and - test */ double rounding_error = 1.E-9; #define DOUBLE_DIGITS 20 /* dt^DOUBLE_DIGITS */ int diff; double ddiff; int product = 1; int known_product; #define MAX_FACTOR 10 #define KNOWN_PRODUCT 3628800 /* 10! */ int logic_and = 1; int logic_or = 0; int bit_and = 1; int bit_or = 0; int exclusiv_bit_or = 0; int logics[LOOPCOUNT]; int i; double dpt; int result = 0; dt = 1. / 3.; known_sum = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 1; i <= LOOPCOUNT; i++) { sum = sum + i; } } if (known_sum != sum) { result++; /*printf("\nError in Sum with integers\n"); */ } diff = (LOOPCOUNT * (LOOPCOUNT + 1)) / 2; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 1; i <= LOOPCOUNT; ++i) { diff = diff - i; } } if (diff != 0) { result++; /*printf("\nError in Difference: Result was %d instead of 0.\n",diff); */ } /* Tests for doubles */ dsum = 0; dpt = 1; for (i = 0; i < DOUBLE_DIGITS; ++i) { dpt *= dt; } dknown_sum = (1 - dpt) / (1 - dt); #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < DOUBLE_DIGITS; ++i) { dsum += pow (dt, i); } } if (dsum != dknown_sum && (((dsum - dknown_sum) < rounding_error) || ((dsum - dknown_sum) > rounding_error))) { result++; /*printf("\nError in sum with doubles: Calculated: %f Expected: %f (Difference: %E)\n",dsum,dknown_sum, dsum-dknown_sum); */ } dpt = 1; for (i = 0; i < DOUBLE_DIGITS; ++i) { dpt *= dt; } ddiff = (1 - dpt) / (1 - dt); #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < DOUBLE_DIGITS; ++i) { ddiff -= pow (dt, i); } } if (ddiff > rounding_error || ddiff < (-rounding_error)) { result++; /*printf("\nError in Difference with doubles: Difference %E\n",ddiff); */ } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 1; i <= MAX_FACTOR; i++) { product *= i; } } known_product = KNOWN_PRODUCT; if (known_product != product) { result++; /*printf("\nError in Product: Known Product: %d\tcalculated Product: %d\n\n",known_product,product); */ } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 1; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { logic_and = (logic_and && logics[i]); } } if (!logic_and) { result++; /*printf("Error in AND part 1\n"); */ } logic_and = 1; logics[LOOPCOUNT / 2] = 0; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { logic_and = logic_and && logics[i]; } } if (logic_and) { result++; /*printf("Error in AND part 2"); */ } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { logic_or = logic_or || logics[i]; } } if (logic_or) { result++; /*printf("Error in OR part 1"); */ } logic_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { logic_or = logic_or || logics[i]; } } if (!logic_or) { result++; /*printf("Error in OR part 2"); */ } for (i = 0; i < LOOPCOUNT; ++i) { logics[i] = 1; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { bit_and = (bit_and & logics[i]); } } if (!bit_and) { result++; /*printf("Error in BIT AND part 1\n"); */ } bit_and = 1; logics[LOOPCOUNT / 2] = 0; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { bit_and = bit_and & logics[i]; } } if (bit_and) { result++; /*printf("Error in BIT AND part 2"); */ } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { bit_or = bit_or | logics[i]; } } if (bit_or) { result++; /*printf("Error in BIT OR part 1\n"); */ } bit_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { bit_or = bit_or | logics[i]; } } if (!bit_or) { result++; /*printf("Error in BIT OR part 2\n"); */ } for (i = 0; i < LOOPCOUNT; i++) { logics[i] = 0; } #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { exclusiv_bit_or = exclusiv_bit_or | logics[i]; } } if (exclusiv_bit_or) { result++; /*printf("Error in EXCLUSIV BIT OR part 1\n"); */ } exclusiv_bit_or = 0; logics[LOOPCOUNT / 2] = 1; #pragma omp parallel { #pragma omp for schedule(dynamic,1) for (i = 0; i < LOOPCOUNT; ++i) { exclusiv_bit_or = exclusiv_bit_or | logics[i]; } } if (!exclusiv_bit_or) { result++; /*printf("Error in EXCLUSIV BIT OR part 2\n"); */ } /*printf("\nResult:%d\n",result); */ return (result == 0); }
Secciones.c
#include <stdio.h> #include <stdlib.h> #ifdef _OPENMP #include <omp.h> #define TRUE 1 #define FALSE 0 #else #define omp_get_thread_num() 0 #endif void funcA(); void funcB(); int main() { #ifdef _OPENMP (void) omp_set_dynamic(FALSE); if (omp_get_dynamic()) {printf("Warning: dynamic adjustment of threads has been set\n");} (void) omp_set_num_threads(4); #endif #pragma omp parallel { #pragma omp sections { #pragma omp section (void) funcA(); #pragma omp section (void) funcB(); } // Final del bloque de secciones } // Final de la region paralela return(0); } void funcA() { printf("En funcA: esta seccion es ejecutada por el hilo %d\n", omp_get_thread_num()); } void funcB() { printf("En funcB: esta seccion es ejecutada por el hilo %d\n", omp_get_thread_num()); }
degeneracy_approx_set.h
#pragma once #include "../general.h" #include <cstdlib> #include <omp.h> #include <gms/third_party/fast_statistics.h> #include <gms/third_party/fast_range.h> #include "boundary_function.h" namespace PpParallel { template<BoundaryFunction boundary, bool useRankFormat = false, class SGraph = RoaringGraph, class Output = std::vector<NodeId>> void getDegeneracyOrderingApproxSGraph(const SGraph &graph, Output &res, const double epsilon = 0.001) { using Set = typename SGraph::Set; auto vSize = graph.num_nodes(); NodeId counter = 0; res.resize(vSize); //Prepare Result //Prepare Counter and Working Set std::vector<int> degreeCounter(vSize); NodeId *vArray = new NodeId[vSize]; #pragma omp parallel for schedule(static, 16) for (int i = 0; i < vSize; i++) { degreeCounter[i] = graph.out_neigh(i).cardinality(); vArray[i] = i; } NodeId *start_index = vArray; NodeId *end_index = vArray + vSize; while (counter < vSize) { auto remaining = end_index - start_index; unsigned int border = boundary(start_index, remaining, degreeCounter, epsilon); #ifdef _OPENMP auto middle_index = __gnu_parallel::partition(start_index, end_index, [border, &degreeCounter](const NodeId v) { return degreeCounter[v] <= border; }); #else auto middle_index = std::partition(start_index, end_index, [border, &degreeCounter](const NodeId v) { return degreeCounter[v] <= border; }); #endif auto mid = middle_index - start_index; #ifdef _OPENMP __gnu_parallel::sort(start_index, middle_index, [&degreeCounter](const NodeId v, const NodeId w) { return degreeCounter[v] < degreeCounter[w]; }); #else std::sort(start_index, middle_index, [&degreeCounter](const NodeId v, const NodeId w) { return degreeCounter[v] < degreeCounter[w]; }); #endif Set X(start_index, mid); #pragma omp parallel { //Add to result set #pragma omp for schedule(static, 16) nowait for (int i = 0; i < mid; i++) { if constexpr (useRankFormat) res[start_index[i]] = counter + i; //Result in Rank-Format else res[counter + i] = start_index[i]; //Result in Order-Format } //Reflect removing the vertices from the graph (PULL style) #pragma omp for schedule(static, 16) for (int i = mid; i < remaining; i++) { auto v = start_index[i]; degreeCounter[v] -= graph.out_neigh(v).intersect_count(X); } } start_index = middle_index; counter += mid; } delete[] vArray; } } // namespace PpParallel
par_relax.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Relaxation scheme * *****************************************************************************/ #include "_hypre_parcsr_ls.h" #include "Common.h" #include "_hypre_lapack.h" #include "par_relax.h" /*-------------------------------------------------------------------------- * hypre_BoomerAMGRelax *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGRelax( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_type, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { HYPRE_Int relax_error = 0; /*--------------------------------------------------------------------------------------- * Switch statement to direct control based on relax_type: * relax_type = 0 -> Jacobi or CF-Jacobi * relax_type = 1 -> Gauss-Seidel <--- very slow, sequential * relax_type = 2 -> Gauss_Seidel: interior points in parallel, * boundary sequential * relax_type = 3 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (forward solve) * relax_type = 4 -> hybrid: SOR-J mix off-processor, SOR on-processor * with outer relaxation parameters (backward solve) * relax_type = 5 -> hybrid: GS-J mix off-processor, chaotic GS on-node * relax_type = 6 -> hybrid: SSOR-J mix off-processor, SSOR on-processor * with outer relaxation parameters * relax_type = 7 -> Jacobi (uses Matvec), only needed in CGNR [GPU-supported] * relax_type = 8 -> hybrid L1 Symm. Gauss-Seidel * relax_type = 9 -> Direct solve, Gaussian elimination * relax_type = 10 -> On-processor direct forward solve for matrices with * triangular structure (indices need not be ordered * triangular) * relax_type = 11 -> Two Stage approximation to GS. Uses the strict lower * part of the diagonal matrix * relax_type = 12 -> Two Stage approximation to GS. Uses the strict lower * part of the diagonal matrix and a second iteration * for additional error approximation * relax_type = 13 -> hybrid L1 Gauss-Seidel forward solve * relax_type = 14 -> hybrid L1 Gauss-Seidel backward solve * relax_type = 15 -> CG * relax_type = 16 -> Scaled Chebyshev * relax_type = 17 -> FCF-Jacobi * relax_type = 18 -> L1-Jacobi [GPU-supported] * relax_type = 19 -> Direct Solve, (old version) * relax_type = 20 -> Kaczmarz * relax_type = 29 -> Direct solve: use gaussian elimination & BLAS * (with pivoting) (old version) * relax_type = 98 -> Direct solve, Gaussian elimination * relax_type = 99 -> Direct solve, Gaussian elimination * relax_type = 199-> Direct solve, Gaussian elimination *-------------------------------------------------------------------------------------*/ switch (relax_type) { case 0: /* Weighted Jacobi */ hypre_BoomerAMGRelax0WeightedJacobi(A, f, cf_marker, relax_points, relax_weight, u, Vtemp); break; case 1: /* Gauss-Seidel VERY SLOW */ hypre_BoomerAMGRelax1GaussSeidel(A, f, cf_marker, relax_points, u); break; case 2: /* Gauss-Seidel: relax interior points in parallel, boundary sequentially */ hypre_BoomerAMGRelax2GaussSeidel(A, f, cf_marker, relax_points, u); break; /* Hybrid: Jacobi off-processor, Gauss-Seidel on-processor (forward loop) */ case 3: hypre_BoomerAMGRelax3HybridGaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 4: /* Hybrid: Jacobi off-processor, Gauss-Seidel/SOR on-processor (backward loop) */ hypre_BoomerAMGRelax4HybridGaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 5: /* Hybrid: Jacobi off-processor, chaotic Gauss-Seidel on-processor */ hypre_BoomerAMGRelax5ChaoticHybridGaussSeidel(A, f, cf_marker, relax_points, u); break; case 6: /* Hybrid: Jacobi off-processor, Symm. Gauss-Seidel/SSOR on-processor with outer relaxation parameter */ hypre_BoomerAMGRelax6HybridSSOR(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 7: /* Jacobi (uses ParMatvec) */ hypre_BoomerAMGRelax7Jacobi(A, f, relax_points, relax_weight, l1_norms, u, Vtemp); break; case 8: /* hybrid L1 Symm. Gauss-Seidel */ hypre_BoomerAMGRelax8HybridL1SSOR(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp); break; /* Hybrid: Jacobi off-processor, ordered Gauss-Seidel on-processor */ case 10: hypre_BoomerAMGRelax10TopoOrderedGaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 11: /* Two Stage Gauss Seidel. Forward sweep only */ hypre_BoomerAMGRelax11TwoStageGaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 12: /* Two Stage Gauss Seidel. Uses the diagonal matrix for the GS part */ hypre_BoomerAMGRelax12TwoStageGaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, u, Vtemp, Ztemp); break; case 13: /* hybrid L1 Gauss-Seidel forward solve */ hypre_BoomerAMGRelax13HybridL1GaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp); break; case 14: /* hybrid L1 Gauss-Seidel backward solve */ hypre_BoomerAMGRelax14HybridL1GaussSeidel(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp); break; case 18: /* weighted L1 Jacobi */ hypre_BoomerAMGRelax18WeightedL1Jacobi(A, f, cf_marker, relax_points, relax_weight, l1_norms, u, Vtemp); break; case 19: /* Direct solve: use gaussian elimination */ relax_error = hypre_BoomerAMGRelax19GaussElim(A, f, u); break; case 20: /* Kaczmarz */ hypre_BoomerAMGRelaxKaczmarz(A, f, omega, l1_norms, u); break; case 98: /* Direct solve: use gaussian elimination & BLAS (with pivoting) */ relax_error = hypre_BoomerAMGRelax98GaussElimPivot(A, f, u); break; } return relax_error; } HYPRE_Int hypre_BoomerAMGRelaxWeightedJacobi_core( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, HYPRE_Int Skip_diag ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); HYPRE_Complex *Vtemp_data = hypre_VectorData(Vtemp_local); HYPRE_Complex *v_ext_data = NULL; HYPRE_Complex *v_buf_data = NULL; HYPRE_Complex zero = 0.0; HYPRE_Real one_minus_weight = 1.0 - relax_weight; HYPRE_Complex res; HYPRE_Int num_procs, my_id, i, j, ii, jj, index, num_sends, start; hypre_ParCSRCommHandle *comm_handle; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); v_ext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, v_buf_data, v_ext_data); } /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { Vtemp_data[i] = u_data[i]; } if (num_procs > 1) { hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { const HYPRE_Complex di = l1_norms ? l1_norms[i] : A_diag_data[A_diag_i[i]]; /*----------------------------------------------------------- * If i is of the right type ( C or F or All ) and diagonal is * nonzero, relax point i; otherwise, skip it. * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------*/ if ( (relax_points == 0 || cf_marker[i] == relax_points) && di != zero ) { res = f_data[i]; for (jj = A_diag_i[i] + Skip_diag; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * Vtemp_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * v_ext_data[ii]; } if (Skip_diag) { u_data[i] *= one_minus_weight; u_data[i] += relax_weight * res / di; } else { u_data[i] += relax_weight * res / di; } } } if (num_procs > 1) { hypre_TFree(v_ext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelax0WeightedJacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, hypre_ParVector *u, hypre_ParVector *Vtemp ) { return hypre_BoomerAMGRelaxWeightedJacobi_core(A, f, cf_marker, relax_points, relax_weight, NULL, u, Vtemp, 1); } HYPRE_Int hypre_BoomerAMGRelax18WeightedL1Jacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_VectorMemoryLocation(x), hypre_VectorMemoryLocation(b) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } if (exec == HYPRE_EXEC_DEVICE) { // XXX GPU calls Relax7 XXX return hypre_BoomerAMGRelax7Jacobi(A, f, relax_points, relax_weight, l1_norms, u, Vtemp); } else #endif { /* in the case of non-CF, use relax-7 which is faster */ if (relax_points == 0) { return hypre_BoomerAMGRelax7Jacobi(A, f, relax_points, relax_weight, l1_norms, u, Vtemp); } else { return hypre_BoomerAMGRelaxWeightedJacobi_core(A, f, cf_marker, relax_points, relax_weight, l1_norms, u, Vtemp, 0); } } } HYPRE_Int hypre_BoomerAMGRelax1GaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); HYPRE_Complex *v_ext_data = NULL; HYPRE_Complex *v_buf_data = NULL; HYPRE_Complex zero = 0.0; HYPRE_Complex res; HYPRE_Int num_procs, my_id, i, j, ii, jj, p, jr, ip, num_sends, num_recvs, vec_start, vec_len; hypre_MPI_Status *status; hypre_MPI_Request *requests; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); v_ext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); status = hypre_CTAlloc(hypre_MPI_Status, num_recvs+num_sends, HYPRE_MEMORY_HOST); requests = hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends, HYPRE_MEMORY_HOST); } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - vec_start; for (j = vec_start; j < vec_start+vec_len; j++) { v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr, requests, status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1) - vec_start; hypre_MPI_Irecv(&v_ext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr, requests, status); } for (i = 0; i < num_rows; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F ) and diagonal is * nonzero, relax point i; otherwise, skip it. * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------*/ if ( (relax_points == 0 || cf_marker[i] == relax_points) && A_diag_data[A_diag_i[i]] != zero ) { res = f_data[i]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * v_ext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } if (num_procs > 1) { hypre_MPI_Barrier(comm); } } } if (num_procs > 1) { hypre_TFree(v_ext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(status, HYPRE_MEMORY_HOST); hypre_TFree(requests, HYPRE_MEMORY_HOST); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelax2GaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); HYPRE_Complex *v_ext_data = NULL; HYPRE_Complex *v_buf_data = NULL; HYPRE_Complex zero = 0.0; HYPRE_Complex res; HYPRE_Int num_procs, my_id, i, j, ii, jj, p, jr, ip, num_sends, num_recvs, vec_start, vec_len; hypre_MPI_Status *status; hypre_MPI_Request *requests; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); num_recvs = hypre_ParCSRCommPkgNumRecvs(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); v_ext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); status = hypre_CTAlloc(hypre_MPI_Status, num_recvs+num_sends, HYPRE_MEMORY_HOST); requests = hypre_CTAlloc(hypre_MPI_Request, num_recvs+num_sends, HYPRE_MEMORY_HOST); } /*----------------------------------------------------------------- * Relax interior points first *-----------------------------------------------------------------*/ for (i = 0; i < num_rows; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F or All ) and diagonal is * nonzero, relax point i; otherwise, skip it. *-----------------------------------------------------------*/ if ( (relax_points == 0 || cf_marker[i] == relax_points) && A_offd_i[i+1] - A_offd_i[i] == zero && A_diag_data[A_diag_i[i]] != zero ) { res = f_data[i]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } for (p = 0; p < num_procs; p++) { jr = 0; if (p != my_id) { for (i = 0; i < num_sends; i++) { ip = hypre_ParCSRCommPkgSendProc(comm_pkg, i); if (ip == p) { vec_start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); vec_len = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1) - vec_start; for (j = vec_start; j < vec_start+vec_len; j++) { v_buf_data[j] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } hypre_MPI_Isend(&v_buf_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } } hypre_MPI_Waitall(jr, requests, status); hypre_MPI_Barrier(comm); } else { if (num_procs > 1) { for (i = 0; i < num_recvs; i++) { ip = hypre_ParCSRCommPkgRecvProc(comm_pkg, i); vec_start = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i); vec_len = hypre_ParCSRCommPkgRecvVecStart(comm_pkg,i+1) - vec_start; hypre_MPI_Irecv(&v_ext_data[vec_start], vec_len, HYPRE_MPI_REAL, ip, 0, comm, &requests[jr++]); } hypre_MPI_Waitall(jr, requests, status); } for (i = 0; i < num_rows; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F or All) and diagonal is * nonzero, relax point i; otherwise, skip it. * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------*/ if ( (relax_points == 0 || cf_marker[i] == relax_points) && A_offd_i[i+1] - A_offd_i[i] != zero && A_diag_data[A_diag_i[i]] != zero) { res = f_data[i]; for (jj = A_diag_i[i]+1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * v_ext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } if (num_procs > 1) { hypre_MPI_Barrier(comm); } } } if (num_procs > 1) { hypre_TFree(v_ext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(status, HYPRE_MEMORY_HOST); hypre_TFree(requests, HYPRE_MEMORY_HOST); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelaxHybridGaussSeidel_core( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp, HYPRE_Int GS_order, HYPRE_Int Symm, HYPRE_Int Skip_diag, HYPRE_Int forced_seq, HYPRE_Int Topo_order ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); hypre_Vector *Vtemp_local = Vtemp ? hypre_ParVectorLocalVector(Vtemp) : NULL; HYPRE_Complex *Vtemp_data = Vtemp_local ? hypre_VectorData(Vtemp_local) : NULL; /* hypre_Vector *Ztemp_local = NULL; HYPRE_Complex *Ztemp_data = NULL; */ HYPRE_Complex *v_ext_data = NULL; HYPRE_Complex *v_buf_data = NULL; HYPRE_Int *proc_ordering = NULL; const HYPRE_Real one_minus_omega = 1.0 - omega; HYPRE_Int num_procs, my_id, num_threads, j, num_sends; hypre_ParCSRCommHandle *comm_handle; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); num_threads = forced_seq ? 1 : hypre_NumThreads(); /* GS order: forward or backward */ const HYPRE_Int gs_order = GS_order > 0 ? 1 : -1; /* for symmetric GS, a forward followed by a backward */ const HYPRE_Int num_sweeps = Symm ? 2 : 1; /* if relax_weight and omega are both 1.0 */ const HYPRE_Int non_scale = relax_weight == 1.0 && omega == 1.0; /* */ const HYPRE_Real prod = 1.0 - relax_weight * omega; /* if (num_threads > 1) { Ztemp_local = hypre_ParVectorLocalVector(Ztemp); Ztemp_data = hypre_VectorData(Ztemp_local); } */ #if defined(HYPRE_USING_PERSISTENT_COMM) // JSP: persistent comm can be similarly used for other smoothers hypre_ParCSRPersistentCommHandle *persistent_comm_handle; #endif if (num_procs > 1) { #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] -= hypre_MPI_Wtime(); #endif if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); #if defined(HYPRE_USING_PERSISTENT_COMM) persistent_comm_handle = hypre_ParCSRCommPkgGetPersistentCommHandle(1, comm_pkg); v_buf_data = (HYPRE_Real *) hypre_ParCSRCommHandleSendDataBuffer(persistent_comm_handle); v_ext_data = (HYPRE_Real *) hypre_ParCSRCommHandleRecvDataBuffer(persistent_comm_handle); #else v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); v_ext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); #endif HYPRE_Int begin = hypre_ParCSRCommPkgSendMapStart(comm_pkg, 0); HYPRE_Int end = hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for HYPRE_SMP_SCHEDULE #endif for (j = begin; j < end; j++) { v_buf_data[j - begin] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_PACK_UNPACK] += hypre_MPI_Wtime(); hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] -= hypre_MPI_Wtime(); #endif #if defined(HYPRE_USING_PERSISTENT_COMM) hypre_ParCSRPersistentCommHandleStart(persistent_comm_handle, HYPRE_MEMORY_HOST, v_buf_data); #else comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, v_buf_data, v_ext_data); #endif #if defined(HYPRE_USING_PERSISTENT_COMM) hypre_ParCSRPersistentCommHandleWait(persistent_comm_handle, HYPRE_MEMORY_HOST, v_ext_data); #else hypre_ParCSRCommHandleDestroy(comm_handle); #endif comm_handle = NULL; #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_HALO_EXCHANGE] += hypre_MPI_Wtime(); #endif } if (Topo_order) { /* Check for ordering of matrix. If stored, get pointer, otherwise * compute ordering and point matrix variable to array. * Used in AIR */ if (!hypre_ParCSRMatrixProcOrdering(A)) { proc_ordering = hypre_CTAlloc(HYPRE_Int, num_rows, HYPRE_MEMORY_HOST); hypre_topo_sort(A_diag_i, A_diag_j, A_diag_data, proc_ordering, num_rows); hypre_ParCSRMatrixProcOrdering(A) = proc_ordering; } else { proc_ordering = hypre_ParCSRMatrixProcOrdering(A); } } /*----------------------------------------------------------------- * Relax all points. *-----------------------------------------------------------------*/ #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] -= hypre_MPI_Wtime(); #endif if ( (num_threads > 1 || !non_scale) && Vtemp_data ) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_rows; j++) { Vtemp_data[j] = u_data[j]; } } if (num_threads > 1) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(j) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { HYPRE_Int ns, ne, sweep; hypre_partition1D(num_rows, num_threads, j, &ns, &ne); for (sweep = 0; sweep < num_sweeps; sweep++) { const HYPRE_Int iorder = num_sweeps == 1 ? gs_order : sweep == 0 ? 1 : -1; const HYPRE_Int ibegin = iorder > 0 ? ns : ne - 1; const HYPRE_Int iend = iorder > 0 ? ne : ns - 1; if (non_scale) { hypre_HybridGaussSeidelNSThreads(A_diag_i, A_diag_j, A_diag_data, A_offd_i, A_offd_j, A_offd_data, f_data, cf_marker, relax_points, l1_norms, u_data, Vtemp_data, v_ext_data, ns, ne, ibegin, iend, iorder, Skip_diag); } else { hypre_HybridGaussSeidelThreads(A_diag_i, A_diag_j, A_diag_data, A_offd_i, A_offd_j, A_offd_data, f_data, cf_marker, relax_points, relax_weight, omega, one_minus_omega, prod, l1_norms, u_data, Vtemp_data, v_ext_data, ns, ne, ibegin, iend, iorder, Skip_diag); } } /* for (sweep = 0; sweep < num_sweeps; sweep++) */ } /* for (j = 0; j < num_threads; j++) */ } else /* if (num_threads > 1) */ { HYPRE_Int sweep; for (sweep = 0; sweep < num_sweeps; sweep++) { const HYPRE_Int iorder = num_sweeps == 1 ? gs_order : sweep == 0 ? 1 : -1; const HYPRE_Int ibegin = iorder > 0 ? 0 : num_rows - 1; const HYPRE_Int iend = iorder > 0 ? num_rows : -1; if (Topo_order) { hypre_HybridGaussSeidelOrderedNS(A_diag_i, A_diag_j, A_diag_data, A_offd_i, A_offd_j, A_offd_data, f_data, cf_marker, relax_points, u_data, NULL, v_ext_data, ibegin, iend, iorder, proc_ordering); } else { if (non_scale) { hypre_HybridGaussSeidelNS(A_diag_i, A_diag_j, A_diag_data, A_offd_i, A_offd_j, A_offd_data, f_data, cf_marker, relax_points, l1_norms, u_data, Vtemp_data, v_ext_data, ibegin, iend, iorder, Skip_diag); } else { hypre_HybridGaussSeidel(A_diag_i, A_diag_j, A_diag_data, A_offd_i, A_offd_j, A_offd_data, f_data, cf_marker, relax_points, relax_weight, omega, one_minus_omega, prod, l1_norms, u_data, Vtemp_data, v_ext_data, ibegin, iend, iorder, Skip_diag); } } } /* for (sweep = 0; sweep < num_sweeps; sweep++) */ } /* if (num_threads > 1) */ #ifndef HYPRE_USING_PERSISTENT_COMM if (num_procs > 1) { hypre_TFree(v_ext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } #endif #ifdef HYPRE_PROFILE hypre_profile_times[HYPRE_TIMER_ID_RELAX] += hypre_MPI_Wtime(); #endif return hypre_error_flag; } /* forward hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax3HybridGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, 1 /* forward */, 0 /* nonsymm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, 1 /* forward */, 0 /* nonsymm */, 1 /* skip diag */, 0, 0); } } /* backward hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax4HybridGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, -1 /* backward */, 0 /* nonsymm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, -1 /* backward */, 0 /* nosymm */, 1 /* skip diag */, 0, 0); } } /* chaotic forward G-S */ HYPRE_Int hypre_BoomerAMGRelax5ChaoticHybridGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); HYPRE_Complex *v_ext_data = NULL; HYPRE_Complex *v_buf_data = NULL; HYPRE_Complex zero = 0.0; HYPRE_Complex res; HYPRE_Int num_procs, my_id, i, j, ii, jj, index, num_sends, start; hypre_ParCSRCommHandle *comm_handle; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (num_procs > 1) { num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); v_buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); v_ext_data = hypre_CTAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg,i+1); j++) { v_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, v_buf_data, v_ext_data); /*----------------------------------------------------------------- * Copy current approximation into temporary vector. *-----------------------------------------------------------------*/ hypre_ParCSRCommHandleDestroy(comm_handle); comm_handle = NULL; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,ii,jj,res) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { /*----------------------------------------------------------- * If i is of the right type ( C or F or All) and diagonal is * nonzero, relax point i; otherwise, skip it. * Relax only C or F points as determined by relax_points. *-----------------------------------------------------------*/ if ( (relax_points == 0 || cf_marker[i] == relax_points) && A_diag_data[A_diag_i[i]] != zero ) { res = f_data[i]; for (jj = A_diag_i[i] + 1; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; res -= A_diag_data[jj] * u_data[ii]; } for (jj = A_offd_i[i]; jj < A_offd_i[i+1]; jj++) { ii = A_offd_j[jj]; res -= A_offd_data[jj] * v_ext_data[ii]; } u_data[i] = res / A_diag_data[A_diag_i[i]]; } } if (num_procs > 1) { hypre_TFree(v_ext_data, HYPRE_MEMORY_HOST); hypre_TFree(v_buf_data, HYPRE_MEMORY_HOST); } return hypre_error_flag; } /* symmetric hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax6HybridSSOR( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, 1, 1 /* symm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, 1, 1 /* symm */, 1 /* skip diag */, 0, 0); } } HYPRE_Int hypre_BoomerAMGRelax7Jacobi( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp ) { HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A); hypre_Vector l1_norms_vec; hypre_ParVector l1_norms_parvec; hypre_VectorData(&l1_norms_vec) = l1_norms; hypre_VectorSize(&l1_norms_vec) = num_rows; /* TODO XXX * The next line is NOT 100% correct, which should be the memory location of l1_norms instead of f * But how do I know it? As said, don't use raw pointers, don't use raw pointers! * It is fine normally since A, f, and l1_norms should live in the same memory space */ hypre_VectorMemoryLocation(&l1_norms_vec) = hypre_ParVectorMemoryLocation(f); hypre_ParVectorLocalVector(&l1_norms_parvec) = &l1_norms_vec; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) HYPRE_Int sync_stream; hypre_GetSyncCudaCompute(&sync_stream); hypre_SetSyncCudaCompute(0); #endif /*----------------------------------------------------------------- * Copy f into temporary vector. *-----------------------------------------------------------------*/ hypre_ParVectorCopy(f, Vtemp); /*----------------------------------------------------------------- * Perform Matvec Vtemp = w * (f - Au) *-----------------------------------------------------------------*/ hypre_ParCSRMatrixMatvec(-relax_weight, A, u, relax_weight, Vtemp); /*----------------------------------------------------------------- * u += D^{-1} * Vtemp, where D_ii = ||A(i,:)||_1 *-----------------------------------------------------------------*/ hypre_ParVectorElmdivpy(Vtemp, &l1_norms_parvec, u); #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) hypre_SetSyncCudaCompute(sync_stream); hypre_SyncCudaComputeStream(hypre_handle()); #endif return hypre_error_flag; } /* symmetric l1 hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax8HybridL1SSOR( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { const HYPRE_Int skip_diag = relax_weight == 1.0 && omega == 1.0 ? 0 : 1; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, 1, 1 /* symm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, 1, 1 /* symm */, skip_diag, 0, 0); } } /* forward hybrid topology ordered G-S */ HYPRE_Int hypre_BoomerAMGRelax10TopoOrderedGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, NULL, u, Vtemp, Ztemp, 1 /* forward */, 0 /* nonsymm */, 1 /* skip_diag */, 1, 1); } /* forward l1 hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax13HybridL1GaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { const HYPRE_Int skip_diag = relax_weight == 1.0 && omega == 1.0 ? 0 : 1; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, 1, 0 /* nonsymm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, 1 /* forward */, 0 /* nonsymm */, skip_diag, 0, 0 ); } } /* backward l1 hybrid G-S */ HYPRE_Int hypre_BoomerAMGRelax14HybridL1GaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { const HYPRE_Int skip_diag = relax_weight == 1.0 && omega == 1.0 ? 0 : 1; #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_ParCSRMatrixMemoryLocation(A), hypre_VectorMemoryLocation(f) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; // TODO implement CF relax on GPUs if (relax_points != 0) { exec = HYPRE_EXEC_HOST; } #if defined(HYPRE_USING_GPU) if (hypre_HandleDeviceGSMethod(hypre_handle()) == 0) { exec = HYPRE_EXEC_HOST; } #endif if (exec == HYPRE_EXEC_DEVICE) { return hypre_BoomerAMGRelaxHybridGaussSeidelDevice(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, -1, 0 /* nonsymm */); } else #endif { return hypre_BoomerAMGRelaxHybridGaussSeidel_core(A, f, cf_marker, relax_points, relax_weight, omega, l1_norms, u, Vtemp, Ztemp, -1 /* backward */, 0 /* nonsymm */, skip_diag, 0, 0 ); } } HYPRE_Int hypre_BoomerAMGRelax19GaussElim( hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u ) { HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt first_ind = hypre_ParVectorFirstIndex(u); HYPRE_Int n_global = (HYPRE_Int) global_num_rows; HYPRE_Int first_index = (HYPRE_Int) first_ind; HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_CSRMatrix *A_CSR; HYPRE_Int *A_CSR_i; HYPRE_Int *A_CSR_j; HYPRE_Real *A_CSR_data; hypre_Vector *f_vector; HYPRE_Real *f_vector_data; HYPRE_Real *A_mat; HYPRE_Real *b_vec; HYPRE_Int i, jj, column, relax_error = 0; /*----------------------------------------------------------------- * Generate CSR matrix from ParCSRMatrix A *-----------------------------------------------------------------*/ /* all processors are needed for these routines */ A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); if (num_rows) { A_CSR_i = hypre_CSRMatrixI(A_CSR); A_CSR_j = hypre_CSRMatrixJ(A_CSR); A_CSR_data = hypre_CSRMatrixData(A_CSR); f_vector_data = hypre_VectorData(f_vector); A_mat = hypre_CTAlloc(HYPRE_Real, n_global*n_global, HYPRE_MEMORY_HOST); b_vec = hypre_CTAlloc(HYPRE_Real, n_global, HYPRE_MEMORY_HOST); /*--------------------------------------------------------------- * Load CSR matrix into A_mat. *---------------------------------------------------------------*/ for (i = 0; i < n_global; i++) { for (jj = A_CSR_i[i]; jj < A_CSR_i[i+1]; jj++) { column = A_CSR_j[jj]; A_mat[i*n_global+column] = A_CSR_data[jj]; } b_vec[i] = f_vector_data[i]; } hypre_gselim(A_mat, b_vec, n_global, relax_error); for (i = 0; i < num_rows; i++) { u_data[i] = b_vec[first_index + i]; } hypre_TFree(A_mat, HYPRE_MEMORY_HOST); hypre_TFree(b_vec, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } else { hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } return relax_error; } HYPRE_Int hypre_BoomerAMGRelax98GaussElimPivot( hypre_ParCSRMatrix *A, hypre_ParVector *f, hypre_ParVector *u ) { HYPRE_BigInt global_num_rows = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_BigInt first_ind = hypre_ParVectorFirstIndex(u); HYPRE_Int n_global = (HYPRE_Int) global_num_rows; HYPRE_Int first_index = (HYPRE_Int) first_ind; HYPRE_Int num_rows = hypre_ParCSRMatrixNumRows(A); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_CSRMatrix *A_CSR; HYPRE_Int *A_CSR_i; HYPRE_Int *A_CSR_j; HYPRE_Real *A_CSR_data; hypre_Vector *f_vector; HYPRE_Real *f_vector_data; HYPRE_Real *A_mat; HYPRE_Real *b_vec; HYPRE_Int i, jj, column, relax_error = 0; HYPRE_Int info; HYPRE_Int one_i = 1; HYPRE_Int *piv; /*----------------------------------------------------------------- * Generate CSR matrix from ParCSRMatrix A *-----------------------------------------------------------------*/ /* all processors are needed for these routines */ A_CSR = hypre_ParCSRMatrixToCSRMatrixAll(A); f_vector = hypre_ParVectorToVectorAll(f); if (num_rows) { A_CSR_i = hypre_CSRMatrixI(A_CSR); A_CSR_j = hypre_CSRMatrixJ(A_CSR); A_CSR_data = hypre_CSRMatrixData(A_CSR); f_vector_data = hypre_VectorData(f_vector); A_mat = hypre_CTAlloc(HYPRE_Real, n_global*n_global, HYPRE_MEMORY_HOST); b_vec = hypre_CTAlloc(HYPRE_Real, n_global, HYPRE_MEMORY_HOST); /*--------------------------------------------------------------- * Load CSR matrix into A_mat. *---------------------------------------------------------------*/ for (i = 0; i < n_global; i++) { for (jj = A_CSR_i[i]; jj < A_CSR_i[i+1]; jj++) { /* need col major */ column = A_CSR_j[jj]; A_mat[i + n_global*column] = A_CSR_data[jj]; } b_vec[i] = f_vector_data[i]; } piv = hypre_CTAlloc(HYPRE_Int, n_global, HYPRE_MEMORY_HOST); /* write over A with LU */ hypre_dgetrf(&n_global, &n_global, A_mat, &n_global, piv, &info); /*now b_vec = inv(A)*b_vec */ hypre_dgetrs("N", &n_global, &one_i, A_mat, &n_global, piv, b_vec, &n_global, &info); hypre_TFree(piv, HYPRE_MEMORY_HOST); for (i = 0; i < num_rows; i++) { u_data[i] = b_vec[first_index+i]; } hypre_TFree(A_mat, HYPRE_MEMORY_HOST); hypre_TFree(b_vec, HYPRE_MEMORY_HOST); hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } else { hypre_CSRMatrixDestroy(A_CSR); A_CSR = NULL; hypre_SeqVectorDestroy(f_vector); f_vector = NULL; } return relax_error; } HYPRE_Int hypre_BoomerAMGRelaxKaczmarz( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Real omega, HYPRE_Real *l1_norms, hypre_ParVector *u ) { MPI_Comm comm = hypre_ParCSRMatrixComm(A); 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_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(A_offd); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); hypre_Vector *f_local = hypre_ParVectorLocalVector(f); HYPRE_Complex *f_data = hypre_VectorData(f_local); HYPRE_Complex *u_offd_data = NULL; HYPRE_Complex *u_buf_data = NULL; HYPRE_Complex res; HYPRE_Int num_procs, my_id, i, j, index, num_sends, start; hypre_ParCSRCommHandle *comm_handle; hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); if (num_procs > 1) { if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); u_buf_data = hypre_TAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); u_offd_data = hypre_TAlloc(HYPRE_Real, num_cols_offd, HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) { u_buf_data[index++] = u_data[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } } comm_handle = hypre_ParCSRCommHandleCreate(1, comm_pkg, u_buf_data, u_offd_data); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(u_buf_data, HYPRE_MEMORY_HOST); } /* Forward local pass */ for (i = 0; i < num_rows; i++) { res = f_data[i]; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { res -= A_diag_data[j] * u_data[A_diag_j[j]]; } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { res -= A_offd_data[j] * u_offd_data[A_offd_j[j]]; } res /= l1_norms[i]; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { u_data[A_diag_j[j]] += omega * res * A_diag_data[j]; } } /* Backward local pass */ for (i = num_rows - 1; i > -1; i--) { res = f_data[i]; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { res -= A_diag_data[j] * u_data[A_diag_j[j]]; } for (j = A_offd_i[i]; j < A_offd_i[i+1]; j++) { res -= A_offd_data[j] * u_offd_data[A_offd_j[j]]; } res /= l1_norms[i]; for (j = A_diag_i[i]; j < A_diag_i[i+1]; j++) { u_data[A_diag_j[j]] += omega * res * A_diag_data[j]; } } hypre_TFree(u_offd_data, HYPRE_MEMORY_HOST); return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelaxTwoStageGaussSeidelHost( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, HYPRE_Int num_inner_iters) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A_diag); 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_Vector *Vtemp_local = hypre_ParVectorLocalVector(Vtemp); HYPRE_Complex *Vtemp_data = hypre_VectorData(Vtemp_local); hypre_Vector *u_local = hypre_ParVectorLocalVector(u); HYPRE_Complex *u_data = hypre_VectorData(u_local); HYPRE_Int i, k, jj, ii; HYPRE_Complex multiplier = 1.0; /* Need to check that EVERY diagonal is nonzero first. If any are, throw exception */ for (i = 0; i < num_rows; i++) { if (A_diag_data[A_diag_i[i]] == 0.0) { hypre_error_in_arg(1); } } hypre_ParCSRMatrixMatvecOutOfPlace(-relax_weight, A, u, relax_weight, f, Vtemp); for (i = 0; i < num_rows; i++) /* Run the smoother */ { // V = V/D Vtemp_data[i] /= A_diag_data[A_diag_i[i]]; // u = u + m*v u_data[i] += multiplier * Vtemp_data[i]; } // adjust for the alternating series multiplier *= -1.0; for (k = 0; k < num_inner_iters; ++k) { // By going from bottom to top, we can update Vtemp in place because // we're operating with the strict, lower triangular matrix for (i = num_rows-1; i >=0; i--) /* Run the smoother */ { // spmv for the row first HYPRE_Complex res = 0.0; for (jj = A_diag_i[i]; jj < A_diag_i[i+1]; jj++) { ii = A_diag_j[jj]; if (ii < i) { res += A_diag_data[jj] * Vtemp_data[ii]; } } // diagonal scaling has to come after the spmv accumulation. It's a row scaling // not column Vtemp_data[i] = res / A_diag_data[A_diag_i[i]]; u_data[i] += multiplier * Vtemp_data[i]; } // adjust for the alternating series multiplier *= -1.0; } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelax11TwoStageGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_VectorMemoryLocation(x), hypre_VectorMemoryLocation(b) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; if (exec == HYPRE_EXEC_DEVICE) { hypre_BoomerAMGRelaxTwoStageGaussSeidelDevice(A, f, relax_weight, omega, u, Vtemp, Ztemp, 1); } else #endif { hypre_BoomerAMGRelaxTwoStageGaussSeidelHost(A, f, relax_weight, omega, u, Vtemp, 1); } return hypre_error_flag; } HYPRE_Int hypre_BoomerAMGRelax12TwoStageGaussSeidel( hypre_ParCSRMatrix *A, hypre_ParVector *f, HYPRE_Int *cf_marker, HYPRE_Int relax_points, HYPRE_Real relax_weight, HYPRE_Real omega, hypre_ParVector *u, hypre_ParVector *Vtemp, hypre_ParVector *Ztemp ) { #if defined(HYPRE_USING_CUDA) || defined(HYPRE_USING_HIP) //HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_VectorMemoryLocation(x), hypre_VectorMemoryLocation(b) ); //RL: TODO back to hypre_GetExecPolicy2 later HYPRE_ExecutionPolicy exec = HYPRE_EXEC_DEVICE; if (exec == HYPRE_EXEC_DEVICE) { hypre_BoomerAMGRelaxTwoStageGaussSeidelDevice(A, f, relax_weight, omega, u, Vtemp, Ztemp, 2); } else #endif { hypre_BoomerAMGRelaxTwoStageGaussSeidelHost(A, f, relax_weight, omega, u, Vtemp, 2); } return hypre_error_flag; }
dbgraph.c
/* * dbgraph.c * * Created on: 2015-7-12 * Author: qiushuang */ #include <omp.h> #include <pthread.h> #include "../include/io.h" #include "../include/dbgraph.h" #include "../include/msp.h" #include "../include/hash.h" #include "../include/bitkmer.h" #define THREADS_PER_TABLE MAX_NUM_THREADS extern long cpu_threads; extern thread_function shift_dictionary[]; //extern __shared__ seq_t shared_spks[]; //extern uint max_num_kmers; //extern uint max_num_spks; //extern uint max_spksize; ull search[NUM_OF_PARTITIONS]; ull collision[NUM_OF_PARTITIONS]; //static evaltime_t inss, inse; //static ull instime[THREADS_PER_TABLE]; //extern ull cpu_count[2]; ull cpu_count[NUM_OF_HASH_DEVICES] = {0, 0, 0, 0}; ull cpu_kmer_count[NUM_OF_HASH_DEVICES] = {0, 0, 0, 0}; extern uint max_num_spks; extern uint max_spksize; extern uint max_num_kmers; extern int read_length; int cns = 0; // read and write by cpu/gpu calling threads int srv = -1; // read by main thread and cpu/gpu calling threads, write only by main thread #define get_reverse_edge(edge, kmer) { \ edge = (kmer.x >> (KMER_UNIT_BITS - 2)) ^ 0x3; } void hash_kmers2 (uint num, uint * indices_all, uch * lenarr_all, rid_t * ridarr_all, seq_t * spks_all, const int k, const int tabid, ull * searches, ull * collisions) { omp_set_num_threads (cpu_threads); #pragma omp parallel { int threads_per_table = omp_get_num_threads (); int spknum_th = (num + threads_per_table - 1) / threads_per_table; if (spknum_th <= threads_per_table) spknum_th = num/threads_per_table; int thid = omp_get_thread_num (); uint * indices = indices_all + spknum_th * thid; uch * lenarr = lenarr_all + spknum_th * thid; rid_t * ridarr = ridarr_all + spknum_th * thid; seq_t * spks = spks_all; uint tnum = num; if (thid == threads_per_table - 1) { spknum_th = (int)tnum - spknum_th * thid; // printf ("DDDDDEBUG: %u\n", spknum_th); } // evaltime_t inss, inse; // ull insth = 0; int r; uint index; uch len; uch mark; kmer_t kmer[2]; seq_t * spk_ptr; uint seed = DEFAULT_SEED; // set it as a fixed number or input argument hashval_t hash[2]; // hash[0] is hash value for kmer, hash[1] is hash value for reverse kmer rid_t rid; int flag; edge_type edge[2]; // edge[0] is edge for kmer, edge[1] is redge for reverse kmer unit_kmer_t * ptr; int table_index; int i; for (r = 0; r < spknum_th; r++) { mark = lenarr[r] & 0x80; // mark whether the most significant bit is 0 or 1 len = lenarr[r] & 0x7f; // do not need to add k, for its utilization rid = ridarr[r]; index = indices[r]; spk_ptr = spks + index; // point to the superkmer /* initialize kmer and its reverse */ #ifdef LONG_KMER kmer[0].x = kmer[0].y = kmer[0].z = kmer[0].w = 0; kmer[1].x = kmer[1].y = kmer[1].z = kmer[1].w = 0; #else kmer[0].x = 0, kmer[0].y = 0; kmer[1].x = 0, kmer[1].y = 0; #endif i = 0; /* Get first kmer from superkmer and insert/update into hashtable */ if (mark) { get_first_kmer_cpu (&kmer[0], spk_ptr, k + 1); get_reverse_edge (edge[1], kmer[0]); // get redge for reverse if mark == 1 kmer_32bit_left_shift (&kmer[0], 2); i++; } else get_first_kmer_cpu (&kmer[0], spk_ptr, k); edge[0] = (*(spk_ptr + (k + i) / 4) >> (6 - ((k + i) % 4) * 2)) & 0x3; i++; /* get reverse complementary of the kmer */ get_reverse (&kmer[0], &kmer[1]); #ifdef LONG_KMER table_index = (128 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 128 - k * 2); #else table_index = (64 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 64 - k * 2); #endif hash[0] = murmur_hash3_32 ((uint *)&kmer[0], seed); hash[1] = murmur_hash3_32 ((uint *)&kmer[1], seed); if (hash[0] == hash[1]) { int ret = compare_2kmers_cpu (&kmer[0], &kmer[1]); if (ret >= 0) flag = 0; else flag = 1; } else if (hash[0] < hash[1]) flag = 0; else flag = 1; if ( mark ) { // gettimeofday (&inss, NULL); if (find_and_update2_hashtab_with_hash (hash[flag], &kmer[flag], edge[flag], edge[(1 + flag) % 2] + 4, rid, tabid, searches, collisions) == false) { printf ("cpu*******hash kmer error: cannot find space or element!\n"); } // gettimeofday (&inse, NULL); // insth += ((inse.tv_sec * 1000000 + inse.tv_usec) - (inss.tv_sec * 1000000 + inss.tv_usec)); } else { // gettimeofday (&inss, NULL); if ( find_and_update_hashtab_with_hash (hash[flag], &kmer[flag], edge[0] + flag * 4, rid, tabid, searches, collisions) == false ) { printf ("cpu*******hash kmer error: cannot find space or element!\n"); } // gettimeofday (&inse, NULL); // insth += ((inse.tv_sec * 1000000 + inse.tv_usec) - (inss.tv_sec * 1000000 + inss.tv_usec)); } ptr = (unit_kmer_t *)&kmer[0] + (k * 2) / KMER_UNIT_BITS; for (; i < len - 1; i++) { /* Get redge from previous kmer */ get_reverse_edge (edge[1], kmer[0]); /* Get next kmer by using its edge */ kmer_32bit_left_shift (&kmer[0], 2); *ptr |= ((unit_kmer_t)edge[0]) << (KMER_UNIT_BITS - (k * 2) % KMER_UNIT_BITS); edge[0] = (*(spk_ptr + (k + i) / 4) >> (6 - ((k + i) % 4) * 2)) & 0x3; /* get reverse complementary of the kmer */ get_reverse (&kmer[0], &kmer[1]); #ifdef LONG_KMER table_index = (128 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 128 - k * 2); #else table_index = (64 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 64 - k * 2); #endif hash[0] = murmur_hash3_32 ((uint *)&kmer[0], seed); hash[1] = murmur_hash3_32 ((uint *)&kmer[1], seed); if (hash[0] == hash[1]) { int ret = compare_2kmers_cpu (&kmer[0], &kmer[1]); if (ret >= 0) flag = 0; else flag = 1; } else if (hash[0] < hash[1]) flag = 0; else flag = 1; // gettimeofday (&inss, NULL); if( find_and_update2_hashtab_with_hash (hash[flag], &kmer[flag], edge[flag], edge[(1 + flag) % 2] + 4, rid, tabid, searches, collisions) == false ) { printf ("cpu*******hash kmer error: cannot find space or element!\n"); } // gettimeofday (&inse, NULL); // insth += ((inse.tv_sec * 1000000 + inse.tv_usec) - (inss.tv_sec * 1000000 + inss.tv_usec)); } if (i > len - 1) continue; // in this case, len == 0: the number of kmers is 1 get_reverse_edge (edge[1], kmer[0]); /* Get next kmer by using its edge */ kmer_32bit_left_shift (&kmer[0], 2); *ptr |= ((unit_kmer_t)edge[0]) << (KMER_UNIT_BITS - (k * 2) % KMER_UNIT_BITS); /* get reverse complementary of the kmer */ get_reverse (&kmer[0], &kmer[1]); #ifdef LONG_KMER table_index = (128 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 128 - k * 2); #else table_index = (64 - k * 2) / 32; shift_dictionary[table_index] (&kmer[1], 64 - k * 2); #endif hash[0] = murmur_hash3_32 ((uint *)&kmer[0], seed); hash[1] = murmur_hash3_32 ((uint *)&kmer[1], seed); if (hash[0] == hash[1]) { int ret = compare_2kmers_cpu (&kmer[0], &kmer[1]); if (ret >= 0) flag = 0; else flag = 1; } else if (hash[0] < hash[1]) flag = 0; else flag = 1; if (len + k - 1 == read_length) { // gettimeofday (&inss, NULL); if ( find_and_update_hashtab_with_hash (hash[flag], &kmer[flag], edge[1] + ((1 + flag) % 2) * 4, rid, tabid, searches, collisions) == false ) { printf ("cpu*******hash kmer error: cannot find space or element!\n"); } // gettimeofday (&inse, NULL); // insth += ((inse.tv_sec * 1000000 + inse.tv_usec) - (inss.tv_sec * 1000000 + inss.tv_usec)); } else { edge[0] = (*(spk_ptr + (k + i) / 4) >> (6 - ((k + i) % 4) * 2)) & 0x3; // gettimeofday (&inss, NULL); if( find_and_update2_hashtab_with_hash (hash[flag], &kmer[flag], edge[flag], edge[(1 + flag) % 2] + 4, rid, tabid, searches, collisions) == false ) { printf ("cpu*******hash kmer error: cannot find space or element!\n"); } // gettimeofday (&inse, NULL); // insth += ((inse.tv_sec * 1000000 + inse.tv_usec) - (inss.tv_sec * 1000000 + inss.tv_usec)); } } // instime[thid] += insth; } } inline uint max_kmers (spkmer_t * spkmers, int num_of_partitions) { uint max = spkmers[0].numkmer; uint i; for (i = 1; i < num_of_partitions; i++) { if (spkmers[i].numkmer > max) max = spkmers[i].numkmer; } return max; } void cpu_hash_subgraph_workflow (int total_num_partitions, char * file_dir, spkmer_t * spkmer, dbgraph_t * graph, \ subgraph_t * subgraph, dbtable_t * tbs, int tabid, int k, int p, int world_size, int world_rank) { float write_graph_time = 0; float hash_time = 0; float create_time = 0; float visit_nodes_time = 0; float cpu_qtime = 0; float cpu_stime = 0; int np_per_node = (total_num_partitions + world_size - 1)/world_size; int np_node; // this is the real number of partitions in this compute node if (world_rank == world_size - 1) np_node = total_num_partitions - (world_rank) * np_per_node; else np_node = np_per_node; msp_id_t start_id = np_per_node * world_rank; uint max_nkmers = 0; evaltime_t start, end; evaltime_t cpus, cpue; gettimeofday (&cpus, NULL); while (cns < np_node) { gettimeofday (&start, NULL); uint q = atomic_increase (&cns, 1); while (q > srv) {} // printf ("################queue id: %d ################\n", q); gettimeofday (&end, NULL); cpu_qtime += (float)((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) / 1000; spkmer_t * spkmers = &spkmer[q]; if (spkmers->num == 0) { printf ("!!!!!!!!!!!number of superkmers is 0!!!!!!!!!!!!!!!\n"); continue; } uint num_of_spks = spkmers->num; uint num_of_kmers = spkmers->numkmer; ull spksize = spkmers->spksize; cpu_kmer_count[tabid] += num_of_kmers; ull countn = 0; int j; if (max_nkmers < num_of_kmers) { max_nkmers = num_of_kmers; } uint * indices = spkmers->indices; rid_t * ridarr = (rid_t *)(indices + num_of_spks + 1); uch * lenarr = (uch *)(ridarr + num_of_spks); uch * spks = (uch *)indices + sizeof(uint) * (num_of_spks + 1) + (sizeof(rid_t) + sizeof(uch)) * num_of_spks; /* Hash kmers */ gettimeofday (&start, NULL); create_hashtab (num_of_kmers, sizeof(node_t), graph, tabid); gettimeofday (&end, NULL); create_time += (float)((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) / 1000; gettimeofday (&start, NULL); hash_kmers2 (num_of_spks, indices, lenarr, ridarr, spks, k, tabid, &search[0], &collision[0]); gettimeofday (&end, NULL); hash_time += (float)((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) / 1000; #ifdef USE_DISK_IO // ************* write hashtab to disk for new traversal *********** write_hashtab (file_dir, graph->nodes, graph->size, num_of_kmers, q+start_id, total_num_partitions, tabid); countn = write_graph (graph, k); #else countn = gather_sorted_dbgraph (graph, tbs, subgraph, num_of_kmers, q, start_id, np_node); #endif gettimeofday (&start, NULL); cpu_count[tabid] += countn; // printf ("countn = %lu, count = %lu, partition %d\n", countn, cpu_count[tabid], q); gettimeofday (&end, NULL); write_graph_time += (float)((end.tv_sec * 1000000 + end.tv_usec) - (start.tv_sec * 1000000 + start.tv_usec)) / 1000; free (spkmers->indices); destroy_hashtab (graph); } gettimeofday (&cpue, NULL); print_exec_time (cpus, cpue, "~~~~~~~~~~~~~~~~~overall hashing time on cpu: "); printf ("~~~~~~~~~~~~~~~~cpu queuing time: %f\n", cpu_qtime); printf ("~~~~~~~~~~~~~~~~Test hashing performance - hashing time only: %f\n", hash_time); printf ("~~~~~~~~~~~~~~~~CPU hashing time only: %f\n", hash_time + create_time + write_graph_time); printf ("^^^^^^^^^^^^^^^^ output hash table time: %f\n", write_graph_time); printf ("~~~~~~~~~~~~~~~~ CPU: max number of kmers: %u", max_nkmers); printf ("~~~~~~~~~~~~~~~~ CPU: number of vertices counted: %lu\n", cpu_count[tabid]); printf ("~~~~~~~~~~~~~~~~ CPU: total number of kmers counted: %lu\n", cpu_kmer_count[tabid]); } void * cpu_dbgraph_workflow (void * arg) { cpu_hash_arg * harg = (cpu_hash_arg *) arg; cpu_hash_subgraph_workflow (harg->total_num_partitions, harg->file_dir, harg->superkmers, harg->graph, \ harg->subgraph, harg->tbs, harg->tabid, harg->k, harg->p, harg->world_size, harg->world_rank); return ((void *)0); }
OMPExceptionCatcher.h
/** @file OMPExceptionCatcher.h * @author Mark J. Olah (mjo\@cs.unm DOT edu) * @date 2019 * @copyright See LICENSE file * @brief A lightweight class for managing C++ exception handling strategies for OpenMP methods. * * OpenMP code must catch any exceptions that may have been thrown before exiting the OpenMP block. * This class acts as lightweight wrapper that allows an arbitrary function or lambda expression to be run * safely and efficiently in OMP even if it might throw exceptions. We employ one of 4 possible strategies * as determined By the OMPExceptionCatcher::Strategies enum. * * Strategy's : * OMPExceptionCatcher::Strategies::DoNotTry -- Don't even try, this is a null op to completely disable * this class's effect. * OMPExceptionCatcher::Strategies::Continue -- Catch exceptions and keep going * OMPExceptionCatcher::Strategies::Abort -- Catch exceptions and abort * OMPExceptionCatcher::Strategies::RethrowFirst -- Re-throws first exception thrown by any thread * * * Example useage: * OMPExceptionCatcher catcher(OMPExceptionCatcher<>::Strategies::Continue); * #pragma omp parallel for * for(int n=0; n < N; n++) catcher.run([&]{ my_ouput(n)=do_my calulations(args(n)); } * catcher.rethrow(); //Required only if you ever might use RethrowFirst strategy */ #ifndef OMP_EXCEPTION_CATCHER_H #define OMP_EXCEPTION_CATCHER_H #include<exception> #include<mutex> #include<functional> #include<cstdint> namespace omp_exception_catcher { namespace impl_ { //IntType is a dummy just to allow everything to be a template and static member initialization //to be defined in a header-only file template<class IntType=uint32_t> class OMPExceptionCatcher { public: enum class Strategy:IntType {DoNotTry, Continue, Abort, RethrowFirst}; private: static Strategy GlobalDefaultStrategy; public: static void setGlobalDefaultStrategy(Strategy s) { GlobalDefaultStrategy = s; } OMPExceptionCatcher(): ex(nullptr), strategy(GlobalDefaultStrategy) {} OMPExceptionCatcher(Strategy strategy_): ex(nullptr), strategy(strategy_) {} void rethrow() const { if(strategy==Strategy::RethrowFirst && ex) std::rethrow_exception(ex); } template<class Function, class... Parameters> void run(Function func, Parameters... params) { switch(strategy) { case Strategy::DoNotTry: func(params...); break; case Strategy::Continue: try { func(params...); } catch (...) { } break; case Strategy::Abort: try { func(params...); } catch (...) { std::abort(); } break; case Strategy::RethrowFirst: try { func(params...); } catch (...) { capture(); } break; } } private: std::exception_ptr ex; std::mutex lock; Strategy strategy; void capture() { std::unique_lock<std::mutex> guard(lock); if(!ex) ex = std::current_exception(); } }; template<class IntType> typename OMPExceptionCatcher<IntType>::Strategy OMPExceptionCatcher<IntType>::GlobalDefaultStrategy = OMPExceptionCatcher<IntType>::Strategy::RethrowFirst; } /* namespace omp_exception_catcher::impl_ */ using OMPExceptionCatcher = impl_::OMPExceptionCatcher<uint32_t>; } /* namespace omp_exception_catcher */ #endif
triangle_counting.h
#pragma once #include "util/containers/boolarray.h" #include "util/graph/graph.h" #include "util/libpopcnt.h" #include "util/intersection/set_inter_cnt_utils.h" #define MAX_PACK_NUM (32768) #define FIRST_RANGE_SIZE (32768) using row_ptr_t = uint32_t; template<typename OFF, typename WI, typename WC> void PackWords(graph_t &g, OFF *row_ptrs_beg, int to_pack_num, vector<vector<WI>> &word_indexes, vector<vector<WC>> &words, Timer &tc_timer) { constexpr int word_in_bits = sizeof(WC) * 8; // Construct Words for Range [0, 32768), at most 512 words (given each word 64 bits) #pragma omp for schedule(dynamic, 100) for (auto u = 0u; u < to_pack_num; u++) { auto prev_blk_id = -1; for (auto off = g.num_edges[u]; off < row_ptrs_beg[u]; off++) { auto v = g.adj[off]; int cur_blk_id = v / word_in_bits; if (cur_blk_id != prev_blk_id) { prev_blk_id = cur_blk_id; word_indexes[u].emplace_back(cur_blk_id); words[u].emplace_back(0); } words[u].back() |= static_cast<WC>(1u) << (v % word_in_bits); } } #pragma omp single { log_info("Finish Indexing: %.9lfs", tc_timer.elapsed()); } } inline size_t CountTriBMPAndMergeWithPackDODG(graph_t &g, int max_omp_threads) { Timer tc_timer; int max_d = 0; size_t tc_cnt = 0; auto *row_ptrs_beg = (row_ptr_t *) malloc(sizeof(row_ptr_t) * (g.n + 1)); auto *row_ptrs_end = g.num_edges; using word_t = uint64_t; constexpr int word_in_bits = sizeof(word_t) * 8; int to_pack_num = min<int>(g.n, MAX_PACK_NUM); vector<vector<uint16_t>> word_indexes(to_pack_num); // MAX_PACK_NUM * bits-sizeof(word) vector<vector<word_t>> words(to_pack_num); #pragma omp parallel num_threads(max_omp_threads) { #pragma omp for reduction(max: max_d) for (auto u = 0u; u < g.n; u++) { row_ptrs_beg[u] = lower_bound(g.adj + g.num_edges[u], g.adj + g.num_edges[u + 1], min<int>(FIRST_RANGE_SIZE, g.n)) - g.adj; max_d = max<int>(max_d, g.num_edges[u + 1] - g.num_edges[u]); } #pragma omp single { if (to_pack_num > 0) { log_info("Stop Deg at [%d, %d]", g.num_edges[1] - g.num_edges[0], g.num_edges[to_pack_num] - g.num_edges[to_pack_num - 1]); } log_info("finish init row_ptrs_end, max d: %d, time: %.9lfs", max_d, tc_timer.elapsed()); } PackWords(g, row_ptrs_beg, to_pack_num, word_indexes, words, tc_timer); #pragma omp for schedule(dynamic, 100) reduction(+:tc_cnt) for (auto u = 0u; u < g.n; u++) { static thread_local BoolArray<word_t> bitmap(FIRST_RANGE_SIZE); static thread_local vector<word_t> buffer(FIRST_RANGE_SIZE / word_in_bits); // Index for First Range. if (g.num_edges[u] < row_ptrs_beg[u]) { if (u < to_pack_num) { for (size_t i = 0; i < word_indexes[u].size(); i++) { bitmap.setWord(word_indexes[u][i], words[u][i]); } } else { for (auto off = g.num_edges[u]; off < row_ptrs_beg[u]; off++) { auto w = g.adj[off]; bitmap.set(w); } } } auto du = row_ptrs_end[u + 1] - row_ptrs_beg[u]; for (auto edge_idx = g.num_edges[u]; edge_idx < row_ptrs_end[u + 1]; edge_idx++) { auto v = g.adj[edge_idx]; auto cn_count = 0; // First Range. if (g.num_edges[u] < row_ptrs_beg[u]) { if (v < to_pack_num) { auto num_words_v = word_indexes[v].size(); for (size_t i = 0; i < num_words_v; i++) { buffer[i] = bitmap.getWord(word_indexes[v][i]); } for (size_t i = 0; i < num_words_v; i++) { buffer[i] &= words[v][i]; } cn_count += popcnt(&buffer.front(), sizeof(word_t) * num_words_v); } else { if (g.num_edges[v] < row_ptrs_beg[v]) { cn_count += SetInterCntVecMerge(&g, g.num_edges[u], row_ptrs_beg[u], g.num_edges[v], row_ptrs_beg[v]); } } } // Second Range. auto dv = row_ptrs_end[v + 1] - row_ptrs_beg[v]; if (du > 0 && dv > 0) { cn_count += SetInterCntVecMerge(&g, row_ptrs_beg[u], row_ptrs_end[u + 1], row_ptrs_beg[v], row_ptrs_end[v + 1]); } tc_cnt += cn_count; } // Clear the Index. if (g.num_edges[u] < row_ptrs_beg[u]) { bitmap.reset(); } } } free(row_ptrs_beg); log_info("Forward cost: %.3lf s, Mem Usage: %d KB", tc_timer.elapsed(), getValue()); log_info("Triangle Cnt: %'zu", tc_cnt); return tc_cnt; } inline size_t CountTriBMPAndMergeWithPack(graph_t &g, int max_omp_threads) { Timer tc_timer; int max_d = 0; size_t tc_cnt = 0; auto *row_ptrs_end = (row_ptr_t *) malloc(sizeof(row_ptr_t) * (g.n + 1)); auto *row_ptrs_beg = (row_ptr_t *) malloc(sizeof(row_ptr_t) * (g.n + 1)); size_t workload = 0; size_t workload_large_deg = 0; size_t workload_bmp = 0; using word_t = uint64_t; constexpr int word_in_bits = sizeof(word_t) * 8; int to_pack_num = min<int>(g.n, MAX_PACK_NUM); vector<vector<uint16_t>> word_indexes(to_pack_num); // MAX_PACK_NUM * bits-sizeof(word) vector<vector<word_t>> words(to_pack_num); #pragma omp parallel num_threads(max_omp_threads) { #pragma omp for reduction(max: max_d) for (auto u = 0u; u < g.n; u++) { row_ptrs_end[u + 1] = lower_bound(g.adj + g.num_edges[u], g.adj + g.num_edges[u + 1], u) - g.adj; row_ptrs_beg[u] = lower_bound(g.adj + g.num_edges[u], g.adj + g.num_edges[u + 1], min<int>(FIRST_RANGE_SIZE, u)) - g.adj; max_d = max<int>(max_d, row_ptrs_end[u + 1] - g.num_edges[u]); } #pragma omp single { log_info("Stop Deg at [%d, %d]", g.num_edges[1] - g.num_edges[0], g.num_edges[to_pack_num] - g.num_edges[to_pack_num - 1]); log_info("finish init row_ptrs_end, max d: %d, time: %.9lfs", max_d, tc_timer.elapsed()); } PackWords(g, row_ptrs_beg, to_pack_num, word_indexes, words, tc_timer); #pragma omp for schedule(dynamic, 100) reduction(+:tc_cnt) reduction(+:workload) reduction(+:workload_large_deg) \ reduction(+:workload_bmp) for (auto u = 0u; u < g.n; u++) { static thread_local BoolArray<word_t> bitmap(FIRST_RANGE_SIZE); static thread_local vector<word_t> buffer(FIRST_RANGE_SIZE / word_in_bits); // Index for First Range. if (g.num_edges[u] < row_ptrs_beg[u]) { if (u < to_pack_num) { for (size_t i = 0; i < word_indexes[u].size(); i++) { bitmap.setWord(word_indexes[u][i], words[u][i]); } } else { for (auto off = g.num_edges[u]; off < row_ptrs_beg[u]; off++) { auto w = g.adj[off]; bitmap.set(w); } } } auto du = row_ptrs_end[u + 1] - row_ptrs_beg[u]; for (auto edge_idx = g.num_edges[u]; edge_idx < row_ptrs_end[u + 1]; edge_idx++) { auto v = g.adj[edge_idx]; auto cn_count = 0; // First Range. if (g.num_edges[u] < row_ptrs_beg[u]) { if (v < to_pack_num) { auto num_words_v = word_indexes[v].size(); for (size_t i = 0; i < num_words_v; i++) { #ifdef WORKLOAD_STAT workload++; workload_bmp++; workload_large_deg++; #endif buffer[i] = bitmap.getWord(word_indexes[v][i]); } for (size_t i = 0; i < num_words_v; i++) { buffer[i] &= words[v][i]; } cn_count += popcnt(&buffer.front(), sizeof(word_t) * num_words_v); } else { #ifdef WORKLOAD_STAT auto dv = row_ptrs_beg[v] - g.num_edges[v]; workload += du + dv; workload_large_deg += du + dv; #endif if (g.num_edges[v] < row_ptrs_beg[v]) { cn_count += SetInterCntVecMerge(&g, g.num_edges[u], row_ptrs_beg[u], g.num_edges[v], row_ptrs_beg[v]); } } } // Second Range. auto dv = row_ptrs_end[v + 1] - row_ptrs_beg[v]; if (du > 0 && dv > 0) { #ifdef WORKLOAD_STAT workload += du + dv; #endif cn_count += SetInterCntVecMerge(&g, row_ptrs_beg[u], row_ptrs_end[u + 1], row_ptrs_beg[v], row_ptrs_end[v + 1]); } tc_cnt += cn_count; } // Clear the Index. if (g.num_edges[u] < row_ptrs_beg[u]) { bitmap.reset(); } } } free(row_ptrs_beg); free(row_ptrs_end); log_info("Forward cost: %.3lf s, Mem Usage: %d KB", tc_timer.elapsed(), getValue()); log_info("Triangle Cnt: %'zu", tc_cnt); #ifdef WORKLOAD_STAT log_info("Workload: %s, avg: %s", FormatWithCommas(workload).c_str(), FormatWithCommas(workload / (g.m / 2)).c_str()); log_info("Workload (large-deg vid in [0, %d]): %s, BMP: %s, avg: %s", FIRST_RANGE_SIZE, FormatWithCommas(workload_large_deg).c_str(), FormatWithCommas(workload_bmp).c_str(), FormatWithCommas(workload_large_deg / (g.m / 2)).c_str()); #endif return tc_cnt; } inline size_t CountTriMergeDODG(graph_t &g, int max_omp_threads) { Timer tc_timer; int max_d = 0; size_t tc_cnt = 0; #pragma omp parallel num_threads(max_omp_threads) { #pragma omp for reduction(max: max_d) for (auto u = 0u; u < g.n; u++) { max_d = max<int>(max_d, g.num_edges[u + 1] - g.num_edges[u]); } #pragma omp single { log_info("finish init row_ptrs_end, max d: %d, time: %.9lfs", max_d, tc_timer.elapsed()); } #pragma omp for schedule(dynamic, 100) reduction(+:tc_cnt) for (auto u = 0u; u < g.n; u++) { // Index for First Range. for (auto edge_idx = g.num_edges[u]; edge_idx < g.num_edges[u + 1]; edge_idx++) { auto v = g.adj[edge_idx]; tc_cnt += SetInterLookup(&g, g.num_edges[u], g.num_edges[u + 1], g.num_edges[v], g.num_edges[v + 1]); } } } log_info("Forward Cost: %.9lfs", tc_timer.elapsed()); return tc_cnt; }
csr_matop.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Matrix operation functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #include "csr_matrix.h" /*-------------------------------------------------------------------------- * hypre_CSRMatrixAdd: * adds two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix* hypre_CSRMatrixAddHost ( hypre_CSRMatrix *A, hypre_CSRMatrix *B ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, jcol, num_nonzeros; HYPRE_Int pos; HYPRE_Int *marker; HYPRE_MemoryLocation memory_location_A = hypre_CSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_CSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); if (nrows_A != nrows_B || ncols_A != ncols_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } marker = hypre_CTAlloc(HYPRE_Int, ncols_A, HYPRE_MEMORY_HOST); C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1, memory_location_C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } num_nonzeros = 0; C_i[0] = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; marker[jcol] = ic; num_nonzeros++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] != ic) { marker[jcol] = ic; num_nonzeros++; } } C_i[ic+1] = num_nonzeros; } C = hypre_CSRMatrixCreate(nrows_A, ncols_A, num_nonzeros); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize_v2(C, 0, memory_location_C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } pos = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; C_j[pos] = jcol; C_data[pos] = A_data[ia]; marker[jcol] = pos; pos++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] < C_i[ic]) { C_j[pos] = jcol; C_data[pos] = B_data[ib]; marker[jcol] = pos; pos++; } else { C_data[marker[jcol]] += B_data[ib]; } } } hypre_TFree(marker, HYPRE_MEMORY_HOST); return C; } hypre_CSRMatrix* hypre_CSRMatrixAdd( hypre_CSRMatrix *A, hypre_CSRMatrix *B) { hypre_CSRMatrix *C = NULL; #if defined(HYPRE_USING_CUDA) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_CSRMatrixMemoryLocation(A), hypre_CSRMatrixMemoryLocation(B) ); if (exec == HYPRE_EXEC_DEVICE) { C = hypre_CSRMatrixAddDevice(A, B); } else #endif { C = hypre_CSRMatrixAddHost(A, B); } return C; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixBigAdd: * adds two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixBigAdd( hypre_CSRMatrix *A, hypre_CSRMatrix *B ) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_BigInt *A_j = hypre_CSRMatrixBigJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_BigInt *B_j = hypre_CSRMatrixBigJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_BigInt *C_j; HYPRE_Int ia, ib, ic, num_nonzeros; HYPRE_BigInt jcol; HYPRE_Int pos; HYPRE_Int *marker; HYPRE_MemoryLocation memory_location_A = hypre_CSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_CSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); if (nrows_A != nrows_B || ncols_A != ncols_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } marker = hypre_CTAlloc(HYPRE_Int, ncols_A, HYPRE_MEMORY_HOST); C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1, memory_location_C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } num_nonzeros = 0; C_i[0] = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; marker[jcol] = ic; num_nonzeros++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] != ic) { marker[jcol] = ic; num_nonzeros++; } } C_i[ic+1] = num_nonzeros; } C = hypre_CSRMatrixCreate(nrows_A, ncols_A, num_nonzeros); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize_v2(C, 1, memory_location_C); C_j = hypre_CSRMatrixBigJ(C); C_data = hypre_CSRMatrixData(C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } pos = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; C_j[pos] = jcol; C_data[pos] = A_data[ia]; marker[jcol] = pos; pos++; } for (ib = B_i[ic]; ib < B_i[ic+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] < C_i[ic]) { C_j[pos] = jcol; C_data[pos] = B_data[ib]; marker[jcol] = pos; pos++; } else { C_data[marker[jcol]] += B_data[ib]; } } } hypre_TFree(marker, HYPRE_MEMORY_HOST); return C; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixMultiply * multiplies two CSR Matrices A and B and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix* hypre_CSRMatrixMultiplyHost( hypre_CSRMatrix *A, hypre_CSRMatrix *B) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, ja, jb, num_nonzeros=0; HYPRE_Int row_start, counter; HYPRE_Complex a_entry, b_entry; HYPRE_Int allsquare = 0; HYPRE_Int max_num_threads; HYPRE_Int *jj_count; HYPRE_MemoryLocation memory_location_A = hypre_CSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_CSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); if (ncols_A != nrows_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } if (nrows_A == ncols_B) { allsquare = 1; } C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1, memory_location_C); max_num_threads = hypre_NumThreads(); jj_count = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(ia, ib, ic, ja, jb, num_nonzeros, row_start, counter, a_entry, b_entry) #endif { HYPRE_Int *B_marker = NULL; HYPRE_Int ns, ne, ii, jj; HYPRE_Int size, rest, num_threads; HYPRE_Int i1; ii = hypre_GetThreadNum(); num_threads = hypre_NumActiveThreads(); size = nrows_A/num_threads; rest = nrows_A - size*num_threads; if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } B_marker = hypre_CTAlloc(HYPRE_Int, ncols_B, HYPRE_MEMORY_HOST); for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; num_nonzeros = 0; for (ic = ns; ic < ne; ic++) { C_i[ic] = num_nonzeros; if (allsquare) { B_marker[ic] = ic; num_nonzeros++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; if (B_marker[jb] != ic) { B_marker[jb] = ic; num_nonzeros++; } } } } jj_count[ii] = num_nonzeros; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { jj = jj_count[0]; for (i1 = 1; i1 < ii; i1++) jj += jj_count[i1]; for (i1 = ns; i1 < ne; i1++) C_i[i1] += jj; } else { C_i[nrows_A] = 0; for (i1 = 0; i1 < num_threads; i1++) C_i[nrows_A] += jj_count[i1]; C = hypre_CSRMatrixCreate(nrows_A, ncols_B, C_i[nrows_A]); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize_v2(C, 0, memory_location_C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (ib = 0; ib < ncols_B; ib++) B_marker[ib] = -1; counter = C_i[ns]; for (ic = ns; ic < ne; ic++) { row_start = C_i[ic]; if (allsquare) { B_marker[ic] = counter; C_data[counter] = 0; C_j[counter] = ic; counter++; } for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { ja = A_j[ia]; a_entry = A_data[ia]; for (ib = B_i[ja]; ib < B_i[ja+1]; ib++) { jb = B_j[ib]; b_entry = B_data[ib]; if (B_marker[jb] < row_start) { B_marker[jb] = counter; C_j[B_marker[jb]] = jb; C_data[B_marker[jb]] = a_entry*b_entry; counter++; } else C_data[B_marker[jb]] += a_entry*b_entry; } } } hypre_TFree(B_marker, HYPRE_MEMORY_HOST); } /*end parallel region */ hypre_TFree(jj_count, HYPRE_MEMORY_HOST); return C; } hypre_CSRMatrix* hypre_CSRMatrixMultiply( hypre_CSRMatrix *A, hypre_CSRMatrix *B) { hypre_CSRMatrix *C = NULL; #if defined(HYPRE_USING_CUDA) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy2( hypre_CSRMatrixMemoryLocation(A), hypre_CSRMatrixMemoryLocation(B) ); if (exec == HYPRE_EXEC_DEVICE) { C = hypre_CSRMatrixMultiplyDevice(A,B); } else #endif { C = hypre_CSRMatrixMultiplyHost(A,B); } return C; } hypre_CSRMatrix * hypre_CSRMatrixDeleteZeros( hypre_CSRMatrix *A, HYPRE_Real tol) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); hypre_CSRMatrix *B; HYPRE_Complex *B_data; HYPRE_Int *B_i; HYPRE_Int *B_j; HYPRE_Int zeros; HYPRE_Int i, j; HYPRE_Int pos_A, pos_B; zeros = 0; for (i=0; i < num_nonzeros; i++) if (hypre_cabs(A_data[i]) <= tol) zeros++; if (zeros) { B = hypre_CSRMatrixCreate(nrows_A,ncols_A,num_nonzeros-zeros); hypre_CSRMatrixInitialize(B); B_i = hypre_CSRMatrixI(B); B_j = hypre_CSRMatrixJ(B); B_data = hypre_CSRMatrixData(B); B_i[0] = 0; pos_A = 0; pos_B = 0; for (i=0; i < nrows_A; i++) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (hypre_cabs(A_data[j]) <= tol) { pos_A++; } else { B_data[pos_B] = A_data[pos_A]; B_j[pos_B] = A_j[pos_A]; pos_B++; pos_A++; } } B_i[i+1] = pos_B; } return B; } else return NULL; } /****************************************************************************** * * Finds transpose of a hypre_CSRMatrix * *****************************************************************************/ /** * idx = idx2*dim1 + idx1 * -> ret = idx1*dim2 + idx2 * = (idx%dim1)*dim2 + idx/dim1 */ static inline HYPRE_Int transpose_idx(HYPRE_Int idx, HYPRE_Int dim1, HYPRE_Int dim2) { return idx%dim1*dim2 + idx/dim1; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixTranspose *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixTransposeHost(hypre_CSRMatrix *A, hypre_CSRMatrix **AT, HYPRE_Int data) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); HYPRE_Int num_nonzerosA = hypre_CSRMatrixNumNonzeros(A); HYPRE_Complex *AT_data; /*HYPRE_Int *AT_i;*/ HYPRE_Int *AT_j; HYPRE_Int num_rowsAT; HYPRE_Int num_colsAT; HYPRE_Int num_nonzerosAT; HYPRE_Int max_col; HYPRE_Int i, j; HYPRE_MemoryLocation memory_location = hypre_CSRMatrixMemoryLocation(A); /*-------------------------------------------------------------- * First, ascertain that num_cols and num_nonzeros has been set. * If not, set them. *--------------------------------------------------------------*/ if (!num_nonzerosA) { num_nonzerosA = A_i[num_rowsA]; } if (num_rowsA && num_nonzerosA && ! num_colsA) { max_col = -1; for (i = 0; i < num_rowsA; ++i) { for (j = A_i[i]; j < A_i[i+1]; j++) { if (A_j[j] > max_col) { max_col = A_j[j]; } } } num_colsA = max_col+1; } num_rowsAT = num_colsA; num_colsAT = num_rowsA; num_nonzerosAT = num_nonzerosA; *AT = hypre_CSRMatrixCreate(num_rowsAT, num_colsAT, num_nonzerosAT); hypre_CSRMatrixMemoryLocation(*AT) = memory_location; if (0 == num_colsA) { // JSP: parallel counting sorting breaks down // when A has no columns hypre_CSRMatrixInitialize(*AT); return 0; } AT_j = hypre_CTAlloc(HYPRE_Int, num_nonzerosAT, memory_location); hypre_CSRMatrixJ(*AT) = AT_j; if (data) { AT_data = hypre_CTAlloc(HYPRE_Complex, num_nonzerosAT, memory_location); hypre_CSRMatrixData(*AT) = AT_data; } /*----------------------------------------------------------------- * Parallel count sort *-----------------------------------------------------------------*/ HYPRE_Int *bucket = hypre_TAlloc(HYPRE_Int, (num_colsA + 1)*hypre_NumThreads(), HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int num_threads = hypre_NumActiveThreads(); HYPRE_Int my_thread_num = hypre_GetThreadNum(); HYPRE_Int iBegin = hypre_CSRMatrixGetLoadBalancedPartitionBegin(A); HYPRE_Int iEnd = hypre_CSRMatrixGetLoadBalancedPartitionEnd(A); hypre_assert(iBegin <= iEnd); hypre_assert(iBegin >= 0 && iBegin <= num_rowsA); hypre_assert(iEnd >= 0 && iEnd <= num_rowsA); HYPRE_Int i, j; memset(bucket + my_thread_num*num_colsA, 0, sizeof(HYPRE_Int)*num_colsA); /*----------------------------------------------------------------- * Count the number of entries that will go into each bucket * bucket is used as HYPRE_Int[num_threads][num_colsA] 2D array *-----------------------------------------------------------------*/ for (j = A_i[iBegin]; j < A_i[iEnd]; ++j) { HYPRE_Int idx = A_j[j]; bucket[my_thread_num*num_colsA + idx]++; } /*----------------------------------------------------------------- * Parallel prefix sum of bucket with length num_colsA * num_threads * accessed as if it is transposed as HYPRE_Int[num_colsA][num_threads] *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = my_thread_num*num_colsA + 1; i < (my_thread_num + 1)*num_colsA; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); HYPRE_Int transpose_i_minus_1 = transpose_idx(i - 1, num_threads, num_colsA); bucket[transpose_i] += bucket[transpose_i_minus_1]; } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #pragma omp master #endif { for (i = 1; i < num_threads; ++i) { HYPRE_Int j0 = num_colsA*i - 1, j1 = num_colsA*(i + 1) - 1; HYPRE_Int transpose_j0 = transpose_idx(j0, num_threads, num_colsA); HYPRE_Int transpose_j1 = transpose_idx(j1, num_threads, num_colsA); bucket[transpose_j1] += bucket[transpose_j0]; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (my_thread_num > 0) { HYPRE_Int transpose_i0 = transpose_idx(num_colsA*my_thread_num - 1, num_threads, num_colsA); HYPRE_Int offset = bucket[transpose_i0]; for (i = my_thread_num*num_colsA; i < (my_thread_num + 1)*num_colsA - 1; ++i) { HYPRE_Int transpose_i = transpose_idx(i, num_threads, num_colsA); bucket[transpose_i] += offset; } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif /*---------------------------------------------------------------- * Load the data and column numbers of AT *----------------------------------------------------------------*/ if (data) { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_data[offset] = A_data[j]; AT_j[offset] = i; } } } else { for (i = iEnd - 1; i >= iBegin; --i) { for (j = A_i[i + 1] - 1; j >= A_i[i]; --j) { HYPRE_Int idx = A_j[j]; --bucket[my_thread_num*num_colsA + idx]; HYPRE_Int offset = bucket[my_thread_num*num_colsA + idx]; AT_j[offset] = i; } } } } /*end parallel region */ hypre_CSRMatrixI(*AT) = hypre_TAlloc(HYPRE_Int, num_colsA + 1, memory_location); hypre_TMemcpy(hypre_CSRMatrixI(*AT), bucket, HYPRE_Int, num_colsA + 1, memory_location, HYPRE_MEMORY_HOST); hypre_CSRMatrixI(*AT)[num_colsA] = num_nonzerosA; hypre_TFree(bucket, HYPRE_MEMORY_HOST); return (0); } HYPRE_Int hypre_CSRMatrixTranspose(hypre_CSRMatrix *A, hypre_CSRMatrix **AT, HYPRE_Int data) { HYPRE_Int ierr = 0; #if defined(HYPRE_USING_CUDA) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_CSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { ierr = hypre_CSRMatrixTransposeDevice(A, AT, data); } else #endif { ierr = hypre_CSRMatrixTransposeHost(A, AT, data); } return ierr; } /* RL: TODO add memory locations */ HYPRE_Int hypre_CSRMatrixSplit(hypre_CSRMatrix *Bs_ext, HYPRE_BigInt first_col_diag_B, HYPRE_BigInt last_col_diag_B, HYPRE_Int num_cols_offd_B, HYPRE_BigInt *col_map_offd_B, HYPRE_Int *num_cols_offd_C_ptr, HYPRE_BigInt **col_map_offd_C_ptr, hypre_CSRMatrix **Bext_diag_ptr, hypre_CSRMatrix **Bext_offd_ptr) { HYPRE_Complex *Bs_ext_data = hypre_CSRMatrixData(Bs_ext); HYPRE_Int *Bs_ext_i = hypre_CSRMatrixI(Bs_ext); HYPRE_BigInt *Bs_ext_j = hypre_CSRMatrixBigJ(Bs_ext); HYPRE_Int num_rows_Bext = hypre_CSRMatrixNumRows(Bs_ext); HYPRE_Int B_ext_diag_size = 0; HYPRE_Int B_ext_offd_size = 0; HYPRE_Int *B_ext_diag_i = NULL; HYPRE_Int *B_ext_diag_j = NULL; HYPRE_Complex *B_ext_diag_data = NULL; HYPRE_Int *B_ext_offd_i = NULL; HYPRE_Int *B_ext_offd_j = NULL; HYPRE_Complex *B_ext_offd_data = NULL; HYPRE_Int *my_diag_array; HYPRE_Int *my_offd_array; HYPRE_BigInt *temp; HYPRE_Int max_num_threads; HYPRE_Int cnt = 0; hypre_CSRMatrix *Bext_diag = NULL; hypre_CSRMatrix *Bext_offd = NULL; HYPRE_BigInt *col_map_offd_C = NULL; HYPRE_Int num_cols_offd_C = 0; B_ext_diag_i = hypre_CTAlloc(HYPRE_Int, num_rows_Bext+1, HYPRE_MEMORY_HOST); B_ext_offd_i = hypre_CTAlloc(HYPRE_Int, num_rows_Bext+1, HYPRE_MEMORY_HOST); max_num_threads = hypre_NumThreads(); my_diag_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); my_offd_array = hypre_CTAlloc(HYPRE_Int, max_num_threads, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel #endif { HYPRE_Int size, rest, ii; HYPRE_Int ns, ne; HYPRE_Int i1, i, j; HYPRE_Int my_offd_size, my_diag_size; HYPRE_Int cnt_offd, cnt_diag; HYPRE_Int num_threads = hypre_NumActiveThreads(); size = num_rows_Bext/num_threads; rest = num_rows_Bext - size*num_threads; ii = hypre_GetThreadNum(); if (ii < rest) { ns = ii*size+ii; ne = (ii+1)*size+ii+1; } else { ns = ii*size+rest; ne = (ii+1)*size+rest; } my_diag_size = 0; my_offd_size = 0; for (i=ns; i < ne; i++) { B_ext_diag_i[i] = my_diag_size; B_ext_offd_i[i] = my_offd_size; for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { my_offd_size++; } else { my_diag_size++; } } } my_diag_array[ii] = my_diag_size; my_offd_array[ii] = my_offd_size; #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii) { my_diag_size = my_diag_array[0]; my_offd_size = my_offd_array[0]; for (i1 = 1; i1 < ii; i1++) { my_diag_size += my_diag_array[i1]; my_offd_size += my_offd_array[i1]; } for (i1 = ns; i1 < ne; i1++) { B_ext_diag_i[i1] += my_diag_size; B_ext_offd_i[i1] += my_offd_size; } } else { B_ext_diag_size = 0; B_ext_offd_size = 0; for (i1 = 0; i1 < num_threads; i1++) { B_ext_diag_size += my_diag_array[i1]; B_ext_offd_size += my_offd_array[i1]; } B_ext_diag_i[num_rows_Bext] = B_ext_diag_size; B_ext_offd_i[num_rows_Bext] = B_ext_offd_size; if (B_ext_diag_size) { B_ext_diag_j = hypre_CTAlloc(HYPRE_Int, B_ext_diag_size, HYPRE_MEMORY_HOST); B_ext_diag_data = hypre_CTAlloc(HYPRE_Complex, B_ext_diag_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size) { B_ext_offd_j = hypre_CTAlloc(HYPRE_Int, B_ext_offd_size, HYPRE_MEMORY_HOST); B_ext_offd_data = hypre_CTAlloc(HYPRE_Complex, B_ext_offd_size, HYPRE_MEMORY_HOST); } if (B_ext_offd_size || num_cols_offd_B) { temp = hypre_CTAlloc(HYPRE_BigInt, B_ext_offd_size + num_cols_offd_B, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif cnt_offd = B_ext_offd_i[ns]; cnt_diag = B_ext_diag_i[ns]; for (i = ns; i < ne; i++) { for (j = Bs_ext_i[i]; j < Bs_ext_i[i+1]; j++) { if (Bs_ext_j[j] < first_col_diag_B || Bs_ext_j[j] > last_col_diag_B) { temp[cnt_offd] = Bs_ext_j[j]; B_ext_offd_j[cnt_offd] = Bs_ext_j[j]; B_ext_offd_data[cnt_offd++] = Bs_ext_data[j]; } else { B_ext_diag_j[cnt_diag] = Bs_ext_j[j] - first_col_diag_B; B_ext_diag_data[cnt_diag++] = Bs_ext_data[j]; } } } /* This computes the mappings */ #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif if (ii == 0) { cnt = 0; if (B_ext_offd_size || num_cols_offd_B) { cnt = B_ext_offd_size; for (i=0; i < num_cols_offd_B; i++) { temp[cnt++] = col_map_offd_B[i]; } if (cnt) { hypre_BigQsort0(temp, 0, cnt-1); num_cols_offd_C = 1; HYPRE_BigInt value = temp[0]; for (i = 1; i < cnt; i++) { if (temp[i] > value) { value = temp[i]; temp[num_cols_offd_C++] = value; } } } if (num_cols_offd_C) { col_map_offd_C = hypre_CTAlloc(HYPRE_BigInt, num_cols_offd_C, HYPRE_MEMORY_HOST); } for (i = 0; i < num_cols_offd_C; i++) { col_map_offd_C[i] = temp[i]; } hypre_TFree(temp, HYPRE_MEMORY_HOST); } } #ifdef HYPRE_USING_OPENMP #pragma omp barrier #endif for (i = ns; i < ne; i++) { for (j = B_ext_offd_i[i]; j < B_ext_offd_i[i+1]; j++) { B_ext_offd_j[j] = hypre_BigBinarySearch(col_map_offd_C, B_ext_offd_j[j], num_cols_offd_C); } } } /* end parallel region */ hypre_TFree(my_diag_array, HYPRE_MEMORY_HOST); hypre_TFree(my_offd_array, HYPRE_MEMORY_HOST); Bext_diag = hypre_CSRMatrixCreate(num_rows_Bext, last_col_diag_B-first_col_diag_B+1, B_ext_diag_size); hypre_CSRMatrixMemoryLocation(Bext_diag) = HYPRE_MEMORY_HOST; Bext_offd = hypre_CSRMatrixCreate(num_rows_Bext, num_cols_offd_C, B_ext_offd_size); hypre_CSRMatrixMemoryLocation(Bext_offd) = HYPRE_MEMORY_HOST; hypre_CSRMatrixI(Bext_diag) = B_ext_diag_i; hypre_CSRMatrixJ(Bext_diag) = B_ext_diag_j; hypre_CSRMatrixData(Bext_diag) = B_ext_diag_data; hypre_CSRMatrixI(Bext_offd) = B_ext_offd_i; hypre_CSRMatrixJ(Bext_offd) = B_ext_offd_j; hypre_CSRMatrixData(Bext_offd) = B_ext_offd_data; *col_map_offd_C_ptr = col_map_offd_C; *Bext_diag_ptr = Bext_diag; *Bext_offd_ptr = Bext_offd; *num_cols_offd_C_ptr = num_cols_offd_C; return hypre_error_flag; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixReorder: * Reorders the column and data arrays of a square CSR matrix, such that the * first entry in each row is the diagonal one. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixReorder(hypre_CSRMatrix *A) { HYPRE_Int i, j, tempi, row_size; HYPRE_Complex tempd; HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rowsA = hypre_CSRMatrixNumRows(A); HYPRE_Int num_colsA = hypre_CSRMatrixNumCols(A); /* the matrix should be square */ if (num_rowsA != num_colsA) return -1; for (i = 0; i < num_rowsA; i++) { row_size = A_i[i+1]-A_i[i]; for (j = 0; j < row_size; j++) { if (A_j[j] == i) { if (j != 0) { tempi = A_j[0]; A_j[0] = A_j[j]; A_j[j] = tempi; tempd = A_data[0]; A_data[0] = A_data[j]; A_data[j] = tempd; } break; } /* diagonal element is missing */ if (j == row_size-1) return -2; } A_j += row_size; A_data += row_size; } return 0; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixAddPartial: * adds matrix rows in the CSR matrix B to the CSR Matrix A, where row_nums[i] * defines to which row of A the i-th row of B is added, and returns a CSR Matrix C; * Note: The routine does not check for 0-elements which might be generated * through cancellation of elements in A and B or already contained * in A and B. To remove those, use hypre_CSRMatrixDeleteZeros *--------------------------------------------------------------------------*/ hypre_CSRMatrix * hypre_CSRMatrixAddPartial( hypre_CSRMatrix *A, hypre_CSRMatrix *B, HYPRE_Int *row_nums) { HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int nrows_A = hypre_CSRMatrixNumRows(A); HYPRE_Int ncols_A = hypre_CSRMatrixNumCols(A); HYPRE_Complex *B_data = hypre_CSRMatrixData(B); HYPRE_Int *B_i = hypre_CSRMatrixI(B); HYPRE_Int *B_j = hypre_CSRMatrixJ(B); HYPRE_Int nrows_B = hypre_CSRMatrixNumRows(B); HYPRE_Int ncols_B = hypre_CSRMatrixNumCols(B); hypre_CSRMatrix *C; HYPRE_Complex *C_data; HYPRE_Int *C_i; HYPRE_Int *C_j; HYPRE_Int ia, ib, ic, jcol, num_nonzeros; HYPRE_Int pos, i, i2, j, cnt; HYPRE_Int *marker; HYPRE_Int *map; HYPRE_Int *temp; HYPRE_MemoryLocation memory_location_A = hypre_CSRMatrixMemoryLocation(A); HYPRE_MemoryLocation memory_location_B = hypre_CSRMatrixMemoryLocation(B); /* RL: TODO cannot guarantee, maybe should never assert hypre_assert(memory_location_A == memory_location_B); */ /* RL: in the case of A=H, B=D, or A=D, B=H, let C = D, * not sure if this is the right thing to do. * Also, need something like this in other places * TODO */ HYPRE_MemoryLocation memory_location_C = hypre_max(memory_location_A, memory_location_B); if (ncols_A != ncols_B) { hypre_error_w_msg(HYPRE_ERROR_GENERIC,"Warning! incompatible matrix dimensions!\n"); return NULL; } map = hypre_CTAlloc(HYPRE_Int, nrows_B, HYPRE_MEMORY_HOST); temp = hypre_CTAlloc(HYPRE_Int, nrows_B, HYPRE_MEMORY_HOST); for (i=0; i < nrows_B; i++) { map[i] = i; temp[i] = row_nums[i]; } hypre_qsort2i(temp,map,0,nrows_B-1); marker = hypre_CTAlloc(HYPRE_Int, ncols_A, HYPRE_MEMORY_HOST); C_i = hypre_CTAlloc(HYPRE_Int, nrows_A+1, memory_location_C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } num_nonzeros = 0; C_i[0] = 0; cnt = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; marker[jcol] = ic; num_nonzeros++; } if (cnt < nrows_B && temp[cnt] == ic) { for (j = cnt; j < nrows_B; j++) { if (temp[j] == ic) { i2 = map[cnt++]; for (ib = B_i[i2]; ib < B_i[i2+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] != ic) { marker[jcol] = ic; num_nonzeros++; } } } else { break; } } } C_i[ic+1] = num_nonzeros; } C = hypre_CSRMatrixCreate(nrows_A, ncols_A, num_nonzeros); hypre_CSRMatrixI(C) = C_i; hypre_CSRMatrixInitialize_v2(C, 0, memory_location_C); C_j = hypre_CSRMatrixJ(C); C_data = hypre_CSRMatrixData(C); for (ia = 0; ia < ncols_A; ia++) { marker[ia] = -1; } cnt = 0; pos = 0; for (ic = 0; ic < nrows_A; ic++) { for (ia = A_i[ic]; ia < A_i[ic+1]; ia++) { jcol = A_j[ia]; C_j[pos] = jcol; C_data[pos] = A_data[ia]; marker[jcol] = pos; pos++; } if (cnt < nrows_B && temp[cnt] == ic) { for (j = cnt; j < nrows_B; j++) { if (temp[j] == ic) { i2 = map[cnt++]; for (ib = B_i[i2]; ib < B_i[i2+1]; ib++) { jcol = B_j[ib]; if (marker[jcol] < C_i[ic]) { C_j[pos] = jcol; C_data[pos] = B_data[ib]; marker[jcol] = pos; pos++; } else { C_data[marker[jcol]] += B_data[ib]; } } } else { break; } } } } hypre_TFree(marker, HYPRE_MEMORY_HOST); hypre_TFree(map, HYPRE_MEMORY_HOST); hypre_TFree(temp, HYPRE_MEMORY_HOST); return C; } /*-------------------------------------------------------------------------- * hypre_CSRMatrixSumElts: * Returns the sum of all matrix elements. *--------------------------------------------------------------------------*/ HYPRE_Complex hypre_CSRMatrixSumElts( hypre_CSRMatrix *A ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_CSRMatrixData( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i; for ( i = 0; i < num_nonzeros; ++i ) { sum += data[i]; } return sum; } HYPRE_Real hypre_CSRMatrixFnorm( hypre_CSRMatrix *A ) { HYPRE_Complex sum = 0; HYPRE_Complex *data = hypre_CSRMatrixData( A ); HYPRE_Int num_nonzeros = hypre_CSRMatrixNumNonzeros(A); HYPRE_Int i, nrows, *A_i; nrows = hypre_CSRMatrixNumRows(A); A_i = hypre_CSRMatrixI(A); hypre_assert(num_nonzeros == A_i[nrows]); for ( i = 0; i < num_nonzeros; ++i ) { HYPRE_Complex v = data[i]; sum += v * v; } return sqrt(sum); } /* type == 0, sum, * 1, abs sum * 2, square sum */ void hypre_CSRMatrixComputeRowSumHost( hypre_CSRMatrix *A, HYPRE_Int *CF_i, HYPRE_Int *CF_j, HYPRE_Complex *row_sum, HYPRE_Int type, HYPRE_Complex scal, const char *set_or_add) { HYPRE_Int nrows = hypre_CSRMatrixNumRows(A); HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int i, j; for (i = 0; i < nrows; i++) { HYPRE_Complex row_sum_i = set_or_add[0] == 's' ? 0.0 : row_sum[i]; for (j = A_i[i]; j < A_i[i+1]; j++) { if (CF_i && CF_j && CF_i[i] != CF_j[A_j[j]]) { continue; } if (type == 0) { row_sum_i += scal * A_data[j]; } else if (type == 1) { row_sum_i += scal * fabs(A_data[j]); } else if (type == 2) { row_sum_i += scal * A_data[j] * A_data[j]; } } row_sum[i] = row_sum_i; } } void hypre_CSRMatrixComputeRowSum( hypre_CSRMatrix *A, HYPRE_Int *CF_i, HYPRE_Int *CF_j, HYPRE_Complex *row_sum, HYPRE_Int type, HYPRE_Complex scal, const char *set_or_add) { hypre_assert( (CF_i && CF_j) || (!CF_i && !CF_j) ); #if defined(HYPRE_USING_CUDA) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_CSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { hypre_CSRMatrixComputeRowSumDevice(A, CF_i, CF_j, row_sum, type, scal, set_or_add); } else #endif { hypre_CSRMatrixComputeRowSumHost(A, CF_i, CF_j, row_sum, type, scal, set_or_add); } } void hypre_CSRMatrixExtractDiagonalHost( hypre_CSRMatrix *A, HYPRE_Complex *d, HYPRE_Int type) { HYPRE_Int nrows = hypre_CSRMatrixNumRows(A); HYPRE_Complex *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int i, j; HYPRE_Complex d_i; for (i = 0; i < nrows; i++) { d_i = 0.0; for (j = A_i[i]; j < A_i[i+1]; j++) { if (A_j[j] == i) { if (type == 0) { d_i = A_data[j]; } else if (type == 1) { d_i = fabs(A_data[j]); } break; } } d[i] = d_i; } } /* type 0: diag * 1: abs diag */ void hypre_CSRMatrixExtractDiagonal( hypre_CSRMatrix *A, HYPRE_Complex *d, HYPRE_Int type) { #if defined(HYPRE_USING_CUDA) HYPRE_ExecutionPolicy exec = hypre_GetExecPolicy1( hypre_CSRMatrixMemoryLocation(A) ); if (exec == HYPRE_EXEC_DEVICE) { hypre_CSRMatrixExtractDiagonalDevice(A, d, type); } else #endif { hypre_CSRMatrixExtractDiagonalHost(A, d, type); } }
task-barrier.c
/* * task-barrier.c -- Archer testcase */ //===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // // See tools/archer/LICENSE.txt for details. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // RUN: %libarcher-compile-and-run | FileCheck %s // REQUIRES: tsan #include <omp.h> #include <stdio.h> #include <unistd.h> #include "ompt/ompt-signal.h" int main(int argc, char *argv[]) { int var = 0, a = 0; #pragma omp parallel num_threads(2) shared(var, a) { #pragma omp master { #pragma omp task shared(var) { OMPT_SIGNAL(a); var++; } // Give other thread time to steal the task. OMPT_WAIT(a, 1); } #pragma omp barrier #pragma omp master { var++; } } fprintf(stderr, "DONE\n"); int error = (var != 2); return error; } // CHECK-NOT: ThreadSanitizer: data race // CHECK-NOT: ThreadSanitizer: reported // CHECK: DONE
snoop.c
/* Last changed Time-stamp: <2007-08-26 11:59:45 ivo> */ /* compute the duplex structure of two RNA strands, allowing only inter-strand base pairs. see cofold() for computing hybrid structures without restriction. Ivo Hofacker Vienna RNA package */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> #include "utils.h" #include "energy_par.h" #include "fold_vars.h" #include "snofold.h" #include "pair_mat.h" #include "params.h" #include "snoop.h" #include "PS_dot.h" /* #include "fold.h" */ #include "duplex.h" #include "loop_energies.h" /*@unused@*/ static char rcsid[] UNUSED = "$Id: duplex.c,v 1.8 2007/08/26 10:08:44 ivo Exp $"; #define UNIT 100 #define MINPSCORE -2*UNIT #define PUBLIC #define PRIVATE static #define STACK_BULGE1 1 /* stacking energies for bulges of size 1 */ #define NEW_NINIO 1 /* new asymetry penalty */ PRIVATE void encode_seqs(const char *s1, const char *s2); PRIVATE short *encode_seq(const char *seq); PRIVATE void find_max_snoop(const char *s1, const char *s2, const int max, const int alignment_length, const int* position, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char* name, const int fullStemEnergy); PRIVATE void find_max_snoop_XS(const char *s1, const char *s2, const int **access_s1, const int max, const int alignment_length, const int* position, const int *position_j, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy); PRIVATE char * alisnoop_backtrack(int i, int j, const char ** s2, int* Duplex_El, int* Duplex_Er, int* Loop_E, int *Loop_D, int *u, int *pscd, int *psct, int *pscg, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const short **S1, const short **S2); PRIVATE char * snoop_backtrack(int i, int j, const char* s2, int* Duplex_El, int* Duplex_Er, int* Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2); PRIVATE char * snoop_backtrack_XS(int i, int j, const char* s2, int* Duplex_El, int* Duplex_Er, int* Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2); PRIVATE int compare(const void *sub1, const void *sub2); PRIVATE int covscore(const int *types, int n_seq); PRIVATE short * aliencode_seq(const char *sequence); PUBLIC int snoop_subopt_sorted=0; /* from subopt.c, default 0 */ /*@unused@*/ #define MAXLOOP_L 3 #define MIN2(A, B) ((A) < (B) ? (A) : (B)) #define MAX2(A, B) ((A) > (B) ? (A) : (B)) #define ASS 1 PRIVATE paramT *P = NULL; PRIVATE int **c = NULL; /* energy array, given that i-j pair */ PRIVATE int **r = NULL; PRIVATE int **lc = NULL; /* energy array, given that i-j pair */ PRIVATE int **lr = NULL; PRIVATE int **c_fill = NULL; PRIVATE int **r_fill = NULL; PRIVATE int **lpair = NULL; PRIVATE short *S1 = NULL, *SS1 = NULL, *S2 = NULL, *SS2 = NULL; PRIVATE short *S1_fill = NULL, *SS1_fill = NULL, *S2_fill = NULL, *SS2_fill = NULL; PRIVATE int n1,n2; /* sequence lengths */ extern int cut_point; PRIVATE int delay_free=0; /*--------------------------------------------------------------------------*/ snoopT alisnoopfold(const char **s1, const char **s2, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { int s,n_seq; int i, j, E, l1,Emin=INF, i_min=0, j_min=0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden **foldlist; folden **foldlist_XS; int Duplex_El, Duplex_Er,pscd,psct,pscg; int Loop_D; int u; int Loop_E; short **Sali1,**Sali2; int *type,*type2,*type3; Duplex_El=0;Duplex_Er=0;Loop_E=0; Loop_D=0;pscd=0;psct=0;pscg=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS); n1 = (int) strlen(s1[0]); n2 = (int) strlen(s2[0]); for (s=0; s1[s]!=NULL; s++); n_seq = s; for (s=0; s2[s]!=NULL; s++); if (n_seq != s) nrerror("unequal number of sequences in aliduplexfold()\n"); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } c = (int **) space(sizeof(int *) * (n1+1)); r = (int **) space(sizeof(int *) * (n1+1)); for (i=0; i<=n1; i++) { c[i] = (int *) space(sizeof(int) * (n2+1)); r[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ c[i][j]=INF; r[i][j]=INF; } } Sali1 = (short **) space((n_seq+1)*sizeof(short *)); Sali2 = (short **) space((n_seq+1)*sizeof(short *)); for (s=0; s<n_seq; s++) { if (strlen(s1[s]) != n1) nrerror("uneqal seqence lengths"); if (strlen(s2[s]) != n2) nrerror("uneqal seqence lengths"); Sali1[s] = aliencode_seq(s1[s]); Sali2[s] = aliencode_seq(s2[s]); } type = (int *) space(n_seq*sizeof(int)); type2 = (int *) space(n_seq*sizeof(int)); type3 = (int *) space(n_seq*sizeof(int)); /* encode_seqs(s1, s2); */ for (i=6; i<=n1-5; i++) { int U; U=0; for (s=0; s<n_seq; s++) { U+=Sali1[s][i-2]; } U = (U==(n_seq)*4?1:0); for (j=n2-min_d2; j>min_d1; j--) { int type4, k,l,psc,psc2,psc3; for (s=0; s<n_seq; s++) { type[s] = pair[Sali1[s][i]][Sali2[s][j]]; } psc = covscore(type, n_seq); for (s=0; s<n_seq; s++) if (type[s]==0) type[s]=7; c[i][j] = (psc>=MINPSCORE) ? (n_seq*P->DuplexInit) : INF; if (psc<MINPSCORE) continue; if(/* pair[Sali1[i+1]][Sali2[j-1]] && */ U && j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem ) { /*constraint on s2 and i*/ folden *temp; temp=foldlist[j+1]; while(temp->next){ int k = temp->k; for (s=0; s<n_seq; s++) { type2[s]= pair[Sali1[s][i-3]][Sali2[s][k+1]]; type3[s]= pair[Sali1[s][i-4]][Sali2[s][k+1]]; } psc2 = covscore(type2, n_seq); psc3 = covscore(type3, n_seq); if(psc2 > MINPSCORE){ r[i][j]=MIN2(r[i][j],c[i-3][k+1]+temp->energy); } if(psc3 > MINPSCORE){ r[i][j]=MIN2(r[i][j],c[i-4][k+1]+temp->energy); } temp=temp->next; } } /* dangle 5'SIDE relative to the mRNA */ for (s=0; s<n_seq; s++) { c[i][j] += E_ExtLoop(type[s], Sali1[s][i-1],Sali2[s][j+1],P); } for (k=i-1; k>0 && (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2 ; l++) { if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS ) continue; for (E=s=0; s<n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4==0) type4=7; E += E_IntLoop(i-k-1, l-j-1, type4, rtype[type[s]], Sali1[s][k+1], Sali2[s][l-1], Sali1[s][i-1], Sali2[s][j+1],P); } c[i][j] = MIN2(c[i][j], c[k][l] + E); r[i][j] = MIN2(r[i][j], r[k][l] + E); } } c[i][j]-=psc; r[i][j]-=psc; E = r[i][j]; for (s=0; s<n_seq; s++) { E+= E_ExtLoop(rtype[type[s]], Sali2[s][j-1], Sali1[s][i+1], P); /** *** if (i<n1) E += P->dangle3[rtype[type[s]]][Sali1[s][i+1]]; *** if (j>1) E += P->dangle5[rtype[type[s]]][Sali2[s][j-1]]; *** if (type[s]>2) E += P->TerminalAU; **/ } if (E<Emin) { Emin=E; i_min=i; j_min=j; } } } if(Emin > 0){ printf("no target found under the constraints chosen\n"); for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); for(s=0; s<n_seq;s++){ free(Sali1[s]); free(Sali2[s]); } free(Sali1); free(Sali2); free(S2); free(SS1); free(SS2);free(type);free(type2);free(type3); mfe.energy=INF; mfe.structure=NULL; return mfe; } struc = alisnoop_backtrack(i_min, j_min,(const char**) s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, &pscd, &psct, &pscg, penalty, threshloop, threshLE, threshRE,threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,(const short**) Sali1,(const short**) Sali2); /* if (i_min<n1-5) i_min++; */ /* if (j_min>6 ) j_min--; */ l1 = strchr(struc, '&')-struc; mfe.i = i_min-5; mfe.j = j_min-5; mfe.u = u -5; mfe.Duplex_Er = (float) Duplex_Er/100; mfe.Duplex_El = (float) Duplex_El/100; mfe.Loop_D = (float) Loop_D/100; mfe.Loop_E = (float) Loop_E/100; mfe.energy = (float) Emin/100 ; /* mfe.fullStemEnergy = (float) fullStemEnergy/100; */ mfe.pscd = pscd; mfe.psct = psct; mfe.structure = struc; for(s=0; s<n_seq;s++){ free(Sali1[s]);free(Sali2[s]); } free(Sali1);free(Sali2);free(type);free(type2);free(type3); if (!delay_free) { for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); free(S2); free(SS1); free(SS2); } return mfe; } PUBLIC snoopT *alisnoop_subopt(const char **s1, const char **s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { short **Sali1, **Sali2; /* printf("%d %d\n", min_s2, max_s2); */ int i,j,s,n_seq, n1, n2, E, n_subopt=0, n_max; char *struc; snoopT mfe; snoopT *subopt; int thresh; int *type; int Duplex_El, Duplex_Er, Loop_E,pscd,psct,pscg; int Loop_D; Duplex_El=0; Duplex_Er=0; Loop_E=0;Loop_D=0;pscd=0;psct=0;pscg=0; int u; u=0; n_max=16; subopt = (snoopT *) space(n_max*sizeof(snoopT)); delay_free=1; mfe = alisnoopfold(s1, s2, penalty, threshloop, threshLE, threshRE, threshDE,threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if(mfe.energy > 0){ free(subopt); delay_free=0; return NULL; } thresh = MIN2((int) ((mfe.Duplex_Er + mfe.Duplex_El + mfe.Loop_E)*100+0.1 + 410) + delta, threshTE ); /* subopt[n_subopt++]=mfe; */ free(mfe.structure); n1 = strlen(s1[0]); n2 = strlen(s2[0]); for (s=0; s1[s]!=NULL; s++); n_seq = s; Sali1 = (short **) space((n_seq+1)*sizeof(short *)); Sali2 = (short **) space((n_seq+1)*sizeof(short *)); for (s=0; s<n_seq; s++) { if (strlen(s1[s]) != n1) nrerror("uneqal seqence lengths"); if (strlen(s2[s]) != n2) nrerror("uneqal seqence lengths"); Sali1[s] = aliencode_seq(s1[s]); Sali2[s] = aliencode_seq(s2[s]); } Sali1[n_seq]=NULL; Sali2[n_seq]=NULL; type = (int *) space(n_seq*sizeof(int)); for (i=n1; i>1; i--){ for (j=1; j<=n2; j++) { int ii,jj, Ed,psc,skip; for (s=0; s<n_seq; s++) { type[s] = pair[Sali2[s][j]][Sali1[s][i]]; } psc = covscore(type, n_seq); for (s=0; s<n_seq; s++) if (type[s]==0) type[s]=7; if (psc<MINPSCORE) continue; E = Ed = r[i][j]; for (s=0; s<n_seq; s++) { /* if (i<n1-5) Ed += P->dangle3[type[s]][Sali1[s][i+1]]; */ /* if (j>6) Ed += P->dangle5[type[s]][Sali2[s][j-1]]; */ if (type[s]>2) Ed += P->TerminalAU; } if (Ed>thresh) continue; /* too keep output small, remove hits that are dominated by a better one close (w) by. For simplicity we do test without adding dangles, which is slightly inaccurate. */ w=1; for (skip=0, ii=MAX2(i-w,1); (ii<=MIN2(i+w,n1)) && type; ii++) { for (jj=MAX2(j-w,1); jj<=MIN2(j+w,n2); jj++) if (r[ii][jj]<E) {skip=1; break;} } if (skip){continue;} psct=0; pscg=0; struc = alisnoop_backtrack(i,j,s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, &pscd, &psct,&pscg, penalty, threshloop,threshLE,threshRE,threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,(const short int**) Sali1,(const int short **) Sali2); if (Duplex_Er > threshRE || Duplex_El > threshLE || Loop_D > threshD || (Duplex_Er + Duplex_El) > threshDE || (Duplex_Er + Duplex_El + Loop_E) > threshTE || (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) > threshSE) { /* printf(" Duplex_Er %d threshRE %d Duplex_El %d threshLE %d \n" */ /* " Duplex_Er + Duplex_El %d threshDE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E %d threshTE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E + Loop_D %d threshSE %d \n", */ /* Duplex_Er , threshRE , Duplex_El ,threshLE, */ /* Duplex_Er + Duplex_El, threshDE, */ /* Duplex_Er + Duplex_El+ Loop_E , threshTE, */ /* Duplex_Er + Duplex_El+ Loop_E + Loop_D, threshSE); */ Duplex_Er=0; Duplex_El=0; Loop_E = 0; Loop_D = 0; u=0, free(struc); continue; } if (n_subopt+1>=n_max) { n_max *= 2; subopt = (snoopT *) xrealloc(subopt, n_max*sizeof(snoopT)); } subopt[n_subopt].i = i-5; subopt[n_subopt].j = j-5; subopt[n_subopt].u = u-5; subopt[n_subopt].Duplex_Er = Duplex_Er * 0.01; subopt[n_subopt].Duplex_El = Duplex_El * 0.01; subopt[n_subopt].Loop_E = Loop_E * 0.01; subopt[n_subopt].Loop_D = Loop_D * 0.01; subopt[n_subopt].energy = (Duplex_Er +Duplex_El + Loop_E + Loop_D + 410) * 0.01 ; subopt[n_subopt].pscd = pscd * 0.01; subopt[n_subopt].psct = -psct * 0.01; subopt[n_subopt++].structure = struc; /* i=u; */ Duplex_Er=0; Duplex_El=0; Loop_E=0; Loop_D=0;u=0;pscd=0;psct=0; } } for (i=0; i<=n1; i++) {free(c[i]);free(r[i]);} free(c);free(r); for (s=0; s<n_seq; s++) { free(Sali1[s]); free(Sali2[s]); } free(Sali1); free(Sali2); free(type); if (snoop_subopt_sorted) qsort(subopt, n_subopt, sizeof(snoopT), compare); subopt[n_subopt].i =0; subopt[n_subopt].j =0; subopt[n_subopt].structure = NULL; return subopt; } PRIVATE char *alisnoop_backtrack(int i, int j, const char ** snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, int *pscd, int *psct, int *pscg, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2,const short **Sali1, const short **Sali2) { /* backtrack structure going backwards from i, and forwards from j return structure in bracket notation with & as separator */ int k, l, *type,*type2,*type3,type4, E, traced, i0, j0,s,n_seq,psc; int traced_r=0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; n1 = (int) Sali1[0][0]; n2 = (int) Sali2[0][0]; for (s=0; Sali1[s]!=NULL; s++); n_seq = s; for (s=0; Sali2[s]!=NULL; s++); if (n_seq != s) nrerror("unequal number of sequences in alibacktrack()\n"); st1 = (char *) space(sizeof(char)*(n1+1)); st2 = (char *) space(sizeof(char)*(n2+1)); type = (int *) space(n_seq*sizeof(int)); type2 = (int *) space(n_seq*sizeof(int)); type3 = (int *) space(n_seq*sizeof(int)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); i0=i; j0=j; /* MIN2(i+1,n1); j0=MAX2(j-1,1);!modified */ for (s=0; s<n_seq; s++) { type[s] = pair[Sali1[s][i]][Sali2[s][j]]; if(type[s]==0) type[s] = 7; *Duplex_Er += E_ExtLoop(rtype[type[s]], (j>1) ? Sali2[s][j-1] : -1, (i<n1) ? Sali1[s][i+1] : -1, P); /** *** if (i<n1) *Duplex_Er += P->dangle3[rtype[type[s]]][Sali1[s][i+1]]; *** if (j>1) *Duplex_Er += P->dangle5[rtype[type[s]]][Sali2[s][j-1]]; *** if (type[s]>2) *Duplex_Er += P->TerminalAU; **/ } while (i>0 && j<=n2-min_d2 ) { if(!traced_r) { E = r[i][j]; traced=0; st1[i-1] = '<'; st2[j-1] = '>'; for (s=0; s<n_seq; s++) { type[s] = pair[Sali1[s][i]][Sali2[s][j]]; } psc = covscore(type,n_seq); for (s=0; s<n_seq; s++) if (type[s]==0) type[s] = 7; E += psc; *pscd +=psc; for (k=i-1; k>0 && (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2 ; l++) { int LE; if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS) continue; for (s=LE=0; s<n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4==0) type4=7; LE += E_IntLoop(i-k-1, l-j-1, type4, rtype[type[s]], Sali1[s][k+1], Sali2[s][l-1], Sali1[s][i-1], Sali2[s][j+1],P); } if (E == r[k][l]+LE) { traced=1; i=k; j=l; *Duplex_Er+=LE; break; } } if (traced) break; } if(!traced){ int U=0; for (s=0; s<n_seq; s++) { U+=Sali1[s][i-2]; } U = (U==(n_seq)*4?1:0); if(/* pair[Sali1[i+1]][Sali2[j-1]] && */ /* only U's are allowed */ U && j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem ) { int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem+1); min_k = MAX2(j+half_stem+1, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next) { int psc2, psc3; int k = temp->k; for (s=0; s<n_seq; s++) { type2[s]= pair[Sali1[s][i-3]][Sali2[s][k+1]]; type3[s]= pair[Sali1[s][i-4]][Sali2[s][k+1]]; } psc2 = covscore(type2, n_seq); psc3 = covscore(type3, n_seq); if(psc2>MINPSCORE /*&& pair[Sali1[i-4]][Sali2[k+2]]*/ ){ /* introduce structure from RNAfold */ if(E==c[i-3][k+1]+temp->energy){ *Loop_E=temp->energy; st1[i-3]= '|'; *u=i-2; int a,b; /* int fix_ij=indx[k-1+1]+j+1; */ for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[k-1-a+1]+j+1+b; if(cLoop[ij]==temp->energy) { /* int bla; */ struc_loop=alisnobacktrack_fold_from_pair(snoseq, j+1+b, k-a-1+1,psct); a=INF; b=INF; } } } traced=1; traced_r=1; i=i-3;j=k+1; break; } } if (psc3>MINPSCORE /*&& pair[Sali1[i-5]][Sali2[k+2]]*/){ /* introduce structure from RNAfold */ if(E==c[i-4][k+1]+temp->energy){ *Loop_E=temp->energy; st1[i-3]= '|'; *u=i-2; int a,b; /* int fix_ij=indx[k-1+1]+j+1; */ for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[k-1-a+1]+j+1+b; if(cLoop[ij]==temp->energy) { /* int bla; */ struc_loop=alisnobacktrack_fold_from_pair(snoseq, j+1+b, k-a-1+1,psct); a=INF; b=INF; } } } traced=1; traced_r=1; i=i-4;j=k+1; break; } } /* else if */ temp=temp->next; } /* while temp-> next */ } /* test on j */ }/* traced? */ }/* traced_r? */ else{ E = c[i][j]; traced=0; st1[i-1] = '<'; st2[j-1] = '>'; for (s=0; s<n_seq; s++) { type[s] = pair[Sali1[s][i]][Sali2[s][j]]; } psc = covscore(type,n_seq); for (s=0; s<n_seq; s++) if (type[s]==0) type[s] = 7; E += psc; *pscd+=psc; if (!type) nrerror("backtrack failed in fold duplex c"); for (k=i-1; (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2; l++) { int LE; if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS) continue; for (s=LE=0; s<n_seq; s++) { type4 = pair[Sali1[s][k]][Sali2[s][l]]; if (type4==0) type4=7; LE += E_IntLoop(i-k-1, l-j-1, type4, rtype[type[s]], Sali1[s][k+1], Sali2[s][l-1], Sali1[s][i-1], Sali2[s][j+1],P); } if (E == c[k][l]+LE) { traced=1; i=k; j=l; *Duplex_El+=LE; break; } } if (traced) break; } } if (!traced) { for (s=0; s<n_seq; s++) { int correction; correction = E_ExtLoop(type[s], (i>1) ? Sali1[s][i-1] : -1, (j<n2) ? Sali2[s][j+1] : -1, P); *Duplex_El += correction; E -= correction; /** *** if (i>1) {E -= P->dangle5[type[s]][Sali1[s][i-1]]; *Duplex_El +=P->dangle5[type[s]][Sali1[s][i-1]];} *** if (j<n2) {E -= P->dangle3[type[s]][Sali2[s][j+1]]; *Duplex_El +=P->dangle3[type[s]][Sali2[s][j+1]];} *** if (type[s]>2) {E -= P->TerminalAU; *Duplex_El +=P->TerminalAU;} **/ } if (E != n_seq * P->DuplexInit) { nrerror("backtrack failed in fold duplex end"); } else break; } } /* if (i>1) i--; */ /* if (j<n2) j++; */ /* struc = (char *) space(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *) space(i0-i+1+n2-1+1+2); /* declare final duplex structure */ char * struc2; struc2 = (char *) space(n2+1); /* char * struct_const; */ for (k=MAX2(i,1); k<=i0; k++) if (!st1[k-1]) st1[k-1] = '.'; /* for (k=j0; k<=j; k++) if (!st2[k-1]) st2[k-1] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) space(sizeof(char)*(n2+1)); */ for (k=1; k<=n2; k++) { if (!st2[k-1]) st2[k-1] = struc_loop[k-1];/* '.'; */ struc2[k-1] = st2[k-1];/* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } /* char duplexseq_1[j0+1]; */ /* char duplexseq_2[n2-j+3]; */ if(j<n2){ char **duplexseq_1, **duplexseq_2; duplexseq_1 = (char**) space((n_seq+1) * sizeof(char*)); duplexseq_2 = (char**) space((n_seq+1) * sizeof(char*)); for(s=0; s<n_seq; s++){ duplexseq_1[s] = (char*) space((j0)*sizeof(char)); /* modfied j0+1 */ duplexseq_2[s] = (char*) space((n2-j+2)*sizeof(char)); /* modified j+3 */ strncpy(duplexseq_1[s], snoseq[s], j0-1); /* modified j0 */ strcpy(duplexseq_2[s], snoseq[s] + j); /* modified j-1 */ duplexseq_1[s][j0-1]='\0'; /* modified j0 */ duplexseq_2[s][n2-j+1]='\0';/* modified j+2 */ } duplexseq_1[n_seq]=NULL; duplexseq_2[n_seq]=NULL; duplexT temp; temp=aliduplexfold((const char**)duplexseq_1, (const char**)duplexseq_2); *Loop_D = MIN2(0,-410 + (int) 100 * temp.energy*n_seq); if(*Loop_D){ int l1,ibegin, iend, jbegin, jend; l1=strchr(temp.structure, '&')-temp.structure; ibegin=temp.i-l1; iend =temp.i-1; jbegin=temp.j; jend =temp.j+strlen(temp.structure)-l1-2-1; for(k=ibegin+1; k<=iend+1; k++){ struc2[k-1]=temp.structure[k-ibegin-1]; } for(k=jbegin+j; k<=jend+j; k++){ struc2[k-1]=temp.structure[l1+k-j-jbegin+1]; } } for(s=0; s<n_seq; s++){ free(duplexseq_1[s]); free(duplexseq_2[s]); } free(duplexseq_1);free(duplexseq_2); free(temp.structure); } strcpy(struc, st1+MAX2(i-1,0)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2+5, strlen(struc2)-10); free(struc2); free(struc_loop); free(st1); free(st2); free(type);free(type2);free(type3); /* free_arrays(); */ return struc; } void Lsnoop_subopt(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE,const int threshSE,const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char* name, const int fullStemEnergy) { int min_colonne=INF; int max_pos; int max;max=INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int) strlen(s1); n2 = (int) strlen(s2); int *position; position = (int*) space((n1+3)*sizeof(int)); /* int Eminj, Emin_l; */ int i, j; /* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } lc = (int **) space(sizeof(int *) * (5)); lr = (int **) space(sizeof(int *) * (5)); for (i=0; i<5; i++) { lc[i] = (int *) space(sizeof(int) * (n2+1)); lr[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ lc[i][j]=INF; lr[i][j]=INF; } } encode_seqs(s1, s2); for (i=1; i<=n1; i++) { int idx=i%5; int idx_1=(i-1)%5; int idx_2=(i-2)%5; int idx_3=(i-3)%5; int idx_4=(i-4)%5; for (j=n2-min_d2; j>min_d1; j--) { int type, type2, k; type = pair[S1[i]][S2[j]]; lc[idx][j] = (type) ? P->DuplexInit + 2*penalty : INF; lr[idx][j] = INF; if(!type) continue; if( /*pair[S1[i+1]][S2[j-1]] && check that we have a solid base stack after the mLoop */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem+1); min_k = MAX2(j+half_stem+1, n2-max_s2); for(k=min_k; k <= max_k ; k++){ if(mLoop[indx[k-1]+j+1] < 0){ } if(pair[S1[i-3]][S2[k]] /*genau zwei ungepaarte nucleotiden --NU--*/ && mLoop[indx[k-1]+j+1] < threshloop){ lr[idx][j]=MIN2(lr[idx][j], lc[idx_3][k]+mLoop[indx[k-1]+j+1]); } else if(pair[S1[i-4]][S2[k]] && mLoop[indx[k-1]+j+1] < threshloop){/*--NUN--*/ lr[idx][j]=MIN2(lr[idx][j], lc[idx_4][k]+mLoop[indx[k-1]+j+1]); } } } /* dangle 5'SIDE relative to the mRNA */ lc[idx][j] += E_ExtLoop(type, (i>1) ? SS1[i-1] : -1, (j<n2) ? SS2[j+1] : -1, P); /** *** if (i>1) lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** if (j<n2) lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ if(j<n2 && i>1){ type2=pair[S1[i-1]][S2[j+1]]; if(type2>0){ lc[idx][j]=MIN2(lc[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+2*penalty, lc[idx][j]); lr[idx][j]=MIN2(lr[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+2*penalty, lr[idx][j]); } } if(j<n2-1 && i>2){ type2=pair[S1[i-2]][S2[j+2]]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P)+4*penalty, lc[idx][j]); lr[idx][j]=MIN2(lr[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P)+4*penalty, lr[idx][j]); } } if(j<n2-2 && i>3){ type2 = pair[S1[i-3]][S2[j+3]]; if(type2>0){ lc[idx][j]=MIN2(lc[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+6*penalty,lc[idx][j]); lr[idx][j]=MIN2(lr[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+6*penalty,lr[idx][j]); } } /** *** (type>2?P->TerminalAU:0)+(i<(n1)?P->dangle3[rtype[type]][SS1[i+1]]+penalty:0)+(j>1?P->dangle5[rtype[type]][SS2[j-1]]+penalty:0) **/ min_colonne=MIN2(lr[idx][j]+E_ExtLoop(rtype[type], (j > 1) ? SS2[j-1] : -1, (i<n1) ? SS1[i+1] : -1, P), min_colonne); } position[i]=min_colonne; if(max>=min_colonne){ max=min_colonne; max_pos=i; } min_colonne=INF; } free(S1); free(S2); free(SS1); free(SS2); if(max<threshTE){ find_max_snoop(s1, s2, max, alignment_length, position, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,name, fullStemEnergy); } for (i=1; i<5; i++) {free(lc[i]);free(lr[i]);} free(lc[0]);free(lr[0]); free(lc);free(lr); free(position); } void Lsnoop_subopt_list(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE,const int threshSE,const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length,const char *name,const int fullStemEnergy) { int min_colonne=INF; int max_pos; int max;max=INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int) strlen(s1); n2 = (int) strlen(s2); int *position; position = (int*) space((n1+3)*sizeof(int)); /* int Eminj, Emin_l; */ int i, j;/* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } lpair = (int **) space(sizeof(int *) * (6)); lc = (int **) space(sizeof(int *) * (6)); lr = (int **) space(sizeof(int *) * (6)); for (i=0; i<6; i++) { lc[i] = (int *) space(sizeof(int) * (n2+1)); lr[i] = (int *) space(sizeof(int) * (n2+1)); lpair[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ lc[i][j]=INF; lr[i][j]=INF; lpair[i][j]=0; } } encode_seqs(s1, s2); int lim_maxj=n2-min_d2 ; int lim_minj=min_d1; int lim_maxi=n1; for (i=5; i<=lim_maxi; i++) { int idx=i%5; int idx_1=(i-1)%5; int idx_2=(i-2)%5; int idx_3=(i-3)%5; int idx_4=(i-4)%5; for (j=lim_maxj; j>lim_minj; j--) { int type, type2;/* E, k,l; */ type = pair[S1[i]][S2[j]]; lpair[idx][j] = type; lc[idx][j] = (type) ? P->DuplexInit + 2*penalty : INF; lr[idx][j] = INF; if(!type) continue; if( /*pair[S1[i+1]][S2[j-1]] && Be sure it binds*/ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4 ) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem+1); min_k = MAX2(j+half_stem+1, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next){ int k = temp->k; /* if(k >= min_k-1 && k < max_k){ comment to recover normal behaviour */ if(lpair[idx_3][k+1] /*&& lpair[idx_4][k+2]*/){ lr[idx][j]=MIN2(lr[idx][j], lc[idx_3][k+1]+temp->energy);/*--NU--*/ } /*else*/ if(lpair[idx_4][k+1]){/*--NUN--*/ lr[idx][j]=MIN2(lr[idx][j], lc[idx_4][k+1]+temp->energy); } /* } */ temp=temp->next; } } /* dangle 5'SIDE relative to the mRNA */ lc[idx][j] += E_ExtLoop(type, SS1[i-1] , SS2[j+1] , P); /** *** lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ /* if(j<n2 && i>1){ */ /* type2=pair[S1[i-1]][S2[j+1]]; */ type2=lpair[idx_1][j+1]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+2*penalty, lc[idx][j]); lr[idx][j]=MIN2(lr[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+2*penalty, lr[idx][j]); } /* } */ /* if(j<n2-1 && i>2){ */ /* type2=pair[S1[i-2]][S2[j+2]]; */ type2=lpair[idx_2][j+2]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P), lc[idx][j]); lr[idx][j]=MIN2(lr[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P), lr[idx][j]); /* } */ } /* if(j<n2-2 && i>3){ */ /* type2 = pair[S1[i-3]][S2[j+3]]; */ type2 =lpair[idx_3][j+3]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+6*penalty,lc[idx][j]); lr[idx][j]=MIN2(lr[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+6*penalty,lr[idx][j]); /* } */ } /* min_colonne=MIN2(lr[idx][j]+(type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]], min_colonne); */ int bla; bla=lr[idx][j]+E_ExtLoop(rtype[type], SS2[j-1] , SS1[i+1], P)+2*penalty; min_colonne=MIN2(bla, min_colonne); } position[i]=min_colonne; if(max>=min_colonne){ max=min_colonne; max_pos=i; } min_colonne=INF; } free(S1); free(S2); free(SS1); free(SS2); if(max<threshTE){ find_max_snoop(s1, s2, max, alignment_length, position, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,name, fullStemEnergy); } for (i=1; i<6; i++) {free(lc[i]);free(lr[i]);free(lpair[i]);} free(lc[0]);free(lr[0]);free(lpair[0]); free(lc);free(lr);free(lpair); free(position); } PRIVATE void find_max_snoop(const char *s1, const char *s2,const int max, const int alignment_length, const int* position, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char* name, const int fullStemEnergy) { int count=0; int pos=n1+1; int threshold = MIN2(threshTE , max + delta ); /* printf("threshTE %d max %d\n", threshTE, max); */ /* #pragma omp parallel for */ /* for(pos=n1+1;pos>distance;pos--){ */ while(pos-- > 5){ int temp_min=0; if(position[pos]<(threshold)){ int search_range; search_range=distance+1; while(--search_range){ if(position[pos-search_range]<=position[pos-temp_min]){ temp_min=search_range; } } pos-=temp_min; int begin=MAX2(6, pos-alignment_length+1); char *s3 = (char*) space(sizeof(char)*(pos-begin+3+12)); strcpy(s3, "NNNNN"); strncat(s3, (s1+begin-1), pos-begin+2); strcat(s3,"NNNNN\0"); /* printf("%s s3\n", s3); */ snoopT test; test = snoopfold(s3, s2, penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,fullStemEnergy); if(test.energy==INF){ free(s3); continue; } if(test.Duplex_El > threshLE * 0.01 || test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE*0.01) { free(test.structure);free(s3); continue; } int l1; l1 = strchr(test.structure, '&')-test.structure; int shift=0; if(test.i > strlen(s3)-10){ test.i--; l1--; } if(test.i-l1<0){ l1--; shift++; } char *target_struct = (char*) space(sizeof(char) * (strlen(test.structure)+1)); strncpy(target_struct, test.structure+shift, l1); strncat(target_struct, test.structure + (strchr(test.structure, '&')- test.structure), strlen(test.structure) - (strchr(test.structure, '&')- test.structure)); strcat(target_struct,"\0"); char *target; target = (char *) space(l1+1); strncpy(target, (s3+test.i+5-l1), l1); target[l1]='\0'; char *s4; s4 = (char*) space(sizeof(char) *(strlen(s2)-9)); strncpy(s4, s2+5, strlen(s2)-10); s4[strlen(s2)-10]='\0'; printf("%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + 4.1 ) (%5.2f) \n%s&%s\n", target_struct,begin + test.i-5-l1,begin + test.i -6 , begin + test.u -6, test.j+1, test.j + (strrchr(test.structure,'>') - strchr(test.structure,'>'))+1 , test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D,test.fullStemEnergy, target,s4); if(name){ char *temp_seq; char *temp_struc; char psoutput[100]; temp_seq = (char*) space(sizeof(char)*(l1+n2-9)); temp_struc = (char*) space(sizeof(char)*(l1+n2-9)); strcpy(temp_seq, target); strcat(temp_seq, s4); strncpy(temp_struc, target_struct, l1); strcat(temp_struc, target_struct+l1+1); temp_seq[n2+l1-10]='\0'; temp_struc[n2+l1-10]='\0'; cut_point = l1+1; char str[16];char upos[16]; strcpy(psoutput,"sno_"); sprintf(str,"%d",count); strcat(psoutput,str); sprintf(upos,"%d",begin + test.u - 6); strcat(psoutput,"_u_"); strcat(psoutput,upos); strcat(psoutput,"_"); strcat(psoutput,name); strcat(psoutput,".ps\0"); PS_rna_plot_snoop_a(temp_seq, temp_struc, psoutput, NULL, NULL); cut_point = -1; free(temp_seq); free(temp_struc); count++; /* free(psoutput); */ } free(s4); free(test.structure); free(target_struct); free(target); free(s3); } } } snoopT snoopfold(const char *s1, const char *s2, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* int Eminj, Emin_l; */ int i, j, l1, Emin=INF, i_min=0, j_min=0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden** foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; int u; int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); n1 = (int) strlen(s1); n2 = (int) strlen(s2); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } c = (int **) space(sizeof(int *) * (n1+1)); r = (int **) space(sizeof(int *) * (n1+1)); for (i=0; i<=n1; i++) { c[i] = (int *) space(sizeof(int) * (n2+1)); r[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ c[i][j]=INF; r[i][j]=INF; } } encode_seqs(s1, s2); for (i=6; i<=n1-5; i++) { for (j=n2-min_d2; j>min_d1; j--) { int type, type2, E, k,l; type = pair[S1[i]][S2[j]]; c[i][j] = (type ) ? P->DuplexInit : INF; if(!type) continue; if(/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4 ) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem); min_k = MAX2(j+half_stem, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next){ int k = temp->k; /* if(k >= min_k-1 && k < max_k){ uncomment to recovernormal behaviour */ if(pair[S1[i-3]][S2[k+1]] /*&& pair[S1[i-4]][S2[k+2]]*/ ){ r[i][j]=MIN2(r[i][j], c[i-3][k+1]+temp->energy); } /*else*/ if(pair[S1[i-4]][S2[k+1]] /*&& pair[S1[i-5]][S2[k+2]]*/ ){ r[i][j]=MIN2(r[i][j], c[i-4][k+1]+temp->energy); } /* } */ temp=temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** c[i][j] += P->dangle5[type][SS1[i-1]]; *** c[i][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) c[i][j] += P->TerminalAU; **/ c[i][j]+=E_ExtLoop(type, SS1[i-1] , SS2[j+1], P); for (k=i-1; k>0 && (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2 ; l++) { if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS ) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; E = E_IntLoop(i-k-1, l-j-1, type2, rtype[type], SS1[k+1], SS2[l-1], SS1[i-1], SS2[j+1],P); c[i][j] = MIN2(c[i][j], c[k][l]+E+(i-k+l-j)*penalty); r[i][j] = MIN2(r[i][j], r[k][l]+E+(i-k+l-j)*penalty); } } E = r[i][j]; /** *** if (i<n1) E += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) E += P->dangle5[rtype[type]][SS2[j-1]]; *** f (type>2) E += P->TerminalAU; **/ E+=E_ExtLoop(rtype[type], (j > 1) ? SS2[j-1] : -1, (i<n1) ? SS1[i+1] : -1, P); if (E<Emin) { Emin=E; i_min=i; j_min=j; } } } if(Emin > 0){ printf("no target found under the constraints chosen\n"); for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); mfe.energy=INF; return mfe; } struc = snoop_backtrack(i_min, j_min,s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop, threshLE, threshRE,threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); /* if (i_min<n1-5) i_min++; */ /* if (j_min>1 ) j_min--; */ l1 = strchr(struc, '&')-struc; mfe.i = i_min-5; mfe.j = j_min-5; mfe.u = u -5; mfe.Duplex_Er = (float) Duplex_Er/100; mfe.Duplex_El = (float) Duplex_El/100; mfe.Loop_D = (float) Loop_D/100; mfe.Loop_E = (float) Loop_E/100; mfe.energy = (float) Emin/100 ; mfe.fullStemEnergy = (float) fullStemEnergy/100; mfe.structure = struc; if (!delay_free) { for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); } return mfe; } PRIVATE int snoopfold_XS_fill(const char *s1, const char *s2, const int **access_s1, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* int Eminj, Emin_l; */ int i, j, Emin=INF, i_min=0, j_min=0; /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden** foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); n1 = (int) strlen(s1); n2 = (int) strlen(s2); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } c_fill = (int **) space(sizeof(int *) * (n1+1)); r_fill = (int **) space(sizeof(int *) * (n1+1)); for (i=0; i<=n1; i++) { c_fill[i] = (int *) space(sizeof(int) * (n2+1)); r_fill[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ c_fill[i][j]=INF; r_fill[i][j]=INF; } } encode_seqs(s1, s2); int di[5]; di[0]=0; for (i=6; i<=n1-5; i++) { di[1]=access_s1[5][i] - access_s1[4][i-1]; di[2]=access_s1[5][i-1] - access_s1[4][i-2] + di[1]; di[3]=access_s1[5][i-2] - access_s1[4][i-3] + di[2]; di[4]=access_s1[5][i-3] - access_s1[4][i-4] + di[3]; di[1]=MIN2(di[1],165); di[2]=MIN2(di[2],330); di[3]=MIN2(di[3],495); di[4]=MIN2(di[4],660); for (j=n2-min_d2; j>min_d1; j--) { int type, type2, E, k,l; type = pair[S1[i]][S2[j]]; c_fill[i][j] = (type ) ? P->DuplexInit : INF; if(!type) continue; if(/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4 ) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem); min_k = MAX2(j+half_stem, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next){ int k = temp->k; /* if(k >= min_k-1 && k < max_k){ uncomment to recovernormal behaviour */ if(pair[S1[i-3]][S2[k+1]] /*&& pair[S1[i-4]][S2[k+2]]*/ ){ r_fill[i][j]=MIN2(r_fill[i][j], c_fill[i-3][k+1]+temp->energy+ di[3]); } /*else*/ if(pair[S1[i-4]][S2[k+1]] /*&& pair[S1[i-5]][S2[k+2]]*/ ){ r_fill[i][j]=MIN2(r_fill[i][j], c_fill[i-4][k+1]+temp->energy + di[4]); } /* } */ temp=temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** c_fill[i][j] += P->dangle5[type][SS1[i-1]]; *** c_fill[i][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) c_fill[i][j] += P->TerminalAU; **/ c_fill[i][j]+= E_ExtLoop(type, SS1[i-1], SS2[j+1],P); for (k=i-1; k>0 && (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2 ; l++) { if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS ) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; E = E_IntLoop(i-k-1, l-j-1, type2, rtype[type], SS1[k+1], SS2[l-1], SS1[i-1], SS2[j+1],P); c_fill[i][j] = MIN2(c_fill[i][j], c_fill[k][l]+E+di[i-k]); r_fill[i][j] = MIN2(r_fill[i][j], r_fill[k][l]+E+di[i-k]); } } E = r_fill[i][j]; /** *** if (i<n1) E += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) E += P->dangle5[rtype[type]][SS2[j-1]]; *** if (type>2) E += P->TerminalAU; **/ E+= E_ExtLoop(rtype[type], (j > 1) ? SS2[j-1] : -1, (i<n1) ? SS1[i+1] : -1, P); if (E<Emin) { Emin=E; i_min=i; j_min=j; } } } return Emin; } PUBLIC snoopT *snoop_subopt(const char *s1, const char *s2, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* printf("%d %d\n", min_s2, max_s2); */ int i,j, n1, n2, E, n_subopt=0, n_max; char *struc; snoopT mfe; snoopT *subopt; int thresh; int Duplex_El, Duplex_Er, Loop_E; int Loop_D; Duplex_El=0; Duplex_Er=0; Loop_E=0;Loop_D=0; int u; u=0; n_max=16; subopt = (snoopT *) space(n_max*sizeof(snoopT)); delay_free=1; mfe = snoopfold(s1, s2, penalty, threshloop, threshLE, threshRE, threshDE,threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if(mfe.energy > 0){ free(subopt); delay_free=0; return NULL; } thresh = MIN2((int) ((mfe.Duplex_Er + mfe.Duplex_El + mfe.Loop_E)*100+0.1 + 410) + delta, threshTE ); /* subopt[n_subopt++]=mfe; */ free(mfe.structure); n1 = strlen(s1); n2=strlen(s2); for (i=n1; i>0; i--) { for (j=1; j<=n2; j++) { int type, Ed; type = pair[S2[j]][S1[i]]; if (!type) continue; E = Ed = r[i][j]; /** *** if (i<n1) Ed += P->dangle3[type][SS1[i+1]]; *** if (j>1) Ed += P->dangle5[type][SS2[j-1]]; *** if (type>2) Ed += P->TerminalAU; **/ Ed+= E_ExtLoop(type, (j > 1) ? SS2[j-1] : -1, (i<n1) ? SS1[i+1] : -1, P); if (Ed>thresh) continue; /* too keep output small, remove hits that are dominated by a better one close (w) by. For simplicity we do test without adding dangles, which is slightly inaccurate. */ /* w=1; */ /* for (ii=MAX2(i-w,1); (ii<=MIN2(i+w,n1)) && type; ii++) { */ /* for (jj=MAX2(j-w,1); jj<=MIN2(j+w,n2); jj++) */ /* if (r[ii][jj]<E) {type=0; break;} */ /* } */ if (!type) continue; struc = snoop_backtrack(i,j,s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop,threshLE,threshRE,threshDE,threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if (Duplex_Er > threshRE || Duplex_El > threshLE || Loop_D > threshD || (Duplex_Er + Duplex_El) > threshDE || (Duplex_Er + Duplex_El + Loop_E) > threshTE || (Duplex_Er + Duplex_El + Loop_E + Loop_D + 410) > threshSE) { /* printf(" Duplex_Er %d threshRE %d Duplex_El %d threshLE %d \n" */ /* " Duplex_Er + Duplex_El %d threshDE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E %d threshTE %d \n" */ /* " Duplex_Er + Duplex_El + Loop_E + Loop_D %d threshSE %d \n", */ /* Duplex_Er , threshRE , Duplex_El ,threshLE, */ /* Duplex_Er + Duplex_El, threshDE, */ /* Duplex_Er + Duplex_El+ Loop_E , threshTE, */ /* Duplex_Er + Duplex_El+ Loop_E + Loop_D, threshSE); */ Duplex_Er=0; Duplex_El=0; Loop_E = 0; Loop_D = 0; u=0, free(struc); continue; } if (n_subopt+1>=n_max) { n_max *= 2; subopt = (snoopT *) xrealloc(subopt, n_max*sizeof(snoopT)); } subopt[n_subopt].i = i-5; subopt[n_subopt].j = j-5; subopt[n_subopt].u = u-5; subopt[n_subopt].Duplex_Er = Duplex_Er * 0.01; subopt[n_subopt].Duplex_El = Duplex_El * 0.01; subopt[n_subopt].Loop_E = Loop_E * 0.01; subopt[n_subopt].Loop_D = Loop_D * 0.01; subopt[n_subopt].energy = (Duplex_Er +Duplex_El + Loop_E + Loop_D + 410) * 0.01 ; subopt[n_subopt].fullStemEnergy = (float) fullStemEnergy * 0.01; subopt[n_subopt++].structure = struc; Duplex_Er=0; Duplex_El=0; Loop_E=0; Loop_D=0;u=0; } } for (i=0; i<=n1; i++) {free(c[i]);free(r[i]);} free(c);free(r); free(S1); free(S2); free(SS1); free(SS2); delay_free=0; if (snoop_subopt_sorted) qsort(subopt, n_subopt, sizeof(snoopT), compare); subopt[n_subopt].i =0; subopt[n_subopt].j =0; subopt[n_subopt].structure = NULL; return subopt; } PUBLIC void snoop_subopt_XS(const char *s1, const char *s2, const int **access_s1, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { /* printf("%d %d\n", min_s2, max_s2); */ int i,j, E, n_max; /* char *struc; */ /* snoopT mfe; */ int thresh; int Duplex_El, Duplex_Er, Loop_E; int Loop_D; Duplex_El=0; Duplex_Er=0; Loop_E=0;Loop_D=0; int u; u=0; n_max=16; delay_free=1; int Emin = snoopfold_XS_fill(s1, s2, access_s1,penalty, threshloop, threshLE, threshRE, threshDE,threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); if(Emin > 0){ delay_free=0; } thresh = MIN2(-100, threshTE +alignment_length*30); /* n1=strlen(s1); */ /* n2=strlen(s2); */ int n3=strlen(s1); int n4=strlen(s2); S1_fill = (short*)space(sizeof(short)*(n3+2)); S2_fill = (short*)space(sizeof(short)*(n4+2)); SS1_fill = (short*)space(sizeof(short)*(n3+1)); SS2_fill = (short*)space(sizeof(short)*(n4+1)); memcpy(S1_fill, S1, sizeof(short)*n3+2); memcpy(S2_fill, S2, sizeof(short)*n4+2); memcpy(SS1_fill, SS1, sizeof(short)*n3+1); memcpy(SS2_fill, SS2, sizeof(short)*n4+1); free(S1);free(S2);free(SS1);free(SS2); int count=0; for (i=n3-5; i>0; i--) { for (j=1; j<=n4; j++) { int type, Ed; type = pair[S2_fill[j]][S1_fill[i]]; if (!type) continue; E = Ed = r_fill[i][j]; /** ***if (i<n3) Ed += P->dangle3[type][SS1_fill[i+1]]; ***if (j>1) Ed += P->dangle5[type][SS2_fill[j-1]]; ***if (type>2) Ed += P->TerminalAU; **/ Ed+=E_ExtLoop(type, (j > 1) ? SS2[j-1] : -1, (i<n3) ? SS1[i+1] : -1, P); if (Ed>thresh) continue; /* to keep output small, remove hits that are dominated by a better one close (w) by. For simplicity we do test without adding dangles, which is slightly inaccurate. */ /* w=10; */ /* for (ii=MAX2(i-w,1); (ii<=MIN2(i+w,n3-5)) && type; ii++) { */ /* for (jj=MAX2(j-w,1); jj<=MIN2(j+w,n4-5); jj++) */ /* if (r_fill[ii][jj]<E) {type=0; break;} */ /* } */ /* i=ii;j=jj; */ if (!type) continue; int begin=MAX2(5, i-alignment_length); int end =MIN2(n3-5, i-1); char *s3 = (char*) space(sizeof(char)*(end-begin+2)+5); strncpy(s3, (s1+begin), end - begin +1); strcat(s3,"NNNNN\0"); int n5 = strlen(s3); snoopT test = snoopfold_XS(s3, s2, access_s1, i, j ,penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,fullStemEnergy); if(test.energy==INF){ free(s3); continue; } if( test.Duplex_El > threshLE * 0.01 ||test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E) > threshTE*0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE*0.01) { free(test.structure);free(s3); continue; } char *s4; s4 = (char*) space(sizeof(char) *(n4-9)); strncpy(s4, s2+5, n4-10); s4[n4-10]='\0'; char *s5 = space(sizeof(char) * n5-test.i+2-5); strncpy(s5,s3+test.i-1,n5-test.i+1-5); s5[n5-test.i+1-5]='\0'; float dE = ((float) (access_s1[n5-test.i+1-5][i]))*0.01; printf("%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + %5.2f + 4.10) (%5.2f)\n%s&%s\n" , test.structure, i - (n5 - test.i) ,i - 5, i - (n5 - test.u ), j-5, j-5 + (strrchr(test.structure,'>') - strchr(test.structure,'>')), test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10+dE, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D,dE , test.fullStemEnergy, s5,s4); if(name){ int begin_t, end_t, begin_q, end_q, and, pipe,k; char psoutput[100]; begin_q=0; end_q=n4-10; begin_t=0; end_t=n5-test.i+ 1-5; and=end_t+1; pipe=test.u -test.i + 1; cut_point = end_t +1 ; char *catseq, *catstruct;/* *fname; */ catseq = (char*) space(n5 + end_q -begin_q +2); catstruct = (char*) space(n5 + end_q -begin_q +2); strcpy(catseq, s5); strncpy(catstruct, test.structure, end_t); strcat(catseq, s4); strncat(catstruct, test.structure+end_t+1, end_q-begin_q+1); catstruct[end_t - begin_t + end_q-begin_q+2]='\0'; catseq[end_t - begin_t + end_q-begin_q+2]='\0'; int *relative_access; relative_access = space(sizeof(int)*strlen(s5)); relative_access[0] = access_s1[1][i - (n5 - test.i) + 5]; for(k=1;k<strlen(s5);k++){ relative_access[k] = access_s1[k+1][i - (n5 - test.i) + k + 5] - access_s1[k][i - (n5 - test.i) + k + 4]; } char str[16];char upos[16]; strcpy(psoutput,"sno_XS_"); sprintf(str,"%d",count); strcat(psoutput,str); sprintf(upos,"%d",i - (n5 - test.u )); strcat(psoutput,"_u_"); strcat(psoutput,upos); strcat(psoutput,"_"); strcat(psoutput,name); strcat(psoutput,".ps\0"); PS_rna_plot_snoop_a(catseq, catstruct, psoutput,relative_access,NULL); free(catseq);free(catstruct);free(relative_access); count++; } free(s3);free(s4);free(s5);free(test.structure); } } for (i=0; i<=n3; i++) {free(c_fill[i]);free(r_fill[i]);} free(c_fill);free(r_fill); free(S1_fill); free(S2_fill); free(SS1_fill); free(SS2_fill); delay_free=0; } PRIVATE char *snoop_backtrack(int i, int j, const char* snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* backtrack structure going backwards from i, and forwards from j return structure in bracket notation with & as separator */ int k, l, type, type2, E, traced, i0, j0; int traced_r=0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; st1 = (char *) space(sizeof(char)*(n1+1)); st2 = (char *) space(sizeof(char)*(n2+1)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; type=pair[S1[i]][S2[j]]; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); i0=i; j0=j; /** *** if (i<n1) *Duplex_Er += P->dangle3[rtype[type]][SS1[i+1]]; *** if (j>1) *Duplex_Er += P->dangle5[rtype[type]][SS2[j-1]]; *** if (type>2) *Duplex_Er += P->TerminalAU; **/ *Duplex_Er += E_ExtLoop(rtype[type], (j > 1) ? SS2[j-1] : -1, (i<n1) ? SS1[i+1] : -1, P); while (i>0 && j<=n2-min_d2 ) { if(!traced_r) { E = r[i][j]; traced=0; st1[i-1] = '<'; st2[j-1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) nrerror("backtrack failed in fold duplex r"); for (k=i-1; k>0 && (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2 ; l++) { int LE; if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(i-k-1, l-j-1, type2, rtype[type], SS1[k+1], SS2[l-1], SS1[i-1], SS2[j+1],P); if (E == r[k][l]+LE+(i-k+l-j)*penalty) { traced=1; i=k; j=l; *Duplex_Er+=LE; break; } } if (traced) break; } if(!traced){ if(/* pair[S1[i+1]][S2[j-1]] && */ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4) { int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem+1); min_k = MAX2(j+half_stem+1, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next) { int k = temp->k; if(pair[S1[i-3]][S2[k+1]] /*&& pair[S1[i-4]][S2[k+2]]*/ ){ /* introduce structure from RNAfold */ if(E==c[i-3][k+1]+temp->energy){ *Loop_E=temp->energy; st1[i-3]= '|'; *u=i-2; int a,b; /* int fix_ij=indx[k-1+1]+j+1; */ for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[k-1-a+1]+j+1+b; if(cLoop[ij]==temp->energy) { struc_loop=snobacktrack_fold_from_pair(snoseq, j+1+b, k-a-1+1); a=INF; b=INF; } } } traced=1; traced_r=1; i=i-3;j=k+1; break; } } /*else*/ if (pair[S1[i-4]][S2[k+1]] /*&& pair[S1[i-5]][S2[k+2]]*/){ /* introduce structure from RNAfold */ if(E==c[i-4][k+1]+temp->energy){ *Loop_E=temp->energy; st1[i-3]= '|'; *u=i-2; int a,b; /* int fix_ij=indx[k-1+1]+j+1; */ for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[k-1-a+1]+j+1+b; if(cLoop[ij]==temp->energy) { struc_loop=snobacktrack_fold_from_pair(snoseq, j+1+b, k-a-1+1); a=INF; b=INF; } } } traced=1; traced_r=1; i=i-4;j=k+1; break; } } /* else if */ temp=temp->next; } /* while temp-> next */ } /* test on j */ }/* traced? */ }/* traced_r? */ else{ E = c[i][j]; traced=0; st1[i-1] = '<'; st2[j-1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) nrerror("backtrack failed in fold duplex c"); for (k=i-1; (i-k)<MAXLOOP_L; k--) { for (l=j+1; l<=n2; l++) { int LE; if (i-k+l-j>2*MAXLOOP_L-2) break; if (abs(i-k-l+j) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(i-k-1, l-j-1, type2, rtype[type], SS1[k+1], SS2[l-1], SS1[i-1], SS2[j+1],P); if (E == c[k][l]+LE+(i-k+l-j)*penalty) { traced=1; i=k; j=l; *Duplex_El+=LE; break; } } if (traced) break; } } if (!traced) { int correction; correction = E_ExtLoop(type, (i>1) ? SS1[i-1] : -1, (j<n2) ? SS2[j+1] : -1, P); E-=correction; *Duplex_El+=correction; /** *** if (i>1) {E -= P->dangle5[type][SS1[i-1]]; *Duplex_El +=P->dangle5[type][SS1[i-1]];} *** if (j<n2) {E -= P->dangle3[type][SS2[j+1]]; *Duplex_El +=P->dangle3[type][SS2[j+1]];} *** if (type>2) {E -= P->TerminalAU; *Duplex_El +=P->TerminalAU;} **/ if (E != P->DuplexInit) { nrerror("backtrack failed in fold duplex end"); } else break; } } /* if (i>1) i--; */ /* if (j<n2) j++; */ /* struc = (char *) space(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *) space(i0-i+1+n2-1+1+2); /* declare final duplex structure */ char * struc2; struc2 = (char *) space(n2+1); /* char * struct_const; */ for (k=MAX2(i,1); k<=i0; k++) if (!st1[k-1]) st1[k-1] = '.'; /* for (k=j0; k<=j; k++) if (!st2[k-1]) st2[k-1] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) space(sizeof(char)*(n2+1)); */ for (k=1; k<=n2; k++) { if (!st2[k-1]) st2[k-1] = struc_loop[k-1];/* '.'; */ struc2[k-1] = st2[k-1];/* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } char duplexseq_1[j0]; char duplexseq_2[n2-j+2]; if(j<n2){ strncpy(duplexseq_1, snoseq, j0-1); strcpy(duplexseq_2, snoseq + j); duplexseq_1[j0-1]='\0'; duplexseq_2[n2-j+1]='\0'; duplexT temp; temp=duplexfold(duplexseq_1, duplexseq_2); *Loop_D = MIN2(0,-410 + (int) 100 * temp.energy); if(*Loop_D){ int l1,ibegin, iend, jbegin, jend; l1=strchr(temp.structure, '&')-temp.structure; ibegin=temp.i-l1; iend =temp.i-1; jbegin=temp.j; jend =temp.j+strlen(temp.structure)-l1-2-1; for(k=ibegin+1; k<=iend+1; k++){ struc2[k-1]=temp.structure[k-ibegin-1]; } for(k=jbegin+j; k<=jend+j; k++){ struc2[k-1]=temp.structure[l1+k-j-jbegin+1]; } } free(temp.structure); } strcpy(struc, st1+MAX2(i-1,0)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2+5, strlen(struc2)-10); free(struc2); free(struc_loop); free(st1); free(st2); /* free_arrays(); */ return struc; } void Lsnoop_subopt_list_XS(const char *s1, const char *s2, const int **access_s1, int delta, int w, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE,const int threshSE,const int threshD, const int distance, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int alignment_length, const char *name, const int fullStemEnergy) { int min_colonne=INF; int max_pos; int max;max=INF; /* int temp; */ /* int nsubopt=10; */ n1 = (int) strlen(s1); n2 = (int) strlen(s2); int *position; int *position_j; int min_j_colonne; int max_pos_j=INF; position = (int*) space((n1+3)*sizeof(int)); position_j = (int*) space((n1+3)*sizeof(int)); /* int Eminj, Emin_l; */ int i, j;/* l1, Emin=INF, i_min=0, j_min=0; */ /* char *struc; */ /* snoopT mfe; */ int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; /* int u; */ int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop, &foldlist, &foldlist_XS); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } lpair = (int **) space(sizeof(int *) * (6)); lc = (int **) space(sizeof(int *) * (6)); lr = (int **) space(sizeof(int *) * (6)); for (i=0; i<6; i++) { lc[i] = (int *) space(sizeof(int) * (n2+1)); lr[i] = (int *) space(sizeof(int) * (n2+1)); lpair[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ lc[i][j]=INF; lr[i][j]=INF; lpair[i][j]=0; } } encode_seqs(s1, s2); int lim_maxj=n2-min_d2 ; int lim_minj=min_d1; int lim_maxi=n1-5; for (i=5; i<=lim_maxi; i++) { int idx=i%5; int idx_1=(i-1)%5; int idx_2=(i-2)%5; int idx_3=(i-3)%5; int idx_4=(i-4)%5; int di1, di2, di3, di4; di1 = access_s1[5][i] - access_s1[4][i-1]; di2 =access_s1[5][i-1] - access_s1[4][i-2] + di1; di3 = access_s1[5][i-2] - access_s1[4][i-3] + di2; di4 = access_s1[5][i-3] - access_s1[4][i-4] + di3; di1=MIN2(di1,165); di2=MIN2(di2,330); di3=MIN2(di3,495); di4=MIN2(di4,660); for (j=lim_maxj; j>lim_minj; j--) { int type, type2;/* E, k,l; */ type = pair[S1[i]][S2[j]]; lpair[idx][j] = type; lc[idx][j] = (type) ? P->DuplexInit + access_s1[1][i] : INF; lr[idx][j] = INF; if(!type) continue; if( /*pair[S1[i+1]][S2[j-1]] && Be sure it binds*/ j < max_s1 && j > min_s1 && j > n2 - max_s2 - max_half_stem && j < n2 -min_s2 -half_stem && S1[i-2]==4 ) { /*constraint on s2 and i*/ int min_k, max_k; max_k = MIN2(n2-min_s2,j+max_half_stem+1); min_k = MAX2(j+half_stem+1, n2-max_s2); folden * temp; temp=foldlist[j+1]; while(temp->next){ int k = temp->k; /* if(k >= min_k-1 && k < max_k){ comment to recover normal behaviour */ if(lpair[idx_3][k+1] && lc[idx_3][k+1] /*+di3*/ < 411 /*&& lpair[idx_4][k+2]*/){ /* remove second condition */ lr[idx][j]=MIN2(lr[idx][j], di3 + lc[idx_3][k+1]+temp->energy);/*--NU--*/ } /*else*/ if(lpair[idx_4][k+1] && /*di4 +*/ lc[idx_4][k+1] < 411 ){/*--NUN--*/ /* remove second condition */ lr[idx][j]=MIN2(lr[idx][j], di4 + lc[idx_4][k+1]+temp->energy); } /* } */ temp=temp->next; } } /* dangle 5'SIDE relative to the mRNA */ /** *** lc[idx][j] += P->dangle5[type][SS1[i-1]]; *** lc[idx][j] += P->dangle3[type][SS2[j+1]]; *** if (type>2) lc[idx][j] += P->TerminalAU; **/ lc[idx][j]+=E_ExtLoop(type, SS1[i-1] , SS2[j+1] , P); /* if(j<n2 && i>1){ */ /* type2=pair[S1[i-1]][S2[j+1]]; */ type2=lpair[idx_1][j+1]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+di1, lc[idx][j]); lr[idx][j]=MIN2(lr[idx_1][j+1]+E_IntLoop(0,0,type2, rtype[type],SS1[i], SS2[j], SS1[i-1], SS2[j+1], P)+di1, lr[idx][j]); } type2=lpair[idx_2][j+2]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P)+di2, lc[idx][j]); lr[idx][j]=MIN2(lr[idx_2][j+2]+E_IntLoop(1,1,type2, rtype[type],SS1[i-1], SS2[j+1], SS1[i-1], SS2[j+1], P)+di2, lr[idx][j]); } type2 =lpair[idx_3][j+3]; if(type2>0 ){ lc[idx][j]=MIN2(lc[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+di3,lc[idx][j]); lr[idx][j]=MIN2(lr[idx_3][j+3]+E_IntLoop(2,2,type2, rtype[type],SS1[i-2], SS2[j+2], SS1[i-1], SS2[j+1], P)+di3,lr[idx][j]); } int bla; int temp2; temp2=min_colonne; bla=lr[idx][j] + E_ExtLoop(rtype[type], SS2[j-1], SS1[i+1] , P); /** *** (type>2?P->TerminalAU:0)+P->dangle3[rtype[type]][SS1[i+1]]+P->dangle5[rtype[type]][SS2[j-1]]; **/ min_colonne=MIN2(bla, min_colonne); if(temp2>min_colonne){ min_j_colonne=j; } } position[i]=min_colonne; if(max>=min_colonne){ max=min_colonne; max_pos=i; max_pos_j=min_j_colonne; } position_j[i]=min_j_colonne; min_colonne=INF; } free(S1); free(S2); free(SS1); free(SS2); if(max<threshTE + 30*alignment_length){ find_max_snoop_XS(s1, s2, access_s1,max,alignment_length, position, position_j, delta, distance, penalty, threshloop, threshLE, threshRE, threshDE, threshTE, threshSE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2,name,fullStemEnergy); } for (i=1; i<6; i++) {free(lc[i]);free(lr[i]);free(lpair[i]);} free(lc[0]);free(lr[0]);free(lpair[0]); free(lc);free(lr);free(lpair); free(position);free(position_j); } PRIVATE void find_max_snoop_XS(const char *s1, const char *s2, const int **access_s1, const int max, const int alignment_length, const int* position, const int* position_j, const int delta, const int distance, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshTE, const int threshSE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const char *name, const int fullStemEnergy){ int count=0; int n3=strlen(s1); int n4=strlen(s2); int pos=n1-4; int max_pos_j; int threshold = MIN2(threshTE + alignment_length*30, -100); /* printf("threshTE %d max %d\n", threshTE, max); */ /* #pragma omp parallel for */ /* for(pos=n1+1;pos>distance;pos--){ */ while(pos-->5){ int temp_min=0; if(position[pos]<(threshold)){ int search_range; search_range=distance+1; while(--search_range){ if(position[pos-search_range]<=position[pos-temp_min]){ temp_min=search_range; } } pos-=temp_min; max_pos_j=position_j[pos]; int begin=MAX2(5, pos-alignment_length); int end =MIN2(n3-5, pos-1); char *s3 = (char*) space(sizeof(char)*(end-begin+2)+5); strncpy(s3, (s1+begin), end - begin +1); strcat(s3,"NNNNN\0"); int n5 = strlen(s3); snoopT test; test = snoopfold_XS(s3, s2, access_s1, pos, max_pos_j ,penalty, threshloop, threshLE, threshRE, threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2, fullStemEnergy); if(test.energy==INF){ free(s3); continue; } if( test.Duplex_El > threshLE * 0.01 ||test.Duplex_Er > threshRE * 0.01 || test.Loop_D > threshD * 0.01 || (test.Duplex_Er + test.Duplex_El) > threshDE * 0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E) > threshTE*0.01 || (test.Duplex_Er + test.Duplex_El + test.Loop_E + test.Loop_D + 410) > threshSE*0.01) { free(test.structure);free(s3); continue; } char *s4; s4 = (char*) space(sizeof(char) *(n4-9)); strncpy(s4, s2+5, n4-10); s4[n4-10]='\0'; char *s5 = space(sizeof(char) * n5-test.i+2-5); strncpy(s5,s3+test.i-1,n5-test.i+1-5); s5[n5-test.i+1-5]='\0'; float dE = ((float) (access_s1[n5-test.i+1-5][pos]))*0.01; printf("%s %3d,%-3d;%3d : %3d,%-3d (%5.2f = %5.2f + %5.2f + %5.2f + %5.2f + %5.2f + 4.10) (%5.2f)\n%s&%s\n" , test.structure, pos - (n5 - test.i) ,pos - 5, pos - (n5 - test.u ), max_pos_j-5, max_pos_j-5 + (strrchr(test.structure,'>') - strchr(test.structure,'>')), test.Loop_D + test.Duplex_El + test.Duplex_Er + test.Loop_E + 4.10+dE, test.Duplex_El, test.Duplex_Er, test.Loop_E, test.Loop_D,dE ,test.fullStemEnergy, s5,s4); if(name){ int begin_t, end_t, begin_q, end_q, and, pipe, i; char psoutput[100]; begin_q=0; end_q=n4-10; begin_t=0; end_t=n5-test.i+ 1-5; and=end_t+1; pipe=test.u -test.i + 1; cut_point = end_t +1 ; char *catseq, *catstruct;/* *fname; */ catseq = (char*) space(n5 + end_q -begin_q +2); catstruct = (char*) space(n5 + end_q -begin_q +2); strcpy(catseq, s5); strncpy(catstruct, test.structure, end_t); strcat(catseq, s4); strncat(catstruct, test.structure+end_t+1, end_q-begin_q+1); catstruct[end_t - begin_t + end_q-begin_q+2]='\0'; catseq[end_t - begin_t + end_q-begin_q+2]='\0'; int *relative_access; relative_access = space(sizeof(int)*strlen(s5)); relative_access[0] = access_s1[1][pos - (n5 - test.i) + 5]; for(i=1;i<strlen(s5);i++){ relative_access[i] = access_s1[i+1][pos - (n5 - test.i) + i + 5] - access_s1[i][pos - (n5 - test.i) + i + 4]; } char str[16]; char upos[16]; strcpy(psoutput,"sno_XS_"); sprintf(str,"%d",count); strcat(psoutput,str); sprintf(upos,"%d",pos - (n5 - test.u )); strcat(psoutput,"_u_"); strcat(psoutput,upos); strcat(psoutput,"_"); strcat(psoutput,name); strcat(psoutput,".ps\0"); PS_rna_plot_snoop_a(catseq, catstruct, psoutput,relative_access,NULL); free(catseq);free(catstruct);free(relative_access); count++; } free(s3);free(s4);free(s5);free(test.structure); } } } snoopT snoopfold_XS(const char *s1, const char *s2, const int **access_s1, const int pos_i, const int pos_j, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2, const int fullStemEnergy) { /* int Eminj, Emin_l; */ int a,b,i, j, Emin=INF, a_min=0, b_min=0; char *struc; snoopT mfe; int *indx; int *mLoop; int *cLoop; folden** foldlist, **foldlist_XS; int Duplex_El, Duplex_Er; int Loop_D; int u; int Loop_E; Duplex_El=0;Duplex_Er=0;Loop_E=0, Loop_D=0; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); n1 = (int) strlen(s1); n2 = (int) strlen(s2); if ((!P) || (fabs(P->temperature - temperature)>1e-6)) { snoupdate_fold_params(); if(P) free(P); P = scale_parameters(); make_pair_matrix(); } c = (int **) space(sizeof(int *) * (n1+1)); r = (int **) space(sizeof(int *) * (n1+1)); for (i=0; i<=n1; i++) { c[i] = (int *) space(sizeof(int) * (n2+1)); r[i] = (int *) space(sizeof(int) * (n2+1)); for(j=n2; j>-1; j--){ c[i][j]=INF; r[i][j]=INF; } } encode_seqs(s1, s2); i=n1-5; j=pos_j; /* printf("tar: %s\nsno: %s\n ", s1, s2); */ /* printf("pos_i %d pos_j %d\n", pos_i, pos_j); */ /* printf("type %d n1 %d n2 %d S1[n1] %d S2[n2] %d", pair[S1[i]][S2[j]], n1, n2, S1[n1], S2[n2]); */ int type, type2, E, p,q; r[i][j] = P->DuplexInit; /* r[i][j] += P->dangle3[rtype[type]][SS1[i+1]] + P->dangle5[rtype[type]][SS2[j-1]]; */ if(pair[S1[i]][S2[j]]>2) r[i][j]+=P->TerminalAU; for(a=i-1; a>0;a--){ /* i-1 */ r[a+1][0]=INF; for(b=j+1; b<=n2-min_d2;b++){ /* j+1 */ r[a][b]=INF; type = pair[S1[a]][S2[b]]; if(!type) continue; if(S1[a+1]==4){ folden * temp; temp=foldlist_XS[b-1]; while(temp->next) { int k = temp->k; if(pair[S1[a+3]][S2[k-1]] && k< max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 -min_s2 -half_stem /*&& r[a+3][k-1] + access_s1[i-(a+3)+1][pos_i] < 411*/) { /* remove last condition last condition is to check if the interaction is stable enough */ c[a][b]=MIN2(c[a][b], r[a+3][k-1]+temp->energy); } temp=temp->next; } } if(S1[a+2]==4){ folden * temp; temp=foldlist_XS[b-1]; while(temp->next){ int k = temp->k; if(pair[S1[a+4]][S2[k-1]] && k< max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 -min_s2 -half_stem /*&& r[a+4][k-1] + access_s1[i-(a+4)+1][pos_i] < 411 */ ) { /* remove last condition */ c[a][b]=MIN2(c[a][b], r[a+4][k-1]+temp->energy); } temp=temp->next; } } for(p=a+1; p<n1 && (p-a) < MAXLOOP_L; p++) { /* p < n1 */ for (q=b-1; q > 1 ; q--) { /* q > 1 */ if (p-a+b-q>2*MAXLOOP_L-2) break; if (abs((p-a)-(b-q)) >= ASS ) continue; type2 = pair[S1[p]][S2[q]]; if (!type2) continue; E = E_IntLoop(p-a-1, b-q-1, type2, rtype[type],SS1[a+1], SS2[b-1], SS1[p-1], SS2[q+1],P); c[a][b] = MIN2(c[a][b], c[p][q]+E); r[a][b] = MIN2(r[a][b], r[p][q]+E); } } E = c[a][b]; if (type>2) E += P->TerminalAU; /* E +=P->dangle5[rtype[type]][SS1[i+1]]; */ /* E +=P->dangle5[rtype[type]][SS2[j-1]]; */ E+=access_s1[i-a+1][pos_i]; if (E<Emin) { Emin=E; a_min=a; b_min=b; } } } if(Emin > 0){ printf("no target found under the constraints chosen\n"); for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); free(S1); free(S2); free(SS1); free(SS2); mfe.energy=INF; return mfe; } type2=pair[S1[a_min]][S2[b_min]]; if(type2>2) Emin +=P->TerminalAU; mfe.energy = ((float) (Emin))/100; struc = snoop_backtrack_XS(a_min, b_min,s2, &Duplex_El, &Duplex_Er, &Loop_E, &Loop_D, &u, penalty, threshloop, threshLE, threshRE,threshDE, threshD, half_stem, max_half_stem, min_s2, max_s2, min_s1, max_s1, min_d1, min_d2); mfe.i = a_min; mfe.j = b_min; mfe.u = u; mfe.Duplex_Er = (float) Duplex_Er/100; mfe.Duplex_El = (float) Duplex_El/100; mfe.Loop_D = (float) Loop_D/100; mfe.Loop_E = (float) Loop_E/100; mfe.energy = (float) Emin/100 ; mfe.fullStemEnergy = (float) fullStemEnergy/100; mfe.structure = struc; return mfe; } PRIVATE char *snoop_backtrack_XS(int i, int j, const char* snoseq, int *Duplex_El, int *Duplex_Er, int *Loop_E, int *Loop_D, int *u, const int penalty, const int threshloop, const int threshLE, const int threshRE, const int threshDE, const int threshD, const int half_stem, const int max_half_stem, const int min_s2, const int max_s2, const int min_s1, const int max_s1, const int min_d1, const int min_d2) { /* backtrack structure going backwards from i, and forwards from j return structure in bracket notation with & as separator */ int k, l, type, type2, E, traced, i0, j0; int traced_c=0; /* flag for following backtrack in c or r */ char *st1, *st2, *struc; char *struc_loop; st1 = (char *) space(sizeof(char)*(n1+1)); st2 = (char *) space(sizeof(char)*(n2+1)); int *indx; int *mLoop; int *cLoop; folden **foldlist, **foldlist_XS; type=pair[S1[i]][S2[j]]; snoexport_fold_arrays(&indx, &mLoop, &cLoop,&foldlist, &foldlist_XS ); i0=i;j0=j; /* i0=MAX2(i,1); j0=MIN2(j+1,n2); */ while (i<=n1 && j>=1 ) { if(!traced_c) { E = c[i][j]; traced=0; st1[i] = '<'; st2[j-1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) nrerror("backtrack failed in fold duplex c"); for (k=i+1; k>0 && (k-i)<MAXLOOP_L; k++) { for (l=j-1; l>=1 ; l--) { int LE; if (k-i+j-l>2*MAXLOOP_L-2) break; if (abs(k-i-j+l) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(k-i-1, j-l-1, type2, rtype[type], SS1[i+1], SS2[j-1], SS1[k-1], SS2[l+1],P); if (E == c[k][l]+LE) { traced=1; i=k; j=l; *Duplex_El+=LE; break; } } if (traced) break; } if(!traced){ if(S1[i+1]==4) { folden * temp; temp=foldlist_XS[j-1]; while(temp->next) { int k = temp->k; if(pair[S1[i+3]][S2[k-1]] && k< max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 -min_s2 -half_stem ) { if(E==r[i+3][k-1]+temp->energy){ *Loop_E=temp->energy; st1[i+1]= '|'; st1[i+2]='.'; *u=i+1; int a,b; for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[j-1-a]+k+b; if(cLoop[ij]==temp->energy) { struc_loop=snobacktrack_fold_from_pair(snoseq, k+b, j-1-a); a=INF; b=INF; } } } traced=1; traced_c=1; i=i+3;j=k-1; break; } } temp=temp->next; } } if (S1[i+2]==4){ /* introduce structure from RNAfold */ folden * temp; temp=foldlist_XS[j-1]; while(temp->next) { int k = temp->k; if(pair[S1[i+4]][S2[k-1]] && k< max_s1 && k > min_s1 && k > n2 - max_s2 - max_half_stem && k < n2 -min_s2 -half_stem ) { if(E==r[i+4][k-1]+temp->energy){ *Loop_E=temp->energy; st1[i+2]= '|'; st1[i+1]=st1[i+3]='.'; *u=i+2; int a,b; for(a=0; a< MISMATCH ;a++){ for(b=0; b< MISMATCH ; b++){ int ij=indx[j-1-a]+k+b; if(cLoop[ij]==temp->energy) { struc_loop=snobacktrack_fold_from_pair(snoseq, k+b, j-a-1); a=INF; b=INF; } } } traced=1; traced_c=1; i=i+4;j=k-1; break; } } temp=temp->next; } } }/* traced? */ }/* traced_r? */ else{ E = r[i][j]; traced=0; st1[i] = '<'; st2[j-1] = '>'; type = pair[S1[i]][S2[j]]; if (!type) nrerror("backtrack failed in fold duplex r"); for (k=i+1; k>0 && (k-i)<MAXLOOP_L; k++) { for (l=j-1; l>=1 ; l--) { int LE; if (k-i+j-l>2*MAXLOOP_L-2) break; if (abs(k-i-j+l) >= ASS) continue; type2 = pair[S1[k]][S2[l]]; if (!type2) continue; LE = E_IntLoop(k-i-1, j-l-1, type2, rtype[type], SS1[i+1], SS2[j-1], SS1[k-1], SS2[l+1],P); if (E == r[k][l]+LE) { traced=1; i=k; j=l; *Duplex_Er+=LE; break; } } if (traced) break; } } if (!traced) { /* if (i>1) {E -= P->dangle5[type][SS1[i-1]]; *Duplex_El +=P->dangle5[type][SS1[i-1]];} */ /* if (j<n2) {E -= P->dangle3[type][SS2[j+1]]; *Duplex_El +=P->dangle3[type][SS2[j+1]];} */ if (type>2) {E -= P->TerminalAU; *Duplex_Er +=P->TerminalAU;} if (E != P->DuplexInit) { nrerror("backtrack failed in fold duplex end"); } else break; } } /* struc = (char *) space(i0-i+1+j-j0+1+2); */ /* declare final duplex structure */ struc = (char *) space(i-i0+1+n2); /* declare final duplex structure */ char * struc2; struc2 = (char *) space(n2+1); /* char * struct_const; */ for (k=MIN2(i0,1); k<=i; k++) if (!st1[k-1]) st1[k-1] = '.'; /* for (k=j0; k<=j; k++) if (!st2[k-1]) st2[k-1] = struc_loop[k-1];*/ /* '.'; normal */ /* char * struct_const; */ /* struct_const = (char *) space(sizeof(char)*(n2+1)); */ for (k=1; k<=n2; k++) { if (!st2[k-1]) st2[k-1] = struc_loop[k-1];/* '.'; */ struc2[k-1] = st2[k-1];/* '.'; */ /* if (k>=j0 && k<=j){ */ /* struct_const[k-1]='x'; */ /* } */ /* else{ */ /* if(k<j0) {struct_const[k-1]='<';} */ /* if(k>j) {struct_const[k-1]='>';} */ /* } */ } char duplexseq_1[j]; char duplexseq_2[n2-j0+2]; if(j0<n2){ strncpy(duplexseq_1, snoseq, j-1); strcpy(duplexseq_2, snoseq + j0); duplexseq_1[j-1]='\0'; duplexseq_2[n2-j0+1]='\0'; duplexT temp; temp=duplexfold(duplexseq_1, duplexseq_2); *Loop_D = MIN2(0,-410 + (int) 100 * temp.energy); if(*Loop_D){ int l1,ibegin, iend, jbegin, jend; l1=strchr(temp.structure, '&')-temp.structure; ibegin=temp.i-l1; iend =temp.i-1; jbegin=temp.j; jend =temp.j+strlen(temp.structure)-l1-2-1; for(k=ibegin+1; k<=iend+1; k++){ struc2[k-1]=temp.structure[k-ibegin-1]; } for(k=jbegin+j0; k<=jend+j0; k++){ struc2[k-1]=temp.structure[l1+k-j0-jbegin+1]; } } free(temp.structure); } strcpy(struc, st1+MAX2(i0,1)); strcat(struc, "&"); /* strcat(struc, st2); */ strncat(struc, struc2+5, strlen(struc2)-10); free(struc2); free(struc_loop); free(st1); free(st2); for (i=0; i<=n1; i++) {free(r[i]);free(c[i]);} free(c); free(r); free(S1);free(S2);free(SS1);free(SS2); /* free_arrays(); */ return struc; } PRIVATE int covscore(const int *types, int n_seq) { /* calculate co-variance bonus for a pair depending on */ /* compensatory/consistent mutations and incompatible seqs */ /* should be 0 for conserved pairs, >0 for good pairs */ #define NONE -10000 /* score for forbidden pairs */ int k,l,s,score, pscore; int dm[7][7]={{0,0,0,0,0,0,0}, /* hamming distance between pairs */ {0,0,2,2,1,2,2} /* CG */, {0,2,0,1,2,2,2} /* GC */, {0,2,1,0,2,1,2} /* GU */, {0,1,2,2,0,2,1} /* UG */, {0,2,2,1,2,0,2} /* AU */, {0,2,2,2,1,2,0} /* UA */}; int pfreq[8]={0,0,0,0,0,0,0,0}; for (s=0; s<n_seq; s++) pfreq[types[s]]++; if (pfreq[0]*2>n_seq) return NONE; for (k=1,score=0; k<=6; k++) /* ignore pairtype 7 (gap-gap) */ for (l=k+1; l<=6; l++) /* scores for replacements between pairtypes */ /* consistent or compensatory mutations score 1 or 2 */ score += pfreq[k]*pfreq[l]*dm[k][l]; /* counter examples score -1, gap-gap scores -0.25 */ pscore = cv_fact * ((UNIT*score)/n_seq - nc_fact*UNIT*(pfreq[0] + pfreq[7]*0.25)); return pscore; } /*---------------------------------------------------------------------------*/ PRIVATE short * aliencode_seq(const char *sequence) { unsigned int i,l; short *Stemp; l = strlen(sequence); Stemp = (short *) space(sizeof(short)*(l+2)); Stemp[0] = (short) l; /* make numerical encoding of sequence */ for (i=1; i<=l; i++) Stemp[i]= (short) encode_char(toupper(sequence[i-1])); /* for circular folding add first base at position n+1 */ /* Stemp[l+1] = Stemp[1]; */ return Stemp; } PRIVATE short * encode_seq(const char *sequence) { unsigned int i,l; short *S; l = strlen(sequence); extern double nc_fact; S = (short *) space(sizeof(short)*(l+2)); S[0] = (short) l; /* make numerical encoding of sequence */ for (i=1; i<=l; i++) S[i]= (short) encode_char(toupper(sequence[i-1])); /* for circular folding add first base at position n+1 */ S[l+1] = S[1]; return S; } PRIVATE void encode_seqs(const char *s1, const char *s2) { unsigned int i,l; l = strlen(s1); S1 = encode_seq(s1); SS1= (short *) space(sizeof(short)*(l+1)); /* SS1 exists only for the special X K and I bases and energy_set!=0 */ for (i=1; i<=l; i++) { /* make numerical encoding of sequence */ SS1[i] = alias[S1[i]]; /* for mismatches of nostandard bases */ } l = strlen(s2); S2 = encode_seq(s2); SS2= (short *) space(sizeof(short)*(l+1)); /* SS2 exists only for the special X K and I bases and energy_set!=0 */ for (i=1; i<=l; i++) { /* make numerical encoding of sequence */ SS2[i] = alias[S2[i]]; /* for mismatches of nostandard bases */ } } PRIVATE int compare(const void *sub1, const void *sub2) { int d; if (((snoopT *) sub1)->energy > ((snoopT *) sub2)->energy) return 1; if (((snoopT *) sub1)->energy < ((snoopT *) sub2)->energy) return -1; d = ((snoopT *) sub1)->i - ((snoopT *) sub2)->i; if (d!=0) return d; return ((snoopT *) sub1)->j - ((snoopT *) sub2)->j; }
tinyexr.h
/* Copyright (c) 2014 - 2019, Syoyo Fujita and many contributors. 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) #define TINYEXR_ERROR_CANT_WRITE_FILE (-10) #define TINYEXR_ERROR_SERIALZATION_FAILED (-11) // @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_HEADER_ATTRIBUTES (1024) #define TINYEXR_MAX_CUSTOM_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; // array of EXRAttribute. size = // `num_custom_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. } // Simple wrapper API for ParseEXRHeaderFromFile. // checking given file is a EXR file(by just look up header) // @return TINYEXR_SUCCEES for EXR image, TINYEXR_ERROR_INVALID_HEADER for // others extern int IsEXR(const char *filename); // @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. // Use ZIP compression by default. // Returns negative value and may set error string in `err` when there's an // error extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename, const char **err); // @Dado added std::pair<const unsigned char*, size_t> saveEXRFromMemory(const float *data, int width, int height, int components, const int save_as_fp16); // 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); // Free's error message extern void FreeEXRErrorMessage(const char *msg); // 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`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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`. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 success. // Return zero and will set error string in `err` when there's an // error. // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 // When there was an error message, Application must free `err` with // FreeEXRErrorMessage() 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 <iostream> // debug #include <limits> #include <string> #include <vector> #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 #if __has_warning("-Wtautological-constant-compare") #pragma clang diagnostic ignored "-Wtautological-constant-compare" #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 } // namespace miniz #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 void SetErrorMessage(const std::string &msg, const char **err) { if (err) { #ifdef _WIN32 (*err) = _strdup(msg.c_str()); #else (*err) = strdup(msg.c_str()); #endif } } static const int kEXRVersionSize = 8; static void cpy2(unsigned short *dst_val, const unsigned short *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; } 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 } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif static void cpy4(int *dst_val, const int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(unsigned int *dst_val, const unsigned int *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } static void cpy4(float *dst_val, const float *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; } #ifdef __clang__ #pragma clang diagnostic pop #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 } #if 0 static void cpy8(tinyexr::tinyexr_uint64 *dst_val, const tinyexr::tinyexr_uint64 *src_val) { unsigned char *dst = reinterpret_cast<unsigned char *>(dst_val); const unsigned char *src = reinterpret_cast<const unsigned char *>(src_val); dst[0] = src[0]; dst[1] = src[1]; dst[2] = src[2]; dst[3] = src[3]; dst[4] = src[4]; dst[5] = src[5]; dst[6] = src[6]; dst[7] = src[7]; } #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) { if ((*type).compare("string") == 0) { // Accept empty string attribute. marker += sizeof(uint32_t); size -= sizeof(uint32_t); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t); data->resize(1); (*data)[0] = '\0'; return true; } else { 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); } struct ChannelInfo{ 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]; } ; 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; } const unsigned char *data_end = reinterpret_cast<const unsigned char *>(p) + 16; if (data_end >= (data.data() + data.size())) { 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; // Fixes #116: Add bounds check to in buffer. if ((0 > (maxLength -= count)) || (inLength < 0)) 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 bool 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 true; } // Workaround for issue #112. // TODO(syoyo): Add more robust out-of-bounds check in `rleUncompress`. if (src_size <= 2) { return false; } 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))); if (ret != static_cast<int>(uncompressed_size)) { return false; } // // 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; } } return true; } #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. // std::vector<int> hlink(HUF_ENCSIZE); std::vector<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()); std::vector<long long> scode(HUF_ENCSIZE); memset(scode.data(), 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.data()); memcpy(frq, scode.data(), 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; \ } #if 0 #define getCode(po, rlc, c, lc, in, out, ob, oe) \ { \ if (po == rlc) { \ if (lc < 8) getChar(c, lc, in); \ \ lc -= 8; \ \ unsigned char cs = (c >> lc); \ \ if (out + cs > oe) return false; \ \ /* TinyEXR issue 78 */ \ unsigned short s = out[-1]; \ \ while (cs-- > 0) *out++ = s; \ } else if (out < oe) { \ *out++ = po; \ } else { \ return false; \ } \ } #else static bool getCode(int po, int rlc, long long &c, int &lc, const char *&in, const char *in_end, unsigned short *&out, const unsigned short *ob, const unsigned short *oe) { (void)ob; if (po == rlc) { if (lc < 8) { /* TinyEXR issue 78 */ if ((in + 1) >= in_end) { return false; } getChar(c, lc, in); } lc -= 8; unsigned char cs = (c >> lc); if (out + cs > oe) return false; // Bounds check for safety // Issue 100. if ((out - 1) < ob) return false; unsigned short s = out[-1]; while (cs-- > 0) *out++ = s; } else if (out < oe) { *out++ = po; } else { return false; } return true; } #endif // // 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; // begin unsigned short *oe = out + no; // end 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; // std::cout << "lit = " << pl.lit << std::endl; // std::cout << "rlc = " << rlc << std::endl; // std::cout << "c = " << c << std::endl; // std::cout << "lc = " << lc << std::endl; // std::cout << "in = " << in << std::endl; // std::cout << "out = " << out << std::endl; // std::cout << "oe = " << oe << std::endl; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } 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; if (!getCode(pl.p[j], rlc, c, lc, in, ie, out, outb, oe)) { return false; } 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; if (!getCode(pl.lit, rlc, c, lc, in, ie, out, outb, oe)) { return false; } } else { return false; // invalidCode(); // wrong (long) code } } if (out - outb != no) { return false; } // notEnoughData (); return true; } static void countFrequencies(std::vector<long long> &freq, 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; std::vector<long long> freq(HUF_ENCSIZE); countFrequencies(freq, raw, nRaw); int im = 0; int iM = 0; hufBuildEncTable(freq.data(), &im, &iM); char *tableStart = compressed + 20; char *tableEnd = tableStart; hufPackEncTable(freq.data(), im, iM, &tableEnd); int tableLength = tableEnd - tableStart; char *dataStart = tableEnd; int nBits = hufEncode(freq.data(), 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, std::vector<unsigned short> *raw) { if (nCompressed == 0) { if (raw->size() != 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, raw->size(), raw->data()); } // 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) { std::vector<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.data(), minNonZero, maxNonZero); std::vector<unsigned short> lut(USHORT_RANGE); unsigned short maxValue = forwardLutFromBitmap(bitmap.data(), lut.data()); applyLut(lut.data(), &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; } std::vector<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.data(), 0, BITMAP_SIZE); const unsigned char *ptr = inPtr; // minNonZero = *(reinterpret_cast<const unsigned short *>(ptr)); tinyexr::cpy2(&minNonZero, reinterpret_cast<const unsigned short *>(ptr)); // maxNonZero = *(reinterpret_cast<const unsigned short *>(ptr + 2)); tinyexr::cpy2(&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; } std::vector<unsigned short> lut(USHORT_RANGE); memset(lut.data(), 0, sizeof(unsigned short) * USHORT_RANGE); unsigned short maxValue = reverseLutFromBitmap(bitmap.data(), lut.data()); // // Huffman decoding // int length; // length = *(reinterpret_cast<const int *>(ptr)); tinyexr::cpy4(&length, reinterpret_cast<const int *>(ptr)); ptr += sizeof(int); if (size_t((ptr - inPtr) + length) > inLen) { return false; } std::vector<unsigned short> tmpBuffer(tmpBufSize); hufUncompress(reinterpret_cast<const char *>(ptr), length, &tmpBuffer); // // 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.data(), &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 // // ----------------------------------------------------------------- // // TODO(syoyo): Refactor function arguments. 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 if ((width == 0) || (num_lines == 0) || (pixel_data_size == 0)) { // Invalid input #90 return false; } // 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); if (!ret) { return false; } // 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]; // use `cpy` to avoid unaligned memory access when compiler's // optimization is on. tinyexr::cpy2(&(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]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } image += offset; *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; // val = line_ptr[u]; tinyexr::cpy4(&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; // val = line_ptr[u]; tinyexr::cpy4(&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::cpy2(&(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]; size_t offset = 0; if (line_order == 0) { offset = (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { offset = (static_cast<size_t>(height) - 1U - (static_cast<size_t>(line_no) + v)) * static_cast<size_t>(x_stride) + u; } image += offset; *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; // val = line_ptr[u]; tinyexr::cpy4(&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; // val = line_ptr[u]; tinyexr::cpy4(&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()); if (dstLen == 0) { return false; } if (!tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len))) { return false; } // 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::cpy2(&(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; // val = line_ptr[u]; tinyexr::cpy4(&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; // val = line_ptr[u]; tinyexr::cpy4(&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; tinyexr::cpy4(&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++) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::cpy2(&(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 += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // address may not be aliged. use byte-wise copy for safety.#76 // hf.u = line_ptr[u]; tinyexr::cpy2(&(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 + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } if (reinterpret_cast<const unsigned char *>(line_ptr + width) > (data_ptr + data_len)) { // Insufficient data size return false; } for (int u = 0; u < width; u++) { float val; tinyexr::cpy4(&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 + v * pixel_data_size * size_t(width) + channel_offset_list[c] * static_cast<size_t>(width)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += (size_t(y) + v) * size_t(x_stride); } else { outLine += (size_t(height) - 1 - (size_t(y) + v)) * size_t(x_stride); } for (int u = 0; u < width; u++) { if (reinterpret_cast<const unsigned char *>(line_ptr + u) >= (data_ptr + data_len)) { // Corrupsed data? return false; } unsigned int val; tinyexr::cpy4(&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 bool 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 { // ??? return false; } } return true; } 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 (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { if (err) { (*err) += "Insufficient data size for attributes.\n"; } 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)) { if (err) { (*err) += "Failed to read attribute.\n"; } 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.\n"; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) += "# of channels is zero.\n"; } 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_CUSTOM_ATTRIBUTES) if (info->attributes.size() < TINYEXR_MAX_CUSTOM_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; } exr_header->num_custom_attributes = static_cast<int>(info.attributes.size()); if (exr_header->num_custom_attributes > 0) { // TODO(syoyo): Report warning when # of attributes exceeds // `TINYEXR_MAX_CUSTOM_ATTRIBUTES` if (exr_header->num_custom_attributes > TINYEXR_MAX_CUSTOM_ATTRIBUTES) { exr_header->num_custom_attributes = TINYEXR_MAX_CUSTOM_ATTRIBUTES; } exr_header->custom_attributes = static_cast<EXRAttribute *>(malloc( sizeof(EXRAttribute) * size_t(exr_header->num_custom_attributes))); 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; } } else { exr_header->custom_attributes = NULL; } 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, std::string *err) { 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; if ((data_width < 0) || (data_height < 0)) { if (err) { std::stringstream ss; ss << "Invalid data width or data height: " << data_width << ", " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if ((data_width > threshold) || (data_height > threshold)) { if (err) { std::stringstream ss; ss << "data_with or data_height too large. data_width: " << data_width << ", " << "data_height = " << data_height << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } } size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; if (!tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels)) { if (err) { (*err) += "Failed to compute channel layout.\n"; } return TINYEXR_ERROR_INVALID_DATA; } bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { // value check if (exr_header->tile_size_x < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size x : " << exr_header->tile_size_x << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } if (exr_header->tile_size_y < 0) { if (err) { std::stringstream ss; ss << "Invalid tile size y : " << exr_header->tile_size_y << "\n"; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_HEADER; } 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, exr_header->tile_size_x, exr_header->tile_size_y); // 16 byte: tile coordinates // 4 byte : data size // ~ : data(uncompressed or compressed) if (offsets[tile_idx] + sizeof(int) * 5 > size) { if (err) { (*err) += "Insufficient data size.\n"; } return TINYEXR_ERROR_INVALID_DATA; } size_t data_size = size_t(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) { if (err) { (*err) += "Insufficient data length.\n"; } 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 // Don't allow too large image(256GB * pixel_data_size or more). Workaround // for #104. size_t total_data_len = size_t(data_width) * size_t(data_height) * size_t(num_channels); const bool total_data_len_overflown = sizeof(void*) == 8 ? (total_data_len >= 0x4000000000) : false; if ((total_data_len == 0) || total_data_len_overflown ) { if (err) { std::stringstream ss; ss << "Image data size is zero or too large: width = " << data_width << ", height = " << data_height << ", channels = " << num_channels << std::endl; (*err) += ss.str(); } return TINYEXR_ERROR_INVALID_DATA; } 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_t(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 if (data_len == 0) { // TODO(syoyo): May be ok to raise the threshold for example `data_len // < 4` invalid_data = true; } else { // line_no may be negative. 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; 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 // overflow check tinyexr_int64 lno = static_cast<tinyexr_int64>(line_no) - static_cast<tinyexr_int64>(exr_header->data_window[1]); if (lno > std::numeric_limits<int>::max()) { line_no = -1; // invalid } else if (lno < -std::numeric_limits<int>::max()) { line_no = -1; // invalid } else { 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) { if (err) { std::stringstream ss; (*err) += "Invalid data found when decoding pixels.\n"; } 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)) { tinyexr::SetErrorMessage("Invalid argument for DecodeEXRImage().", err); 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 tinyexr::SetErrorMessage("Invalid data width value", err); 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()) { tinyexr::SetErrorMessage("Invalid data height value", err); return TINYEXR_ERROR_INVALID_DATA; } data_height++; if ((data_width < 0) || (data_height < 0)) { tinyexr::SetErrorMessage("data width or data height is negative.", err); return TINYEXR_ERROR_INVALID_DATA; } // Do not allow too large data_width and data_height. header invalid? { const int threshold = 1024 * 8192; // heuristics if (data_width > threshold) { tinyexr::SetErrorMessage("data width too large.", err); return TINYEXR_ERROR_INVALID_DATA; } if (data_height > threshold) { tinyexr::SetErrorMessage("data height too large.", err); 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; // Issue #81 if ((marker + sizeof(tinyexr_uint64)) >= (head + size)) { tinyexr::SetErrorMessage("Insufficient data size in offset table.", err); return TINYEXR_ERROR_INVALID_DATA; } memcpy(&offset, marker, sizeof(tinyexr::tinyexr_uint64)); tinyexr::swap8(&offset); if (offset >= size) { tinyexr::SetErrorMessage("Invalid offset value in DecodeEXRImage.", err); 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 { tinyexr::SetErrorMessage( "Cannot reconstruct lineOffset table in DecodeEXRImage.", err); return TINYEXR_ERROR_INVALID_DATA; } } } { std::string e; int ret = DecodeChunk(exr_image, exr_header, offsets, head, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } // release memory(if exists) if ((exr_header->num_channels > 0) && exr_image && exr_image->images) { for (size_t c = 0; c < size_t(exr_header->num_channels); c++) { if (exr_image->images[c]) { free(exr_image->images[c]); exr_image->images[c] = NULL; } } free(exr_image->images); exr_image->images = NULL; } } return ret; } } } // namespace tinyexr int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { if (out_rgba == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadEXR()", err); 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) { tinyexr::SetErrorMessage("Invalid EXR header.", err); return ret; } if (exr_version.multipart || exr_version.non_image) { tinyexr::SetErrorMessage( "Loading multipart or DeepImage is not supported in LoadEXR() API", err); return TINYEXR_ERROR_INVALID_DATA; // @fixme. } } { int ret = ParseEXRHeaderFromFile(&exr_header, &exr_version, filename, err); if (ret != TINYEXR_SUCCESS) { FreeEXRHeader(&exr_header); 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) { FreeEXRHeader(&exr_header); 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 (exr_header.num_channels == 1) { // Grayscale 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))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { 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) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @todo { free exr_image } FreeEXRHeader(&exr_header); 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))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } } else { 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 IsEXR(const char *filename) { EXRVersion exr_version; int ret = ParseEXRVersionFromFile(&exr_version, filename); if (ret != TINYEXR_SUCCESS) { return TINYEXR_ERROR_INVALID_HEADER; } 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) { tinyexr::SetErrorMessage( "Invalid argument. `memory` or `exr_header` argument is null in " "ParseEXRHeaderFromMemory()", err); // Invalid argument return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Insufficient header/data size.\n", err); 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()) { tinyexr::SetErrorMessage(err_str, err); } } 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) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRFromMemory", err); 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) { tinyexr::SetErrorMessage("Failed to parse EXR version", err); 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; } } // TODO(syoyo): Refactor removing same code as used in LoadEXR(). if (exr_header.num_channels == 1) { // Grayscale 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))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) { for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[0][srcIdx]; (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[0][srcIdx]; } } } } else { 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 { // TODO(syoyo): Support non RGBA image. if (idxR == -1) { tinyexr::SetErrorMessage("R channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxG == -1) { tinyexr::SetErrorMessage("G channel not found", err); // @todo { free exr_image } return TINYEXR_ERROR_INVALID_DATA; } if (idxB == -1) { tinyexr::SetErrorMessage("B channel not found", err); // @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))); if (exr_header.tiled) { for (int it = 0; it < exr_image.num_tiles; it++) { for (int j = 0; j < exr_header.tile_size_y; j++) for (int i = 0; i < exr_header.tile_size_x; i++) { const int ii = exr_image.tiles[it].offset_x * exr_header.tile_size_x + i; const int jj = exr_image.tiles[it].offset_y * exr_header.tile_size_y + j; const int idx = ii + jj * exr_image.width; // out of region check. if (ii >= exr_image.width) { continue; } if (jj >= exr_image.height) { continue; } const int srcIdx = i + j * exr_header.tile_size_x; unsigned char **src = exr_image.tiles[it].images; (*out_rgba)[4 * idx + 0] = reinterpret_cast<float **>(src)[idxR][srcIdx]; (*out_rgba)[4 * idx + 1] = reinterpret_cast<float **>(src)[idxG][srcIdx]; (*out_rgba)[4 * idx + 2] = reinterpret_cast<float **>(src)[idxB][srcIdx]; if (idxA != -1) { (*out_rgba)[4 * idx + 3] = reinterpret_cast<float **>(src)[idxA][srcIdx]; } else { (*out_rgba)[4 * idx + 3] = 1.0; } } } } else { 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) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); 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); if (filesize < 16) { tinyexr::SetErrorMessage("File size too short " + std::string(filename), err); return TINYEXR_ERROR_INVALID_FILE; } 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)) { tinyexr::SetErrorMessage("Invalid argument for LoadEXRImageFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (exr_header->header_len == 0) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); 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) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToMemory", err); return 0; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return 0; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); 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) { tinyexr::SetErrorMessage("Pixel type must be FLOAT for ZFP compression", err); 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<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++) { // 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))); 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)); // line_ptr[x] = f32.f; tinyexr::cpy4(line_ptr + x, &(f32.f)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { for (int y = 0; y < h; y++) { // 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))); 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); // line_ptr[x] = val; tinyexr::cpy2(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++) { // 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))); 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)); // line_ptr[x] = h16.u; tinyexr::cpy2(line_ptr + x, &(h16.u)); } } } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // 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))); 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)); // line_ptr[x] = val; tinyexr::cpy4(line_ptr + x, &val); } } } else { assert(0); } } else if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { for (int y = 0; y < h; y++) { // 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))); 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); // line_ptr[x] = val; tinyexr::cpy4(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 = 8192 + static_cast<unsigned int>( 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++) { offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } size_t totalSize = static_cast<size_t>(offset); { 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)); } if (memory.size() == 0) { tinyexr::SetErrorMessage("Output memory size is zero", err); return 0; } (*memory_out) = static_cast<unsigned char *>(malloc(totalSize)); memcpy((*memory_out), &memory.at(0), memory.size()); unsigned char *memory_ptr = *memory_out + memory.size(); for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { memcpy(memory_ptr, &data_list[i].at(0), data_list[i].size()); memory_ptr += data_list[i].size(); } return totalSize; // 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) { tinyexr::SetErrorMessage("Invalid argument for SaveEXRImageToFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #if !TINYEXR_USE_PIZ if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { tinyexr::SetErrorMessage("PIZ compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #if !TINYEXR_USE_ZFP if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { tinyexr::SetErrorMessage("ZFP compression is not supported in this build", err); return TINYEXR_ERROR_UNSUPPORTED_FEATURE; } #endif #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "wb"); #else FILE *fp = fopen(filename, "wb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if (mem_size == 0) { return TINYEXR_ERROR_SERIALZATION_FAILED; } size_t written_size = 0; if ((mem_size > 0) && mem) { written_size = fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); if (written_size != mem_size) { tinyexr::SetErrorMessage("Cannot write a file", err); return TINYEXR_ERROR_CANT_WRITE_FILE; } return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { tinyexr::SetErrorMessage("Invalid argument for LoadDeepEXR", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _MSC_VER FILE *fp = NULL; errno_t errcode = fopen_s(&fp, filename, "rb"); if ((0 != errcode) || (!fp)) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); return TINYEXR_ERROR_CANT_OPEN_FILE; } #else FILE *fp = fopen(filename, "rb"); if (!fp) { tinyexr::SetErrorMessage("Cannot read a file " + std::string(filename), err); 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); tinyexr::SetErrorMessage("File size is zero : " + std::string(filename), err); 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) { tinyexr::SetErrorMessage("Invalid magic number", err); 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) { tinyexr::SetErrorMessage("Unsupported version or scanline", err); 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)) { std::stringstream ss; ss << "Failed to parse attribute\n"; tinyexr::SetErrorMessage(ss.str(), err); 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) { std::stringstream ss; ss << "Unsupported compression type : " << compression_type; tinyexr::SetErrorMessage(ss.str(), err); 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)) { tinyexr::SetErrorMessage("Failed to parse channel info", err); return TINYEXR_ERROR_INVALID_DATA; } num_channels = static_cast<int>(channels.size()); if (num_channels < 1) { tinyexr::SetErrorMessage("Invalid channels format", err); 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 { tinyexr::SetErrorMessage("Unsupported compression format", err); 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; unsigned int *src_ptr = reinterpret_cast<unsigned int *>( &sample_data.at(size_t(data_offset) + x * sizeof(int))); tinyexr::cpy4(&ui, src_ptr); 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; const unsigned short *src_ptr = reinterpret_cast<unsigned short *>( &sample_data.at(size_t(data_offset) + x * sizeof(short))); tinyexr::cpy2(&(f16.u), src_ptr); 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; const float *src_ptr = reinterpret_cast<float *>( &sample_data.at(size_t(data_offset) + x * sizeof(float))); tinyexr::cpy4(&f, src_ptr); 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 FreeEXRErrorMessage(const char *msg) { if (msg) { free(reinterpret_cast<void *>(const_cast<char *>(msg))); } return; } 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); } } if (exr_header->custom_attributes) { free(exr_header->custom_attributes); } 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); } } free(exr_image->tiles); } 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) { tinyexr::SetErrorMessage("Invalid argument for ParseEXRHeaderFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); 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) { tinyexr::SetErrorMessage("fread() error on " + std::string(filename), err); 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 tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromMemory", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } if (size < tinyexr::kEXRVersionSize) { tinyexr::SetErrorMessage("Data size too short", err); 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) { tinyexr::SetErrorMessage(err_str, err); return ret; } if (empty_header) { marker += 1; // skip '\0' break; } // `chunkCount` must exist in the header. if (info.chunk_count == 0) { tinyexr::SetErrorMessage( "`chunkCount' attribute is not found in the header.", err); 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) { tinyexr::SetErrorMessage( "Invalid argument for ParseEXRMultipartHeaderFromFile()", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); 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) { tinyexr::SetErrorMessage("`fread' error. file may be corrupted.", err); 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)) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromMemory()", err); 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) { tinyexr::SetErrorMessage("EXRHeader variable is not initialized.", err); 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) { tinyexr::SetErrorMessage("Invalid offset size in EXR header chunks.", err); 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) { tinyexr::SetErrorMessage("Invalid `part number' in EXR header chunks.", err); return TINYEXR_ERROR_INVALID_DATA; } } std::string e; int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size, &e); if (ret != TINYEXR_SUCCESS) { if (!e.empty()) { tinyexr::SetErrorMessage(e, err); } 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) { tinyexr::SetErrorMessage( "Invalid argument for LoadEXRMultipartImageFromFile", err); return TINYEXR_ERROR_INVALID_ARGUMENT; } #ifdef _WIN32 FILE *fp = NULL; fopen_s(&fp, filename, "rb"); #else FILE *fp = fopen(filename, "rb"); #endif if (!fp) { tinyexr::SetErrorMessage("Cannot read file " + std::string(filename), err); 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, const char **err) { if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), err); return TINYEXR_ERROR_INVALID_ARGUMENT; } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } 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) } } 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; } std::pair<const unsigned char*, size_t> saveEXRFromMemory(const float *data, int width, int height, int components, const int save_as_fp16) { EXRImage image{}; const char *err{}; if ((components == 1) || components == 3 || components == 4) { // OK } else { std::stringstream ss; ss << "Unsupported component value : " << components << std::endl; tinyexr::SetErrorMessage(ss.str(), &err); } EXRHeader header; InitEXRHeader(&header); if ((width < 16) && (height < 16)) { // No compression for small image. header.compression_type = TINYEXR_COMPRESSIONTYPE_NONE; } else { header.compression_type = TINYEXR_COMPRESSIONTYPE_ZIP; } 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) } } unsigned char* memoryBuffer{}; auto size = SaveEXRImageToMemory(&image, &header, &memoryBuffer, &err); free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return {memoryBuffer, size}; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
omp.c
#include <omp.h> #include <stdio.h> #include <stdlib.h> #define CHUNK 100 #define NMAX 100000000 #define OMP_THREADS 16 static void sum_guided(const double *a, const double *b, double *c, const int n, const int chunk) { int i; #pragma omp parallel for schedule(guided, chunk) shared(a, b, c) default(none) for (i = 0; i < n; ++i) { c[i] = a[i] + b[i]; } } static void sum_dynamic(const double *a, const double *b, double *c, const int n, const int chunk) { int i; #pragma omp parallel for schedule(dynamic, chunk) shared(a, b, c) default(none) for (i = 0; i < n; ++i) { c[i] = a[i] + b[i]; } } static void sum_static(const double *a, const double *b, double *c, const int n, const int chunk) { int i; #pragma omp parallel for schedule(static, chunk) shared(a, b, c) default(none) for (i = 0; i < n; ++i) { c[i] = a[i] + b[i]; } } static void print_arr(const double *arr, const int n) { const int n_max = n < 10 ? n : 10; for (int i = 0; i < n_max; ++i) { printf("%.3f ", arr[i]); } printf("\n"); } static void profile_methods(const double *a, const double *b, double *c, const int n, const int chunk) { omp_set_dynamic(0); omp_set_num_threads(OMP_THREADS); printf("\nNum threads: %d, N: %d\n", OMP_THREADS, n); double start_time, end_time; // Method: guided. printf("\nGuided:\n"); start_time = omp_get_wtime(); sum_guided(a, b, c, n, chunk); end_time = omp_get_wtime(); printf("\nTIME OF WORK IS: %f\n", end_time - start_time); print_arr(c, n); // Method: dynamic. printf("\nDynamic:\n"); start_time = omp_get_wtime(); sum_dynamic(a, b, c, n, chunk); end_time = omp_get_wtime(); printf("\nTIME OF WORK IS: %f\n", end_time - start_time); print_arr(c, n); // Method: static. printf("\nStatic:\n"); start_time = omp_get_wtime(); sum_static(a, b, c, n, chunk); end_time = omp_get_wtime(); printf("\nTIME OF WORK IS: %f\n", end_time - start_time); print_arr(c, n); } int main(int argc, char *argv[]) { const int n = NMAX; double *a = malloc(sizeof(double) * n); double *b = malloc(sizeof(double) * n); double *c = malloc(sizeof(double) * n); for (int i = 0; i < n; ++i) { a[i] = 1; b[i] = 2; } /* const int n = 5; double *a = malloc(sizeof(double)*n); double *b = malloc(sizeof(double)*n); double *c = malloc(sizeof(double)*n); a[0] = 8, b[0] = 1; a[1] = 4, b[1] = 2; a[2] = 3, b[2] = 3; a[3] = 2, b[3] = 4; a[4] = 1, b[4] = 5; */ profile_methods(a, b, c, n, CHUNK); free(a); free(b); free(c); return 0; }
GB_binop__min_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__min_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_uint32) // A*D function (colscale): GB (_AxD__min_uint32) // D*A function (rowscale): GB (_DxB__min_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__min_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__min_uint32) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_uint32) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_uint32) // C=scalar+B GB (_bind1st__min_uint32) // C=scalar+B' GB (_bind1st_tran__min_uint32) // C=A+scalar GB (_bind2nd__min_uint32) // C=A'+scalar GB (_bind2nd_tran__min_uint32) // C type: uint32_t // A type: uint32_t // A pattern? 0 // B type: uint32_t // B pattern? 0 // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ uint32_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) \ uint32_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) \ uint32_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) \ 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_IMIN (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_MIN || GxB_NO_UINT32 || GxB_NO_MIN_UINT32) //------------------------------------------------------------------------------ // 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__min_uint32) ( 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 //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__min_uint32) ( 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__min_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__min_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 uint32_t uint32_t bwork = (*((uint32_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__min_uint32) ( 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 uint32_t *restrict Cx = (uint32_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__min_uint32) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, 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 } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_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 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) ; uint32_t alpha_scalar ; uint32_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint32_t *) alpha_scalar_in)) ; beta_scalar = (*((uint32_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__min_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__min_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__min_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__min_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__min_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)) ; 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] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_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 ; 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] = GB_IMIN (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] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_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] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_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
argon2_fmt_plug.c
/* * This software is Copyright (c) 2016 Agnieszka Bielec <bielecagnieszka8 at gmail.com>, * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * merged argon2d and argon2i into a single format file. JimF. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_argon2; #elif FMT_REGISTERS_H john_register_one(&fmt_argon2); #else #include <string.h> #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "params.h" #include "common.h" #include "formats.h" #include "options.h" #include "argon2.h" #include "argon2_core.h" #include "argon2_encoding.h" #include "memdbg.h" #define FORMAT_LABEL "argon2" #define FORMAT_NAME "" #define FORMAT_TAG_d "$argon2d$" #define FORMAT_TAG_i "$argon2i$" #define FORMAT_TAG_LEN (sizeof(FORMAT_TAG_d)-1) #if defined(__XOP__) #define ALGORITHM_NAME "Blake2 XOP" #elif defined(__AVX__) #define ALGORITHM_NAME "Blake2 AVX" #elif defined(__SSSE3__) #define ALGORITHM_NAME "Blake2 SSSE3" #elif defined(__SSE2__) #define ALGORITHM_NAME "Blake2 SSE2" #else #define ALGORITHM_NAME "Blake2" #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 100 //only in john #define BINARY_SIZE 256 //only in john #define BINARY_ALIGN sizeof(uint32_t) #define SALT_SIZE 64 //only in john #define SALT_ALIGN sizeof(uint32_t) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define OMP_SCALE 16 #ifdef _OPENMP #define THREAD_NUMBER omp_get_thread_num() #else #define THREAD_NUMBER 1 #endif static struct fmt_tests tests[] = { {"$argon2d$v=19$m=4096,t=3,p=1$ZGFtYWdlX2RvbmU$w9w3s5/zV8+PcAZlJhnTCOE+vBkZssmZf6jOq3dKv50","password"}, {"$argon2i$v=19$m=4096,t=3,p=1$ZGFtYWdlX2RvbmU$N59QwnpxDQZRj1/cO6bqm408dD6Z2Z9LKYpwFJSPVKA","password"}, {"$argon2d$v=19$m=4096,t=3,p=1$c2hvcnRfc2FsdA$zMrTcOAOUje6UqObRVh84Pe1K6gumcDqqGzRM0ILzYmj","sacrificed"}, {"$argon2i$v=19$m=4096,t=3,p=1$c2hvcnRfc2FsdA$1l4kAwUdAApoCbFH7ghBEf7bsdrOQzE4axIJ3PV0Ncrd","sacrificed"}, {"$argon2d$v=19$m=16384,t=3,p=1$c2hvcnRfc2FsdA$TLSTPihIo+5F67Y1vJdfWdB9","blessed_dead"}, {"$argon2i$v=19$m=16384,t=3,p=1$c2hvcnRfc2FsdA$vvjDVog22A5x9eljmB+2yC8y","blessed_dead"}, {"$argon2d$v=19$m=16384,t=4,p=3$YW5vdGhlcl9zYWx0$yw93eMxC8REPAwbQ0e/q43jR9+RI9HI/DHP75uzm7tQfjU734oaI3dzcMWjYjHzVQD+J4+MG+7oyD8dN/PtnmPCZs+UZ67E+rkXJ/wTvY4WgXgAdGtJRrAGxhy4rD7d5G+dCpqhrog","death_dying"}, {"$argon2i$v=19$m=16384,t=4,p=3$YW5vdGhlcl9zYWx0$K7unxwO5aeuZCpnIJ06FMCRKod3eRg8oIRzQrK3E6mGbyqlTvvl47jeDWq/5drF1COJkEF9Ty7FWXJZHa+vqlf2YZGp/4qSlAvKmdtJ/6JZU32iQItzMRwcfujHE+PBjbL5uz4966A","death_dying"}, {NULL} }; struct argon2_salt { uint32_t t_cost, m_cost, lanes; uint32_t hash_size; uint32_t salt_length; char salt[SALT_SIZE]; argon2_type type; }; static struct argon2_salt saved_salt; static region_t * memory; static void **pseudo_rands; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int *saved_len; static int threads; static size_t saved_mem_size; static uint32_t saved_segment_length; static unsigned char (*crypted)[BINARY_SIZE]; static void *get_salt(char *ciphertext); static void init(struct fmt_main *self) { int i; #ifdef _OPENMP int omp_t = omp_get_max_threads(); threads=omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #else threads=1; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypted = mem_calloc(self->params.max_keys_per_crypt, (BINARY_SIZE)); saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(int)); memory=mem_calloc(threads, sizeof(region_t)); pseudo_rands=mem_calloc(threads,sizeof(void*)); for (i=0;i<threads;i++) { init_region_t(&memory[i]); pseudo_rands[i]=NULL; } saved_mem_size=0; saved_segment_length=0; } static void done(void) { int i; for (i=0;i<threads;i++) { free_region_t(&memory[i]); MEM_FREE(pseudo_rands[i]); } MEM_FREE(memory); MEM_FREE(pseudo_rands); MEM_FREE(saved_len); MEM_FREE(crypted); MEM_FREE(saved_key); } static void print_memory(double memory) { char s[]="\0kMGT"; int i=0; while(memory>=1024) { memory/=1024; i++; } printf("memory per hash : %.2lf %cB\n",memory,s[i]); } static void reset(struct db_main *db) { static int printed=0; if (!printed && options.verbosity > VERB_LEGACY) { int i; uint32_t m_cost, prev_m_cost; m_cost=prev_m_cost=0; if (!db) { for (i = 0; tests[i].ciphertext; i++) { struct argon2_salt *salt; salt=get_salt(tests[i].ciphertext); m_cost = MAX(m_cost, salt->m_cost); if (i==0) { printf("\n"); prev_m_cost=m_cost; print_memory(sizeof(block)*m_cost); } } if (prev_m_cost!=m_cost) { printf("max "); print_memory(sizeof(block)*m_cost); } } else { struct db_salt *salts = db->salts; while (salts != NULL) { struct argon2_salt * salt=salts->salt; m_cost = MAX(m_cost, salt->m_cost); salts = salts->next; } printf("\n"); print_memory(sizeof(block)*m_cost); } } } static void ctx_init(argon2_context *ctx) { //size_t maxadlen = ctx->adlen; //size_t maxsaltlen = ctx->saltlen; //size_t maxoutlen = ctx->outlen; static uint8_t out[BINARY_SIZE]; static uint8_t salt[SALT_SIZE]; ctx->adlen=0; ctx->saltlen=SALT_SIZE; ctx->outlen=BINARY_SIZE; ctx->out=out; ctx->salt=salt; } static int valid(char *ciphertext, struct fmt_main *self) { argon2_context ctx; int res; ctx_init(&ctx); if (!strncmp(ciphertext, FORMAT_TAG_d, FORMAT_TAG_LEN)) res=argon2_decode_string(&ctx, ciphertext, Argon2_d); else if (!strncmp(ciphertext, FORMAT_TAG_i, FORMAT_TAG_LEN)) res=argon2_decode_string(&ctx, ciphertext, Argon2_i); else return 0; if (res!=ARGON2_OK || ctx.outlen < 8) return 0; return 1; } static void set_key(char *key, int index) { saved_len[index] = strnzcpyn(saved_key[index], key, sizeof(*saved_key)); } static char *get_key(int index) { return saved_key[index]; } static void *get_binary(char *ciphertext) { static char out[BINARY_SIZE]; argon2_context ctx; ctx_init(&ctx); if (!strncmp(ciphertext, FORMAT_TAG_d, FORMAT_TAG_LEN)) argon2_decode_string(&ctx, ciphertext, Argon2_d); else argon2_decode_string(&ctx, ciphertext, Argon2_i); memset(out, 0, BINARY_SIZE); memcpy(out, ctx.out, ctx.outlen); return out; } static void *get_salt(char *ciphertext) { static struct argon2_salt salt; argon2_context ctx; memset(&salt,0,sizeof(salt)); ctx_init(&ctx); if (!strncmp(ciphertext, FORMAT_TAG_d, FORMAT_TAG_LEN)) { argon2_decode_string(&ctx, ciphertext, Argon2_d); salt.type = Argon2_d; } else { argon2_decode_string(&ctx, ciphertext, Argon2_i); salt.type = Argon2_i; } salt.salt_length = ctx.saltlen; salt.m_cost = ctx.m_cost; salt.t_cost = ctx.t_cost; salt.lanes = ctx.lanes; salt.hash_size = ctx.outlen; memcpy(salt.salt, ctx.salt, ctx.saltlen); return (void *)&salt; } static void set_salt(void *salt) { uint32_t i; size_t mem_size; uint32_t segment_length, memory_blocks; memcpy(&saved_salt,salt,sizeof(struct argon2_salt)); mem_size=sizeof(block)*saved_salt.m_cost; memory_blocks = saved_salt.m_cost; if (memory_blocks < 2 * ARGON2_SYNC_POINTS * saved_salt.lanes) { memory_blocks = 2 * ARGON2_SYNC_POINTS * saved_salt.lanes; } segment_length = memory_blocks / (saved_salt.lanes * ARGON2_SYNC_POINTS); if (mem_size>saved_mem_size) { if (saved_mem_size>0) for (i=0;i<threads;i++) free_region_t(&memory[i]); for (i=0;i<threads;i++) alloc_region_t(&memory[i],mem_size); saved_mem_size=mem_size; } if (segment_length>saved_segment_length) { if (saved_segment_length>0) for (i=0;i<threads;i++) MEM_FREE(pseudo_rands[i]); for (i=0;i<threads;i++) pseudo_rands[i]=mem_calloc(sizeof(uint64_t), segment_length); saved_segment_length=segment_length; } } static int cmp_all(void *binary, int count) { int i; for (i = 0; i < count; i++) { if (!memcmp(binary, crypted[i], saved_salt.hash_size)) return 1; } return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypted[index], saved_salt.hash_size); } static int cmp_exact(char *source, int index) { return 1; } static int crypt_all(int *pcount, struct db_salt *salt) { int i; const int count = *pcount; #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < count; i++) { argon2_hash(saved_salt.t_cost, saved_salt.m_cost, saved_salt.lanes, saved_key[i], saved_len[i], saved_salt.salt, saved_salt.salt_length, crypted[i], saved_salt.hash_size, 0, 0, saved_salt.type, ARGON2_VERSION_NUMBER, memory[THREAD_NUMBER%threads].aligned, pseudo_rands[THREAD_NUMBER%threads]); } return count; } #define COMMON_GET_HASH_VAR crypted #include "common-get-hash.h" static int salt_hash(void *_salt) { int i; struct argon2_salt *salt = (struct argon2_salt*)_salt; unsigned int hash = 0; char *p = salt->salt; for (i=0;i<salt->salt_length;i++) { hash <<= 1; hash += (unsigned char)*p++; if (hash >> SALT_HASH_LOG) { hash ^= hash >> SALT_HASH_LOG; hash &= (SALT_HASH_SIZE - 1); } } hash ^= hash >> SALT_HASH_LOG; hash &= (SALT_HASH_SIZE - 1); return hash; } #if FMT_MAIN_VERSION > 11 static unsigned int tunable_cost_t(void *_salt) { struct argon2_salt *salt=(struct argon2_salt *)_salt; return salt->t_cost; } static unsigned int tunable_cost_m(void *_salt) { struct argon2_salt *salt=(struct argon2_salt *)_salt; return salt->m_cost; } static unsigned int tunable_cost_p(void *_salt) { struct argon2_salt *salt=(struct argon2_salt *)_salt; return salt->lanes; } static unsigned int tunable_cost_type(void *_salt) { struct argon2_salt *salt=(struct argon2_salt *)_salt; return (int)salt->type; } #endif struct fmt_main fmt_argon2 = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, sizeof(struct argon2_salt), SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef _OPENMP FMT_OMP | #endif FMT_CASE | FMT_8_BIT, { "t", "m", "p", "type [0:Argon2d 1:Argon2i]" }, {0}, tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { tunable_cost_t, tunable_cost_m, tunable_cost_p, tunable_cost_type, }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { #define COMMON_GET_HASH_LINK #include "common-get-hash.h" }, cmp_all, cmp_one, cmp_exact } }; #endif
attention.c
#include "darknet.h" #ifdef WIN32 #include <time.h> #else #include <sys/time.h> #endif #include <assert.h> #define class temp void extend_data_truth(data *d, int n, float val) { int i, j; for(i = 0; i < d->y.rows; ++i){ d->y.vals[i] = (float*)realloc(d->y.vals[i], (d->y.cols+n)*sizeof(float)); for(j = 0; j < n; ++j){ d->y.vals[i][d->y.cols + j] = val; } } d->y.cols += n; } matrix network_loss_data(network *net, data test) { int i,b; int k = 1; matrix pred = make_matrix(test.X.rows, k); float *X = (float*)calloc(net->batch*test.X.cols, sizeof(float)); float *y = (float*)calloc(net->batch*test.y.cols, sizeof(float)); for(i = 0; i < test.X.rows; i += net->batch){ for(b = 0; b < net->batch; ++b){ if(i+b == test.X.rows) break; memcpy(X+b*test.X.cols, test.X.vals[i+b], test.X.cols*sizeof(float)); memcpy(y+b*test.y.cols, test.y.vals[i+b], test.y.cols*sizeof(float)); } network orig = *net; net->input = X; net->truth = y; net->train = 0; net->delta = 0; forward_network(net); *net = orig; float *delta = net->layers[net->n-1].output; for(b = 0; b < net->batch; ++b){ if(i+b == test.X.rows) break; int t = max_index(y + b*test.y.cols, 1000); float err = sum_array(delta + b*net->outputs, net->outputs); pred.vals[i+b][0] = -err; //pred.vals[i+b][0] = 1-delta[b*net->outputs + t]; } } free(X); free(y); return pred; } void train_attention(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear) { int i, j; float avg_cls_loss = -1; float avg_att_loss = -1; char *base = basecfg(cfgfile); printf("%s\n", base); printf("%d\n", ngpus); network **nets = (network**)calloc(ngpus, sizeof(network*)); srand(time(0)); int seed = rand(); for(i = 0; i < ngpus; ++i){ srand(seed); #ifdef GPU if(gpu_index >= 0){ opencl_set_device(gpus[i]); } #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network *net = nets[0]; int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); list *options = read_data_cfg(datacfg); char *backup_directory = option_find_str(options, "backup", "/backup/"); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *train_list = option_find_str(options, "train", "data/train.list"); int classes = option_find_int(options, "classes", 2); char **labels = get_labels(label_list); list *plist = get_paths(train_list); char **paths = (char **)list_to_array(plist); printf("%d\n", plist->size); int N = plist->size; double time; int divs=3; int size=2; load_args args = {0}; args.w = divs*net->w/size; args.h = divs*net->h/size; args.size = divs*net->w/size; args.threads = 32; args.hierarchy = net->hierarchy; args.min = net->min_ratio*args.w; args.max = net->max_ratio*args.w; args.angle = net->angle; args.aspect = net->aspect; args.exposure = net->exposure; args.saturation = net->saturation; args.hue = net->hue; args.paths = paths; args.classes = classes; args.n = imgs; args.m = N; args.labels = labels; args.type = CLASSIFICATION_DATA; data train; data buffer; pthread_t load_thread; args.d = &buffer; load_thread = load_data(args); int epoch = (*net->seen)/N; while(get_current_batch(net) < net->max_batches || net->max_batches == 0){ time = what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); data resized = resize_data(train, net->w, net->h); extend_data_truth(&resized, divs*divs, 0); data *tiles = tile_data(train, divs, size); printf("Loaded: %lf seconds\n", what_time_is_it_now()-time); time = what_time_is_it_now(); float aloss = 0; float closs = 0; int z; for (i = 0; i < divs*divs/ngpus; ++i) { #pragma omp parallel for for(j = 0; j < ngpus; ++j){ int index = i*ngpus + j; extend_data_truth(tiles+index, divs*divs, SECRET_NUM); matrix deltas = network_loss_data(nets[j], tiles[index]); for(z = 0; z < resized.y.rows; ++z){ resized.y.vals[z][train.y.cols + index] = deltas.vals[z][0]; } free_matrix(deltas); } } int *inds = (int*)calloc(resized.y.rows, sizeof(int)); for(z = 0; z < resized.y.rows; ++z){ int index = max_index(resized.y.vals[z] + train.y.cols, divs*divs); inds[z] = index; for(i = 0; i < divs*divs; ++i){ resized.y.vals[z][train.y.cols + i] = (i == index)? 1 : 0; } } data best = select_data(tiles, inds); free(inds); #ifdef GPU if(gpu_index >= 0) { if (ngpus == 1) { closs = train_network(net, train); } else { closs = train_networks(nets, ngpus, train, 4); } } else { closs = train_network(net, train); } #else closs = train_network(net, train); #endif for (i = 0; i < divs*divs; ++i) { printf("%.2f ", resized.y.vals[0][train.y.cols + i]); if((i+1)%divs == 0) printf("\n"); free_data(tiles[i]); } free_data(best); printf("\n"); image im = float_to_image(64,64,3,resized.X.vals[0]); //show_image(im, "orig"); //cvWaitKey(100); /* image im1 = float_to_image(64,64,3,tiles[i].X.vals[0]); image im2 = float_to_image(64,64,3,resized.X.vals[0]); show_image(im1, "tile"); show_image(im2, "res"); */ #ifdef GPU if(gpu_index >= 0) { if (ngpus == 1) { aloss = train_network(net, train); } else { aloss = train_networks(nets, ngpus, train, 4); } } else { aloss = train_network(net, train); } #else aloss = train_network(net, train); #endif for(i = 0; i < divs*divs; ++i){ printf("%f ", nets[0]->output[1000 + i]); if ((i+1) % divs == 0) printf("\n"); } printf("\n"); free_data(resized); free_data(train); if(avg_cls_loss == -1) avg_cls_loss = closs; if(avg_att_loss == -1) avg_att_loss = aloss; avg_cls_loss = avg_cls_loss*.9 + closs*.1; avg_att_loss = avg_att_loss*.9 + aloss*.1; printf("%ld, %.3f: Att: %f, %f avg, Class: %f, %f avg, %f rate, %lf seconds, %ld images\n", get_current_batch(net), (float)(*net->seen)/N, aloss, avg_att_loss, closs, avg_cls_loss, get_current_rate(net), what_time_is_it_now()-time, *net->seen); if(*net->seen/N > epoch){ epoch = *net->seen/N; char buff[256]; sprintf(buff, "%s/%s_%d.weights",backup_directory,base, epoch); save_weights(net, buff); } if(get_current_batch(net)%1000 == 0){ char buff[256]; sprintf(buff, "%s/%s.backup",backup_directory,base); save_weights(net, buff); } } char buff[256]; sprintf(buff, "%s/%s.weights", backup_directory, base); save_weights(net, buff); pthread_join(load_thread, 0); free_network(net); free_ptrs((void**)labels, classes); free_ptrs((void**)paths, plist->size); free_list(plist); free(base); } void validate_attention_single(char *datacfg, char *filename, char *weightfile) { int i, j; network *net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list *options = read_data_cfg(datacfg); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *leaf_list = option_find_str(options, "leaves", 0); if(leaf_list) change_leaves(net->hierarchy, leaf_list); char *valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char **labels = get_labels(label_list); list *plist = get_paths(valid_list); char **paths = (char **)list_to_array(plist); int m = plist->size; free_list(plist); float avg_acc = 0; float avg_topk = 0; int *indexes = (int*)calloc(topk, sizeof(int)); int divs = 4; int size = 2; int extra = 0; float *avgs = (float*)calloc(classes, sizeof(float)); int *inds = (int*)calloc(divs*divs, sizeof(int)); for(i = 0; i < m; ++i){ int class = -1; char *path = paths[i]; for(j = 0; j < classes; ++j){ if(strstr(path, labels[j])){ class = j; break; } } image im = load_image_color(paths[i], 0, 0); image resized = resize_min(im, net->w*divs/size); image crop = crop_image(resized, (resized.w - net->w*divs/size)/2, (resized.h - net->h*divs/size)/2, net->w*divs/size, net->h*divs/size); image rcrop = resize_image(crop, net->w, net->h); //show_image(im, "orig"); //show_image(crop, "cropped"); //cvWaitKey(0); float *pred = network_predict(net, rcrop.data); //pred[classes + 56] = 0; for(j = 0; j < divs*divs; ++j){ printf("%.2f ", pred[classes + j]); if((j+1)%divs == 0) printf("\n"); } printf("\n"); copy_cpu(classes, pred, 1, avgs, 1); top_k(pred + classes, divs*divs, divs*divs, inds); show_image(crop, "crop", 0); for(j = 0; j < extra; ++j){ int index = inds[j]; int row = index / divs; int col = index % divs; int y = row * crop.h / divs - (net->h - crop.h/divs)/2; int x = col * crop.w / divs - (net->w - crop.w/divs)/2; printf("%d %d %d %d\n", row, col, y, x); image tile = crop_image(crop, x, y, net->w, net->h); float *pred = network_predict(net, tile.data); axpy_cpu(classes, 1., pred, 1, avgs, 1); show_image(tile, "tile", 10); } if(net->hierarchy) hierarchy_predictions(pred, net->outputs, net->hierarchy, 1, 1); if(rcrop.data != resized.data) free_image(rcrop); if(resized.data != im.data) free_image(resized); free_image(im); free_image(crop); top_k(pred, classes, topk, indexes); if(indexes[0] == class) avg_acc += 1; for(j = 0; j < topk; ++j){ if(indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1)); } } void validate_attention_multi(char *datacfg, char *filename, char *weightfile) { int i, j; network *net = load_network(filename, weightfile, 0); set_batch_network(net, 1); srand(time(0)); list *options = read_data_cfg(datacfg); char *label_list = option_find_str(options, "labels", "data/labels.list"); char *valid_list = option_find_str(options, "valid", "data/train.list"); int classes = option_find_int(options, "classes", 2); int topk = option_find_int(options, "top", 1); char **labels = get_labels(label_list); list *plist = get_paths(valid_list); int scales[] = {224, 288, 320, 352, 384}; int nscales = sizeof(scales)/sizeof(scales[0]); char **paths = (char **)list_to_array(plist); int m = plist->size; free_list(plist); float avg_acc = 0; float avg_topk = 0; int *indexes = (int*)calloc(topk, sizeof(int)); for(i = 0; i < m; ++i){ int class = -1; char *path = paths[i]; for(j = 0; j < classes; ++j){ if(strstr(path, labels[j])){ class = j; break; } } float *pred = (float*)calloc(classes, sizeof(float)); image im = load_image_color(paths[i], 0, 0); for(j = 0; j < nscales; ++j){ image r = resize_min(im, scales[j]); resize_network(net, r.w, r.h); float *p = network_predict(net, r.data); if(net->hierarchy) hierarchy_predictions(p, net->outputs, net->hierarchy, 1 , 1); axpy_cpu(classes, 1, p, 1, pred, 1); flip_image(r); p = network_predict(net, r.data); axpy_cpu(classes, 1, p, 1, pred, 1); if(r.data != im.data) free_image(r); } free_image(im); top_k(pred, classes, topk, indexes); free(pred); if(indexes[0] == class) avg_acc += 1; for(j = 0; j < topk; ++j){ if(indexes[j] == class) avg_topk += 1; } printf("%d: top 1: %f, top %d: %f\n", i, avg_acc/(i+1), topk, avg_topk/(i+1)); } } void predict_attention(char *datacfg, char *cfgfile, char *weightfile, char *filename, int top) { network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", 0); if(!name_list) name_list = option_find_str(options, "labels", "data/labels.list"); if(top == 0) top = option_find_int(options, "top", 1); int i = 0; char **names = get_labels(name_list); clock_t time; int *indexes = (int*)calloc(top, sizeof(int)); char buff[256]; char *input = buff; while(1){ if(filename){ strncpy(input, filename, 256); }else{ printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if(!input) return; strtok(input, "\n"); } image im = load_image_color(input, 0, 0); int resize = im.w != net->w || im.h != net->h; image r = resize ? letterbox_image(im, net->w, net->h) : im; //resize_network(&net, r.w, r.h); //printf("%d %d\n", r.w, r.h); float *X = r.data; time=clock(); float *predictions = network_predict(net, X); if(net->hierarchy) hierarchy_predictions(predictions, net->outputs, net->hierarchy, 1, 1); top_k(predictions, net->outputs, top, indexes); fprintf(stderr, "%s: Predicted in %f seconds.\n", input, sec(clock()-time)); for(i = 0; i < top; ++i){ int index = indexes[i]; //if(net->hierarchy) printf("%d, %s: %f, parent: %s \n",index, names[index], predictions[index], (net->hierarchy->parent[index] >= 0) ? names[net->hierarchy->parent[index]] : "Root"); //else printf("%s: %f\n",names[index], predictions[index]); printf("%5.2f%%: %s\n", predictions[index]*100, names[index]); } if(r.data != im.data) free_image(r); free_image(im); if (filename) break; } } void run_attention(int argc, char **argv) { if(argc < 4){ fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char *gpu_list = find_char_arg(argc, argv, "-gpus", 0); int ngpus; int *gpus = read_intlist(gpu_list, &ngpus, gpu_index); int top = find_int_arg(argc, argv, "-t", 0); int clear = find_arg(argc, argv, "-clear"); char *data = argv[3]; char *cfg = argv[4]; char *weights = (argc > 5) ? argv[5] : 0; char *filename = (argc > 6) ? argv[6]: 0; char *layer_s = (argc > 7) ? argv[7]: 0; if(0==strcmp(argv[2], "predict")) predict_attention(data, cfg, weights, filename, top); else if(0==strcmp(argv[2], "train")) train_attention(data, cfg, weights, gpus, ngpus, clear); else if(0==strcmp(argv[2], "valid")) validate_attention_single(data, cfg, weights); else if(0==strcmp(argv[2], "validmulti")) validate_attention_multi(data, cfg, weights); } #undef class
omp-par-scope.c
/* This testcase is part of GDB, the GNU debugger. Copyright 2017-2020 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <omp.h> omp_lock_t lock; omp_lock_t lock2; /* Enforce execution order between two threads using a lock. */ static void omp_set_lock_in_order (int num, omp_lock_t *lock) { /* Ensure that thread num 0 first sets the lock. */ if (num == 0) omp_set_lock (lock); #pragma omp barrier /* Block thread num 1 until it can set the lock. */ if (num == 1) omp_set_lock (lock); /* This bit here is guaranteed to be executed first by thread num 0, and once thread num 0 unsets the lock, to be executed by thread num 1. */ ; } /* Testcase for checking access to variables in a single / outer scope. Make sure that variables not referred to in the parallel section are accessible from the debugger. */ void single_scope (void) { static int s1 = -41, s2 = -42, s3 = -43; int i1 = 11, i2 = 12, i3 = 13; #pragma omp parallel num_threads (2) shared (s1, i1) private (s2, i2) { int thread_num = omp_get_thread_num (); omp_set_lock_in_order (thread_num, &lock); s2 = 100 * (thread_num + 1) + 2; i2 = s2 + 10; #pragma omp critical printf ("single_scope: thread_num=%d, s1=%d, i1=%d, s2=%d, i2=%d\n", thread_num, s1, i1, s2, i2); omp_unset_lock (&lock); } printf ("single_scope: s1=%d, s2=%d, s3=%d, i1=%d, i2=%d, i3=%d\n", s1, s2, s3, i1, i2, i3); } static int file_scope_var = 9876; /* Testcase for checking access to variables from parallel region nested within more than one lexical scope. Of particular interest are variables which are not referenced in the parallel section. */ void multi_scope (void) { int i01 = 1, i02 = 2; { int i11 = 11, i12 = 12; { int i21 = -21, i22 = 22; #pragma omp parallel num_threads (2) \ firstprivate (i01) \ shared (i11) \ private (i21) { int thread_num = omp_get_thread_num (); omp_set_lock_in_order (thread_num, &lock); i21 = 100 * (thread_num + 1) + 21; #pragma omp critical printf ("multi_scope: thread_num=%d, i01=%d, i11=%d, i21=%d\n", thread_num, i01, i11, i21); omp_unset_lock (&lock); } printf ("multi_scope: i01=%d, i02=%d, i11=%d, " "i12=%d, i21=%d, i22=%d\n", i01, i02, i11, i12, i21, i22); } } } /* Nested functions in C is a GNU extension. Some non-GNU compilers define __GNUC__, but they don't support nested functions. So, unfortunately, we can't use that for our test. */ #if HAVE_NESTED_FUNCTION_SUPPORT /* Testcase for checking access of variables from within parallel region in a lexically nested function. */ void nested_func (void) { static int s1 = -42; int i = 1, j = 2, k = 3; void foo (int p, int q, int r) { int x = 4; { int y = 5, z = 6; #pragma omp parallel num_threads (2) shared (i, p, x) private (j, q, y) { int tn = omp_get_thread_num (); omp_set_lock_in_order (tn, &lock); j = 1000 * (tn + 1); q = j + 1; y = q + 1; #pragma omp critical printf ("nested_func: tn=%d: i=%d, p=%d, x=%d, j=%d, q=%d, y=%d\n", tn, i, p, x, j, q, y); omp_unset_lock (&lock); } } } foo (10, 11, 12); i = 101; j = 102; k = 103; foo (20, 21, 22); } #endif /* Testcase for checking access to variables from within a nested parallel region. */ void nested_parallel (void) { int i = 1, j = 2; int l = -1; omp_set_nested (1); omp_set_dynamic (0); #pragma omp parallel num_threads (2) private (l) { int num = omp_get_thread_num (); omp_set_lock_in_order (num, &lock); int nthr = omp_get_num_threads (); int off = num * nthr; int k = off + 101; l = off + 102; #pragma omp parallel num_threads (2) shared (num) { int inner_num = omp_get_thread_num (); omp_set_lock_in_order (inner_num, &lock2); #pragma omp critical printf ("nested_parallel (inner threads): outer thread num = %d, thread num = %d\n", num, inner_num); omp_unset_lock (&lock2); } #pragma omp critical printf ("nested_parallel (outer threads) %d: k = %d, l = %d\n", num, k, l); omp_unset_lock (&lock); } } int main (int argc, char **argv) { omp_init_lock (&lock); omp_init_lock (&lock2); single_scope (); multi_scope (); #if HAVE_NESTED_FUNCTION_SUPPORT nested_func (); #endif nested_parallel (); omp_destroy_lock (&lock); omp_destroy_lock (&lock2); return 0; }
main.c
#include "main.h" inline uint64_t linear_sample(struct RNG_state* seed) { state saved_state[6]; state state; union Register saved_cipher[5]; // printf("START SAMPLING !!! \n"); // PRINT(saved_state,saved_cipher); RAND(state,seed); COPY(saved_state[0], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); ENCR(&saved_cipher[0], state); COPY(saved_state[1], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); ENCR(&saved_cipher[1], state); COPY(saved_state[2], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); ENCR(&saved_cipher[2], state); COPY(saved_state[3], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); ENCR(&saved_cipher[3], state); COPY(saved_state[4], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); ENCR(&saved_cipher[4], state); COPY(saved_state[5], state); // printf("======================================================\n"); // STATE(state); // printf("======================================================\n"); // PRINT(saved_state,saved_cipher); // printf("STOP SAMPLING !!! \n"); return MASK(saved_state, saved_cipher); } int main(int argc, char const *argv[]) { struct Properties *prop; struct RNG_state *seed; uint32_t small_seed = 0; uint64_t num = 1; int64_t res = 0; int64_t inbalance = 0; uint64_t bias = 0; uint64_t i = 0; uint32_t tid; uint8_t progress = 0; uint8_t t_progress = 0; uint32_t shift = 0; srand((uint32_t) time(NULL)); small_seed = (uint32_t) rand(); prop = read_args(argc, argv); shift = (WEIGHT * 2 + 5 - ilog2(prop->num_proc_to_use)); num <<= shift; # pragma omp parallel private(i, tid, seed) shared(num) reduction(+:bias,inbalance) { tid = (uint32_t) omp_get_thread_num(); seed = init_aesrand_r(small_seed^tid,tid); #pragma omp parallel for private(i) shared(bias,inbalance) shared(num) for(i = 0 ; i < num; ++i) { res = linear_sample(seed); inbalance += 1 - 2*res; bias += res; if(tid == 0) { t_progress = ((i << 7) >> shift); if( progress < t_progress) { printf("\rProgress (over 128): %u%%", progress); progress = t_progress; } } } } num = num * prop->num_proc_to_use; print_results(WEIGHT, num, inbalance, bias); }
pr27388-1.c
/* PR middle-end/27388 */ /* { dg-do compile } */ /* { dg-options "-fopenmp -fdump-tree-omplower" } */ int n, o; void foo (void) { #pragma omp parallel firstprivate (n) { int i; #pragma omp parallel for firstprivate (n) for (i = 0; i < 10; i++) ++n; #pragma omp atomic o += n; } } /* { dg-final { scan-tree-dump-times "shared\\\(i\\\)" 0 "omplower" } } */ /* { dg-final { scan-tree-dump-times "private\\\(i\\\)" 1 "omplower" } } */ /* { dg-final { cleanup-tree-dump "omplower" } } */
ddd_out_h.h
//**************************************************************************************** // // Copyright (c) 2015-2020, Yoshifumi Nakamura <nakamura@riken.jp> // Copyright (c) 2015-2020, Yuta Mukai <mukai.yuta@fujitsu.com> // Copyright (c) 2018-2020, Ken-Ichi Ishikawa <ishikawa@theo.phys.sci.hirosima-u.ac.jp> // Copyright (c) 2019-2020, Issaku Kanamori <kanamori-i@riken.jp> // // // 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 listed // in this license in the documentation and/or other materials // provided with the distribution. // // * Neither the name of the copyright holders 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. // //---------------------------------------------------------------------------------------- // ACKNOWLEDGMENT // // This software has been developed in a co-design working group for the lattice QCD // supported by MEXT's programs for the Development and Improvement for the Next // Generation Ultra High-Speed Computer System, under its Subsidies for Operating the // Specific Advanced Large Research Facilities, and Priority Issue 9 // (Elucidation of the Fundamental Laws and Evolution of the Universe) to be tackled by // using the Supercomputer Fugaku. // //**************************************************************************************** #ifndef _DDD_OUT_H_H #define _DDD_OUT_H_H #include "ddd_out_h_0_inline.h" //---------------------------------------------------------------------------------------- preprocess mult D for boundary void ddd_out_pre_h_(const sch_t * __restrict__ in, const int *idomain) // // Send for Wilson/Clover operator, Deo or Doe, in a even/odd domain block // // oute = oute + factor Meo ine // // or // // outo = outo + factor Moe ino // // Note: Deo = -kappa Meo, Doe = -kappa Moe // // in : quark field in an even/odd domain (odd for idomain = 0, even for idomain = 1). // input domain is opposite to idomain // idomain : domain index, 0 for even output, 1 for odd output // { // // pack data for send // _S_MULT_WD_DEO_OUT_SEND_HPC_TIC_; int xdmn, ydmn, zdmn, tdmn; xdmn = 1 - *idomain; if (npe[1] == 1) { ydmn = *idomain; } else { ydmn = 1 - *idomain; } if (npe[2] == 1) { zdmn = *idomain; } else { zdmn = 1 - *idomain; } if (npe[3] == 1) { tdmn = *idomain; } else { tdmn = 1 - *idomain; } pgluh_t __restrict__ gx = &gluh[vols*0 + NDIM*vols*xdmn]; pgluh_t __restrict__ gy = &gluh[vols*1 + NDIM*vols*ydmn]; pgluh_t __restrict__ gz = &gluh[vols*2 + NDIM*vols*zdmn]; pgluh_t __restrict__ gt = &gluh[vols*3 + NDIM*vols*tdmn]; #pragma omp parallel { #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int z = 0; z < nz; ++z) { for (int y = 0; y < ny; ++y) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; int iy = nxs*y; // X-forward { //int x = nxs-1; int ixf = 0 + iy + iz + it; int i0 = y + ny*z + ny*nz*t; __mult_x_forw_pre_3_(xfh_send[i0],in[vols*xdmn+ixf]); } // X-backward { //int x = 0; int ixb = nxs-1 + iy + iz + it; int i1 = y + ny*z + ny*nz*t; projsch1_t a __attribute__((aligned(_ALIGN_SIZE))); __mult_x_back_pre_3_(a,in[vols*xdmn+ixb]); __mult_udag_y_3_(xbh_send[i1],a,(*(gx + ixb))); } } } } #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int z = 0; z < nz; ++z) { for (int x = 0; x < nxs; ++x) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; // // Y-forward send // { //int y = ny-1; int iyf = x + iz + it; int i2 = x + nxs*z + nxs*nz*t; __mult_y_forw_pre_(yfh_send[i2],in[vols*ydmn+iyf]); } // // Y-backward send // { //int y = 0; int iyb = x + iz + it + (ny-1)*nxs; int i3 = x + nxs*z + nxs*nz*t; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_y_back_pre_(a,in[vols*ydmn+iyb]); __mult_udag_y_(ybh_send[i3],a,(*(gy + iyb))); } } } } #pragma omp for collapse(3) nowait for (int t = 0; t < nt; ++t) { for (int y = 0; y < ny; ++y) { for (int x = 0; x < nxs; ++x) { int it = nxs*ny*nz*t; int iy = nxs*y; // // Z-forward send // { //int z = nz-1; int izf = x + iy + it; int i4 = x + nxs*y + nxs*ny*t; __mult_z_forw_pre_(zfh_send[i4],in[vols*zdmn+izf]); } // // Z-backward send // { //int z = 0; int izb = x + iy + it + (nz-1)*nxs*ny; int i5 = x + nxs*y + nxs*ny*t; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_z_back_pre_(a,in[vols*zdmn+izb]); __mult_udag_y_(zbh_send[i5],a,(*(gz + izb))); } } } } #pragma omp for collapse(3) nowait for (int z = 0; z < nz; ++z) { for (int y = 0; y < ny; ++y) { for (int x = 0; x < nxs; ++x) { int iz = nxs*ny*z; int iy = nxs*y; // // T-forward send // { //int t = nt-1; int itf = x + iy + iz; int i6 = x + nxs*y + nxs*ny*z; __mult_t_forw_pre_(tfh_send[i6],in[vols*tdmn+itf]); } // // T-backward send // { //int t = 0; int itb = x + iy + iz + (nt-1)*nxs*ny*nz; int i7 = x + nxs*y + nxs*ny*z; __attribute__((aligned(_ALIGN_SIZE))) projsch_t a; __mult_t_back_pre_(a,in[vols*tdmn+itb]); __mult_udag_y_(tbh_send[i7],a,(*(gt + itb))); } } } } #pragma omp barrier } // end of omp parallel _S_MULT_WD_DEO_OUT_SEND_HPC_TOC_; #pragma omp single nowait { if (*idomain == 0) { memcpy(xfh_recv, xfh_send, sizeof(half)*12*ny*nz*nt); } else { xbound_h_start(0); } if (*idomain == 1) { memcpy(xbh_recv, xbh_send, sizeof(half)*12*ny*nz*nt); } else { xbound_h_start(1); } xbound_h_start(2); xbound_h_start(3); xbound_h_start(4); xbound_h_start(5); xbound_h_start(6); xbound_h_start(7); } } //---------------------------------------------------------------------------------------- postprocess mult D for boundary void ddd_out_pos_h_(sch_t * __restrict__ out, const sch_t * __restrict__ in, const int *idomain, float factor) // // Multiply Wilson/Clover operator from odd/even to even/odd domain // // oute = oute + factor Meo ino // or // outo = outo + factor Moe ine // // Note: Deo = -kappa Meo, Doe = -kappa Moe // // out : quark field in an even/odd domain (output) // in : quark field in an odd/even domain (input) // idomain : domain index, 0 for even output, 1 for odd output // factor : a factor for hopping parameter kappa or -kappa // { pgluh_t __restrict__ gx = &gluh[vols*0 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gy = &gluh[vols*1 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gz = &gluh[vols*2 + NDIM*vols*(*idomain)]; pgluh_t __restrict__ gt = &gluh[vols*3 + NDIM*vols*(*idomain)]; half hfactor = half(factor); #pragma omp single { xbound_h_wait(0); xbound_h_wait(1); xbound_h_wait(2); xbound_h_wait(3); xbound_h_wait(4); xbound_h_wait(5); xbound_h_wait(6); xbound_h_wait(7); } _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TIC_; #pragma omp parallel for collapse(4) for (int t = 0; t < nt; t++) { for (int z = 0; z < nz; z++) { for (int y = 0; y < ny; y++) { for (int x = 0; x < nxs; x++) { if (x == nxs-1 || y == ny-1 || z == nz-1 || t == nt-1 || x==0 || y == 0 || z == 0 || t == 0 ) { int it = nxs*ny*nz*t; int iz = nxs*ny*z; int iy = nxs*y; int i0 = x + iy + iz + it; sch_t tmp __attribute__((aligned(_ALIGN_SIZE))) ; for(int c = 0; c < 3; c++) { for(int s = 0; s < 4; s++) { for(int ri = 0; ri < 2; ri++) { for(int j = 0; j < VLENS; j++) { tmp.c[c][s][ri][j] = half(0.0f); } } } } // // X-forward // if ( x == nxs-1 ) { _mult_forw_x_recv_; } // // X-backward // if ( x == 0 ) { _mult_back_x_recv_; } // // Y-forward // if ( y == ny-1 ) { _mult_forw_y_recv_; } // // Y-backward // if ( y == 0 ) { _mult_back_y_recv_; } // // Z-forward // if ( z == nz-1 ) { _mult_forw_z_recv_; } // // Z-backward // if ( z == 0 ) { _mult_back_z_recv_; } // // T-forward // if ( t == nt-1 ) { _mult_forw_t_recv_; } // // T-backward // if ( t == 0 ) { _mult_back_t_recv_; } __mult_clvh( tmp.cv, clvh[i0 + vols*(*idomain)].cv); sch_t *outi = out + i0; //#pragma loop norecurrence for (int c = 0; c < 3; c++) { for (int s = 0; s < 4; s++) { for (int j = 0; j < VLENS; j++) { outi->c[c][s][0][j] += tmp.c[c][s][0][j] * hfactor; outi->c[c][s][1][j] += tmp.c[c][s][1][j] * hfactor; } } } } // if edge sites } } } } _S_MULT_WD_DEO_OUT_RECV_HPC_CALC_TOC_; #pragma omp single { xbound_h_send_waitall(); } } #endif
fft-cuda.c
/* Copyright 2013, 2015. The Regents of the University of California. * Copyright 2019. Uecker Lab, University Medical Center Göttingen. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2012-2019 Martin Uecker <martin.uecker@med.uni-goettingen.de> * Christian Holme <christian.holme@med.uni-goettingen.de> * * * Internal interface to the CUFFT library used in fft.c. */ #include <stdbool.h> #include <complex.h> #include <assert.h> #include <limits.h> #include "misc/misc.h" #include "num/multind.h" #include "fft-cuda.h" #ifdef USE_CUDA #include <cufft.h> #include "num/gpuops.h" #ifndef CFL_SIZE #define CFL_SIZE sizeof(complex float) #endif struct fft_cuda_plan_s { cufftHandle cufft; struct fft_cuda_plan_s* chain; bool backwards; long batch; long idist; long odist; }; struct iovec { long n; long is; long os; }; // detect if flags has blocks of 1's seperated by 0's static bool noncontiguous_flags(int D, unsigned long flags) { bool o = false; bool z = false; for (int i = 0; i < D; i++) { bool curr_bit = MD_IS_SET(flags, i); if (curr_bit) // found a block of ones o = true; if (o && !curr_bit) // found the end of a block of ones z = true; if (o && z && curr_bit) // found a second block of ones return true; } return false; } static struct fft_cuda_plan_s* fft_cuda_plan0(unsigned int D, const long dimensions[D], unsigned long flags, const long ostrides[D], const long istrides[D], bool backwards) { // TODO: This is not optimal, as it will often create separate fft's where they // are not needed. And since we compute blocks, we could also recurse // into both blocks... if (noncontiguous_flags(D, flags)) return NULL; PTR_ALLOC(struct fft_cuda_plan_s, plan); unsigned int N = D; plan->batch = 1; plan->odist = 0; plan->idist = 0; plan->backwards = backwards; plan->chain = NULL; struct iovec dims[N]; struct iovec hmdims[N]; assert(0 != flags); // the cufft interface is strange, but we do our best... unsigned int k = 0; unsigned int l = 0; for (unsigned int i = 0; i < N; i++) { if (1 == dimensions[i]) continue; if (MD_IS_SET(flags, i)) { dims[k].n = dimensions[i]; dims[k].is = istrides[i] / CFL_SIZE; dims[k].os = ostrides[i] / CFL_SIZE; k++; } else { hmdims[l].n = dimensions[i]; hmdims[l].is = istrides[i] / CFL_SIZE; hmdims[l].os = ostrides[i] / CFL_SIZE; l++; } } assert(k > 0); int cudims[k]; int cuiemb[k]; int cuoemb[k]; long batchdims[l]; long batchistr[l]; long batchostr[l]; int lis = dims[0].is; int los = dims[0].os; if (k > 3) goto errout; for (unsigned int i = 0; i < k; i++) { // assert(dims[i].is == lis); // assert(dims[i].os == los); cudims[k - 1 - i] = dims[i].n; cuiemb[k - 1 - i] = dims[i].n; cuoemb[k - 1 - i] = dims[i].n; lis = dims[i].n * dims[i].is; los = dims[i].n * dims[i].os; } for (unsigned int i = 0; i < l; i++) { batchdims[i] = hmdims[i].n; batchistr[i] = hmdims[i].is; batchostr[i] = hmdims[i].os; } int istride = dims[0].is; int ostride = dims[0].os; int idist = lis; int odist = los; int cubs = 1; // check that batch dimensions can be collapsed to one unsigned int bi = md_calc_blockdim(l, batchdims, batchistr, hmdims[0].is); unsigned int bo = md_calc_blockdim(l, batchdims, batchostr, hmdims[0].os); if (bi != bo) goto errout; if (bi > 0) { idist = hmdims[0].is; odist = hmdims[0].os; cubs = md_calc_size(bi, batchdims); } if (l != bi) { // check that batch dimensions can be collapsed to one if (l - bi != md_calc_blockdim(l - bi, batchdims + bi, batchistr + bi, hmdims[bi].is)) goto errout; if (l - bo != md_calc_blockdim(l - bo, batchdims + bo, batchostr + bo, hmdims[bo].os)) goto errout; plan->idist = hmdims[bi].is; plan->odist = hmdims[bo].os; plan->batch = md_calc_size(l - bi, batchdims + bi); } assert(k <= 3); int err; #pragma omp critical err = cufftPlanMany(&plan->cufft, k, cudims, cuiemb, istride, idist, cuoemb, ostride, odist, CUFFT_C2C, cubs); if (CUFFT_SUCCESS != err) goto errout; return PTR_PASS(plan); errout: PTR_FREE(plan); return NULL; } static unsigned long find_msb(unsigned long flags) { for (unsigned int i = 1; i < CHAR_BIT * sizeof(flags); i *= 2) flags |= flags >> i; return (flags + 1) / 2; } struct fft_cuda_plan_s* fft_cuda_plan(unsigned int D, const long dimensions[D], unsigned long flags, const long ostrides[D], const long istrides[D], bool backwards) { assert(0u != flags); assert(0u == (flags & ~md_nontriv_dims(D, dimensions))); struct fft_cuda_plan_s* plan = fft_cuda_plan0(D, dimensions, flags, ostrides, istrides, backwards); if (NULL != plan) return plan; unsigned long msb = find_msb(flags); if (flags & msb) { struct fft_cuda_plan_s* plan = fft_cuda_plan0(D, dimensions, msb, ostrides, istrides, backwards); if (NULL == plan) return NULL; plan->chain = fft_cuda_plan(D, dimensions, flags & ~msb, ostrides, ostrides, backwards); if (NULL == plan->chain) { fft_cuda_free_plan(plan); return NULL; } return plan; } return NULL; } void fft_cuda_free_plan(struct fft_cuda_plan_s* cuplan) { if (NULL != cuplan->chain) fft_cuda_free_plan(cuplan->chain); cufftDestroy(cuplan->cufft); xfree(cuplan); } void fft_cuda_exec(struct fft_cuda_plan_s* cuplan, complex float* dst, const complex float* src) { assert(cuda_ondevice(src)); assert(cuda_ondevice(dst)); assert(NULL != cuplan); int err; for (int i = 0; i < cuplan->batch; i++) { if (CUFFT_SUCCESS != (err = cufftExecC2C(cuplan->cufft, (cufftComplex*)src + i * cuplan->idist, (cufftComplex*)dst + i * cuplan->odist, (!cuplan->backwards) ? CUFFT_FORWARD : CUFFT_INVERSE))) error("CUFFT: %d\n", err); } if (NULL != cuplan->chain) fft_cuda_exec(cuplan->chain, dst, dst); } #endif
bitedge_monte_carlo.h
#ifndef BITEDGE_MONTE_CARLO_H_ #define BITEDGE_MONTE_CARLO_H_ #include <set> #include <queue> #include <bitset> #include "../ugraph_io/ugraph_structures.h" #include "../utils/memory_monitor.h" #include "../utils/convergence_helper.h" #include "../ugraph_io/file_io.h" #include "../utils/globals.h" #include "../utils/bitmap.h" namespace CPU_ALGOS{ struct EdgeBits_T{ std::vector<bool> bits; EdgeBits_T():bits(0){} }; int bitedge_traverse_run( uint source, uint target, std::vector<initial_vertex> graph, std::vector<EdgeBits_T> edgeBits, uint nEdges, int k); //void find_k_monte_carlo(Graph & graph) void find_k_bitedge_monte_carlo(std::vector<initial_vertex> & graph, uint nEdges, std::vector<std::pair<uint, uint>> source_target_pairs, uint nQuery) { std::cout << "Init Monte Carlo Sampling (Finding K)..." << std::endl; int num_reached = 0; int k = 0; double reliability; std::vector<double> reliability_k, reliability_j; double curr_avg_r = 2.0; double prev_avg_r = 3.0; double avg_r = 0.0; double diff_sq_sum = 0.0; bool write_flag = true; uint source, target; std::pair<uint, uint> source_target_pair; std::cout << std::endl << "Reading Source-Target file..." << std::endl; memory_monitor mm = memory_monitor(); std::thread t1(&memory_monitor::update_peak_memory, std::ref(mm)); t1.detach(); while ( fabs(curr_avg_r - prev_avg_r) > ALGO_CONF::kReliabilityThreshold && k < ALGO_CONF::kMaximumRound) { /*k < k_limit*/ // Step up k k += ALGO_CONF::kKStepUp; std::cout << std::endl << "k = " << k << std::endl; int sumBits = k * nEdges; // Reset var reliability_k.clear(); //Generate K sampling possible world auto start_g = std::chrono::high_resolution_clock::time_point::max(); auto finish_g = std::chrono::high_resolution_clock::time_point::max(); start_g = std::chrono::high_resolution_clock::now(); int numVertices = graph.size(); std::vector<EdgeBits_T> edgeBits(numVertices); int edgeInx = 0; for(int v = 0; v < numVertices; v++){ uint vdegree = graph.at(v).nbrs.size(); if( vdegree != 0 ){ for( uint inbr = 0; inbr < vdegree; inbr++){ edge ee = graph.at(v).nbrs.at(inbr).edgeValue; edgeInx ++; bool temp_bit; for(int i=0; i < k; i++){ if ( check_exist( ee.probability.at(0)) ) { temp_bit = true; }else{ temp_bit = false; } edgeBits.at(v).bits.push_back(temp_bit); } } } } finish_g = std::chrono::high_resolution_clock::now(); auto duration_g = std::chrono::duration_cast<std::chrono::milliseconds>(finish_g - start_g).count(); std::cout << "Sampling Possible World time = " << duration_g << " ms" << std::endl; for (size_t i = 0; i < source_target_pairs.size(); i++) { source_target_pair = source_target_pairs[i]; source = source_target_pair.first; target = source_target_pair.second; // Reset var reliability_j.clear(); diff_sq_sum = 0.0; write_flag = true; for (int j = 0; j < ALGO_CONF::kRepeatForVariance; j++) { std::cout << j << "th iteration" << std::endl; // Reset initial conditions num_reached = 0; // Start time auto start = std::chrono::high_resolution_clock::time_point::max(); auto finish = std::chrono::high_resolution_clock::time_point::max(); start = std::chrono::high_resolution_clock::now(); mm.start_monitoring(); //Traverse K possible world auto start_t = std::chrono::high_resolution_clock::time_point::max(); auto finish_t = std::chrono::high_resolution_clock::time_point::max(); start_t = std::chrono::high_resolution_clock::now(); #pragma omp parallel for num_threads(1) num_reached = num_reached + bitedge_traverse_run(source, target, graph, edgeBits, nEdges, k); finish_t = std::chrono::high_resolution_clock::now(); auto duration_t = std::chrono::duration_cast<std::chrono::milliseconds>(finish_t - start_t).count(); std::cout << "Traversal time = " << duration_t << " ms" << std::endl; std::cout<< "num_reached: "<< num_reached << std::endl; // Calculate reliability reliability = num_reached / (double)k; // Stop time finish = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(finish - start).count(); std::cout << "Current utilize : K=" << k << " possible world." << std::endl; std::cout << "Reliability Estimator, R^ (" << source << ", " << target << ") = " << reliability << std::endl; std::cout << "Execution time = " << duration << " ms" << std::endl << std::endl; if (write_flag) { append_results_to_file(k, reliability, duration, mm.get_peak_memory(), "MonteCarlo_k_" + std::to_string(i) + "_"+ std::to_string(numVertices)+ ".csv"); write_flag = false; } // Add r to vector reliability_j.push_back(reliability); } // Add r to vector of r reliability_k.push_back(reliability); // Variance calculation avg_r = convergence_helper::get_avg_reliability(reliability_j); for (int j = 0; j < ALGO_CONF::kRepeatForVariance; j++) { auto difference_sq = pow(reliability_j[j] - avg_r, 2); diff_sq_sum += difference_sq; } append_results_to_file(k, diff_sq_sum / (ALGO_CONF::kRepeatForVariance - 1), 0, i, "MC_variance_" + std::to_string(numVertices)+".csv"); } // Calulate avg r prev_avg_r = curr_avg_r; curr_avg_r = convergence_helper::get_avg_reliability(reliability_k); } mm.stop_monitoring(); } void op_and (bool * a, bool* b, int k, bool *c){ for(int i = 0; i< k ; i++) c[i] = a[i] & b[i]; } void op_or (bool * a, bool* b, int k, bool *c){ for(int i = 0; i < k ; i++) c[i] = a[i] | b[i]; } int count_bits(bool * a, int k){ int n = 0; for(int i = 0; i< k ; i++) if(a[i] == 1) n++; return n; } int bitedge_traverse_run( uint source, uint target, std::vector<initial_vertex> graph, std::vector<EdgeBits_T> edgeBits, uint nEdges, int k) { std::cout<< "Start source-target = " << source << ","<< target << std::endl; std::queue<uint> worklist; std::set<uint> explored; uint v, w; uint nVertices = graph.size(); bool vbits[nVertices][k]; for(int i = 0; i< nVertices; i++){ for(int j = 0; j< k; j++){ vbits[i][j] = false; } } // Add source in worklist for(int i = 0; i< k; i++) vbits[source][i] = true; worklist.push(source); explored.insert(source); if (source == target) { return 1*k; } while (!worklist.empty()) { v = worklist.front(); worklist.pop(); // T -> S: Iterate through all ingoing edges from t -> s uint vdegree = graph.at(v).nbrs.size(); if ( vdegree != 0) { for( uint i = 0; i < vdegree; i++){ w = graph.at(v).nbrs.at(i).tgtIndex; edge ee = graph.at(v).nbrs.at(i).edgeValue; //bool * ee_bits = edgeBits.at(v).bits.at(i); std::vector<bool>::const_iterator bits_offset = edgeBits.at(v).bits.begin() + k*i; std::vector<bool>::const_iterator bits_offset2 = edgeBits.at(v).bits.begin() + k*(i+1); std::vector<bool> vee_bits( bits_offset, bits_offset2); bool ee_bits[k]; for(int j = 0 ; j < k; j++) ee_bits[j] = vee_bits[j]; bool temp_bits[k]; op_and(ee_bits, vbits[v], k, temp_bits); op_or( vbits[w], temp_bits, k, temp_bits ); for(int j = 0; j< k; j++) vbits[w][j] = temp_bits[j]; if (explored.count(w) == 0) { worklist.push(w); explored.insert(w); }else { // Edge does not exist } } } } return count_bits(vbits[target], k); } } #endif
84298b.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; }; int Kernel(struct dataobj *restrict block_sizes_vec, struct dataobj *restrict damp_vec, const float dt, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict usol_vec, struct dataobj *restrict vp_vec, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads) { int (*restrict block_sizes) __attribute__ ((aligned (64))) = (int (*)) block_sizes_vec->data; float(*restrict damp)[damp_vec->size[1]][damp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[damp_vec->size[1]][damp_vec->size[2]])damp_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src)[save_src_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_vec->size[1]])save_src_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; float(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (float(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict usol)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]] __attribute__((aligned(64))) = (float(*)[usol_vec->size[1]][usol_vec->size[2]][usol_vec->size[3]])usol_vec->data; float(*restrict vp)[vp_vec->size[1]][vp_vec->size[2]] __attribute__((aligned(64))) = (float(*)[vp_vec->size[1]][vp_vec->size[2]])vp_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; printf(" Tiles: %d, %d ::: Blocks %d, %d \n", x0_blk0_size, y0_blk0_size, xb_size, yb_size); int sf = 6; int t_blk_size = 2 * sf * (time_M - time_m); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size + 1) { for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size + 1) { for (int time = t_blk, t0 = (time + 1) % (3), t1 = (time) % (3), t2 = (time + 2) % (3); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (3), t1 = (((time / sf) % (time_M - time_m + 1))) % (3), t2 = (((time / sf) % (time_M - time_m + 1)) + 2) % (3)) { int tw = ((time / sf) % (time_M - time_m + 1)); /* Begin section0 */ #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size)), (y0_blk0 + y0_blk0_size - 1)); y++) { #pragma omp simd aligned(damp, usol, vp : 64) for (int z = z_m; z <= z_M; z += 1) { float r7 = -2.98277778F * usol[t1][x - time + 12][y - time + 12][z + 12]; float r6 = 1.0 / dt; float r5 = 1.0 / (dt * dt); float r4 = 1.0 / (vp[x - time + 12][y - time + 12][z + 12] * vp[x - time + 12][y - time + 12][z + 12]); usol[t0][x - time + 12][y - time + 12][z + 12] = (r4 * (-r5 * (-2.0F * usol[t1][x - time + 12][y - time + 12][z + 12] + usol[t2][x - time + 12][y - time + 12][z + 12])) + r6 * (damp[x - time + 1][y - time + 1][z + 1] * usol[t1][x - time + 12][y - time + 12][z + 12]) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 12][y - time + 12][z + 6] + usol[t1][x - time + 12][y - time + 12][z + 18]) + 1.03896104e-3F * (usol[t1][x - time + 12][y - time + 12][z + 7] + usol[t1][x - time + 12][y - time + 12][z + 17]) - 8.92857143e-3F * (usol[t1][x - time + 12][y - time + 12][z + 8] + usol[t1][x - time + 12][y - time + 12][z + 16]) + 5.29100529e-2F * (usol[t1][x - time + 12][y - time + 12][z + 9] + usol[t1][x - time + 12][y - time + 12][z + 15]) - 2.67857143e-1F * (usol[t1][x - time + 12][y - time + 12][z + 10] + usol[t1][x - time + 12][y - time + 12][z + 14]) + 1.71428571F * (usol[t1][x - time + 12][y - time + 12][z + 11] + usol[t1][x - time + 12][y - time + 12][z + 13])) / ((h_z * h_z)) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 12][y - time + 6][z + 12] + usol[t1][x - time + 12][y - time + 18][z + 12]) + 1.03896104e-3F * (usol[t1][x - time + 12][y - time + 7][z + 12] + usol[t1][x - time + 12][y - time + 17][z + 12]) - 8.92857143e-3F * (usol[t1][x - time + 12][y - time + 8][z + 12] + usol[t1][x - time + 12][y - time + 16][z + 12]) + 5.29100529e-2F * (usol[t1][x - time + 12][y - time + 9][z + 12] + usol[t1][x - time + 12][y - time + 15][z + 12]) - 2.67857143e-1F * (usol[t1][x - time + 12][y - time + 10][z + 12] + usol[t1][x - time + 12][y - time + 14][z + 12]) + 1.71428571F * (usol[t1][x - time + 12][y - time + 11][z + 12] + usol[t1][x - time + 12][y - time + 13][z + 12])) / ((h_y * h_y)) + (r7 - 6.01250601e-5F * (usol[t1][x - time + 6][y - time + 12][z + 12] + usol[t1][x - time + 18][y - time + 12][z + 12]) + 1.03896104e-3F * (usol[t1][x - time + 7][y - time + 12][z + 12] + usol[t1][x - time + 17][y - time + 12][z + 12]) - 8.92857143e-3F * (usol[t1][x - time + 8][y - time + 12][z + 12] + usol[t1][x - time + 16][y - time + 12][z + 12]) + 5.29100529e-2F * (usol[t1][x - time + 9][y - time + 12][z + 12] + usol[t1][x - time + 15][y - time + 12][z + 12]) - 2.67857143e-1F * (usol[t1][x - time + 10][y - time + 12][z + 12] + usol[t1][x - time + 14][y - time + 12][z + 12]) + 1.71428571F * (usol[t1][x - time + 11][y - time + 12][z + 12] + usol[t1][x - time + 13][y - time + 12][z + 12])) / ((h_x * h_x))) / (r4 * r5 + r6 * damp[x - time + 1][y - time + 1][z + 1]); } #pragma omp simd aligned(damp, usol, vp : 64) for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; usol[t0][x - time + 12][y - time + 12][zind + 12] += r0;} } } } } } } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; return 0; }
opencl_agilekeychain_fmt_plug.c
/* 1Password Agile Keychain cracker patch for JtR. Hacked together during * July of 2012 by Dhiru Kholia <dhiru.kholia at gmail.com>. * * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> and * Copyright (c) 2012 Dhiru Kholia <dhiru.kholia at gmail.com>, and it is * hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. * * This software is based on "agilekeychain" project but no actual code is * borrowed from it. * * "agilekeychain" project is at https://bitbucket.org/gwik/agilekeychain */ #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_agilekeychain; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_agilekeychain); #else #include <string.h> #include <openssl/aes.h> #ifdef _OPENMP #include <omp.h> #endif #include "arch.h" #include "formats.h" #include "common.h" #include "misc.h" #include "common-opencl.h" #include "options.h" #define FORMAT_LABEL "agilekeychain-opencl" #define FORMAT_NAME "1Password Agile Keychain" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL AES" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 0 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(struct custom_salt) #define BINARY_ALIGN MEM_ALIGN_WORD #define SALT_ALIGN MEM_ALIGN_WORD #define SALTLEN 8 #define CTLEN 1040 #define uint8_t unsigned char #define uint16_t unsigned short #define uint32_t ARCH_WORD_32 #define OCL_CONFIG "agilekeychain" typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } keychain_password; typedef struct { uint32_t v[16/4]; } keychain_hash; typedef struct { uint8_t length; uint8_t salt[SALTLEN]; int iterations; int outlen; } keychain_salt; static int *cracked; static int any_cracked; static struct fmt_tests keychain_tests[] = { {"$agilekeychain$2*1000*8*7146eaa1cca395e5*1040*e7eb81496717d35f12b83024bb055dec00ea82843886cbb8d0d77302a85d89b1d2c0b5b8275dca44c168cba310344be6eea3a79d559d0846a9501f4a012d32b655047673ef66215fc2eb4e944a9856130ee7cd44523017bbbe2957e6a81d1fd128434e7b83b49b8a014a3e413a1d76b109746468070f03f19d361a21c712ef88e05b04f8359f6dd96c1c4487ea2c9df22ea9029e9bc8406d37850a5ead03062283a42218c134d05ba40cddfe46799c931291ec238ee4c11dc71d2b7e018617d4a2bf95a0c3c1f98ea14f886d94ee2a65871418c7c237f1fe52d3e176f8ddab6dfd4bc039b6af36ab1bc9981689c391e71703e31979f732110b84d5fccccf59c918dfcf848fcd80c6da62ced6e231497b9cbef22d5edca439888556bae5e7b05571ac34ea54fafc03fb93e4bc17264e50a1d04b688fcc8bc715dd237086c2537c32de34bbb8a29de0208800af2a9b561551ae6561099beb61045f22dbe871fab5350e40577dd58b4c8fb1232f3f85b8d2e028e5535fd131988a5df4c0408929b8eac6d751dcc698aa1d79603251d90a216ae5e28bffc0610f61fefe0a23148dcc65ab88b117dd3b8d311157424867eb0261b8b8c5b11def85d434dd4c6dc7036822a279a77ec640b28da164bea7abf8b634ba0e4a13d9a31fdcfebbdbe53adcdf2564d656e64923f76bc2619428abdb0056ce20f47f3ece7d4d11dc55d2969684ca336725561cb27ce0504d57c88a2782daccefb7862b385d494ce70fef93d68e673b12a68ba5b8c93702be832d588ac935dbf0a7b332e42d1b6da5f87aed03498a37bb41fc78fcdbe8fe1f999fe756edf3a375beb54dd508ec45af07985f1430a105e552d9817106ae12d09906c4c28af575d270308a950d05c07da348f59571184088d46bbef3e7a2ad03713e90b435547b23f340f0f5d00149838d9919d40dac9b337920c7e577647fe4e2811f05b8e888e3211d9987cf922883aa6e53a756e579f7dff91c297fcc5cda7d10344545f64099cfd2f8fd59ee5c580ca97cf8b17e0222b764df25a2a52b81ee9db41b3c296fcea1203b367e55d321c3504aeda8913b0cae106ccf736991030088d581468264b8486968e868a44172ad904d97e3e52e8370aaf52732e6ee6cc46eb33a901afc6b7c687b8f6ce0b2b4cdfe19c7139615195a052051becf39383ab83699a383a26f8a36c78887fe27ea7588c0ea21a27357ff9923a3d23ca2fb04ad671b63f8a8ec9b7fc969d3bece0f5ff19a40bc327b9905a6de2193ffe3aa1997e9266205d083776e3b94869164abcdb88d64b8ee5465f7165b75e1632abd364a24bb1426889955b8f0354f75c6fb40e254f7de53d8ef7fee9644bf2ebccd934a72bb1cc9c19d354d66996acbddd60d1241657359d9074a4b313b21af2ee4f10cf20f4122a5fad4ee4f37a682ffb7234bea61985d1ad130bfb9f4714461fb574dbf851c*1000*8*c05f3bc3e7f3cad7*1040*f3e3d091b64da1529b04b2795898b717faad59f7dae4bda25e6e267c28a56a7702e51991b2a3fb034cdda2d9bfd531dfd2c3af00f39fdfe8bcbdde02ab790415bcf071d133b15f647f55ff512730ae4914ce20b72184c827f6350ac768b00c9eab0e3322e084bb3e9e9439a10030950f5504dcc4f7ba614b27fde99bd0d743a58341e90ec313395486eb8068df205b7bdf25134ed97dd2e2883d7eb3e63b659602ada765084a69d7ed8fc55b60aa67718cc9e5bf31ab8f3029b32a4b001071848d2b76b5f4b921d2169ca287e9e78ecd904d040c817c7c7cde4ba8510b462e139c16519962ca0adb7d5f89d431cd4541a9a7aaec8d799697f4d3947d87884bed32ada13db725c72ab6450ac8fe989a94917cca784bcf6ffbe756f19d4e8897e0f80d8c318e13e5b30fc356646aaf038a952b0781f12dfef1f4bd6922ae05a573eeff4dbb064cfbb0fd62962a6a53a8de308da2b8e83baebfe261cb127f874a5eff3f05cda123ab2ba559cf444ce33b6845f4c902733b8982044151a8aa1859769082ade5928f2d4f616ce972ae8dde1f2be37d496ad16057008dfe678c75cbdc53db25ed311edbcf8b2a73bcd2809f6bd1d389aaeed82a75fa15676d08aa5390efdc189c180be6a52ec5a7371304d26e477039197671377d1ea3d6ee41e68a42348a4fe9a1d2400eaeba8ed0a7419b9694d780456d96378c00318a5be0f41afa887476b3bebb7cf30d61ca8fc77de35671a3053a517aa39444e01e1752da3146dc97eec5849d6f025c3d4bc6e0499b901f629d8a081ad35ed33602cbef5e9a68f090170fcc1f285eb094e3dc619740a067fd2aeeb20abbb17926c3ad097f3f0bad4de540d1829a985cd7e700100622ec47da046071c11a1597e5f093268b4ed79ffcf2450b9ba2b649b932fbce912bdb4da010581bd9c731be792c8f75177f6c8c4e1756d63a1491a8aae4bb11beeca118e7d08073b500dd82b81e4bdbeb15625afca8f1c8e06b2360da972587516ef62e91d1d9aad90e62226d53363bff318f5af21f69c234731ac22b09506a1b807d2366e88905668d960c7963daa93046e9a56db1d7a437e9a37aa7a2945197265478b264ec14d383030ef73504fd26d4be9e72ebddb14a00bf6bd66a3adaa1d17cada378a2b0bc852f961af52333f7966f8a60738dfd47e79ce537082f187117ffd31f54f53356b671154dfa245671c4cd054c1a8d303a202fccfae6d3f9e3646838cef38703b5e660b5ce7679f5898d801908f90092dbec335c98e4002041287fe9bfa7d7828a29ab240ec2cedc9fa12cfd7c3ef7b61dad4fbf2ef9c0a904dbde1b3792fb5178607608dc9fc2fbc85addf89fa3df94317e729810b508356b5bb176cdb022afb0ec5eeff4d5081b66733d1be1b54cc4f080bfc33187663b5ab185472b35dc8812e201472e6af376c43ee23aa2db6cd04bddd79b99b0c28c48a5ae", "openwall"}, {NULL} }; static struct custom_salt { unsigned int nkeys; unsigned int iterations[2]; unsigned int saltlen[2]; unsigned char salt[2][SALTLEN]; unsigned int ctlen[2]; unsigned char ct[2][CTLEN]; } *cur_salt; static cl_int cl_error; static keychain_password *inbuffer; static keychain_hash *outbuffer; static keychain_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; size_t insize, outsize, settingsize, cracked_size; #define MIN(a, b) (((a) > (b)) ? (b) : (a)) #define MAX(a, b) (((a) > (b)) ? (a) : (b)) #define OCL_CONFIG "agilekeychain" #define STEP 0 #define SEED 256 // This file contains auto-tuning routine(s). Has to be included after formats definitions. #include "opencl-autotune.h" #include "memdbg.h" static const char * warn[] = { "xfer: ", ", crypt: ", ", xfer: " }; /* ------- Helper functions ------- */ static size_t get_task_max_work_group_size() { return autotune_get_task_max_work_group_size(FALSE, 0, crypt_kernel); } static size_t get_task_max_size() { return 0; } static size_t get_default_workgroup() { if (cpu(device_info[gpu_id])) return get_platform_vendor_id(platform_id) == DEV_INTEL ? 8 : 1; else return 64; } static void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(keychain_password) * gws; outsize = sizeof(keychain_hash) * gws; settingsize = sizeof(keychain_salt); cracked_size = sizeof(*cracked) * gws; inbuffer = mem_calloc(insize); outbuffer = mem_alloc(outsize); cracked = mem_calloc(cracked_size); /// Allocate memory mem_in = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, insize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem in"); mem_setting = clCreateBuffer(context[gpu_id], CL_MEM_READ_ONLY, settingsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem setting"); mem_out = clCreateBuffer(context[gpu_id], CL_MEM_WRITE_ONLY, outsize, NULL, &cl_error); HANDLE_CLERROR(cl_error, "Error allocating mem out"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 0, sizeof(mem_in), &mem_in), "Error while setting mem_in kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 1, sizeof(mem_out), &mem_out), "Error while setting mem_out kernel argument"); HANDLE_CLERROR(clSetKernelArg(crypt_kernel, 2, sizeof(mem_setting), &mem_setting), "Error while setting mem_salt kernel argument"); } static void release_clobj(void) { HANDLE_CLERROR(clReleaseMemObject(mem_in), "Release mem in"); HANDLE_CLERROR(clReleaseMemObject(mem_setting), "Release mem setting"); HANDLE_CLERROR(clReleaseMemObject(mem_out), "Release mem out"); MEM_FREE(inbuffer); MEM_FREE(outbuffer); MEM_FREE(cracked); } static void done(void) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); } static void init(struct fmt_main *self) { char build_opts[64]; snprintf(build_opts, sizeof(build_opts), "-DKEYLEN=%d -DSALTLEN=%d -DOUTLEN=%d", PLAINTEXT_LENGTH, (int)sizeof(currentsalt.salt), (int)sizeof(outbuffer->v)); opencl_init("$JOHN/kernels/pbkdf2_hmac_sha1_unsplit_kernel.cl", gpu_id, build_opts); crypt_kernel = clCreateKernel(program[gpu_id], "derive_key", &cl_error); HANDLE_CLERROR(cl_error, "Error creating kernel"); // Initialize openCL tuning (library) for this format. opencl_init_auto_setup(SEED, 0, NULL, warn, 1, self, create_clobj, release_clobj, sizeof(keychain_password), 0); // Auto tune execution from shared/included code. autotune_run(self, 1, 0, 1000); } static int valid(char *ciphertext, struct fmt_main *self) { char *ctcopy, *keeptr; int ctlen; int saltlen; char *p; if (strncmp(ciphertext, "$agilekeychain$", 15) != 0) return 0; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 15; if ((p = strtok(ctcopy, "*")) == NULL) /* nkeys */ goto err; if(atoi(p) > 2) goto err; if ((p = strtok(NULL, "*")) == NULL) /* iterations */ goto err; if ((p = strtok(NULL, "*")) == NULL) /* salt length */ goto err; saltlen = atoi(p); if(saltlen > SALTLEN) goto err; if ((p = strtok(NULL, "*")) == NULL) /* salt */ goto err; if(strlen(p) != saltlen * 2) goto err; if ((p = strtok(NULL, "*")) == NULL) /* ct length */ goto err; ctlen = atoi(p); if (ctlen > CTLEN) goto err; if ((p = strtok(NULL, "*")) == NULL) /* ciphertext */ goto err; if(strlen(p) != ctlen * 2) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void *get_salt(char *ciphertext) { char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); ctcopy += 15; /* skip over "$agilekeychain$" */ p = strtok(ctcopy, "*"); cs.nkeys = atoi(p); p = strtok(NULL, "*"); cs.iterations[0] = atoi(p); p = strtok(NULL, "*"); cs.saltlen[0] = atoi(p); p = strtok(NULL, "*"); for (i = 0; i < cs.saltlen[0]; i++) cs.salt[0][i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtok(NULL, "*"); cs.ctlen[0] = atoi(p); p = strtok(NULL, "*"); for (i = 0; i < cs.ctlen[0]; i++) cs.ct[0][i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; memcpy((char*)currentsalt.salt, cur_salt->salt, cur_salt->saltlen[0]); currentsalt.length = cur_salt->saltlen[0]; currentsalt.iterations = cur_salt->iterations[0]; currentsalt.outlen = 16; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy salt to gpu"); } #undef set_key static void set_key(char *key, int index) { uint8_t length = strlen(key); if (length > PLAINTEXT_LENGTH) length = PLAINTEXT_LENGTH; inbuffer[index].length = length; memcpy(inbuffer[index].v, key, length); } static char *get_key(int index) { static char ret[PLAINTEXT_LENGTH + 1]; uint8_t length = inbuffer[index].length; memcpy(ret, inbuffer[index].v, length); ret[length] = '\0'; return ret; } static int akcdecrypt(unsigned char *derived_key, unsigned char *data) { unsigned char out[CTLEN]; int pad, n, i, key_size; AES_KEY akey; unsigned char iv[16]; memcpy(iv, data + CTLEN - 32, 16); if(AES_set_decrypt_key(derived_key, 128, &akey) < 0) { fprintf(stderr, "AES_set_decrypt_key failed in crypt!\n"); } AES_cbc_encrypt(data + CTLEN - 16, out + CTLEN - 16, 16, &akey, iv, AES_DECRYPT); // now check padding pad = out[CTLEN - 1]; if(pad < 1 || pad > 16) /* AES block size is 128 bits = 16 bytes */ // "Bad padding byte. You probably have a wrong password" return -1; n = CTLEN - pad; key_size = n / 8; if(key_size != 128 && key_size != 192 && key_size != 256) // "invalid key size" return -1; for(i = n; i < CTLEN; i++) if(out[i] != pad) // "Bad padding. You probably have a wrong password" return -1; return 0; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int index; global_work_size = (count + local_work_size - 1) / local_work_size * local_work_size; if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel HANDLE_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, &local_work_size, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back HANDLE_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) if (!akcdecrypt((unsigned char*)outbuffer[index].v, cur_salt->ct[0])) { 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; } #if FMT_MAIN_VERSION > 11 static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations[0]; } #endif struct fmt_main fmt_opencl_agilekeychain = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_NOT_EXACT, #if FMT_MAIN_VERSION > 11 { "iteration count", }, #endif keychain_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, #if FMT_MAIN_VERSION > 11 { iteration_count, }, #endif fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */ #endif /* HAVE_OPENCL */
shear.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % SSSSS H H EEEEE AAA RRRR % % SS H H E A A R R % % SSS HHHHH EEE AAAAA RRRR % % SS H H E A A R R % % SSSSS H H EEEEE A A R R % % % % % % MagickCore Methods to Shear or Rotate an Image by an Arbitrary Angle % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2016 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 % % % % http://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. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % The XShearImage() and YShearImage() methods are based on the paper "A Fast % Algorithm for General Raster Rotatation" by Alan W. Paeth, Graphics % Interface '86 (Vancouver). ShearRotateImage() is adapted from a similar % method based on the Paeth paper written by Michael Halle of the Spatial % Imaging Group, MIT Media Lab. % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/channel.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/decorate.h" #include "MagickCore/distort.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/matrix.h" #include "MagickCore/memory_.h" #include "MagickCore/list.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/quantum.h" #include "MagickCore/resource_.h" #include "MagickCore/shear.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" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C r o p T o F i t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CropToFitImage() crops the sheared image as determined by the bounding box % as defined by width and height and shearing angles. % % The format of the CropToFitImage method is: % % MagickBooleanType CropToFitImage(Image **image, % const double x_shear,const double x_shear, % const double width,const double height, % const MagickBooleanType rotate,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear, width, height: Defines a region of the image to crop. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType CropToFitImage(Image **image, const double x_shear,const double y_shear, const double width,const double height, const MagickBooleanType rotate,ExceptionInfo *exception) { Image *crop_image; PointInfo extent[4], min, max; RectangleInfo geometry, page; register ssize_t i; /* Calculate the rotated image size. */ extent[0].x=(double) (-width/2.0); extent[0].y=(double) (-height/2.0); extent[1].x=(double) width/2.0; extent[1].y=(double) (-height/2.0); extent[2].x=(double) (-width/2.0); extent[2].y=(double) height/2.0; extent[3].x=(double) width/2.0; extent[3].y=(double) height/2.0; for (i=0; i < 4; i++) { extent[i].x+=x_shear*extent[i].y; extent[i].y+=y_shear*extent[i].x; if (rotate != MagickFalse) extent[i].x+=x_shear*extent[i].y; extent[i].x+=(double) (*image)->columns/2.0; extent[i].y+=(double) (*image)->rows/2.0; } min=extent[0]; max=extent[0]; for (i=1; i < 4; i++) { if (min.x > extent[i].x) min.x=extent[i].x; if (min.y > extent[i].y) min.y=extent[i].y; if (max.x < extent[i].x) max.x=extent[i].x; if (max.y < extent[i].y) max.y=extent[i].y; } geometry.x=(ssize_t) ceil(min.x-0.5); geometry.y=(ssize_t) ceil(min.y-0.5); geometry.width=(size_t) floor(max.x-min.x+0.5); geometry.height=(size_t) floor(max.y-min.y+0.5); page=(*image)->page; (void) ParseAbsoluteGeometry("0x0+0+0",&(*image)->page); crop_image=CropImage(*image,&geometry,exception); if (crop_image == (Image *) NULL) return(MagickFalse); crop_image->page=page; *image=DestroyImage(*image); *image=crop_image; return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s k e w I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DeskewImage() removes skew from the image. Skew is an artifact that % occurs in scanned images because of the camera being misaligned, % imperfections in the scanning or surface, or simply because the paper was % not placed completely flat when scanned. % % The result will be auto-croped if the artifact "deskew:auto-crop" is % defined, while the amount the image is to be deskewed, in degrees is also % saved as the artifact "deskew:angle". % % If the artifact "deskew:auto-crop" is given the image will be automatically % cropped of the excess background. The value is the border width of all % pixels around the edge that will be used to determine an average border % color for the automatic trim. % % The format of the DeskewImage method is: % % Image *DeskewImage(const Image *image,const double threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o threshold: separate background from foreground. % % o exception: return any errors or warnings in this structure. % */ static void RadonProjection(const Image *image,MatrixInfo *source_matrixs, MatrixInfo *destination_matrixs,const ssize_t sign,size_t *projection) { MatrixInfo *swap; register MatrixInfo *p, *q; register ssize_t x; size_t step; p=source_matrixs; q=destination_matrixs; for (step=1; step < GetMatrixColumns(p); step*=2) { for (x=0; x < (ssize_t) GetMatrixColumns(p); x+=2*(ssize_t) step) { register ssize_t i; ssize_t y; unsigned short element, neighbor; for (i=0; i < (ssize_t) step; i++) { for (y=0; y < (ssize_t) (GetMatrixRows(p)-i-1); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i+1,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i+1,y,&neighbor) == MagickFalse) continue; } for ( ; y < (ssize_t) (GetMatrixRows(p)-i); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x+i+step,y+i,&neighbor) == MagickFalse) continue; neighbor+=element; if (SetMatrixElement(q,x+2*i,y,&neighbor) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } for ( ; y < (ssize_t) GetMatrixRows(p); y++) { if (GetMatrixElement(p,x+i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i,y,&element) == MagickFalse) continue; if (SetMatrixElement(q,x+2*i+1,y,&element) == MagickFalse) continue; } } } swap=p; p=q; q=swap; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) \ magick_threads(image,image,1,1) #endif for (x=0; x < (ssize_t) GetMatrixColumns(p); x++) { register ssize_t y; size_t sum; sum=0; for (y=0; y < (ssize_t) (GetMatrixRows(p)-1); y++) { ssize_t delta; unsigned short element, neighbor; if (GetMatrixElement(p,x,y,&element) == MagickFalse) continue; if (GetMatrixElement(p,x,y+1,&neighbor) == MagickFalse) continue; delta=(ssize_t) element-(ssize_t) neighbor; sum+=delta*delta; } projection[GetMatrixColumns(p)+sign*x-1]=sum; } } static MagickBooleanType RadonTransform(const Image *image, const double threshold,size_t *projection,ExceptionInfo *exception) { CacheView *image_view; MatrixInfo *destination_matrixs, *source_matrixs; MagickBooleanType status; size_t count, width; ssize_t j, y; unsigned char c; unsigned short bits[256]; for (width=1; width < ((image->columns+7)/8); width<<=1) ; source_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); destination_matrixs=AcquireMatrixInfo(width,image->rows,sizeof(unsigned short), exception); if ((source_matrixs == (MatrixInfo *) NULL) || (destination_matrixs == (MatrixInfo *) NULL)) { if (destination_matrixs != (MatrixInfo *) NULL) destination_matrixs=DestroyMatrixInfo(destination_matrixs); if (source_matrixs != (MatrixInfo *) NULL) source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } if (NullMatrix(source_matrixs) == MagickFalse) { destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickFalse); } for (j=0; j < 256; j++) { c=(unsigned char) j; for (count=0; c != 0; c>>=1) count+=c & 0x01; bits[j]=(unsigned short) count; } status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=(ssize_t) (image->columns+7)/8; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,--i,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,-1,projection); (void) NullMatrix(source_matrixs); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t i, x; size_t bit, byte; unsigned short value; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } bit=0; byte=0; i=0; for (x=0; x < (ssize_t) image->columns; x++) { byte<<=1; if (((MagickRealType) GetPixelRed(image,p) < threshold) || ((MagickRealType) GetPixelGreen(image,p) < threshold) || ((MagickRealType) GetPixelBlue(image,p) < threshold)) byte|=0x01; bit++; if (bit == 8) { value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); bit=0; byte=0; } p+=GetPixelChannels(image); } if (bit != 0) { byte<<=(8-bit); value=bits[byte]; (void) SetMatrixElement(source_matrixs,i++,y,&value); } } RadonProjection(image,source_matrixs,destination_matrixs,1,projection); image_view=DestroyCacheView(image_view); destination_matrixs=DestroyMatrixInfo(destination_matrixs); source_matrixs=DestroyMatrixInfo(source_matrixs); return(MagickTrue); } static void GetImageBackgroundColor(Image *image,const ssize_t offset, ExceptionInfo *exception) { CacheView *image_view; PixelInfo background; double count; ssize_t y; /* Compute average background color. */ if (offset <= 0) return; GetPixelInfo(image,&background); count=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; if ((y >= offset) && (y < ((ssize_t) image->rows-offset))) continue; p=GetCacheViewVirtualPixels(image_view,0,y,image->columns,1,exception); if (p == (const Quantum *) NULL) continue; for (x=0; x < (ssize_t) image->columns; x++) { if ((x >= offset) && (x < ((ssize_t) image->columns-offset))) continue; background.red+=QuantumScale*GetPixelRed(image,p); background.green+=QuantumScale*GetPixelGreen(image,p); background.blue+=QuantumScale*GetPixelBlue(image,p); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) background.alpha+=QuantumScale*GetPixelAlpha(image,p); count++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); image->background_color.red=(double) ClampToQuantum(QuantumRange* background.red/count); image->background_color.green=(double) ClampToQuantum(QuantumRange* background.green/count); image->background_color.blue=(double) ClampToQuantum(QuantumRange* background.blue/count); if ((GetPixelAlphaTraits(image) & UpdatePixelTrait) != 0) image->background_color.alpha=(double) ClampToQuantum(QuantumRange* background.alpha/count); } MagickExport Image *DeskewImage(const Image *image,const double threshold, ExceptionInfo *exception) { AffineMatrix affine_matrix; const char *artifact; double degrees; Image *clone_image, *crop_image, *deskew_image, *median_image; MagickBooleanType status; RectangleInfo geometry; register ssize_t i; size_t max_projection, *projection, width; ssize_t skew; /* Compute deskew angle. */ for (width=1; width < ((image->columns+7)/8); width<<=1) ; projection=(size_t *) AcquireQuantumMemory((size_t) (2*width-1), sizeof(*projection)); if (projection == (size_t *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); status=RadonTransform(image,threshold,projection,exception); if (status == MagickFalse) { projection=(size_t *) RelinquishMagickMemory(projection); ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); } max_projection=0; skew=0; for (i=0; i < (ssize_t) (2*width-1); i++) { if (projection[i] > max_projection) { skew=i-(ssize_t) width+1; max_projection=projection[i]; } } projection=(size_t *) RelinquishMagickMemory(projection); degrees=RadiansToDegrees(-atan((double) skew/width/8)); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule(), " Deskew angle: %g",degrees); /* Deskew image. */ clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) return((Image *) NULL); { char angle[MagickPathExtent]; (void) FormatLocaleString(angle,MagickPathExtent,"%.20g",degrees); (void) SetImageArtifact(clone_image,"deskew:angle",angle); } (void) SetImageVirtualPixelMethod(clone_image,BackgroundVirtualPixelMethod, exception); affine_matrix.sx=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.rx=sin(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.ry=(-sin(DegreesToRadians(fmod((double) degrees,360.0)))); affine_matrix.sy=cos(DegreesToRadians(fmod((double) degrees,360.0))); affine_matrix.tx=0.0; affine_matrix.ty=0.0; artifact=GetImageArtifact(image,"deskew:auto-crop"); if (IsStringTrue(artifact) == MagickFalse) { deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); return(deskew_image); } /* Auto-crop image. */ GetImageBackgroundColor(clone_image,(ssize_t) StringToLong(artifact), exception); deskew_image=AffineTransformImage(clone_image,&affine_matrix,exception); clone_image=DestroyImage(clone_image); if (deskew_image == (Image *) NULL) return((Image *) NULL); median_image=StatisticImage(deskew_image,MedianStatistic,3,3,exception); if (median_image == (Image *) NULL) { deskew_image=DestroyImage(deskew_image); return((Image *) NULL); } geometry=GetImageBoundingBox(median_image,exception); median_image=DestroyImage(median_image); if (image->debug != MagickFalse) (void) LogMagickEvent(TransformEvent,GetMagickModule()," Deskew geometry: " "%.20gx%.20g%+.20g%+.20g",(double) geometry.width,(double) geometry.height,(double) geometry.x,(double) geometry.y); crop_image=CropImage(deskew_image,&geometry,exception); deskew_image=DestroyImage(deskew_image); return(crop_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e g r a l R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IntegralRotateImage() rotates the image an integral of 90 degrees. It % allocates the memory necessary for the new Image structure and returns a % pointer to the rotated image. % % The format of the IntegralRotateImage method is: % % Image *IntegralRotateImage(const Image *image,size_t rotations, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o rotations: Specifies the number of 90 degree rotations. % */ MagickExport Image *IntegralRotateImage(const Image *image,size_t rotations, ExceptionInfo *exception) { #define RotateImageTag "Rotate/Image" CacheView *image_view, *rotate_view; Image *rotate_image; MagickBooleanType status; MagickOffsetType progress; RectangleInfo page; /* Initialize rotated image attributes. */ assert(image != (Image *) NULL); page=image->page; rotations%=4; if (rotations == 0) return(CloneImage(image,0,0,MagickTrue,exception)); if ((rotations == 1) || (rotations == 3)) rotate_image=CloneImage(image,image->rows,image->columns,MagickTrue, exception); else rotate_image=CloneImage(image,image->columns,image->rows,MagickTrue, exception); if (rotate_image == (Image *) NULL) return((Image *) NULL); /* Integral rotate the image. */ status=MagickTrue; progress=0; image_view=AcquireVirtualCacheView(image,exception); rotate_view=AcquireAuthenticCacheView(rotate_image,exception); switch (rotations) { case 1: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 90 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,(ssize_t) (rotate_image->columns-(tile_y+height)),y+tile_x,height,1, exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((height-1)*width+y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelReadMask(image,tile_pixels) == 0) { tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels-=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 2: { register ssize_t y; /* Rotate 180 degrees. */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,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(rotate_view,0,(ssize_t) (image->rows-y- 1),image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } q+=GetPixelChannels(rotate_image)*image->columns; for (x=0; x < (ssize_t) image->columns; x++) { register ssize_t i; q-=GetPixelChannels(rotate_image); if (GetPixelReadMask(image,p) == 0) { p+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,p[i],q); } p+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif proceed=SetImageProgress(image,RotateImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } case 3: { size_t tile_height, tile_width; ssize_t tile_y; /* Rotate 270 degrees. */ GetPixelCacheTileSize(image,&tile_width,&tile_height); tile_width=image->columns; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(status) \ magick_threads(image,image,1,1) #endif for (tile_y=0; tile_y < (ssize_t) image->rows; tile_y+=(ssize_t) tile_height) { register ssize_t tile_x; if (status == MagickFalse) continue; tile_x=0; for ( ; tile_x < (ssize_t) image->columns; tile_x+=(ssize_t) tile_width) { MagickBooleanType sync; register const Quantum *magick_restrict p; register Quantum *magick_restrict q; register ssize_t y; size_t height, width; width=tile_width; if ((tile_x+(ssize_t) tile_width) > (ssize_t) image->columns) width=(size_t) (tile_width-(tile_x+tile_width-image->columns)); height=tile_height; if ((tile_y+(ssize_t) tile_height) > (ssize_t) image->rows) height=(size_t) (tile_height-(tile_y+tile_height-image->rows)); p=GetCacheViewVirtualPixels(image_view,tile_x,tile_y,width,height, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (y=0; y < (ssize_t) width; y++) { register const Quantum *magick_restrict tile_pixels; register ssize_t x; if (status == MagickFalse) continue; q=QueueCacheViewAuthenticPixels(rotate_view,tile_y,(ssize_t) (y+ rotate_image->rows-(tile_x+width)),height,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } tile_pixels=p+((width-1)-y)*GetPixelChannels(image); for (x=0; x < (ssize_t) height; x++) { register ssize_t i; if (GetPixelReadMask(image,tile_pixels) == 0) { tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel=GetPixelChannelChannel(image,i); PixelTrait traits=GetPixelChannelTraits(image,channel); PixelTrait rotate_traits=GetPixelChannelTraits(rotate_image, channel); if ((traits == UndefinedPixelTrait) || (rotate_traits == UndefinedPixelTrait)) continue; SetPixelChannel(rotate_image,channel,tile_pixels[i],q); } tile_pixels+=width*GetPixelChannels(image); q+=GetPixelChannels(rotate_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_IntegralRotateImage) #endif sync=SyncCacheViewAuthenticPixels(rotate_view,exception); if (sync == MagickFalse) status=MagickFalse; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,RotateImageTag,progress+=tile_height, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,RotateImageTag,(MagickOffsetType) image->rows-1,image->rows); Swap(page.width,page.height); Swap(page.x,page.y); if (page.width != 0) page.x=(ssize_t) (page.width-rotate_image->columns-page.x); break; } default: break; } rotate_view=DestroyCacheView(rotate_view); image_view=DestroyCacheView(image_view); rotate_image->type=image->type; rotate_image->page=page; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + X S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % XShearImage() shears the image in the X direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a vertical % Y-axis. X shears will widen an image creating 'empty' triangles on the left % and right sides of the source image. % % The format of the XShearImage method is: % % MagickBooleanType XShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the X % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType XShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define XShearImageTag "XShear/Image" typedef enum { LEFT, RIGHT } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t y; /* X shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; background=image->background_color; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,height,1) #endif for (y=0; y < (ssize_t) height; y++) { PixelInfo pixel, source, destination; double area, displacement; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; ssize_t step; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,0,y_offset+y,image->columns,1, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=x_offset*GetPixelChannels(image); displacement=degrees*(double) (y-height/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=RIGHT; else { displacement*=(-1.0); direction=LEFT; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case LEFT: { /* Transfer pixels left-to-right. */ if (step > x_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { if ((x_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case RIGHT: { /* Transfer pixels right-to-left. */ p+=width*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) width; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (x_offset+width+step-i) > image->columns) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area,&destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_XShearImage) #endif proceed=SetImageProgress(image,XShearImageTag,progress++,height); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Y S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % YShearImage shears the image in the Y direction with a shear angle of % 'degrees'. Positive angles shear counter-clockwise (right-hand rule), and % negative angles shear clockwise. Angles are measured relative to a % horizontal X-axis. Y shears will increase the height of an image creating % 'empty' triangles on the top and bottom of the source image. % % The format of the YShearImage method is: % % MagickBooleanType YShearImage(Image *image,const double degrees, % const size_t width,const size_t height, % const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: A double representing the shearing angle along the Y % axis. % % o width, height, x_offset, y_offset: Defines a region of the image % to shear. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType YShearImage(Image *image,const double degrees, const size_t width,const size_t height,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define YShearImageTag "YShear/Image" typedef enum { UP, DOWN } ShearDirection; CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; PixelInfo background; ssize_t x; /* Y Shear image. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; background=image->background_color; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_threads(image,image,width,1) #endif for (x=0; x < (ssize_t) width; x++) { ssize_t step; double area, displacement; PixelInfo pixel, source, destination; register Quantum *magick_restrict p, *magick_restrict q; register ssize_t i; ShearDirection direction; if (status == MagickFalse) continue; p=GetCacheViewAuthenticPixels(image_view,x_offset+x,0,1,image->rows, exception); if (p == (Quantum *) NULL) { status=MagickFalse; continue; } p+=y_offset*GetPixelChannels(image); displacement=degrees*(double) (x-width/2.0); if (displacement == 0.0) continue; if (displacement > 0.0) direction=DOWN; else { displacement*=(-1.0); direction=UP; } step=(ssize_t) floor((double) displacement); area=(double) (displacement-step); step++; pixel=background; GetPixelInfo(image,&source); GetPixelInfo(image,&destination); switch (direction) { case UP: { /* Transfer pixels top-to-bottom. */ if (step > y_offset) break; q=p-step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { if ((y_offset+i) < step) { p+=GetPixelChannels(image); GetPixelInfoPixel(image,p,&pixel); q+=GetPixelChannels(image); continue; } GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); p+=GetPixelChannels(image); q+=GetPixelChannels(image); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); SetPixelViaPixelInfo(image,&destination,q); q+=GetPixelChannels(image); for (i=0; i < (step-1); i++) { SetPixelViaPixelInfo(image,&background,q); q+=GetPixelChannels(image); } break; } case DOWN: { /* Transfer pixels bottom-to-top. */ p+=height*GetPixelChannels(image); q=p+step*GetPixelChannels(image); for (i=0; i < (ssize_t) height; i++) { p-=GetPixelChannels(image); q-=GetPixelChannels(image); if ((size_t) (y_offset+height+step-i) > image->rows) continue; GetPixelInfoPixel(image,p,&source); CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &source,(double) GetPixelAlpha(image,p),area, &destination); SetPixelViaPixelInfo(image,&destination,q); GetPixelInfoPixel(image,p,&pixel); } CompositePixelInfoAreaBlend(&pixel,(double) pixel.alpha, &background,(double) background.alpha,area,&destination); q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&destination,q); for (i=0; i < (step-1); i++) { q-=GetPixelChannels(image); SetPixelViaPixelInfo(image,&background,q); } break; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_YShearImage) #endif proceed=SetImageProgress(image,YShearImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearImage() creates a new image that is a shear_image copy of an existing % one. Shearing slides one edge of an image along the X or Y axis, creating % a parallelogram. An X direction shear slides an edge along the X axis, % while a Y direction shear slides an edge along the Y axis. The amount of % the shear is controlled by a shear angle. For X direction shears, x_shear % is measured relative to the Y axis, and similarly, for Y direction shears % y_shear is measured relative to the X axis. Empty triangles left over from % shearing the image are filled with the background color defined by member % 'background_color' of the image.. ShearImage() allocates the memory % necessary for the new Image structure and returns a pointer to the new image. % % ShearImage() is based on the paper "A Fast Algorithm for General Raster % Rotatation" by Alan W. Paeth. % % The format of the ShearImage method is: % % Image *ShearImage(const Image *image,const double x_shear, % const double y_shear,ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o x_shear, y_shear: Specifies the number of degrees to shear the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearImage(const Image *image,const double x_shear, const double y_shear,ExceptionInfo *exception) { Image *integral_image, *shear_image; MagickBooleanType status; PointInfo shear; RectangleInfo border_info, bounds; 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 ((x_shear != 0.0) && (fmod(x_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); if ((y_shear != 0.0) && (fmod(y_shear,90.0) == 0.0)) ThrowImageException(ImageError,"AngleIsDiscontinuous"); /* Initialize shear angle. */ integral_image=CloneImage(image,0,0,MagickTrue,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan(DegreesToRadians(fmod(x_shear,360.0)))); shear.y=tan(DegreesToRadians(fmod(y_shear,360.0))); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute image size. */ bounds.width=image->columns+(ssize_t) floor(fabs(shear.x)*image->rows+0.5); bounds.x=(ssize_t) ceil((double) image->columns+((fabs(shear.x)*image->rows)- image->columns)/2.0-0.5); bounds.y=(ssize_t) ceil((double) image->rows+((fabs(shear.y)*bounds.width)- image->rows)/2.0-0.5); /* Surround image with border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; shear_image=BorderImage(integral_image,&border_info,image->compose,exception); integral_image=DestroyImage(integral_image); if (shear_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Shear the image. */ if (shear_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(shear_image,OpaqueAlphaChannel,exception); status=XShearImage(shear_image,shear.x,image->columns,image->rows,bounds.x, (ssize_t) (shear_image->rows-image->rows)/2,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=YShearImage(shear_image,shear.y,bounds.width,image->rows,(ssize_t) (shear_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { shear_image=DestroyImage(shear_image); return((Image *) NULL); } status=CropToFitImage(&shear_image,shear.x,shear.y,(MagickRealType) image->columns,(MagickRealType) image->rows,MagickFalse,exception); shear_image->alpha_trait=image->alpha_trait; shear_image->compose=image->compose; shear_image->page.width=0; shear_image->page.height=0; if (status == MagickFalse) shear_image=DestroyImage(shear_image); return(shear_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S h e a r R o t a t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ShearRotateImage() creates a new image that is a rotated copy of an existing % one. Positive angles rotate counter-clockwise (right-hand rule), while % negative angles rotate clockwise. Rotated images are usually larger than % the originals and have 'empty' triangular corners. X axis. Empty % triangles left over from shearing the image are filled with the background % color defined by member 'background_color' of the image. ShearRotateImage % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % ShearRotateImage() is based on the paper "A Fast Algorithm for General % Raster Rotatation" by Alan W. Paeth. ShearRotateImage is adapted from a % similar method based on the Paeth paper written by Michael Halle of the % Spatial Imaging Group, MIT Media Lab. % % The format of the ShearRotateImage method is: % % Image *ShearRotateImage(const Image *image,const double degrees, % ExceptionInfo *exception) % % A description of each parameter follows. % % o image: the image. % % o degrees: Specifies the number of degrees to rotate the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ShearRotateImage(const Image *image,const double degrees, ExceptionInfo *exception) { Image *integral_image, *rotate_image; MagickBooleanType status; MagickRealType angle; PointInfo shear; RectangleInfo border_info, bounds; size_t height, rotations, shear_width, width; /* Adjust rotation angle. */ 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); angle=degrees; while (angle < -45.0) angle+=360.0; for (rotations=0; angle > 45.0; rotations++) angle-=90.0; rotations%=4; /* Calculate shear equations. */ integral_image=IntegralRotateImage(image,rotations,exception); if (integral_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); shear.x=(-tan((double) DegreesToRadians(angle)/2.0)); shear.y=sin((double) DegreesToRadians(angle)); if ((shear.x == 0.0) && (shear.y == 0.0)) return(integral_image); if (SetImageStorageClass(integral_image,DirectClass,exception) == MagickFalse) { integral_image=DestroyImage(integral_image); return(integral_image); } if (integral_image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(integral_image,OpaqueAlphaChannel,exception); /* Compute maximum bounds for 3 shear operations. */ width=integral_image->columns; height=integral_image->rows; bounds.width=(size_t) floor(fabs((double) height*shear.x)+width+0.5); bounds.height=(size_t) floor(fabs((double) bounds.width*shear.y)+height+0.5); shear_width=(size_t) floor(fabs((double) bounds.height*shear.x)+ bounds.width+0.5); bounds.x=(ssize_t) floor((double) ((shear_width > bounds.width) ? width : bounds.width-shear_width+2)/2.0+0.5); bounds.y=(ssize_t) floor(((double) bounds.height-height+2)/2.0+0.5); /* Surround image with a border. */ integral_image->border_color=integral_image->background_color; integral_image->compose=CopyCompositeOp; border_info.width=(size_t) bounds.x; border_info.height=(size_t) bounds.y; rotate_image=BorderImage(integral_image,&border_info,image->compose, exception); integral_image=DestroyImage(integral_image); if (rotate_image == (Image *) NULL) ThrowImageException(ResourceLimitError,"MemoryAllocationFailed"); /* Rotate the image. */ status=XShearImage(rotate_image,shear.x,width,height,bounds.x,(ssize_t) (rotate_image->rows-height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=YShearImage(rotate_image,shear.y,bounds.width,height,(ssize_t) (rotate_image->columns-bounds.width)/2,bounds.y,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=XShearImage(rotate_image,shear.x,bounds.width,bounds.height,(ssize_t) (rotate_image->columns-bounds.width)/2,(ssize_t) (rotate_image->rows- bounds.height)/2,exception); if (status == MagickFalse) { rotate_image=DestroyImage(rotate_image); return((Image *) NULL); } status=CropToFitImage(&rotate_image,shear.x,shear.y,(MagickRealType) width, (MagickRealType) height,MagickTrue,exception); rotate_image->alpha_trait=image->alpha_trait; rotate_image->compose=image->compose; rotate_image->page.width=0; rotate_image->page.height=0; if (status == MagickFalse) rotate_image=DestroyImage(rotate_image); return(rotate_image); }
expected_output.c
#include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> #include <polybench.h> #include "jacobi-1d.h" /** * 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 */ /*jacobi-1d.c: this file is part of PolyBench/C*/ /*Include polybench common header.*/ /*Include benchmark-specific header.*/ /*Array initialization.*/ static void init_array(int n, double A[2000], double B[2000]) { int i; for(i = 0; i < n; i++) { A[i] = ((double) i + 2) / n; B[i] = ((double) i + 3) / n; } } /*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 n, double A[2000]) { int i; fprintf(stderr, "==BEGIN DUMP_ARRAYS==\n"); fprintf(stderr, "begin dump: %s", "A"); for(i = 0; i < n; i++) { if(i % 20 == 0) fprintf(stderr, "\n"); fprintf(stderr, "%0.2lf ", A[i]); } fprintf(stderr, "\nend dump: %s\n", "A"); fprintf(stderr, "==END DUMP_ARRAYS==\n"); } /*Main computational kernel. The whole function will be timed, including the call and return.*/ static void kernel_jacobi_1d(int tsteps, int n, double A[2000], double B[2000]) { int t, i; /*************** Clava msgError ************** unsolved dependency for arrayAccess A use : RW ****************************************/ for(t = 0; t < tsteps; t++) { #pragma omp parallel for default(shared) private(i) firstprivate(n, A) for(i = 1; i < n - 1; i++) B[i] = 0.33333 * (A[i - 1] + A[i] + A[i + 1]); #pragma omp parallel for default(shared) private(i) firstprivate(n, B) for(i = 1; i < n - 1; i++) A[i] = 0.33333 * (B[i - 1] + B[i] + B[i + 1]); } } int main(int argc, char **argv) { /*Retrieve problem size.*/ int n = 2000; int tsteps = 500; /*Variable declaration/allocation.*/ double (*A)[2000]; A = (double (*)[2000]) polybench_alloc_data(2000 + 0, sizeof(double)); ; double (*B)[2000]; B = (double (*)[2000]) polybench_alloc_data(2000 + 0, sizeof(double)); ; /*Initialize array(s).*/ init_array(n, *A, *B); /*Start timer.*/ ; /*Run kernel.*/ kernel_jacobi_1d(tsteps, n, *A, *B); /*Stop and print timer.*/ ; ; /*Prevent dead-code elimination. All live-out data must be printed by the function call in argument.*/ if(argc > 42 && !strcmp(argv[0], "")) print_array(n, *A); /*Be clean.*/ free((void *) A); ; free((void *) B); ; return 0; }
omp-for-dynamic.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> int main() { int i,j; #pragma omp parallel for schedule(static) for(i = 0; i < 11; i++) { printf("Static Hello World %d\n", i); } #pragma omp parallel for schedule(static, 1) for(i = 0; i < 11; i++) { printf("Static1 Hello World %d\n", i); } #pragma omp parallel for schedule(static, 2) for(i = 0; i < 11; i++) { printf("Static2 Hello World %d\n", i); } printf("\nDynamic loop\n"); #pragma omp parallel for schedule(dynamic) for(i = 0; i < 9; i++) { printf("Thread %d: Dynamic Hello World %d\n", omp_get_thread_num(), i); } printf("\nStatic Ordered loop\n"); #pragma omp parallel for schedule(static) ordered for(i = 0; i < 10; i++) { #pragma omp ordered printf("Thread %d: Static Ordered Hello World %d\n", omp_get_thread_num(), i); } printf("\nDynamic Ordered loop\n"); #pragma omp parallel for schedule(dynamic) ordered for(i = 0; i < 16; i++) { #pragma omp ordered printf("Thread %d: Dynamic Ordered Hello World %d\n", omp_get_thread_num(), i); } return 0; }
linked_notasks.c
#include <stdlib.h> #include <stdio.h> #include "omp.h" #define N 15 #define FS 30 #define NMAX 20 struct node { int data; int fibdata; struct node* next; }; int fib(int n) { int x, y; if (n < 2) { return (n); } else { x = fib(n - 1); y = fib(n - 2); return (x + y); } } void processwork(struct node* p) { int n; n = p->data; p->fibdata = fib(n); } struct node* init_list(struct node* p) { int i; struct node* head = NULL; struct node* temp = NULL; head = malloc(sizeof(struct node)); p = head; p->data = FS; p->fibdata = 0; for (i=0; i< N; i++) { temp = malloc(sizeof(struct node)); p->next = temp; p = temp; p->data = FS + i + 1; p->fibdata = i+1; } p->next = NULL; return head; } int main(int argc, char *argv[]) { double start, end; struct node *p=NULL; struct node *temp=NULL; struct node *head=NULL; struct node *parr[NMAX]; int i, count=0; printf("Process linked list\n"); printf(" Each linked list node will be processed by function 'processwork()'\n"); printf(" Each ll node will compute %d fibonacci numbers beginning with %d\n",N,FS); p = init_list(p); head = p; start = omp_get_wtime(); { while (p != NULL) { processwork(p); p = p->next; } } end = omp_get_wtime(); printf("serial Compute Time: %f seconds\n", end - start); p = head; start = omp_get_wtime(); { // count number of items in the list. Strictly speaking this isn't // needed since we know there are N elements in the list. But in // most cases you don't know this and need to count nodes. while (p != NULL) { p = p->next; count++; } // traverse the list and collect pointers into an array. p = head; for(i=0; i<count; i++) { parr[i] = p; p = p->next; } // do the work in parallel #pragma omp parallel { #pragma omp single printf(" %d threads \n",omp_get_num_threads()); #pragma omp for schedule(dynamic,1) for(i=0; i<count; i++) processwork(parr[i]); } } end = omp_get_wtime(); p = head; while (p != NULL) { printf("%d : %d\n",p->data, p->fibdata); temp = p->next; free (p); p = temp; } free (p); printf("Compute Time: %f seconds\n", end - start); return 0; }
atomic_utilities.h
// | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Riccardo Rossi // Denis Demidov // #if !defined(KRATOS_ATOMIC_UTILITIES_H_INCLUDED ) #define KRATOS_ATOMIC_UTILITIES_H_INCLUDED // System includes // External includes #ifdef KRATOS_SMP_OPENMP #include <omp.h> #endif // Project includes #include "includes/define.h" #include "containers/array_1d.h" namespace Kratos { ///@addtogroup KratosCore /** * collection of utilities for atomic updates of simple types. (essentially mimics the omp atomic) */ /** * @param target variable being atomically updated by doing target += value * @param value value being added */ template<class TDataType> inline void AtomicAdd(TDataType& target, const TDataType& value) { #pragma omp atomic target += value; } /** * @param target variable being atomically updated by doing target += value * @param value value being added * Specialization for array_1d * Note that the update is not really atomic, but rather is done component by component */ template <class TDataType, std::size_t ArraySize> inline void AtomicAdd(array_1d<TDataType,ArraySize>& target, const array_1d<TDataType,ArraySize>& value) { for (std::size_t i=0; i<ArraySize; ++i) { AtomicAdd(target[i], value[i]); } } /** * @param target vector variable being atomically updated by doing target += value * @param value vector value being added * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicAddVector(TVectorType1& target, const TVectorType2& value) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicAddVector- Sizes are: " << target.size() << " for target and " << value.size() << " for value " << std::endl; for(std::size_t i=0; i<target.size(); ++i) { AtomicAdd(target[i], value[i]); } } /** * @param target matrix variable being atomically updated by doing target -= value * @param value matrix value being subtracted * Note that the update is not really atomic, but rather is done component by component */ template<class TMatrixType1, class TMatrixType2> inline void AtomicAddMatrix(TMatrixType1& target, const TMatrixType2& value) { KRATOS_DEBUG_ERROR_IF(target.size1() != value.size1() || target.size2() != value.size2()) << "matrix size mismatch in matrix AtomicAddMatrix- Sizes are: " << target.size1() << "x" << target.size2() << " for target and " << value.size1() << "x" << value.size2() << " for value " << std::endl; for(std::size_t i=0; i<target.size1(); ++i) { for(std::size_t j=0; j<target.size2(); ++j) { AtomicAdd(target(i,j), value(i,j)); } } } /** * @param target vector variable being atomically updated by doing target -= value * @param value vector value being subtracted */ template<class TDataType> inline void AtomicSub(TDataType& target, const TDataType& value) { #pragma omp atomic target -= value; } /** * @param target variable being atomically updated by doing target -= value * @param value value being subtracted * Specialization for array_1d * Note that the update is not really atomic, but rather is done component by component */ template <class TDataType, std::size_t ArraySize> inline void AtomicSub(array_1d<TDataType,ArraySize>& target, const array_1d<TDataType,ArraySize>& value) { for(std::size_t i=0; i<ArraySize; ++i) { AtomicSub(target[i], value[i]); } } /** * @param target vector variable being atomically updated by doing target -= value * @param value vector value being subtracted * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicSubVector(TVectorType1& target, const TVectorType2& value) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicSubVector- Sizes are: " << target.size() << " for target and " << value.size() << " for value " << std::endl; for(std::size_t i=0; i<target.size(); ++i) { AtomicSub(target[i], value[i]); } } /** * @param target matrix variable being atomically updated by doing target -= value * @param value matrix value being subtracted * Note that the update is not really atomic, but rather is done component by component */ template<class TMatrixType1, class TMatrixType2> inline void AtomicSubMatrix(TMatrixType1& target, const TMatrixType2& value) { KRATOS_DEBUG_ERROR_IF(target.size1() != value.size1() || target.size2() != value.size2()) << "matrix size mismatch in matrix AtomicSubMatrix- Sizes are: " << target.size1() << "x" << target.size2() << " for target and " << value.size1() << "x" << value.size2() << " for value " << std::endl; for(std::size_t i=0; i<target.size1(); ++i) { for(std::size_t j=0; j<target.size2(); ++j) { AtomicSub(target(i,j), value(i,j)); } } } /** @param target vector variable being atomically updated by doing target *= value * @param value vector value being multiplied */ template<class TDataType> inline void AtomicMult(TDataType& target, const TDataType& value) { #pragma omp atomic target *= value; } /** @param target variable being atomically updated by doing target *= value * @param value value being multiplied * Specialization for array_1d * Note that the update is not really atomic, but rather is done component by component */ template <class TDataType, std::size_t ArraySize> inline void AtomicMult(array_1d<TDataType,ArraySize>& target, const array_1d<TDataType,ArraySize>& value) { for(std::size_t i=0; i<ArraySize; ++i) { AtomicMult(target[i], value[i]); } } /** @param target vector variable being atomically updated by doing target *= value * @param value vector value being multiplied * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicMultVector(TVectorType1& target, const TVectorType2& value) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicMultVector- Sizes are: " << target.size() << " for target and " << value.size() << " for value " << std::endl; for(std::size_t i=0; i<target.size(); ++i) { AtomicMult(target[i], value[i]); } } /** * @param target matrix variable being atomically updated by doing target *= value * @param value matrix value being multiplied * Note that the update is not really atomic, but rather is done component by component */ template<class TMatrixType1, class TMatrixType2> inline void AtomicMultMatrix(TMatrixType1& target, const TMatrixType2& value) { KRATOS_DEBUG_ERROR_IF(target.size1() != value.size1() || target.size2() != value.size2()) << "matrix size mismatch in matrix AtomicMultMatrix- Sizes are: " << target.size1() << "x" << target.size2() << " for target and " << value.size1() << "x" << value.size2() << " for value " << std::endl; for(std::size_t i=0; i<target.size1(); ++i) { for(std::size_t j=0; j<target.size2(); ++j) { AtomicMult(target(i,j), value(i,j)); } } } /** @param target vector variable being atomically updated by doing target *= 1.0/value * @param value vector value being divided */ template<class TDataType> inline void AtomicDiv(TDataType& target, const TDataType& value) { AtomicMult(target, 1.0/value); } /** @param target variable being atomically updated by doing target *= 1.0/value * @param value value being divided * Specialization for array_1d * Note that the update is not really atomic, but rather is done component by component */ template <class TDataType, std::size_t ArraySize> inline void AtomicDiv(array_1d<TDataType,ArraySize>& target, const array_1d<TDataType,ArraySize>& value) { for(std::size_t i=0; i<ArraySize; ++i) { AtomicDiv(target[i], value[i]); } } /** @param target vector variable being atomically updated by doing target *= 1.0/value * @param value vector value being divided * Note that the update is not really atomic, but rather is done component by component */ template<class TVectorType1, class TVectorType2> inline void AtomicDivVector(TVectorType1& target, const TVectorType2& value) { KRATOS_DEBUG_ERROR_IF(target.size() != value.size()) << "vector size mismatch in vector AtomicDivVector- Sizes are: " << target.size() << " for target and " << value.size() << " for value " << std::endl; for(std::size_t i=0; i<target.size(); ++i) { AtomicDiv(target[i], value[i]); } } /** * @param target matrix variable being atomically updated by doing target *= 1.0/value * @param value matrix value being divided * Note that the update is not really atomic, but rather is done component by component */ template<class TMatrixType1, class TMatrixType2> inline void AtomicDivMatrix(TMatrixType1& target, const TMatrixType2& value) { KRATOS_DEBUG_ERROR_IF(target.size1() != value.size1() || target.size2() != value.size2()) << "matrix size mismatch in matrix AtomicDivMatrix- Sizes are: " << target.size1() << "x" << target.size2() << " for target and " << value.size1() << "x" << value.size2() << " for value " << std::endl; for(std::size_t i=0; i<target.size1(); ++i) { for(std::size_t j=0; j<target.size2(); ++j) { AtomicDiv(target(i,j), value(i,j)); } } } } // namespace Kratos. #endif // KRATOS_ATOMIC_UTILITIES_H_INCLUDED defined
composite.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC OOO M M PPPP OOO SSSSS IIIII TTTTT EEEEE % % C O O MM MM P P O O SS I T E % % C O O M M M PPPP O O SSS I T EEE % % C O O M M P O O SS I T E % % CCCC OOO M M P OOO SSSSS IIIII T EEEEE % % % % % % MagickCore Image Composite Methods % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/cache-view.h" #include "MagickCore/channel.h" #include "MagickCore/client.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite.h" #include "MagickCore/composite-private.h" #include "MagickCore/constitute.h" #include "MagickCore/draw.h" #include "MagickCore/exception-private.h" #include "MagickCore/fx.h" #include "MagickCore/gem.h" #include "MagickCore/geometry.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/morphology.h" #include "MagickCore/option.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantum.h" #include "MagickCore/resample.h" #include "MagickCore/resource_.h" #include "MagickCore/string_.h" #include "MagickCore/thread-private.h" #include "MagickCore/threshold.h" #include "MagickCore/token.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #include "MagickCore/version.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p o s i t e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CompositeImage() returns the second image composited onto the first % at the specified offset, using the specified composite method. % % The format of the CompositeImage method is: % % MagickBooleanType CompositeImage(Image *image, % const Image *source_image,const CompositeOperator compose, % const MagickBooleanType clip_to_self,const ssize_t x_offset, % const ssize_t y_offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the canvas image, modified by he composition % % o source_image: the source image. % % o compose: This operator affects how the composite is applied to % the image. The operators and how they are utilized are listed here % http://www.w3.org/TR/SVG12/#compositing. % % o clip_to_self: set to MagickTrue to limit composition to area composed. % % o x_offset: the column offset of the composited image. % % o y_offset: the row offset of the composited image. % % Extra Controls from Image meta-data in 'image' (artifacts) % % o "compose:args" % A string containing extra numerical arguments for specific compose % methods, generally expressed as a 'geometry' or a comma separated list % of numbers. % % Compose methods needing such arguments include "BlendCompositeOp" and % "DisplaceCompositeOp". % % o exception: return any errors or warnings in this structure. % */ /* Composition based on the SVG specification: A Composition is defined by... Color Function : f(Sc,Dc) where Sc and Dc are the normizalized colors Blending areas : X = 1 for area of overlap, ie: f(Sc,Dc) Y = 1 for source preserved Z = 1 for canvas preserved Conversion to transparency (then optimized) Dca' = f(Sc, Dc)*Sa*Da + Y*Sca*(1-Da) + Z*Dca*(1-Sa) Da' = X*Sa*Da + Y*Sa*(1-Da) + Z*Da*(1-Sa) Where... Sca = Sc*Sa normalized Source color divided by Source alpha Dca = Dc*Da normalized Dest color divided by Dest alpha Dc' = Dca'/Da' the desired color value for this channel. Da' in in the follow formula as 'gamma' The resulting alpla value. Most functions use a blending mode of over (X=1,Y=1,Z=1) this results in the following optimizations... gamma = Sa+Da-Sa*Da; gamma = 1 - QuantumScale*alpha * QuantumScale*beta; opacity = QuantumScale*alpha*beta; // over blend, optimized 1-Gamma The above SVG definitions also define that Mathematical Composition methods should use a 'Over' blending mode for Alpha Channel. It however was not applied for composition modes of 'Plus', 'Minus', the modulus versions of 'Add' and 'Subtract'. Mathematical operator changes to be applied from IM v6.7... 1) Modulus modes 'Add' and 'Subtract' are obsoleted and renamed 'ModulusAdd' and 'ModulusSubtract' for clarity. 2) All mathematical compositions work as per the SVG specification with regard to blending. This now includes 'ModulusAdd' and 'ModulusSubtract'. 3) When the special channel flag 'sync' (syncronize channel updates) is turned off (enabled by default) then mathematical compositions are only performed on the channels specified, and are applied independantally of each other. In other words the mathematics is performed as 'pure' mathematical operations, rather than as image operations. */ static Image *BlendConvolveImage(const Image *image,const char *kernel, ExceptionInfo *exception) { Image *clone_image, *convolve_image; KernelInfo *kernel_info; /* Convolve image with a kernel. */ kernel_info=AcquireKernelInfo(kernel,exception); if (kernel_info == (KernelInfo *) NULL) return((Image *) NULL); clone_image=CloneImage(image,0,0,MagickTrue,exception); if (clone_image == (Image *) NULL) { kernel_info=DestroyKernelInfo(kernel_info); return((Image *) NULL); } (void) SetImageAlphaChannel(clone_image,OffAlphaChannel,exception); convolve_image=ConvolveImage(clone_image,kernel_info,exception); kernel_info=DestroyKernelInfo(kernel_info); clone_image=DestroyImage(clone_image); return(convolve_image); } static Image *BlendMagnitudeImage(const Image *dx_image,const Image *dy_image, ExceptionInfo *exception) { CacheView *dx_view, *dy_view, *magnitude_view; Image *magnitude_image; MagickBooleanType status = MagickTrue; ssize_t y; /* Generate the magnitude between two images. */ magnitude_image=CloneImage(dx_image,0,0,MagickTrue,exception); if (magnitude_image == (Image *) NULL) return(magnitude_image); dx_view=AcquireVirtualCacheView(dx_image,exception); dy_view=AcquireVirtualCacheView(dy_image,exception); magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(dx_image,magnitude_image,dx_image->rows,1) #endif for (y=0; y < (ssize_t) dx_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; Quantum *magick_restrict r; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(dx_view,0,y,dx_image->columns,1,exception); q=GetCacheViewVirtualPixels(dy_view,0,y,dx_image->columns,1,exception); r=GetCacheViewAuthenticPixels(magnitude_view,0,y,dx_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) dx_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(dx_image); i++) { PixelChannel channel = GetPixelChannelChannel(dx_image,i); PixelTrait traits = GetPixelChannelTraits(dx_image,channel); PixelTrait dy_traits = GetPixelChannelTraits(dy_image,channel); if ((traits == UndefinedPixelTrait) || (dy_traits == UndefinedPixelTrait) || ((dy_traits & UpdatePixelTrait) == 0)) continue; r[i]=ClampToQuantum(hypot((double) p[i],(double) GetPixelChannel(dy_image,channel,q))); } p+=GetPixelChannels(dx_image); q+=GetPixelChannels(dy_image); r+=GetPixelChannels(magnitude_image); } if (SyncCacheViewAuthenticPixels(magnitude_view,exception) == MagickFalse) status=MagickFalse; } magnitude_view=DestroyCacheView(magnitude_view); dy_view=DestroyCacheView(dy_view); dx_view=DestroyCacheView(dx_view); if (status == MagickFalse) magnitude_image=DestroyImage(magnitude_image); return(magnitude_image); } static Image *BlendMaxMagnitudeImage(const Image *alpha_image, const Image *beta_image,const Image *dx_image,const Image *dy_image, ExceptionInfo *exception) { CacheView *alpha_view, *beta_view, *dx_view, *dy_view, *magnitude_view; Image *magnitude_image; MagickBooleanType status = MagickTrue; ssize_t y; /* Select the larger of two magnitudes. */ magnitude_image=CloneImage(alpha_image,0,0,MagickTrue,exception); if (magnitude_image == (Image *) NULL) return(magnitude_image); alpha_view=AcquireVirtualCacheView(alpha_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); dx_view=AcquireVirtualCacheView(dx_image,exception); dy_view=AcquireVirtualCacheView(dy_image,exception); magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(alpha_image,magnitude_image,alpha_image->rows,1) #endif for (y=0; y < (ssize_t) alpha_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q, *magick_restrict r, *magick_restrict s; Quantum *magick_restrict t; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(alpha_view,0,y,alpha_image->columns,1, exception); q=GetCacheViewVirtualPixels(beta_view,0,y,alpha_image->columns,1,exception); r=GetCacheViewVirtualPixels(dx_view,0,y,alpha_image->columns,1,exception); s=GetCacheViewVirtualPixels(dy_view,0,y,alpha_image->columns,1,exception); t=GetCacheViewAuthenticPixels(magnitude_view,0,y,alpha_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (const Quantum *) NULL) || (s == (const Quantum *) NULL) || (t == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) alpha_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++) { PixelChannel channel = GetPixelChannelChannel(alpha_image,i); PixelTrait traits = GetPixelChannelTraits(alpha_image,channel); PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel); if ((traits == UndefinedPixelTrait) || (beta_traits == UndefinedPixelTrait) || ((beta_traits & UpdatePixelTrait) == 0)) continue; if (p[i] > GetPixelChannel(beta_image,channel,q)) t[i]=GetPixelChannel(dx_image,channel,r); else t[i]=GetPixelChannel(dy_image,channel,s); } p+=GetPixelChannels(alpha_image); q+=GetPixelChannels(beta_image); r+=GetPixelChannels(dx_image); s+=GetPixelChannels(dy_image); t+=GetPixelChannels(magnitude_image); } if (SyncCacheViewAuthenticPixels(magnitude_view,exception) == MagickFalse) status=MagickFalse; } magnitude_view=DestroyCacheView(magnitude_view); dy_view=DestroyCacheView(dy_view); dx_view=DestroyCacheView(dx_view); beta_view=DestroyCacheView(beta_view); alpha_view=DestroyCacheView(alpha_view); if (status == MagickFalse) magnitude_image=DestroyImage(magnitude_image); return(magnitude_image); } static Image *BlendSumImage(const Image *alpha_image,const Image *beta_image, const double attenuate,const double sign,ExceptionInfo *exception) { CacheView *alpha_view, *beta_view, *sum_view; Image *sum_image; MagickBooleanType status = MagickTrue; ssize_t y; /* Add or subtract and optionally attenuate two images. */ sum_image=CloneImage(alpha_image,0,0,MagickTrue,exception); if (sum_image == (Image *) NULL) return(sum_image); alpha_view=AcquireVirtualCacheView(alpha_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); sum_view=AcquireAuthenticCacheView(sum_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(alpha_image,sum_image,alpha_image->rows,1) #endif for (y=0; y < (ssize_t) alpha_image->rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; Quantum *magick_restrict r; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(alpha_view,0,y,alpha_image->columns,1, exception); q=GetCacheViewVirtualPixels(beta_view,0,y,alpha_image->columns,1,exception); r=GetCacheViewAuthenticPixels(sum_view,0,y,alpha_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL) || (r == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) alpha_image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++) { PixelChannel channel = GetPixelChannelChannel(alpha_image,i); PixelTrait traits = GetPixelChannelTraits(alpha_image,channel); PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel); if ((traits == UndefinedPixelTrait) || (beta_traits == UndefinedPixelTrait) || ((beta_traits & UpdatePixelTrait) == 0)) continue; r[i]=ClampToQuantum(attenuate*(p[i]+sign* GetPixelChannel(beta_image,channel,q))); } p+=GetPixelChannels(alpha_image); q+=GetPixelChannels(beta_image); r+=GetPixelChannels(sum_image); } if (SyncCacheViewAuthenticPixels(sum_view,exception) == MagickFalse) status=MagickFalse; } sum_view=DestroyCacheView(sum_view); beta_view=DestroyCacheView(beta_view); alpha_view=DestroyCacheView(alpha_view); if (status == MagickFalse) sum_image=DestroyImage(sum_image); return(sum_image); } static Image *BlendDivergentImage(const Image *alpha_image, const Image *beta_image,ExceptionInfo *exception) { #define FreeDivergentResources() \ { \ if (dy_image != (Image *) NULL) \ dy_image=DestroyImage(dy_image); \ if (dx_image != (Image *) NULL) \ dx_image=DestroyImage(dx_image); \ if (magnitude_beta != (Image *) NULL) \ magnitude_beta=DestroyImage(magnitude_beta); \ if (dy_beta != (Image *) NULL) \ dy_beta=DestroyImage(dy_beta); \ if (dx_beta != (Image *) NULL) \ dx_beta=DestroyImage(dx_beta); \ if (magnitude_alpha != (Image *) NULL) \ magnitude_alpha=DestroyImage(magnitude_alpha); \ if (dy_alpha != (Image *) NULL) \ dy_alpha=DestroyImage(dy_alpha); \ if (dx_alpha != (Image *) NULL) \ dx_alpha=DestroyImage(dx_alpha); \ } Image *divergent_image = (Image *) NULL, *dx_alpha = (Image *) NULL, *dx_beta = (Image *) NULL, *dx_divergent = (Image *) NULL, *dx_image = (Image *) NULL, *dy_alpha = (Image *) NULL, *dy_beta = (Image *) NULL, *dy_divergent = (Image *) NULL, *dy_image = (Image *) NULL, *magnitude_alpha = (Image *) NULL, *magnitude_beta = (Image *) NULL; /* Create X and Y gradient images for alpha image and the magnitude. */ dx_alpha=BlendConvolveImage(alpha_image,"3x1:-0.5,0.0,0.5",exception); if (dx_alpha == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } dy_alpha=BlendConvolveImage(alpha_image,"1x3:-0.5,0.0,0.5",exception); if (dy_alpha == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } magnitude_alpha=BlendMagnitudeImage(dx_alpha,dy_alpha,exception); if (magnitude_alpha == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } /* Create X and Y gradient images for beta and the magnitude. */ dx_beta=BlendConvolveImage(beta_image,"3x1:-0.5,0.0,0.5",exception); if (dx_beta == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } dy_beta=BlendConvolveImage(beta_image,"1x3:-0.5,0.0,0.5",exception); if (dy_beta == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } magnitude_beta=BlendMagnitudeImage(dx_beta,dy_beta,exception); if (magnitude_beta == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } /* Select alpha or beta gradient for larger of two magnitudes. */ dx_image=BlendMaxMagnitudeImage(magnitude_alpha,magnitude_beta,dx_alpha, dx_beta,exception); if (dx_image == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } dy_image=BlendMaxMagnitudeImage(magnitude_alpha,magnitude_beta,dy_alpha, dy_beta,exception); if (dy_image == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } dx_beta=DestroyImage(dx_beta); dx_alpha=DestroyImage(dx_alpha); magnitude_beta=DestroyImage(magnitude_beta); magnitude_alpha=DestroyImage(magnitude_alpha); /* Create divergence of gradients dx and dy and divide by 4 as guide image. */ dx_divergent=BlendConvolveImage(dx_image,"3x1:-0.5,0.0,0.5",exception); if (dx_divergent == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } dy_divergent=BlendConvolveImage(dy_image,"1x3:-0.5,0.0,0.5",exception); if (dy_divergent == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } divergent_image=BlendSumImage(dx_divergent,dy_divergent,0.25,1.0,exception); dy_divergent=DestroyImage(dy_divergent); dx_divergent=DestroyImage(dx_divergent); if (divergent_image == (Image *) NULL) { FreeDivergentResources(); return((Image *) NULL); } FreeDivergentResources(); return(divergent_image); } static MagickBooleanType BlendMaskAlphaChannel(Image *image, const Image *mask_image,ExceptionInfo *exception) { CacheView *image_view, *mask_view; MagickBooleanType status = MagickTrue; ssize_t y; /* Threshold the alpha channel. */ if (SetImageAlpha(image,OpaqueAlpha,exception) == MagickFalse) return(MagickFalse); image_view=AcquireAuthenticCacheView(image,exception); mask_view=AcquireVirtualCacheView(mask_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 Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,image->columns,1,exception); q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { Quantum alpha = GetPixelAlpha(mask_image,p); ssize_t i = GetPixelChannelOffset(image,AlphaPixelChannel); if (fabs((double) alpha) >= MagickEpsilon) q[i]=(Quantum) 0; p+=GetPixelChannels(mask_image); q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); image_view=DestroyCacheView(image_view); return(status); } static Image *BlendMeanImage(Image *image,const Image *mask_image, ExceptionInfo *exception) { CacheView *alpha_view, *mask_view, *mean_view; double mean[MaxPixelChannels]; Image *mean_image; MagickBooleanType status = MagickTrue; ssize_t j, y; /* Compute the mean of the image. */ (void) memset(mean,0,MaxPixelChannels*sizeof(*mean)); alpha_view=AcquireVirtualCacheView(image,exception); for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *magick_restrict p; ssize_t x; p=GetCacheViewVirtualPixels(alpha_view,0,y,image->columns,1, exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; x++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if (traits == UndefinedPixelTrait) continue; mean[i]+=QuantumScale*p[i]; } p+=GetPixelChannels(image); } } alpha_view=DestroyCacheView(alpha_view); if (y < (ssize_t) image->rows) return((Image *) NULL); for (j=0; j < (ssize_t) GetPixelChannels(image); j++) mean[j]=(double) QuantumRange*mean[j]/image->columns/ image->rows; /* Replace any unmasked pixels with the mean pixel. */ mean_image=CloneImage(image,0,0,MagickTrue,exception); if (mean_image == (Image *) NULL) return(mean_image); mask_view=AcquireVirtualCacheView(mask_image,exception); mean_view=AcquireAuthenticCacheView(mean_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(mask_image,mean_image,mean_image->rows,1) #endif for (y=0; y < (ssize_t) mean_image->rows; y++) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(mask_view,0,y,mean_image->columns,1,exception); q=GetCacheViewAuthenticPixels(mean_view,0,y,mean_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) mean_image->columns; x++) { Quantum alpha = GetPixelAlpha(mask_image,p), mask = GetPixelReadMask(mask_image,p); ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(mean_image); i++) { PixelChannel channel = GetPixelChannelChannel(mean_image,i); PixelTrait traits = GetPixelChannelTraits(mean_image,channel); if (traits == UndefinedPixelTrait) continue; if (mask <= (QuantumRange/2)) q[i]=(Quantum) 0; else if (fabs((double) alpha) >= MagickEpsilon) q[i]=ClampToQuantum(mean[i]); } p+=GetPixelChannels(mask_image); q+=GetPixelChannels(mean_image); } if (SyncCacheViewAuthenticPixels(mean_view,exception) == MagickFalse) status=MagickFalse; } mask_view=DestroyCacheView(mask_view); mean_view=DestroyCacheView(mean_view); if (status == MagickFalse) mean_image=DestroyImage(mean_image); return(mean_image); } static MagickBooleanType BlendRMSEResidual(const Image *alpha_image, const Image *beta_image,double *residual,ExceptionInfo *exception) { CacheView *alpha_view, *beta_view; double area = 0.0; MagickBooleanType status = MagickTrue; size_t columns = MagickMax(alpha_image->columns,beta_image->columns), rows = MagickMax(alpha_image->rows,beta_image->rows); ssize_t y; *residual=0.0; alpha_view=AcquireVirtualCacheView(alpha_image,exception); beta_view=AcquireVirtualCacheView(beta_image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(alpha_image,alpha_image,rows,1) #endif for (y=0; y < (ssize_t) rows; y++) { const Quantum *magick_restrict p, *magick_restrict q; double channel_residual; size_t local_area = 0; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(alpha_view,0,y,columns,1,exception); q=GetCacheViewVirtualPixels(beta_view,0,y,columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (const Quantum *) NULL)) { status=MagickFalse; continue; } channel_residual=0.0; for (x=0; x < (ssize_t) columns; x++) { double Da, Sa; ssize_t i; if ((GetPixelReadMask(alpha_image,p) <= (QuantumRange/2)) || (GetPixelReadMask(beta_image,q) <= (QuantumRange/2))) { p+=GetPixelChannels(alpha_image); q+=GetPixelChannels(beta_image); continue; } Sa=QuantumScale*GetPixelAlpha(alpha_image,p); Da=QuantumScale*GetPixelAlpha(beta_image,q); for (i=0; i < (ssize_t) GetPixelChannels(alpha_image); i++) { double distance; PixelChannel channel = GetPixelChannelChannel(alpha_image,i); PixelTrait traits = GetPixelChannelTraits(alpha_image,channel); PixelTrait beta_traits = GetPixelChannelTraits(beta_image,channel); if ((traits == UndefinedPixelTrait) || (beta_traits == UndefinedPixelTrait) || ((beta_traits & UpdatePixelTrait) == 0)) continue; if (channel == AlphaPixelChannel) distance=QuantumScale*(p[i]-GetPixelChannel(beta_image,channel,q)); else distance=QuantumScale*(Sa*p[i]-Da*GetPixelChannel(beta_image,channel, q)); channel_residual+=distance*distance; } local_area++; p+=GetPixelChannels(alpha_image); q+=GetPixelChannels(beta_image); } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlendRMSEResidual) #endif { area+=local_area; *residual+=channel_residual; } } area=PerceptibleReciprocal(area); beta_view=DestroyCacheView(beta_view); alpha_view=DestroyCacheView(alpha_view); *residual=sqrt(*residual*area/(double) GetImageChannels(alpha_image)); return(status); } static void CompositeHCL(const MagickRealType red,const MagickRealType green, const MagickRealType blue,MagickRealType *hue,MagickRealType *chroma, MagickRealType *luma) { MagickRealType b, c, g, h, max, r; /* Convert RGB to HCL colorspace. */ assert(hue != (MagickRealType *) NULL); assert(chroma != (MagickRealType *) NULL); assert(luma != (MagickRealType *) NULL); r=red; g=green; b=blue; max=MagickMax(r,MagickMax(g,b)); c=max-(MagickRealType) MagickMin(r,MagickMin(g,b)); h=0.0; if (c == 0) h=0.0; else if (red == max) h=fmod((g-b)/c+6.0,6.0); else if (green == max) h=((b-r)/c)+2.0; else if (blue == max) h=((r-g)/c)+4.0; *hue=(h/6.0); *chroma=QuantumScale*c; *luma=QuantumScale*(0.298839*r+0.586811*g+0.114350*b); } static MagickBooleanType CompositeOverImage(Image *image, const Image *source_image,const MagickBooleanType clip_to_self, const ssize_t x_offset,const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *image_view, *source_view; const char *value; MagickBooleanType clamp, status; MagickOffsetType progress; ssize_t y; /* Composite image. */ status=MagickTrue; progress=0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); status=MagickTrue; progress=0; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; PixelInfo canvas_pixel, source_pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*(ssize_t) GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, Sa, Sc, Sca; ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); alpha=Sa+Da-Sa*Da; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((source_traits == UndefinedPixelTrait) && (channel != AlphaPixelChannel)) continue; if (channel == AlphaPixelChannel) { /* Set alpha channel. */ pixel=QuantumRange*alpha; q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Sc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; gamma=PerceptibleReciprocal(alpha); pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); return(status); } static void HCLComposite(const MagickRealType hue,const MagickRealType chroma, const MagickRealType luma,MagickRealType *red,MagickRealType *green, MagickRealType *blue) { MagickRealType b, c, g, h, m, r, x; /* Convert HCL to RGB colorspace. */ assert(red != (MagickRealType *) NULL); assert(green != (MagickRealType *) NULL); assert(blue != (MagickRealType *) NULL); h=6.0*hue; c=chroma; x=c*(1.0-fabs(fmod(h,2.0)-1.0)); r=0.0; g=0.0; b=0.0; if ((0.0 <= h) && (h < 1.0)) { r=c; g=x; } else if ((1.0 <= h) && (h < 2.0)) { r=x; g=c; } else if ((2.0 <= h) && (h < 3.0)) { g=c; b=x; } else if ((3.0 <= h) && (h < 4.0)) { g=x; b=c; } else if ((4.0 <= h) && (h < 5.0)) { r=x; b=c; } else if ((5.0 <= h) && (h < 6.0)) { r=c; b=x; } m=luma-(0.298839*r+0.586811*g+0.114350*b); *red=QuantumRange*(r+m); *green=QuantumRange*(g+m); *blue=QuantumRange*(b+m); } static MagickBooleanType SaliencyBlendImage(Image *image, const Image *source_image,const ssize_t x_offset,const ssize_t y_offset, const double iterations,const double residual_threshold,const size_t tick, ExceptionInfo *exception) { Image *crop_image, *divergent_image, *relax_image, *residual_image = (Image *) NULL; KernelInfo *kernel_info; MagickBooleanType status = MagickTrue, verbose = MagickFalse; RectangleInfo crop_info = { source_image->columns, source_image->rows, x_offset, y_offset }; ssize_t i; /* Saliency blend composite operator. */ crop_image=CropImage(image,&crop_info,exception); if (crop_image == (Image *) NULL) return(MagickFalse); (void) SetImageArtifact(crop_image,"compose:clamp","off"); divergent_image=BlendDivergentImage(crop_image,source_image,exception); if (divergent_image == (Image *) NULL) { crop_image=DestroyImage(crop_image); return(MagickFalse); } (void) ResetImagePage(crop_image,"0x0+0+0"); relax_image=BlendMeanImage(crop_image,source_image,exception); if (relax_image == (Image *) NULL) { crop_image=DestroyImage(crop_image); divergent_image=DestroyImage(divergent_image); return(MagickFalse); } status=BlendMaskAlphaChannel(crop_image,source_image,exception); if (status == MagickFalse) { crop_image=DestroyImage(crop_image); divergent_image=DestroyImage(divergent_image); return(MagickFalse); } residual_image=CloneImage(relax_image,0,0,MagickTrue,exception); if (residual_image == (Image *) NULL) { crop_image=DestroyImage(crop_image); relax_image=DestroyImage(relax_image); return(MagickFalse); } /* Convolve relaxed image and blur area of interest. */ kernel_info=AcquireKernelInfo("3x3:0,0.25,0,0.25,0,0.25,0,0.25,0",exception); if (kernel_info == (KernelInfo *) NULL) { crop_image=DestroyImage(crop_image); residual_image=DestroyImage(residual_image); relax_image=DestroyImage(relax_image); return(MagickFalse); } verbose=IsStringTrue(GetImageArtifact(image,"verbose")); if (verbose != MagickFalse) (void) FormatLocaleFile(stderr,"saliency blending:\n"); for (i=0; i < (ssize_t) iterations; i++) { double residual = 1.0; Image *convolve_image, *sum_image; convolve_image=ConvolveImage(relax_image,kernel_info,exception); if (convolve_image == (Image *) NULL) break; relax_image=DestroyImage(relax_image); relax_image=convolve_image; sum_image=BlendSumImage(relax_image,divergent_image,1.0,-1.0,exception); if (sum_image == (Image *) NULL) break; relax_image=DestroyImage(relax_image); relax_image=sum_image; status=CompositeOverImage(relax_image,crop_image,MagickTrue,0,0,exception); if (status == MagickFalse) break; status=BlendRMSEResidual(relax_image,residual_image,&residual,exception); if (status == MagickFalse) break; if ((verbose != MagickFalse) && ((i % MagickMax(tick,1)) == 0)) (void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual); if (residual < residual_threshold) { if (verbose != MagickFalse) (void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual); break; } residual_image=DestroyImage(residual_image); residual_image=CloneImage(relax_image,0,0,MagickTrue,exception); if (residual_image == (Image *) NULL) break; } kernel_info=DestroyKernelInfo(kernel_info); crop_image=DestroyImage(crop_image); divergent_image=DestroyImage(divergent_image); residual_image=DestroyImage(residual_image); /* Composite relaxed over the background image. */ status=CompositeOverImage(image,relax_image,MagickTrue,x_offset,y_offset, exception); relax_image=DestroyImage(relax_image); return(status); } static MagickBooleanType SeamlessBlendImage(Image *image, const Image *source_image,const ssize_t x_offset,const ssize_t y_offset, const double iterations,const double residual_threshold,const size_t tick, ExceptionInfo *exception) { Image *crop_image, *foreground_image, *mean_image, *relax_image, *residual_image, *sum_image; KernelInfo *kernel_info; MagickBooleanType status = MagickTrue, verbose = MagickFalse; RectangleInfo crop_info = { source_image->columns, source_image->rows, x_offset, y_offset }; ssize_t i; /* Seamless blend composite operator. */ crop_image=CropImage(image,&crop_info,exception); if (crop_image == (Image *) NULL) return(MagickFalse); (void) SetImageArtifact(crop_image,"compose:clamp","off"); (void) ResetImagePage(crop_image,"0x0+0+0"); sum_image=BlendSumImage(crop_image,source_image,1.0,-1.0,exception); crop_image=DestroyImage(crop_image); if (sum_image == (Image *) NULL) return(MagickFalse); mean_image=BlendMeanImage(sum_image,source_image,exception); sum_image=DestroyImage(sum_image); if (mean_image == (Image *) NULL) return(MagickFalse); relax_image=CloneImage(mean_image,0,0,MagickTrue,exception); if (relax_image == (Image *) NULL) { mean_image=DestroyImage(mean_image); return(MagickFalse); } status=BlendMaskAlphaChannel(mean_image,source_image,exception); if (status == MagickFalse) { relax_image=DestroyImage(relax_image); mean_image=DestroyImage(mean_image); return(MagickFalse); } residual_image=CloneImage(relax_image,0,0,MagickTrue,exception); if (residual_image == (Image *) NULL) { relax_image=DestroyImage(relax_image); mean_image=DestroyImage(mean_image); return(MagickFalse); } /* Convolve relaxed image and blur area of interest. */ kernel_info=AcquireKernelInfo("3x3:0,0.25,0,0.25,0,0.25,0,0.25,0",exception); if (kernel_info == (KernelInfo *) NULL) { residual_image=DestroyImage(residual_image); relax_image=DestroyImage(relax_image); mean_image=DestroyImage(mean_image); return(MagickFalse); } verbose=IsStringTrue(GetImageArtifact(image,"verbose")); if (verbose != MagickFalse) (void) FormatLocaleFile(stderr,"seamless blending:\n"); for (i=0; i < (ssize_t) iterations; i++) { double residual = 1.0; Image *convolve_image; convolve_image=ConvolveImage(relax_image,kernel_info,exception); if (convolve_image == (Image *) NULL) break; relax_image=DestroyImage(relax_image); relax_image=convolve_image; status=CompositeOverImage(relax_image,mean_image,MagickTrue,0,0,exception); if (status == MagickFalse) break; status=BlendRMSEResidual(relax_image,residual_image,&residual,exception); if (status == MagickFalse) break; if ((verbose != MagickFalse) && ((i % MagickMax(tick,1)) == 0)) (void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual); if (residual < residual_threshold) { if (verbose != MagickFalse) (void) FormatLocaleFile(stderr," %g: %g\n",(double) i,(double) residual); break; } if (residual_image != (Image *) NULL) residual_image=DestroyImage(residual_image); residual_image=CloneImage(relax_image,0,0,MagickTrue,exception); if (residual_image == (Image *) NULL) break; } kernel_info=DestroyKernelInfo(kernel_info); mean_image=DestroyImage(mean_image); residual_image=DestroyImage(residual_image); /* Composite the foreground image over the background image. */ foreground_image=BlendSumImage(source_image,relax_image,1.0,1.0,exception); relax_image=DestroyImage(relax_image); if (foreground_image == (Image *) NULL) return(MagickFalse); (void) SetImageMask(foreground_image,ReadPixelMask,(const Image *) NULL, exception); status=CompositeOverImage(image,foreground_image,MagickTrue,x_offset,y_offset, exception); foreground_image=DestroyImage(foreground_image); return(status); } MagickExport MagickBooleanType CompositeImage(Image *image, const Image *composite,const CompositeOperator compose, const MagickBooleanType clip_to_self,const ssize_t x_offset, const ssize_t y_offset,ExceptionInfo *exception) { #define CompositeImageTag "Composite/Image" CacheView *source_view, *image_view; const char *value; GeometryInfo geometry_info; Image *canvas_image, *source_image; MagickBooleanType clamp, compose_sync, status; MagickOffsetType progress; MagickRealType amount, canvas_dissolve, midpoint, percent_luma, percent_chroma, source_dissolve, threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(composite != (Image *) NULL); assert(composite->signature == MagickCoreSignature); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); source_image=CloneImage(composite,0,0,MagickTrue,exception); if (source_image == (const Image *) NULL) return(MagickFalse); (void) SetImageColorspace(source_image,image->colorspace,exception); if ((compose == OverCompositeOp) || (compose == SrcOverCompositeOp)) { status=CompositeOverImage(image,source_image,clip_to_self,x_offset, y_offset,exception); source_image=DestroyImage(source_image); return(status); } amount=0.5; canvas_image=(Image *) NULL; canvas_dissolve=1.0; clamp=MagickTrue; value=GetImageArtifact(image,"compose:clamp"); if (value != (const char *) NULL) clamp=IsStringTrue(value); compose_sync=MagickTrue; value=GetImageArtifact(image,"compose:sync"); if (value != (const char *) NULL) compose_sync=IsStringTrue(value); SetGeometryInfo(&geometry_info); percent_luma=100.0; percent_chroma=100.0; source_dissolve=1.0; threshold=0.05f; switch (compose) { case CopyCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; if ((source_image->alpha_trait == UndefinedPixelTrait) && (image->alpha_trait != UndefinedPixelTrait)) (void) SetImageAlphaChannel(source_image,OpaqueAlphaChannel,exception); status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *p; Quantum *q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { ssize_t i; if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } for (i=0; i < (ssize_t) GetPixelChannels(source_image); i++) { PixelChannel channel = GetPixelChannelChannel(source_image,i); PixelTrait source_traits = GetPixelChannelTraits(source_image, channel); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((source_traits == UndefinedPixelTrait) || (traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case IntensityCompositeOp: { if ((x_offset < 0) || (y_offset < 0)) break; if ((x_offset+(ssize_t) source_image->columns) > (ssize_t) image->columns) break; if ((y_offset+(ssize_t) source_image->rows) > (ssize_t) image->rows) break; status=MagickTrue; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(source_image,image,source_image->rows,1) #endif for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *p; Quantum *q; ssize_t x; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=GetCacheViewAuthenticPixels(image_view,x_offset,y+y_offset, source_image->columns,1,exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) source_image->columns; x++) { if (GetPixelReadMask(source_image,p) <= (QuantumRange/2)) { p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); continue; } SetPixelAlpha(image,clamp != MagickFalse ? ClampPixel(GetPixelIntensity(source_image,p)) : ClampToQuantum(GetPixelIntensity(source_image,p)),q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(image); } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,CompositeImageTag,(MagickOffsetType) y,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); return(status); } case CopyAlphaCompositeOp: case ChangeMaskCompositeOp: { /* Modify canvas outside the overlaid region and require an alpha channel to exist, to add transparency. */ if (image->alpha_trait == UndefinedPixelTrait) (void) SetImageAlphaChannel(image,OpaqueAlphaChannel,exception); break; } case BlurCompositeOp: { CacheView *canvas_view; double angle_range, angle_start, height, width; PixelInfo pixel; ResampleFilter *resample_filter; SegmentInfo blur; /* Blur Image by resampling dictated by an overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,angle]]. */ canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } /* Gather the maximum blur sigma values from user. */ flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (const char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & WidthValue) == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionWarning, "InvalidSetting","'%s' '%s'","compose:args",value); source_image=DestroyImage(source_image); canvas_image=DestroyImage(canvas_image); return(MagickFalse); } /* Users input sigma now needs to be converted to the EWA ellipse size. The filter defaults to a sigma of 0.5 so to make this match the users input the ellipse size needs to be doubled. */ width=2.0*geometry_info.rho; height=width; if ((flags & HeightValue) != 0) height=2.0*geometry_info.sigma; /* Default the unrotated ellipse width and height axis vectors. */ blur.x1=width; blur.x2=0.0; blur.y1=0.0; blur.y2=height; if ((flags & XValue) != 0 ) { MagickRealType angle; /* Rotate vectors if a rotation angle is given. */ angle=DegreesToRadians(geometry_info.xi); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } angle_start=0.0; angle_range=0.0; if ((flags & YValue) != 0 ) { /* Lets set a angle range and calculate in the loop. */ angle_start=DegreesToRadians(geometry_info.xi); angle_range=DegreesToRadians(geometry_info.psi)-angle_start; } /* Set up a gaussian cylindrical filter for EWA Bluring. As the minimum ellipse radius of support*1.0 the EWA algorithm can only produce a minimum blur of 0.5 for Gaussian (support=2.0) This means that even 'No Blur' will be still a little blurry! The solution (as well as the problem of preventing any user expert filter settings, is to set our own user settings, restore them afterwards. */ resample_filter=AcquireResampleFilter(image,exception); SetResampleFilter(resample_filter,GaussianFilter); /* Perform the variable blurring of each pixel in image. */ GetPixelInfo(image,&pixel); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } if (fabs(angle_range) > MagickEpsilon) { MagickRealType angle; angle=angle_start+angle_range*QuantumScale* GetPixelBlue(source_image,p); blur.x1=width*cos(angle); blur.x2=width*sin(angle); blur.y1=(-height*sin(angle)); blur.y2=height*cos(angle); } ScaleResampleFilter(resample_filter, blur.x1*QuantumScale*GetPixelRed(source_image,p), blur.y1*QuantumScale*GetPixelGreen(source_image,p), blur.x2*QuantumScale*GetPixelRed(source_image,p), blur.y2*QuantumScale*GetPixelGreen(source_image,p) ); (void) ResamplePixelColor(resample_filter,(double) x_offset+x, (double) y_offset+y,&pixel,exception); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } resample_filter=DestroyResampleFilter(resample_filter); source_view=DestroyCacheView(source_view); canvas_view=DestroyCacheView(canvas_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DisplaceCompositeOp: case DistortCompositeOp: { CacheView *canvas_view; MagickRealType horizontal_scale, vertical_scale; PixelInfo pixel; PointInfo center, offset; /* Displace/Distort based on overlay gradient map: X = red_channel; Y = green_channel; compose:args = x_scale[,y_scale[,center.x,center.y]] */ canvas_image=CloneImage(image,0,0,MagickTrue,exception); if (canvas_image == (Image *) NULL) { source_image=DestroyImage(source_image); return(MagickFalse); } SetGeometryInfo(&geometry_info); flags=NoValue; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) flags=ParseGeometry(value,&geometry_info); if ((flags & (WidthValue | HeightValue)) == 0 ) { if ((flags & AspectValue) == 0) { horizontal_scale=(MagickRealType) (source_image->columns-1)/2.0; vertical_scale=(MagickRealType) (source_image->rows-1)/2.0; } else { horizontal_scale=(MagickRealType) (image->columns-1)/2.0; vertical_scale=(MagickRealType) (image->rows-1)/2.0; } } else { horizontal_scale=geometry_info.rho; vertical_scale=geometry_info.sigma; if ((flags & PercentValue) != 0) { if ((flags & AspectValue) == 0) { horizontal_scale*=(source_image->columns-1)/200.0; vertical_scale*=(source_image->rows-1)/200.0; } else { horizontal_scale*=(image->columns-1)/200.0; vertical_scale*=(image->rows-1)/200.0; } } if ((flags & HeightValue) == 0) vertical_scale=horizontal_scale; } /* Determine fixed center point for absolute distortion map Absolute distort == Displace offset relative to a fixed absolute point Select that point according to +X+Y user inputs. default = center of overlay image arg flag '!' = locations/percentage relative to background image */ center.x=(MagickRealType) x_offset; center.y=(MagickRealType) y_offset; if (compose == DistortCompositeOp) { if ((flags & XValue) == 0) if ((flags & AspectValue) != 0) center.x=(MagickRealType) ((image->columns-1)/2.0); else center.x=(MagickRealType) (x_offset+(source_image->columns-1)/ 2.0); else if ((flags & AspectValue) != 0) center.x=geometry_info.xi; else center.x=(MagickRealType) (x_offset+geometry_info.xi); if ((flags & YValue) == 0) if ((flags & AspectValue) != 0) center.y=(MagickRealType) ((image->rows-1)/2.0); else center.y=(MagickRealType) (y_offset+(source_image->rows-1)/2.0); else if ((flags & AspectValue) != 0) center.y=geometry_info.psi; else center.y=(MagickRealType) (y_offset+geometry_info.psi); } /* Shift the pixel offset point as defined by the provided, displacement/distortion map. -- Like a lens... */ GetPixelInfo(image,&pixel); image_view=AcquireVirtualCacheView(image,exception); source_view=AcquireVirtualCacheView(source_image,exception); canvas_view=AcquireAuthenticCacheView(canvas_image,exception); for (y=0; y < (ssize_t) source_image->rows; y++) { MagickBooleanType sync; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (((y+y_offset) < 0) || ((y+y_offset) >= (ssize_t) image->rows)) continue; p=GetCacheViewVirtualPixels(source_view,0,y,source_image->columns,1, exception); q=QueueCacheViewAuthenticPixels(canvas_view,0,y,canvas_image->columns,1, exception); if ((p == (const Quantum *) NULL) || (q == (Quantum *) NULL)) break; for (x=0; x < (ssize_t) source_image->columns; x++) { if (((x_offset+x) < 0) || ((x_offset+x) >= (ssize_t) image->columns)) { p+=GetPixelChannels(source_image); continue; } /* Displace the offset. */ offset.x=(double) (horizontal_scale*(GetPixelRed(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.x+((compose == DisplaceCompositeOp) ? x : 0); offset.y=(double) (vertical_scale*(GetPixelGreen(source_image,p)- (((MagickRealType) QuantumRange+1.0)/2.0)))/(((MagickRealType) QuantumRange+1.0)/2.0)+center.y+((compose == DisplaceCompositeOp) ? y : 0); status=InterpolatePixelInfo(image,image_view, UndefinedInterpolatePixel,(double) offset.x,(double) offset.y, &pixel,exception); if (status == MagickFalse) break; /* Mask with the 'invalid pixel mask' in alpha channel. */ pixel.alpha=(MagickRealType) QuantumRange*(QuantumScale*pixel.alpha)* (QuantumScale*GetPixelAlpha(source_image,p)); SetPixelViaPixelInfo(canvas_image,&pixel,q); p+=GetPixelChannels(source_image); q+=GetPixelChannels(canvas_image); } if (x < (ssize_t) source_image->columns) break; sync=SyncCacheViewAuthenticPixels(canvas_view,exception); if (sync == MagickFalse) break; } canvas_view=DestroyCacheView(canvas_view); source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); source_image=DestroyImage(source_image); source_image=canvas_image; break; } case DissolveCompositeOp: { /* Geometry arguments to dissolve factors. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0; if ((source_dissolve-MagickEpsilon) < 0.0) source_dissolve=0.0; if ((source_dissolve+MagickEpsilon) > 1.0) { canvas_dissolve=2.0-source_dissolve; source_dissolve=1.0; } if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; if ((canvas_dissolve-MagickEpsilon) < 0.0) canvas_dissolve=0.0; } break; } case BlendCompositeOp: { value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); source_dissolve=geometry_info.rho/100.0; canvas_dissolve=1.0-source_dissolve; if ((flags & SigmaValue) != 0) canvas_dissolve=geometry_info.sigma/100.0; } break; } case SaliencyBlendCompositeOp: { double residual_threshold = 0.0002, iterations = 400.0; size_t tick = 100; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); iterations=geometry_info.rho; if ((flags & SigmaValue) != 0) residual_threshold=geometry_info.sigma; if ((flags & XiValue) != 0) tick=(size_t) geometry_info.xi; } status=SaliencyBlendImage(image,composite,x_offset,y_offset,iterations, residual_threshold,tick,exception); source_image=DestroyImage(source_image); return(status); } case SeamlessBlendCompositeOp: { double residual_threshold = 0.0002, iterations = 400.0; size_t tick = 100; value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); iterations=geometry_info.rho; if ((flags & SigmaValue) != 0) residual_threshold=geometry_info.sigma; if ((flags & XiValue) != 0) tick=(size_t) geometry_info.xi; } status=SeamlessBlendImage(image,composite,x_offset,y_offset,iterations, residual_threshold,tick,exception); source_image=DestroyImage(source_image); return(status); } case MathematicsCompositeOp: { /* Just collect the values from "compose:args", setting. Unused values are set to zero automagically. Arguments are normally a comma separated list, so this probably should be changed to some 'general comma list' parser, (with a minimum number of values) */ SetGeometryInfo(&geometry_info); value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); if (flags == NoValue) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidGeometry","`%s'",value); } break; } case ModulateCompositeOp: { /* Determine the luma and chroma scale. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); percent_luma=geometry_info.rho; if ((flags & SigmaValue) != 0) percent_chroma=geometry_info.sigma; } break; } case ThresholdCompositeOp: { /* Determine the amount and threshold. */ value=GetImageArtifact(image,"compose:args"); if (value != (char *) NULL) { flags=ParseGeometry(value,&geometry_info); amount=geometry_info.rho; threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold=0.05f; } threshold*=QuantumRange; break; } default: break; } /* Composite image. */ status=MagickTrue; progress=0; midpoint=((MagickRealType) QuantumRange+1.0)/2; source_view=AcquireVirtualCacheView(source_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(source_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { const Quantum *pixels; MagickRealType blue, chroma, green, hue, luma, red; PixelInfo canvas_pixel, source_pixel; const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; if (clip_to_self != MagickFalse) { if (y < y_offset) continue; if ((y-y_offset) >= (ssize_t) source_image->rows) continue; } /* If pixels is NULL, y is outside overlay region. */ pixels=(Quantum *) NULL; p=(Quantum *) NULL; if ((y >= y_offset) && ((y-y_offset) < (ssize_t) source_image->rows)) { p=GetCacheViewVirtualPixels(source_view,0,y-y_offset, source_image->columns,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; continue; } pixels=p; if (x_offset < 0) p-=x_offset*(ssize_t) GetPixelChannels(source_image); } q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } hue=0.0; chroma=0.0; luma=0.0; GetPixelInfo(image,&canvas_pixel); GetPixelInfo(source_image,&source_pixel); for (x=0; x < (ssize_t) image->columns; x++) { double gamma; MagickRealType alpha, Da, Dc, Dca, DcaDa, Sa, SaSca, Sc, Sca; ssize_t i; size_t channels; if (clip_to_self != MagickFalse) { if (x < x_offset) { q+=GetPixelChannels(image); continue; } if ((x-x_offset) >= (ssize_t) source_image->columns) break; } if ((pixels == (Quantum *) NULL) || (x < x_offset) || ((x-x_offset) >= (ssize_t) source_image->columns)) { Quantum source[MaxPixelChannels]; /* Virtual composite: Sc: source color. Dc: canvas color. */ (void) GetOneVirtualPixel(source_image,x-x_offset,y-y_offset,source, exception); for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits=GetPixelChannelTraits(source_image, channel); if ((traits == UndefinedPixelTrait) || (source_traits == UndefinedPixelTrait)) continue; switch (compose) { case AlphaCompositeOp: case ChangeMaskCompositeOp: case CopyAlphaCompositeOp: case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case OutCompositeOp: case SrcInCompositeOp: case SrcOutCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=(MagickRealType) q[i]; break; } case ClearCompositeOp: case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { if (channel == AlphaPixelChannel) pixel=(MagickRealType) TransparentAlpha; else pixel=0.0; break; } case BlendCompositeOp: case DissolveCompositeOp: { if (channel == AlphaPixelChannel) pixel=canvas_dissolve*GetPixelAlpha(source_image,source); else pixel=(MagickRealType) source[channel]; break; } default: { pixel=(MagickRealType) source[channel]; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } q+=GetPixelChannels(image); continue; } /* Authentic composite: Sa: normalized source alpha. Da: normalized canvas alpha. */ Sa=QuantumScale*GetPixelAlpha(source_image,p); Da=QuantumScale*GetPixelAlpha(image,q); switch (compose) { case BumpmapCompositeOp: case ColorBurnCompositeOp: case ColorDodgeCompositeOp: case DarkenCompositeOp: case DifferenceCompositeOp: case DivideDstCompositeOp: case DivideSrcCompositeOp: case ExclusionCompositeOp: case FreezeCompositeOp: case HardLightCompositeOp: case HardMixCompositeOp: case InterpolateCompositeOp: case LightenCompositeOp: case LinearBurnCompositeOp: case LinearDodgeCompositeOp: case LinearLightCompositeOp: case MathematicsCompositeOp: case MinusDstCompositeOp: case MinusSrcCompositeOp: case MultiplyCompositeOp: case NegateCompositeOp: case OverlayCompositeOp: case PegtopLightCompositeOp: case PinLightCompositeOp: case ReflectCompositeOp: case ScreenCompositeOp: case SoftBurnCompositeOp: case SoftDodgeCompositeOp: case SoftLightCompositeOp: case StampCompositeOp: case VividLightCompositeOp: { alpha=RoundToUnity(Sa+Da-Sa*Da); break; } case DstAtopCompositeOp: case DstInCompositeOp: case InCompositeOp: case SrcInCompositeOp: { alpha=Sa*Da; break; } case DissolveCompositeOp: { alpha=source_dissolve*Sa*(-canvas_dissolve*Da)+source_dissolve*Sa+ canvas_dissolve*Da; break; } case DstOverCompositeOp: case OverCompositeOp: case SrcOverCompositeOp: { alpha=Sa+Da-Sa*Da; break; } case DstOutCompositeOp: { alpha=Da*(1.0-Sa); break; } case OutCompositeOp: case SrcOutCompositeOp: { alpha=Sa*(1.0-Da); break; } case BlendCompositeOp: case PlusCompositeOp: { alpha=RoundToUnity(source_dissolve*Sa+canvas_dissolve*Da); break; } case XorCompositeOp: { alpha=Sa+Da-2.0*Sa*Da; break; } case ModulusAddCompositeOp: { if ((Sa+Da) <= 1.0) { alpha=(Sa+Da); break; } alpha=((Sa+Da)-1.0); break; } case ModulusSubtractCompositeOp: { if ((Sa-Da) >= 0.0) { alpha=(Sa-Da); break; } alpha=((Sa-Da)+1.0); break; } default: { alpha=1.0; break; } } switch (compose) { case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case ModulateCompositeOp: case RMSECompositeOp: case SaturateCompositeOp: { GetPixelInfoPixel(source_image,p,&source_pixel); GetPixelInfoPixel(image,q,&canvas_pixel); break; } default: break; } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { MagickRealType pixel, sans; PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait source_traits = GetPixelChannelTraits(source_image,channel); if (traits == UndefinedPixelTrait) continue; if ((channel == AlphaPixelChannel) && ((traits & UpdatePixelTrait) != 0)) { /* Set alpha channel. */ switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case CopyBlackCompositeOp: case CopyBlueCompositeOp: case CopyCyanCompositeOp: case CopyGreenCompositeOp: case CopyMagentaCompositeOp: case CopyRedCompositeOp: case CopyYellowCompositeOp: case SrcAtopCompositeOp: case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Da; break; } case BumpmapCompositeOp: { pixel=GetPixelIntensity(source_image,p)*Da; break; } case ChangeMaskCompositeOp: { if (IsFuzzyEquivalencePixel(source_image,p,image,q) != MagickFalse) pixel=(MagickRealType) TransparentAlpha; else pixel=QuantumRange*Da; break; } case ClearCompositeOp: { pixel=(MagickRealType) TransparentAlpha; break; } case ColorizeCompositeOp: case HueCompositeOp: case LuminizeCompositeOp: case RMSECompositeOp: case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Da; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=QuantumRange*Sa; break; } if (Sa < Da) { pixel=QuantumRange*Da; break; } pixel=QuantumRange*Sa; break; } case CopyAlphaCompositeOp: { if (source_image->alpha_trait == UndefinedPixelTrait) pixel=GetPixelIntensity(source_image,p); else pixel=QuantumRange*Sa; break; } case BlurCompositeOp: case CopyCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: case DstAtopCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sa; break; } case DarkenIntensityCompositeOp: { if (compose_sync == MagickFalse) { pixel=GetPixelIntensity(source_image,p) < GetPixelIntensity(image,q) ? Sa : Da; break; } pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case DifferenceCompositeOp: { pixel=QuantumRange*fabs((double) (Sa-Da)); break; } case FreezeCompositeOp: { pixel=QuantumRange*(1.0-(1.0-Sa)*(1.0-Sa)* PerceptibleReciprocal(Da)); if (pixel < 0.0) pixel=0.0; break; } case InterpolateCompositeOp: { pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sa)-0.25* cos(MagickPI*Da)); break; } case LightenIntensityCompositeOp: { if (compose_sync == MagickFalse) { pixel=GetPixelIntensity(source_image,p) > GetPixelIntensity(image,q) ? Sa : Da; break; } pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sa : Da; break; } case ModulateCompositeOp: { pixel=QuantumRange*Da; break; } case MultiplyCompositeOp: { if (compose_sync == MagickFalse) { pixel=QuantumRange*Sa*Da; break; } pixel=QuantumRange*alpha; break; } case NegateCompositeOp: { pixel=QuantumRange*((1.0-Sa-Da)); break; } case ReflectCompositeOp: { pixel=QuantumRange*(Sa*Sa*PerceptibleReciprocal(1.0-Da)); if (pixel > QuantumRange) pixel=QuantumRange; break; } case StampCompositeOp: { pixel=QuantumRange*(Sa+Da*Da-1.0); break; } case StereoCompositeOp: { pixel=QuantumRange*(Sa+Da)/2; break; } default: { pixel=QuantumRange*alpha; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); continue; } if (source_traits == UndefinedPixelTrait) continue; /* Sc: source color. Dc: canvas color. */ Sc=(MagickRealType) GetPixelChannel(source_image,channel,p); Dc=(MagickRealType) q[i]; if ((traits & CopyPixelTrait) != 0) { /* Copy channel. */ q[i]=ClampToQuantum(Dc); continue; } /* Porter-Duff compositions: Sca: source normalized color multiplied by alpha. Dca: normalized canvas color multiplied by alpha. */ Sca=QuantumScale*Sa*Sc; Dca=QuantumScale*Da*Dc; SaSca=Sa*PerceptibleReciprocal(Sca); DcaDa=Dca*PerceptibleReciprocal(Da); switch (compose) { case DarkenCompositeOp: case LightenCompositeOp: case ModulusSubtractCompositeOp: { gamma=PerceptibleReciprocal(1.0-alpha); break; } default: { gamma=PerceptibleReciprocal(alpha); break; } } pixel=Dc; switch (compose) { case AlphaCompositeOp: { pixel=QuantumRange*Sa; break; } case AtopCompositeOp: case SrcAtopCompositeOp: { pixel=QuantumRange*(Sca*Da+Dca*(1.0-Sa)); break; } case BlendCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc+canvas_dissolve*Da*Dc); break; } case CopyCompositeOp: case ReplaceCompositeOp: case SrcCompositeOp: { pixel=QuantumRange*Sca; break; } case BlurCompositeOp: case DisplaceCompositeOp: case DistortCompositeOp: { pixel=Sc; break; } case BumpmapCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } pixel=QuantumScale*GetPixelIntensity(source_image,p)*Dc; break; } case ChangeMaskCompositeOp: { pixel=Dc; break; } case ClearCompositeOp: { pixel=0.0; break; } case ColorBurnCompositeOp: { if ((Sca == 0.0) && (Dca == Da)) { pixel=QuantumRange*gamma*(Sa*Da+Dca*(1.0-Sa)); break; } if (Sca == 0.0) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-Sa*Da*MagickMin(1.0,(1.0-DcaDa)* SaSca)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorDodgeCompositeOp: { if ((Sca*Da+Dca*Sa) >= Sa*Da) pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); else pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(Sa-Sca)+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case ColorizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &sans,&sans,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case CopyAlphaCompositeOp: { pixel=Dc; break; } case CopyBlackCompositeOp: { if (channel == BlackPixelChannel) pixel=(MagickRealType) GetPixelBlack(source_image,p); break; } case CopyBlueCompositeOp: case CopyYellowCompositeOp: { if (channel == BluePixelChannel) pixel=(MagickRealType) GetPixelBlue(source_image,p); break; } case CopyGreenCompositeOp: case CopyMagentaCompositeOp: { if (channel == GreenPixelChannel) pixel=(MagickRealType) GetPixelGreen(source_image,p); break; } case CopyRedCompositeOp: case CopyCyanCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case DarkenCompositeOp: { /* Darken is equivalent to a 'Minimum' method OR a greyscale version of a binary 'Or' OR the 'Intersection' of pixel sets. */ if (compose_sync == MagickFalse) { pixel=MagickMin(Sc,Dc); break; } if ((Sca*Da) < (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case DarkenIntensityCompositeOp: { if (compose_sync == MagickFalse) { pixel=GetPixelIntensity(source_image,p) < GetPixelIntensity(image,q) ? Sc : Dc; break; } pixel=Sa*GetPixelIntensity(source_image,p) < Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case DifferenceCompositeOp: { if (compose_sync == MagickFalse) { pixel=fabs((double) Sc-Dc); break; } pixel=QuantumRange*gamma*(Sca+Dca-2.0*MagickMin(Sca*Da,Dca*Sa)); break; } case DissolveCompositeOp: { pixel=gamma*(source_dissolve*Sa*Sc-source_dissolve*Sa* canvas_dissolve*Da*Dc+canvas_dissolve*Da*Dc); break; } case DivideDstCompositeOp: { if (compose_sync == MagickFalse) { pixel=QuantumRange*(Sc/PerceptibleReciprocal(Dc)); break; } if ((fabs((double) Sca) < MagickEpsilon) && (fabs((double) Dca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (fabs((double) Dca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*Da*Da/Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case DivideSrcCompositeOp: { if (compose_sync == MagickFalse) { pixel=QuantumRange*(Dc/PerceptibleReciprocal(Sc)); break; } if ((fabs((double) Dca) < MagickEpsilon) && (fabs((double) Sca) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } if (fabs((double) Sca) < MagickEpsilon) { pixel=QuantumRange*gamma*(Da*Sa+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } pixel=QuantumRange*gamma*(Dca*Sa*SaSca+Dca*(1.0-Sa)+Sca*(1.0-Da)); break; } case DstAtopCompositeOp: { pixel=QuantumRange*(Dca*Sa+Sca*(1.0-Da)); break; } case DstCompositeOp: case NoCompositeOp: { pixel=QuantumRange*Dca; break; } case DstInCompositeOp: { pixel=QuantumRange*gamma*(Dca*Sa); break; } case DstOutCompositeOp: { pixel=QuantumRange*gamma*(Dca*(1.0-Sa)); break; } case DstOverCompositeOp: { pixel=QuantumRange*gamma*(Dca+Sca*(1.0-Da)); break; } case ExclusionCompositeOp: { pixel=QuantumRange*gamma*(Sca*Da+Dca*Sa-2.0*Sca*Dca+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case FreezeCompositeOp: { pixel=QuantumRange*gamma*(1.0-(1.0-Sca)*(1.0-Sca)* PerceptibleReciprocal(Dca)); if (pixel < 0.0) pixel=0.0; break; } case HardLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(2.0*Sca*Dca+Sca*(1.0-Da)+Dca*(1.0- Sa)); break; } pixel=QuantumRange*gamma*(Sa*Da-2.0*(Da-Dca)*(Sa-Sca)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } case HardMixCompositeOp: { pixel=gamma*(((Sca+Dca) < 1.0) ? 0.0 : QuantumRange); break; } case HueCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &hue,&sans,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case InCompositeOp: case SrcInCompositeOp: { pixel=QuantumRange*(Sca*Da); break; } case InterpolateCompositeOp: { pixel=QuantumRange*(0.5-0.25*cos(MagickPI*Sca)-0.25* cos(MagickPI*Dca)); break; } case LinearBurnCompositeOp: { /* LinearBurn: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Sc + Dc - 1 */ pixel=QuantumRange*gamma*(Sca+Dca-Sa*Da); break; } case LinearDodgeCompositeOp: { pixel=gamma*(Sa*Sc+Da*Dc); break; } case LinearLightCompositeOp: { /* LinearLight: as defined by Abode Photoshop, according to http://www.simplefilter.de/en/basics/mixmods.html is: f(Sc,Dc) = Dc + 2*Sc - 1 */ pixel=QuantumRange*gamma*((Sca-Sa)*Da+Sca+Dca); break; } case LightenCompositeOp: { if (compose_sync == MagickFalse) { pixel=MagickMax(Sc,Dc); break; } if ((Sca*Da) > (Dca*Sa)) { pixel=QuantumRange*(Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*(Dca+Sca*(1.0-Da)); break; } case LightenIntensityCompositeOp: { /* Lighten is equivalent to a 'Maximum' method OR a greyscale version of a binary 'And' OR the 'Union' of pixel sets. */ if (compose_sync == MagickFalse) { pixel=GetPixelIntensity(source_image,p) > GetPixelIntensity(image,q) ? Sc : Dc; break; } pixel=Sa*GetPixelIntensity(source_image,p) > Da*GetPixelIntensity(image,q) ? Sc : Dc; break; } case LuminizeCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&sans,&luma); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case MathematicsCompositeOp: { /* 'Mathematics' a free form user control mathematical composition is defined as... f(Sc,Dc) = A*Sc*Dc + B*Sc + C*Dc + D Where the arguments A,B,C,D are (currently) passed to composite as a command separated 'geometry' string in "compose:args" image artifact. A = a->rho, B = a->sigma, C = a->xi, D = a->psi Applying the SVG transparency formula (see above), we get... Dca' = Sa*Da*f(Sc,Dc) + Sca*(1.0-Da) + Dca*(1.0-Sa) Dca' = A*Sca*Dca + B*Sca*Da + C*Dca*Sa + D*Sa*Da + Sca*(1.0-Da) + Dca*(1.0-Sa) */ if (compose_sync == MagickFalse) { pixel=geometry_info.rho*Sc*Dc+geometry_info.sigma*Sc+ geometry_info.xi*Dc+geometry_info.psi; break; } pixel=QuantumRange*gamma*(geometry_info.rho*Sca*Dca+ geometry_info.sigma*Sca*Da+geometry_info.xi*Dca*Sa+ geometry_info.psi*Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case MinusDstCompositeOp: { if (compose_sync == MagickFalse) { pixel=Dc-Sc; break; } pixel=gamma*(Sa*Sc+Da*Dc-2.0*Da*Dc*Sa); break; } case MinusSrcCompositeOp: { /* Minus source from canvas. f(Sc,Dc) = Sc - Dc */ if (compose_sync == MagickFalse) { pixel=Sc-Dc; break; } pixel=gamma*(Da*Dc+Sa*Sc-2.0*Sa*Sc*Da); break; } case ModulateCompositeOp: { ssize_t offset; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } offset=(ssize_t) (GetPixelIntensity(source_image,p)-midpoint); if (offset == 0) { pixel=Dc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); luma+=(0.01*percent_luma*offset)/midpoint; chroma*=0.01*percent_chroma; HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ModulusAddCompositeOp: { if (compose_sync == MagickFalse) { pixel=(Sc+Dc); break; } if ((Sca+Dca) <= 1.0) { pixel=QuantumRange*(Sca+Dca); break; } pixel=QuantumRange*((Sca+Dca)-1.0); break; } case ModulusSubtractCompositeOp: { if (compose_sync == MagickFalse) { pixel=(Sc-Dc); break; } if ((Sca-Dca) >= 0.0) { pixel=QuantumRange*(Sca-Dca); break; } pixel=QuantumRange*((Sca-Dca)+1.0); break; } case MultiplyCompositeOp: { if (compose_sync == MagickFalse) { pixel=QuantumScale*Dc*Sc; break; } pixel=QuantumRange*gamma*(Sca*Dca+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case NegateCompositeOp: { pixel=QuantumRange*(1.0-fabs(1.0-Sca-Dca)); break; } case OutCompositeOp: case SrcOutCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)); break; } case OverCompositeOp: case SrcOverCompositeOp: { pixel=QuantumRange*gamma*(Sca+Dca*(1.0-Sa)); break; } case OverlayCompositeOp: { if ((2.0*Dca) < Da) { pixel=QuantumRange*gamma*(2.0*Dca*Sca+Dca*(1.0-Sa)+Sca*(1.0- Da)); break; } pixel=QuantumRange*gamma*(Da*Sa-2.0*(Sa-Sca)*(Da-Dca)+Dca*(1.0-Sa)+ Sca*(1.0-Da)); break; } case PegtopLightCompositeOp: { /* PegTop: A Soft-Light alternative: A continuous version of the Softlight function, producing very similar results. f(Sc,Dc) = Dc^2*(1-2*Sc) + 2*Sc*Dc http://www.pegtop.net/delphi/articles/blendmodes/softlight.htm. */ if (fabs((double) Da) < MagickEpsilon) { pixel=QuantumRange*gamma*Sca; break; } pixel=QuantumRange*gamma*(Dca*Dca*(Sa-2.0*Sca)/Da+Sca*(2.0*Dca+1.0- Da)+Dca*(1.0-Sa)); break; } case PinLightCompositeOp: { /* PinLight: A Photoshop 7 composition method http://www.simplefilter.de/en/basics/mixmods.html f(Sc,Dc) = Dc<2*Sc-1 ? 2*Sc-1 : Dc>2*Sc ? 2*Sc : Dc */ if ((Dca*Sa) < (Da*(2.0*Sca-Sa))) { pixel=QuantumRange*gamma*(Sca*(Da+1.0)-Sa*Da+Dca*(1.0-Sa)); break; } if ((Dca*Sa) > (2.0*Sca*Da)) { pixel=QuantumRange*gamma*(Sca*Da+Sca+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Sca*(1.0-Da)+Dca); break; } case PlusCompositeOp: { if (compose_sync == MagickFalse) { pixel=(Dc+Sc); break; } pixel=QuantumRange*(Sca+Dca); break; } case ReflectCompositeOp: { pixel=QuantumRange*gamma*(Sca*Sca*PerceptibleReciprocal(1.0-Dca)); if (pixel > QuantumRange) pixel=QuantumRange; break; } case RMSECompositeOp: { double gray; if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } gray=sqrt( (canvas_pixel.red-source_pixel.red)* (canvas_pixel.red-source_pixel.red)+ (canvas_pixel.green-source_pixel.green)* (canvas_pixel.green-source_pixel.green)+ (canvas_pixel.blue-source_pixel.blue)* (canvas_pixel.blue-source_pixel.blue)/3.0); switch (channel) { case RedPixelChannel: pixel=gray; break; case GreenPixelChannel: pixel=gray; break; case BluePixelChannel: pixel=gray; break; default: pixel=Dc; break; } break; } case SaturateCompositeOp: { if (fabs((double) (QuantumRange*Sa-TransparentAlpha)) < MagickEpsilon) { pixel=Dc; break; } if (fabs((double) (QuantumRange*Da-TransparentAlpha)) < MagickEpsilon) { pixel=Sc; break; } CompositeHCL(canvas_pixel.red,canvas_pixel.green,canvas_pixel.blue, &hue,&chroma,&luma); CompositeHCL(source_pixel.red,source_pixel.green,source_pixel.blue, &sans,&chroma,&sans); HCLComposite(hue,chroma,luma,&red,&green,&blue); switch (channel) { case RedPixelChannel: pixel=red; break; case GreenPixelChannel: pixel=green; break; case BluePixelChannel: pixel=blue; break; default: pixel=Dc; break; } break; } case ScreenCompositeOp: { /* Screen: a negated multiply: f(Sc,Dc) = 1.0-(1.0-Sc)*(1.0-Dc) */ if (compose_sync == MagickFalse) { pixel=Sc+Dc-Sc*Dc; break; } pixel=QuantumRange*gamma*(Sca+Dca-Sca*Dca); break; } case SoftBurnCompositeOp: { if ((Sca+Dca) < 1.0) pixel=QuantumRange*gamma*(0.5*Dca*PerceptibleReciprocal(1.0-Sca)); else pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Sca)* PerceptibleReciprocal(Dca)); break; } case SoftDodgeCompositeOp: { if ((Sca+Dca) < 1.0) pixel=QuantumRange*gamma*(0.5*Sca*PerceptibleReciprocal(1.0-Dca)); else pixel=QuantumRange*gamma*(1.0-0.5*(1.0-Dca)* PerceptibleReciprocal(Sca)); break; } case SoftLightCompositeOp: { if ((2.0*Sca) < Sa) { pixel=QuantumRange*gamma*(Dca*(Sa+(2.0*Sca-Sa)*(1.0-DcaDa))+ Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if (((2.0*Sca) > Sa) && ((4.0*Dca) <= Da)) { pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(4.0*DcaDa* (4.0*DcaDa+1.0)*(DcaDa-1.0)+7.0*DcaDa)+Sca*(1.0-Da)+ Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa+Da*(2.0*Sca-Sa)*(pow(DcaDa,0.5)- DcaDa)+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case StampCompositeOp: { pixel=QuantumRange*(Sca+Dca*Dca-1.0); break; } case StereoCompositeOp: { if (channel == RedPixelChannel) pixel=(MagickRealType) GetPixelRed(source_image,p); break; } case ThresholdCompositeOp: { MagickRealType delta; delta=Sc-Dc; if ((MagickRealType) fabs((double) (2.0*delta)) < threshold) { pixel=gamma*Dc; break; } pixel=gamma*(Dc+delta*amount); break; } case VividLightCompositeOp: { /* VividLight: A Photoshop 7 composition method. See http://www.simplefilter.de/en/basics/mixmods.html. f(Sc,Dc) = (2*Sc < 1) ? 1-(1-Dc)/(2*Sc) : Dc/(2*(1-Sc)) */ if ((fabs((double) Sa) < MagickEpsilon) || (fabs((double) (Sca-Sa)) < MagickEpsilon)) { pixel=QuantumRange*gamma*(Sa*Da+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } if ((2.0*Sca) <= Sa) { pixel=QuantumRange*gamma*(Sa*(Da+Sa*(Dca-Da)* PerceptibleReciprocal(2.0*Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } pixel=QuantumRange*gamma*(Dca*Sa*Sa*PerceptibleReciprocal(2.0* (Sa-Sca))+Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } case XorCompositeOp: { pixel=QuantumRange*(Sca*(1.0-Da)+Dca*(1.0-Sa)); break; } default: { pixel=Sc; break; } } q[i]=clamp != MagickFalse ? ClampPixel(pixel) : ClampToQuantum(pixel); } p+=GetPixelChannels(source_image); channels=GetPixelChannels(source_image); if (p >= (pixels+channels*source_image->columns)) p=pixels; 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,CompositeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } source_view=DestroyCacheView(source_view); image_view=DestroyCacheView(image_view); if (canvas_image != (Image * ) NULL) canvas_image=DestroyImage(canvas_image); else source_image=DestroyImage(source_image); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T e x t u r e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TextureImage() repeatedly tiles the texture image across and down the image % canvas. % % The format of the TextureImage method is: % % MagickBooleanType TextureImage(Image *image,const Image *texture, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o texture_image: This image is the texture to layer on the background. % */ MagickExport MagickBooleanType TextureImage(Image *image,const Image *texture, ExceptionInfo *exception) { #define TextureImageTag "Texture/Image" CacheView *image_view, *texture_view; Image *texture_image; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"..."); assert(image->signature == MagickCoreSignature); if (texture == (const Image *) NULL) return(MagickFalse); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); texture_image=CloneImage(texture,0,0,MagickTrue,exception); if (texture_image == (const Image *) NULL) return(MagickFalse); (void) TransformImageColorspace(texture_image,image->colorspace,exception); (void) SetImageVirtualPixelMethod(texture_image,TileVirtualPixelMethod, exception); status=MagickTrue; if ((image->compose != CopyCompositeOp) && ((image->compose != OverCompositeOp) || (image->alpha_trait != UndefinedPixelTrait) || (texture_image->alpha_trait != UndefinedPixelTrait))) { /* Tile texture onto the image background. */ for (y=0; y < (ssize_t) image->rows; y+=(ssize_t) texture_image->rows) { ssize_t x; if (status == MagickFalse) continue; for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { MagickBooleanType thread_status; thread_status=CompositeImage(image,texture_image,image->compose, MagickTrue,x+texture_image->tile_offset.x,y+ texture_image->tile_offset.y,exception); if (thread_status == MagickFalse) { status=thread_status; break; } } if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } (void) SetImageProgress(image,TextureImageTag,(MagickOffsetType) image->rows,image->rows); texture_image=DestroyImage(texture_image); return(status); } /* Tile texture onto the image background (optimized). */ status=MagickTrue; texture_view=AcquireVirtualCacheView(texture_image,exception); image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(texture_image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; const Quantum *p, *pixels; ssize_t x; Quantum *q; size_t width; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(texture_view,texture_image->tile_offset.x, (y+texture_image->tile_offset.y) % texture_image->rows, texture_image->columns,1,exception); q=QueueCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if ((pixels == (const Quantum *) NULL) || (q == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x+=(ssize_t) texture_image->columns) { ssize_t j; p=pixels; width=texture_image->columns; if ((x+(ssize_t) width) > (ssize_t) image->columns) width=image->columns-x; for (j=0; j < (ssize_t) width; j++) { ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(texture_image); i++) { PixelChannel channel = GetPixelChannelChannel(texture_image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); PixelTrait texture_traits=GetPixelChannelTraits(texture_image, channel); if ((traits == UndefinedPixelTrait) || (texture_traits == UndefinedPixelTrait)) continue; SetPixelChannel(image,channel,p[i],q); } p+=GetPixelChannels(texture_image); q+=GetPixelChannels(image); } } sync=SyncCacheViewAuthenticPixels(image_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; proceed=SetImageProgress(image,TextureImageTag,(MagickOffsetType) y, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } texture_view=DestroyCacheView(texture_view); image_view=DestroyCacheView(image_view); texture_image=DestroyImage(texture_image); return(status); }
SymbolicDerivatives.h
#ifndef _SymbolicDerivatives_H_ #define _SymbolicDerivatives_H_ using namespace std; #ifdef _OPENMP #include <omp.h> #endif #define WITH_MMVII false #define WITH_EIGEN false #if WITH_EIGEN #include "ExternalInclude/Eigen/Dense" // TODO => replace with standard eigen file #define EIGEN_ALLIGNMENT_IN_MMVII EIGEN_MAKE_ALIGNED_OPERATOR_NEW #else #define EIGEN_ALLIGNMENT_IN_MMVII #endif /* */ /** \file SymbolicDerivates.h \brief File for generating symbolic derivate Classes for generated symbolic derivative. All classes are single template classes. The template parameter indicate the numerical type used for storage/computation (float, double ...) This file is the only file to include. It contains : * declaration of operators * definition of "main" classes : cFormula , cCoordinatorF , cImplemF " ; * the 3 class for Atomic formula who will (probably) stay the same : Unkown, Observation, Constants This file include 2 files corresponding to following type of formula : * classes for "unary" formulas in "MMVII_FormDer_UnaryOp.h" * classes for "binary" formulas in "MMVII_FormDer_BinaryOp.h" These 2 files have "vocation" to be extended during the future. ------------------------------------------------- * cFormula<Type> : represent a mathematicall formula; as in math : - if F is a formula, exp(F), log(F) ....are formulas - if F1 and F2 are formulas, F1+F2 , F1*F2 ... are formulas - there exist some atomic formulas like constants, unknown and observations - if F is a formula F->Derivate(k) is a formula corresponding to is derivate dF/dXk Formulas are a complete algebric type. * cCoordinatorF<Type> : is the "coordinator" class. This class has, between others, the responsability of : - creating the initial atomic formula corresponding to unknowns and observation - maintain an inventory of existing formulas for efficiency purpose * Using this library is mainly : - create a coordinator with a given number of unkown and observations - create a formula using atoms an operator, generally the user function creating a formula will be a template that can operate on any complete algebric type (double, float, Formula , jets ...) - indicate to the coordinator the formula you want work on, with generally its derivate - evaluate the values of the formula for given unknows and observations cFormula<Type> is no more than an encapsulation of a pointer on the "concrete" class cImplemF. * cImplemF<Type> : is the mother class of all the formula. It's a pure abstract class, it contains several pure virtual methods. The two main methods are "Derivate" and "ComputeBuf", this is the two methods the users will have to define when extension to the library with new operator is required. - cFormula<Type> Derivate(int aK) return the formula of its derivate by Xk. Heres is two example extract from the code, one for multiplication, other from unknowns : o return mF2*mF1->Derivate(aK) + mF1*mF2->Derivate(aK); // From cMulF : (FG)' = F'G + FG' o return (aK==mNumUnk) ? tImplemF::mCoordF->Cste1() : tImplemF::mCoordF->Cste0(); // from cUnknownF - void ComputeBuf(int aK0,int aK1) : update the buffer of its data, once it subformula has been updated, this is method that does the real job. Here an extract from cExpF and cDivF : o for (int aK=aK0 ; aK<aK1 ; aK++) mDataBuf[aK] = std::exp(mDataF[aK]); o for (int aK=aK0 ; aK<aK1 ; aK++) mDataBuf[aK] = mDataF1[aK] / mDataF2[aK]; */ #include "SymbDer_Common.h" #if (WITH_MMVII) #include "include/MMVII_all.h" #include "include/MMVII_Derivatives.h" using namespace MMVII; #else //========================================================== WITH_MMVI class cMemCheck { }; #include <memory> #include <map> #include <iostream> #include <cassert> #include "memory.h" #include <memory> #include <iostream> #include <fstream> #include <string> #include <typeinfo> #include <vector> #include <list> #include <map> #include <ctime> #include <chrono> #include <math.h> #include <cmath> #include <algorithm> #include <sstream> #include <iomanip> #endif //========================================================== WITH_MMVI // REDUCTION RULES // TODO => REPLACE BY METHOD ON COORDINATOR WHEN THEY IMPROVE THINGS .... #define DOREDUCE false #define REDUCE_CSTE true // Cste+Cste => cste #define REDUCE_MM DOREDUCE // - - x => x ; a-(-b) => a+b #define REDUCE_ASSOCP DOREDUCE /* B + (A + C) = > A + ( B + C), more generally order the + operator, could be done with '*' */ #define REDUCE_DISTRIB DOREDUCE // A#B ~ A#C=> A#(B~C) ; # in "*/" and ~ in "+-" #define REDUCE_ApA DOREDUCE // A+A => 2*A, not good by itself, but may creat other reduc #define REDUCE_DIST1 DOREDUCE // A + A*C => A *(1+C) si C est csteto have all constant close static inline void SHOW_REDUCE(const std::string & aMes) {} // std::cout << "REDUCE " << aMes << "\n";} namespace NS_SymbolicDerivative { /* *************************************************** */ /* */ /* P0-Definition of global functions */ /* */ /* *************************************************** */ /// The CreateCste is required for formula, so we need it also on num type template <class Type> inline Type CreateCste(const Type & aV,const Type &) { return aV; } /// because pow is defined in std and there is cast int->float that would make it unaccessible template <class Type> inline Type pow(const Type & aV,const int & aExp) { return std::pow(aV,Type(aExp)); } //============= BASIC ERROR HANDLING ============== /** This function computes derivates by finites difference It is used in the tests to check correction of symbolic derivatives. Also used in didactic parts. */ template <class Type,class TypeFct> std::vector<Type> NumericalDerivate ( TypeFct & aFctr, ///< Function const std::vector<Type> & aVUk, ///< Unknown const std::vector<Type> & aVObs, ///< Observations int aNumVar, ///< Num of unknown we derivate by const Type & aEpsilon ///< "Small" number to compute variations ) { std::vector<Type> aVPlus = aVUk; aVPlus.at(aNumVar) += aEpsilon; std::vector<Type> aResPlus = aFctr( aVPlus,aVObs); std::vector<Type> aVMinus = aVUk; aVMinus.at(aNumVar) -= aEpsilon; std::vector<Type> aResMinus = aFctr( aVMinus,aVObs); std::vector<Type> aDerivate; for (size_t aK=0 ; aK<aResPlus.size() ; aK++) aDerivate.push_back((aResPlus.at(aK)-aResMinus.at(aK)) / (2*aEpsilon)); return aDerivate; } /* *************************************************** */ /* *************************************************** */ /* * * */ /* * Main user interace * */ /* * * */ /* *************************************************** */ /* *************************************************** */ // ------------- The two classes visible by user are cFormula and cCoordinatorF ------ /** Abstraction of mathemicall formula, this the object manipulated by user, its has all algerbric operation required. This object is just an encapsulation of a pointer on cImplemF. */ template <class TypeElem> class cFormula ; /** Class for managing the "context", i.e. coordinating all the formula and their derivative corresponding to a single use . */ template <class TypeElem> class cCoordinatorF; // -------- Declaration all binary operators ---------------- // For each operator with have the 3 versions "Formula x Formula" , // "Number x Formula" and "Formula x Number" , the two last are rather // syntactic suggar (i.e. make usage easier, but do not extend the library power) // Operator + template <class TypeElem> cFormula <TypeElem> operator +(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator +(const TypeElem & aV1,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator +(const cFormula <TypeElem> & aF1,const TypeElem & aV2); // Operator * template <class TypeElem> cFormula <TypeElem> operator *(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator *(const TypeElem & aV1,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator *(const cFormula <TypeElem> & aF1,const TypeElem & aV2); // Operator - template <class TypeElem> cFormula <TypeElem> operator -(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator -(const TypeElem & aV1,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator -(const cFormula <TypeElem> & aF1,const TypeElem & aV2); // Operator / template <class TypeElem> cFormula <TypeElem> operator /(const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator /(const TypeElem & aV1,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> operator /(const cFormula <TypeElem> & aF1,const TypeElem & aV2); // pow template <class TypeElem> cFormula <TypeElem> pow (const cFormula <TypeElem> & aF1 ,const cFormula <TypeElem> & aF2); template <class TypeElem> cFormula <TypeElem> pow (const TypeElem & aV1,const cFormula <TypeElem> & aF2); /// This one defined in MMVII_FormDer_UnaryOp.h template <class TypeElem> cFormula <TypeElem> pow (const cFormula <TypeElem> & aF1,const TypeElem & aV2); template <class TypeElem> cFormula <TypeElem> pow (const cFormula <TypeElem> & aF1,const int & aV2); // -------- integer low power ---------------- template <class TypeElem> cFormula <TypeElem> square(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> cube(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow4(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow5(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow6(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow7(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow8(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> pow9(const cFormula <TypeElem> & aF); // --- other unary operator template <class TypeElem> cFormula <TypeElem> exp(const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> operator - (const cFormula <TypeElem> & aF); template <class TypeElem> cFormula <TypeElem> log(const cFormula <TypeElem> & aF); // ---- sometime we need a templetized way to create constants template <class T> cFormula<T> CreateCste(const T & aV,const cFormula<T> & aF); /// --- powI , return pow of integral exponent, template <class Type> Type powI(const Type & aV,const int & aExp) { switch (aExp) { // case 0 : return Type(1.0); case 0 : return CreateCste(1.0,aV); case 1 : return aV; case 2 : return square(aV); case 3 : return cube(aV); case 4 : return pow4(aV); case 5 : return pow5(aV); case 6 : return pow6(aV); case 7 : return pow7(aV); case 8 : return pow8(aV); case 9 : return pow9(aV); } // else use the classical pow return pow(aV,aExp); } // -------- Declaration of Coordinator class ---------------- template <class TypeElem> class cCoordinatorF : public cCalculator<TypeElem>,public cMemCheck { public : typedef cFormula <TypeElem> tFormula; typedef std::vector<TypeElem> tOneRes; // --------------------------- Constructors / Destructor ------------------- /// Constructor with explicit Id for Unknown/Observation. Used if we want to analyze the generated code inline cCoordinatorF(const string &aName, int SzBuf, const std::vector<std::string> & aVecUK, const std::vector<std::string> & aVecObs); /// Constructor with basic Id (used if we dont generate code, or dont want to analyse it by human) inline cCoordinatorF(const string &aName, int SzBuf,int aNbUnknown,int aNbObservation); /// Destructeur will free allocated formulas virtual ~cCoordinatorF(); /// Copies are not allowed on this kind of object. cCoordinatorF(const cCoordinatorF<TypeElem> &) = delete; // --------------------------- Accessors to Atomic Formulas ------------------- const std::vector<tFormula>& VUk() const {return mVFormUnknowns;} ///< Unknowns const std::vector<tFormula>& VObs() const {return mVFormObservations;} ///< Observations // --------------------------- Manipulation ------------------- /// Set the formulas that with be used for computation void SetCurFormulas(const std::vector<tFormula> &); /** SetCurFormulas + all its derivative , order of storage will be VF0 dVF0/dX0 dVF0/dX1 .... VF1 dVF1/dX0 ... */ void SetCurFormulasWithDerivative(const std::vector<tFormula> & aVF); // ---------- Code generator --------------- /** Generate code, class cName , file cName.h, cName.cpp. Return filename w/o ext, or "" if error */ std::string GenerateCode(const std::string &aFilePrefix="CodeGen_") const { return GenCodeShortExpr(aFilePrefix); } std::string GenerateCodeTemplate(const std::string &aFilePrefix="CodeGen_") const { return GenCodeShortExprTemplate(aFilePrefix); } std::string GenerateCodeForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const { return GenCodeShortExprForType(aTypeName,aFilePrefix); } std::string GenCodeShortExpr(const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, "", true); } std::string GenCodeLonExpr(const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, "", false); } std::string GenCodeShortExprTemplate(const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, "template<>", true); } std::string GenCodeLonExprTemplate(const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, "template<>", false); } std::string GenCodeShortExprForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, aTypeName, true); } std::string GenCodeLonExprForType(const std::string& aTypeName, const std::string &aFilePrefix="CodeGen_") const { return GenCodeCommon(aFilePrefix, aTypeName, false); } private : // END-USER /* ================================================================================= ABOVE WAS THE REAL PUBLIC PART OF cCoordinatorF FOR USER OF LIBRARY. THE REST IS PUBLIC FOR IMPLEMENTERS BUT NOT NEEDED BY USER =====================================================================================*/ public : // Result of several evaluation are stored in a buffer, Eigen vector are used // as they implement efficiently arithmetical operation // typedef Eigen::Array<TypeElem, 1, Eigen::Dynamic> tBuf; typedef std::vector<TypeElem> tBuf; // --------------------------- Acces to function from names, values ------------------- /// Indicate if the formula corresponding to a given string already exist inline bool ExistFunc(const std::string & aName) const { return (mDicoFunc.find(aName) != mDicoFunc.end()); } /// Func of given name, Error if don't exist inline tFormula FuncOfName(const std::string & aName) const ; /// Add a function (put it in dico), Error if already exist inline void AddFormula(tFormula aPF) { if (ExistFunc(aPF->Name())) InternalError ("Multiple add of identic name :[" + aPF->Name() + "]",this->Name()); mDicoFunc[aPF->Name()] = aPF; mVAllFormula.push_back(aPF); aPF->TryReducAssoc(); } /// Func of given constant, create if don't exist inline tFormula CsteOfVal(const TypeElem & aCste) ; tFormula Cste0() const {return mCste0;} ///< Acces to a current constant tFormula Cste1() const {return mCste1;} ///< Another Acces to a current constant tFormula Cste2() const {return mCste2;} ///< Yet another Acces to a current constant /// Tuning --- Print the stack of function as a tree inline void ShowStackFunc() const; /// Formula used for computation, const std::vector<tFormula>& VReached() const {return mVReachedF;} // Current (top) formulas const std::vector<tFormula>& VCurrent() const {return mVCurF;} size_t NbCurFonc() const {return mVAllFormula.size();} private : /// Called by cCalculator::PushNewEvals to Set Unknown/Observations virtual void SetNewUks(const std::vector<TypeElem> &aVUks) override; virtual void SetNewObs(const std::vector<TypeElem> &aVObs) override; /** Make the evaluation of current functions on pushed values */ virtual void DoEval() override; /// Used to generate automatically Id for Unknown/Observatio, when we dont need to control them explicitely static std::vector<std::string> MakeAutomId(const std::string & aPrefix,int aNb); std::string GenCodeCommon(const string &aPrefix, string aTypeName, bool isShortExpr) const; std::string TypeElemName() const; size_t mNbCste; ///< Number Cste std::vector<tFormula> mVFormUnknowns; ///< Vector of All Unknowns std::vector<tFormula> mVFormObservations; ///< Vector of All Observations std::map<std::string,tFormula> mDicoFunc; ///< Map Name => Func std::vector<tFormula> mVAllFormula; ///< Vector of All Func, allow to parse them in creation order std::map<TypeElem,tFormula> mDicoCste; ///< Map Value => Func Constant tFormula mCste0; ///< Fonc constant null tFormula mCste1; ///< Fonc constant 1 tFormula mCste2; ///< Fonc constant 1 std::vector<tFormula> mVCurF; ///< Current evaluted formulas std::vector<tFormula> mVReachedF; ///< Formula "reachable" i.e. necessary to comput mVCurF }; /* ************************************************** * * * Pre-Declaration of all classes * * Not required by compilation * * (Except for cImplemF )but I like to have * * a quick view of all existing classes * * * * **************************************************/ /** "Mother" Interface class of all classes implementing the service , abstract class with pure virtual method */ template <class TypeElem> class cImplemF ; // --------------- "Atomic" function : Unknown, constant, observation----------------- template <class TypeElem> class cAtomicF ; ///< Mother Class of all atomic formulas /// "Observations" corresponding to user constant (change for each evaluation) template <class TypeElem> class cObservationF ; /// "Constant" function template <class TypeElem> class cConstantF ; /// "Unknown" for representing coordinates function X0,X1,X2 .... template <class TypeElem> class cUnknownF; // ----------------------------- Unary operator ------------------------------------ template <class TypeElem> class cUnaryF ; ///< Mother Class of all unary operator template <class TypeElem> class cSquareF ; ///< Class for square operator template <class TypeElem> class cExpF ; ///< Class for exponential operator template <class TypeElem> class cMin1F ; ///< Class for Unary Minus template <class TypeElem> class cLogF ; ///< Class for neperien log // -------------------------------- Binary operator ------------------------------------- template <class TypeElem> class cBinaryF ; ///< Mother class of binary operators template <class TypeElem> class cSumF ; ///< Class for sum of 2 functions template <class TypeElem> class cMulF ; ///< Class for multiplication of 2 functions template <class TypeElem> class cSubF ; ///< Class for substraction of 2 functions template <class TypeElem> class cDivF ; ///< Class for division of 2 functions template <class TypeElem> class cPowF ; ///< Class for division of 2 functions /* *************************************************** */ /* *************************************************** */ /* * * */ /* * Definition of all classes * */ /* * * */ /* *************************************************** */ /* *************************************************** */ // ------------------- 2 "Main" Classes ------------------------- // cFormula / cImplemF // ---------------------------------------------------------------- template <class TypeElem> class cImplemF : public cMemCheck { public : // See eigen documentation, this macro is mandatory for alignment reason // EIGEN_MAKE_ALIGNED_OPERATOR_NEW EIGEN_ALLIGNMENT_IN_MMVII typedef TypeElem tElem; typedef cCoordinatorF<TypeElem> tCoordF; typedef typename tCoordF::tBuf tBuf; typedef typename tCoordF::tFormula tFormula; //----------- For derivation and reduction-------------- virtual bool IsCste(const TypeElem &) const {return false;} ///< To redefine in constant func, Used for simplification in "/ * + -" virtual bool IsDistribInt() const {return false;} ///< To redefine in *,/ for distributivity virtual tFormula Derivate(int aK) const = 0; ///< Compute the formula of it's derivative to Kth unknown /** In this functionwe try to make reduction using associativity (and maybe others), as we want to do it only on maximal chains of + (or *) this has to be run by the father of the chain */ void TryReducAssoc(); virtual cImplemF<TypeElem> * ReducAssoc() {return this;} virtual bool IsMult() const {return false;} virtual bool IsSum() const {return false;} bool ReducAssocTried() const {return mReducAssocTried;} virtual cFormula<TypeElem> VOper2(const tFormula &,const tFormula &) const; ///< Use in distributive reducion to recal the operator binaire if suitable // -------------- For Computation ------------------------- /// Method that wil compute data inside mBuf virtual void ComputeBuf(int aK0,int aK1) =0; /// Return "Sub"-formula referenced virtual std::vector<tFormula> Ref() const =0; // ---------- Accessors --------------- const std::string & Name() const {return mName;} ///< Standard accessor tCoordF * CoordF() const {return mCoordF;} ///< Standard accesor int NumGlob() const {return mNumGlob;} ///< Standard accessor // ---------- Acces to Buf data --------------- void SetBuf(size_t anIndex,const TypeElem & aVal) {mBuf.at(anIndex) = aVal;} const TypeElem & GetBuf(size_t anIndex) {return mBuf.at(anIndex);} TypeElem * DataBuf() {return mDataBuf;} // ---------- Reached Flag --------------- bool Reached() const {return mReached;} ///< Standard accessor void SetReached(bool IsReached) {mReached = IsReached;} ///< Fix Reached /// Compute in the reference graphe and put formula explored in VReached void CalcRecursiveDepth(std::vector<tFormula> & VReached) ; int Depth() const {return mDepth;} ///< Standard accessor void SetDepth(int aDepth) {mDepth = aDepth;} ///< Fix Reached // ---------- Code gen ----------------------- virtual bool isAtomic() const { return false;} virtual std::string GenCodeFormName() const {return NameGlob();} // Name of formula, referenced value for Atomic virtual std::string GenCodeShortExpr() const = 0; // N-Addresses code generation virtual std::string GenCodeDef() const = 0; // Formula definition generation virtual std::string GenCodeRef() const; // Formula reference generation int UsedCnt() const {return mUsedCnt;} ///< Standard accessor // ---------- Tuning / Debugging / Analysing --------------- /// Used to print constant from generic formula virtual const TypeElem * ValCste() const {return nullptr;} /// Infixed "Pretty" Print . For tuning and checking (i.e correction of reduction, derivative, rewrite ...) virtual std::string InfixPPrint() const =0; /// Number of reference that would occur without reduction on identic formula (to test performance in paper) int RecursiveRec() const; // Every where a reference name is needed std::string NameGlob() const { return "F" + std::to_string(NumGlob());} /// Access at global level is 4 reducing, also it is used 4 implemant in Unary & Binary virtual const std::string & NameOperator() const = 0; // -------------------- Destructor / Constructor -------------------------- virtual ~cImplemF () {} ///< Add a virtual ~X() when we have virtual methods, who knows ... protected : inline cImplemF (tCoordF * aCoordF,const std::string & aName) : mCoordF (aCoordF), mBuf (mCoordF->SzBuf(),TypeElem(0.0)), mDataBuf (mBuf.data()), mName (aName), mNumGlob (mCoordF->NbCurFonc()), mReached (false), mDepth (-1), mUsedCnt (0), mReducAssocTried (false) { } tCoordF * mCoordF; ///< Coordinator that manage all the funcion cooperating tBuf mBuf; ///< Buf to store values TypeElem * mDataBuf; ///< Raw pointer const std::string mName; ///< string represention of the formula as for ex : C2, X1, V0 , square F3, F18/F3 ... int mNumGlob; ///< Global number (!= Num in class) bool mReached; ///< Flag to know if a formula is usefull for compute current int mDepth; ///< Used for topological sort private : cImplemF (const cImplemF<TypeElem> &) = delete; ///< No Copy unsigned mUsedCnt; bool mReducAssocTried; }; template <class TypeElem> class cFormula { public : typedef cCoordinatorF<TypeElem> tCoordF; typedef cImplemF<TypeElem> tImplemF; typedef typename tCoordF::tFormula tFormula; // -------------------- constructor ------------------- /// Construct from a pointer, standard cFormula (tImplemF * aRawPtr) : mPtr (aRawPtr) { } /// Default constructor, required by some code (vector ?) cFormula (): cFormula <TypeElem> (nullptr) { } // --------------- operator on pointer --------------------- // UNUSED 4 NOW tImplemF & operator*() const {return *mPtr;} ///< Standard behaviour of a pointer tImplemF * operator->() const {return mPtr;} ///< Standard behaviour of a pointer tImplemF * RawPtr() const {return mPtr;} ///< Explicit acces // DO NOT WORK const std::unique_ptr<tImplemF> operator->() const {return std::unique_ptr<mPtr>;} bool IsNull() const {return mPtr==nullptr;} ///< Safer than giving acces to raw pointer // --------------- Naming --------------------- /// Generate the unique indentifier of a binary expression std::string NameFormulaBin(const std::string & aNameOper,const tFormula & aF2) const { return (*this)->NameGlob() + aNameOper + aF2->NameGlob(); } /// Generate the unique indentifier of a unary expression std::string NameFormulaUn(const std::string & aNameOper) const { return aNameOper + " " + (*this)->NameGlob(); } /// To allow destruction without giving access to raw pointer void FreeMem() {delete mPtr; mPtr=nullptr;} private : tImplemF* mPtr; ///< Faster than shared and deallocation is easy as object controlled by context }; /* *************************************************** */ /* *************************************************** */ /* * * */ /* * ATOMIC FORMULA * */ /* * * */ /* *************************************************** */ /* *************************************************** */ /* ---------------------------------------------------------- Class for atomic formula MOTHER CLASS : cAtomicF DERIVED : cUnknownF / cObservationF / cConstantF ----------------------------------------------------------------*/ template <class TypeElem> class cAtomicF : public cImplemF<TypeElem> { public : typedef cImplemF<TypeElem> tImplemF; typedef typename tImplemF::tCoordF tCoordF; typedef typename tCoordF::tFormula tFormula; /// Should work always std::string InfixPPrint() const override {return tImplemF::Name();} /// Rule deriv=0 , work by default (constant and observations) tFormula Derivate(int aK) const override {return tImplemF::mCoordF->Cste0();} /// Generally nothing to do in atomic, their buffer has been filled witj adequate values void ComputeBuf(int aK0,int aK1) override { } std::vector<tFormula> Ref() const override{return std::vector<tFormula>();} protected : bool isAtomic() const override { return true;} std::string GenCodeFormName() const override { return this->Name();} std::string GenCodeShortExpr() const override { return this->GenCodeFormName();} std::string GenCodeRef() const override { return this->GenCodeFormName();} std::string GenCodeDef() const override { return mCodeValue;} inline cAtomicF(tCoordF * aCoordF,const std::string& aName) : tImplemF (aCoordF,aName) { } std::string mCodeValue; }; template <class TypeElem> class cUnknownF : public cAtomicF<TypeElem> { public : typedef cAtomicF<TypeElem> tAtom; typedef typename tAtom::tImplemF tImplemF; typedef typename tImplemF::tCoordF tCoordF; typedef typename tCoordF::tFormula tFormula; const std::string & NameOperator() const override {static std::string s("UK"); return s;} std::string InfixPPrint() const override {return tImplemF::Name();} /// rule : dXi/dXj = delta(i,j) tFormula Derivate(int aK) const override { return (aK==mNumUnk) ? tImplemF::mCoordF->Cste1() : tImplemF::mCoordF->Cste0(); } friend tCoordF; private : inline cUnknownF(tCoordF * aCoordF,const std::string& aName,int aNum) : tAtom (aCoordF,aName), mNumUnk (aNum) { this->mCodeValue = "this->mVUk[aK][" + std::to_string(mNumUnk) + "]"; } int mNumUnk; ///< Number of the Unknown; like : 0 for X0, 1 for X1 ... }; template <class TypeElem> class cObservationF : public cAtomicF<TypeElem> { public : typedef cAtomicF<TypeElem> tAtom; typedef typename tAtom::tImplemF tImplemF; typedef typename tImplemF::tCoordF tCoordF; typedef typename tCoordF::tFormula tFormula; friend tCoordF; const std::string & NameOperator() const override {static std::string s("Obs"); return s;} private : inline cObservationF(tCoordF * aCoordF,const std::string & aName,int aNum) : tAtom (aCoordF,aName), mNum (aNum) { this->mCodeValue = "this->mVObs[aK][" + std::to_string(mNum) + "]"; } int mNum; ///< Number of the Observation; like : 0 for V0, 1 for V1 ... }; template <class TypeElem> class cConstantF : public cAtomicF<TypeElem> { public : typedef cAtomicF<TypeElem> tAtom; typedef typename tAtom::tImplemF tImplemF; typedef typename tImplemF::tCoordF tCoordF; typedef typename tCoordF::tFormula tFormula; typedef typename tCoordF::tBuf tBuf; friend tCoordF; bool IsCste(const TypeElem &K) const override {return mVal==K;} ///< Here we know if we are a constant of value K const TypeElem * ValCste() const override {return &mVal;} const std::string & NameOperator() const override {static std::string s("Cste"); return s;} protected : inline cConstantF(tCoordF * aCoordF,const std::string & aName,int aNum,const TypeElem& aVal) : tAtom (aCoordF,aName), mNum (aNum), mVal (aVal) { for (auto & aV : tImplemF::mBuf) aV = aVal; // Initialize buf with const val std::stringstream ss; // Precision that ensures that Num0 -> ASCII -> Num1 => Num1 == Num0 // May cause some odd but correct value for non exactly representable numbers ss << std::setprecision(std::numeric_limits<decltype(mVal)>::max_digits10) << mVal; this->mCodeValue = ss.str(); } std::string GenCodeFormName() const override { return this->mCodeValue;} int mNum; const TypeElem mVal; }; /* *************************************************** */ /* *************************************************** */ /* * * */ /* * cFormula / cImplemF / cCoordinatorF * */ /* * External Definition of methods * */ /* * * */ /* *************************************************** */ /* *************************************************** */ /* ---------------------- */ /* cFormula */ /* ---------------------- */ template <class T> cFormula<T> CreateCste(const T & aV,const cFormula<T> & aF) { return aF->CoordF()->CsteOfVal(aV); } /* ---------------------- */ /* cImplemF */ /* ---------------------- */ template <class TypeElem> int cImplemF<TypeElem>::RecursiveRec() const { int aRes = 1; for (const auto & aF : Ref()) { aRes += aF->RecursiveRec(); } return aRes; } template <class TypeElem> void cImplemF<TypeElem>::CalcRecursiveDepth(std::vector<tFormula> & aVReached) { if (mDepth != -1) { mUsedCnt++; return; // if we were already here , nothing to do } mUsedCnt = 1; for (const auto & aF : Ref()) { aF->CalcRecursiveDepth(aVReached); // parse sub formula mDepth = std::max(mDepth,aF->mDepth); // Memo max depth } mDepth++; // my depth is 1 + max of depth of my referenced formulas aVReached.push_back(tFormula(this)); } template <class TypeElem> void cImplemF<TypeElem>::TryReducAssoc() { for (auto & aF : Ref()) { // F will not belong to the terminal command that will have to reparsed // If we are in the config (A+B) + .. maybe the chain will grow later if (aF->NameOperator() != NameOperator()) { aF = aF->ReducAssoc(); } aF->mReducAssocTried = true; } } template <class TypeElem> cFormula<TypeElem> cImplemF<TypeElem>::VOper2(const tFormula & aF1,const tFormula &) const { InternalError("Incorrect virtual binary operation",this->mCoordF->Name()); return aF1; } template <class TypeElem> std::string cImplemF<TypeElem>::GenCodeRef() const { if (UsedCnt() == 1) { return GenCodeDef(); } else { return GenCodeFormName(); } } /* ---------------------- */ /* cCoordinatorF */ /* ---------------------- */ template <class TypeElem> std::vector<std::string> cCoordinatorF<TypeElem>::MakeAutomId(const std::string & aPrefix,int aNb) { std::vector<std::string> aRes; for (int aK=0 ; aK<aNb ; aK++) aRes.push_back(aPrefix+ std::to_string(aK)); return aRes; } template <class TypeElem> cCoordinatorF<TypeElem>::cCoordinatorF ( const std::string & aName, int aSzBuf, const std::vector<std::string> & aVNameUK, const std::vector<std::string> & aVNameObs ) : cCalculator<TypeElem>(aName,aSzBuf,aVNameUK.size(),aVNameObs.size()), mNbCste (0), mCste0 (CsteOfVal(0.0)), mCste1 (CsteOfVal(1.0)), mCste2 (CsteOfVal(2.0)) { // Generate all the function corresponding to unknown for (size_t aNumUK=0 ; aNumUK<this->mNbUK ; aNumUK++) { tFormula aFuncUK(new cUnknownF<TypeElem>(this,aVNameUK[aNumUK],aNumUK)); // Create it mVFormUnknowns.push_back(aFuncUK); // Push it in vector of coordinat func AddFormula(aFuncUK); // Add to all func } // Generate all the function corresponding to observations for (size_t aNumObs=0 ; aNumObs<this->mNbObs ; aNumObs++) { tFormula aFuncObs(new cObservationF<TypeElem>(this,aVNameObs[aNumObs],aNumObs)); // Create it mVFormObservations.push_back(aFuncObs); // Push it in vector of coordinat func AddFormula(aFuncObs); // Add to all func } } template <class TypeElem> cCoordinatorF<TypeElem>::cCoordinatorF(const string &aName, int aSzBuf, int aNbUK, int aNbObs) : cCoordinatorF<TypeElem>(aName,aSzBuf,MakeAutomId("X",aNbUK),MakeAutomId("V",aNbObs)) { } template <class TypeElem> cCoordinatorF<TypeElem>::~cCoordinatorF() { for (auto & aForm : mVAllFormula) { aForm.FreeMem(); } } template <class TypeElem> cFormula<TypeElem> cCoordinatorF<TypeElem>::CsteOfVal(const TypeElem & aCste) { tFormula & aRef = mDicoCste[aCste]; if (aRef.IsNull()) // If it was not existing, the map contain now the def element { // The ! is used to make constant first in alphab order, used for reduction ? aRef=tFormula(new cConstantF<TypeElem>(this,"_C"+std::to_string(mNbCste),mNbCste,aCste)); mNbCste++; AddFormula(aRef); } return aRef; } template <class TypeElem> cFormula <TypeElem> cCoordinatorF<TypeElem>::FuncOfName(const std::string & aName) const { const auto & anIt = mDicoFunc.find(aName); if (anIt == mDicoFunc.end()) InternalError ("Try to acces non existing name :[" + aName + "]",this->Name()); return anIt->second; } template <class TypeElem> void cCoordinatorF<TypeElem>::SetNewUks(const std::vector<TypeElem> & aVUks) { for (size_t aK=0 ; aK<aVUks.size() ; aK++) // Init Vals of formulas buffer { mVFormUnknowns[aK]->SetBuf(this->mNbInBuf,aVUks[aK]); } } template <class TypeElem> void cCoordinatorF<TypeElem>::SetNewObs(const std::vector<TypeElem> & aVObs) { for (size_t aK=0 ; aK<aVObs.size() ; aK++) // Init Vals of formulas buffer { mVFormObservations[aK]->SetBuf(this->mNbInBuf,aVObs[aK]); } } template <class TypeElem> void cCoordinatorF<TypeElem>::SetCurFormulasWithDerivative(const std::vector<tFormula> & aVF) { std::vector<tFormula> aVWDer; for (const auto & aF : aVF) { aVWDer.push_back(aF); for (size_t aUK=0 ; aUK<this->mNbUK ; aUK++) { aVWDer.push_back(aF->Derivate(aUK)); } } SetCurFormulas(aVWDer); this->mWithDer = true; this->mSzInterval = 1+this->mNbUK; this->mNbElem = aVF.size(); } template <class TypeElem> void cCoordinatorF<TypeElem>::SetCurFormulas(const std::vector<tFormula> & aVF0) { std::vector<tFormula> aVF; for(auto aF : aVF0) { if (! aF->ReducAssocTried()) { aF = tFormula(aF->ReducAssoc()); // std::cout << "GGGGGGGG " << aF->Name() << " \n"; } aVF.push_back(aF); } this->mWithDer=false; this->mSzInterval = 1; this->mNbElem = aVF0.size(); mVCurF = aVF; // Erase previous for (auto & aF : mVReachedF) aF->SetDepth(-1); mVReachedF.clear(); // Compute depth for topologicall sort for (auto & aF : mVCurF) { aF->CalcRecursiveDepth(mVReachedF); } // Use depth to have topological sort // In fact it is probably not necessary to make this sort, initial order of reaching order // should work; by the way : no dammage .. std::sort ( mVReachedF.begin(), mVReachedF.end(), [](const tFormula & aF1,const tFormula &aF2) {return aF1->Depth() < aF2->Depth();} ); // Make Buf of Res to have right size for (auto & aLine : this->mBufLineRes) { aLine.resize(mVCurF.size()); } } template <class TypeElem> void cCoordinatorF<TypeElem>::DoEval() { // Make the real hard stuff, compute the data, the depedancy ordering should make it coherent #ifdef _OPENMP #pragma omp parallel { size_t thread_num = omp_get_thread_num(); size_t num_threads = omp_get_num_threads(); size_t start = thread_num * this->mNbInBuf / num_threads; size_t end = (thread_num + 1) * this->mNbInBuf / num_threads; if (end>start) { for (auto & aF : mVReachedF) { aF->ComputeBuf(start,end); } } } #else for (auto & aF : mVReachedF) { aF->ComputeBuf(0,this->mNbInBuf); } #endif for (size_t aKLine=0 ; aKLine<this->mNbInBuf ; aKLine++) { std::vector<TypeElem> & aLine = this->mBufLineRes[aKLine]; for (size_t aKFunc=0 ; aKFunc< mVCurF.size() ; aKFunc++) aLine[aKFunc] = mVCurF[aKFunc]->GetBuf(aKLine); } } template <class TypeElem> void cCoordinatorF<TypeElem>::ShowStackFunc() const { for (const auto & aForm : mVAllFormula) { if (aForm->Depth()==-1) std::cout << "---" ; else std::cout << "-" << aForm->Depth() << "-"; std::cout << aForm->UsedCnt() << "- "; std::cout << aForm->NameGlob() << " => " << aForm->Name(); const TypeElem * aPV = aForm->ValCste(); if (aPV) std::cout << " ; Val=" << *aPV; std::cout << "\n"; } std::cout << "REACHED "; for (const auto & aForm : mVReachedF) { std::cout << aForm->NumGlob() << " "; } std::cout << "\n"; std::cout << "CUR "; for (const auto & aForm : mVCurF) { std::cout << aForm->NumGlob() << " "; } std::cout << "\n"; } template <class TypeElem> std::string cCoordinatorF<TypeElem>::GenCodeCommon(const std::string& aPrefix, std::string aTypeName, bool isShortExpr) const { std::string aName = this->Name(); if (aName.size() == 0) UserSError("Formula name is empty.",this->Name()); for (auto &c : aName) { if (!std::isalnum(c) && c != '_') UserSError("Formula name is not a valid C++ identifier: '_,a..z,A..Z,0..9' only.",this->Name()); } std::string aClassName = "c" + aName; if (aTypeName.size()==0) aTypeName = this->TypeElemName(); bool isTemplated = aTypeName=="template<>"; if (isTemplated) aTypeName = "TypeElem"; std::string aVectorName = "std::vector<" + aTypeName + ">"; if (! isShortExpr) aClassName = aClassName + "LongExpr"; std::string aParentClass = "cCalculator<" + aTypeName + ">"; std::string aFileName = aPrefix + aClassName; std::ofstream aOs(aFileName + ".h"); if (!aOs) return ""; aOs << "#ifdef _OPENMP\n" "#include <omp.h>\n" "#endif\n" "#include \"SymbDer/SymbDer_Common.h\"\n" "\n" "namespace NS_SymbolicDerivative {\n\n"; if (isTemplated) { aOs << "template<typename TypeElem>\n"; } aOs << "class " << aClassName << " : public " << aParentClass << "\n" "{\n" "public:\n" " typedef " << aParentClass << " Super;\n" " " << aClassName << "(size_t aSzBuf) : \n" " Super(\"" << aName << "\", aSzBuf," << this->mNbUK << "," << this->mNbObs << "," << this->mWithDer << "," << this->mSzInterval << "),\n" " mVUk(aSzBuf),mVObs(aSzBuf)\n" " {\n" " this->mNbElem = " << this->mNbElem << ";\n" " for (auto& line : this->mBufLineRes)\n" " line.resize(" << mVCurF.size() << ");\n" " for (auto& aUk : this->mVUk)\n" " aUk.resize(this->NbUk());\n" " for (auto& aObs : this->mVObs)\n" " aObs.resize(this->NbObs());\n" " }\n" " static std::string FormulaName() { return \"" << aName << "\";}\n" "protected:\n" " virtual void SetNewUks(const " << aVectorName << " & aVUks) override\n" " {\n" " for (size_t i=0; i<this->NbUk(); i++)\n" " this->mVUk[this->mNbInBuf][i] = aVUks[i];\n" " }\n" " virtual void SetNewObs(const " << aVectorName << " & aVObs) override\n" " {\n" " for (size_t i=0; i<this->NbObs(); i++)\n" " this->mVObs[this->mNbInBuf][i] = aVObs[i];\n" " }\n" " virtual void DoEval() override;\n" " std::vector<" << aVectorName << "> mVUk;\n" " std::vector<" << aVectorName << "> mVObs;\n" "};\n" "\n"; if (! isTemplated) { aOs << "} // namespace NS_SymbolicDerivative\n"; aOs = std::ofstream(aFileName + ".cpp"); if (!aOs) return ""; aOs << "#include \"" + aFileName + ".h\"\n" "\n" "namespace NS_SymbolicDerivative {\n" "\n" "void " << aClassName << "::DoEval()\n"; } else { aOs << "\n" "template<typename TypeElem>\n" "void " << aClassName << "<TypeElem>::DoEval()\n"; } aOs << "{\n" "#ifdef _OPENMP\n" "#pragma omp parallel for\n" "#endif\n" " for (size_t aK=0; aK < this->mNbInBuf; aK++) {\n" "// Declare local vars in loop to make them per thread\n"; for (auto & aForm : mVFormUnknowns) aOs << " " << aTypeName << " &" << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n"; for (const auto & aForm : mVFormObservations) aOs << " " << aTypeName << " &" << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n"; if (isShortExpr) { for (const auto & aForm : mVReachedF) { if (!aForm->isAtomic()) aOs << " " << aTypeName << " " << aForm->GenCodeFormName() << " = " << aForm->GenCodeShortExpr() << ";\n"; } for (size_t i=0; i<mVCurF.size(); i++) aOs << " this->mBufLineRes[aK][" << i << "] = " << mVCurF[i]->GenCodeFormName() << ";\n"; } else { for (const auto & aForm : mVReachedF) { if (aForm->UsedCnt() != 1 && !aForm->isAtomic()) { aOs << " " << aTypeName << " " << aForm->GenCodeFormName() << " = " << aForm->GenCodeDef() << ";\n"; } } for (size_t i=0; i<mVCurF.size(); i++) aOs << " this->mBufLineRes[aK][" << i << "] = " << mVCurF[i]->GenCodeRef() << ";\n"; } aOs << " }\n" "}\n\n" "} // namespace NS_SymbolicDerivative\n"; return aFileName; } template<> inline std::string cCoordinatorF<double>::TypeElemName() const {return "double";} template<> inline std::string cCoordinatorF<float>::TypeElemName() const {return "float";} template<typename T> struct Detect_if_TypeElemName_is_defined : std::false_type { }; template<class TypeElem> inline std::string cCoordinatorF<TypeElem>::TypeElemName() const { static_assert( Detect_if_TypeElemName_is_defined<TypeElem>::value , "** You must define cCoordinatorF::TypeElemName() for you type **"); return ""; } } // NS_Symbolic_Derivative #include "SymbDer_UnaryOp.h" #include "SymbDer_BinaryOp.h" /* https://www.itl.nist.gov/div898/strd/nls/data/ratkowsky3.shtml http://en.wikipedia.org/wiki/Automatic_differentiation https://git.irc.umbc.edu/photorig/openMVG/blob/260584fda68dce095e279362efd24a2d7d7cf5d9/src/third_party/ceres-solver/include/ceres/jet.h https://mc-stan.org/ http://www.met.reading.ac.uk/clouds/adept/array_features.html http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.89.7749&rep=rep1&type=pdf http://www.autodiff.org/ */ #endif // _SymbolicDerivatives_H_
GB_unaryop__lnot_fp32_int16.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__lnot_fp32_int16 // op(A') function: GB_tran__lnot_fp32_int16 // C type: float // A type: int16_t // cast: float cij = (float) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int16_t #define GB_CTYPE \ float // 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 != 0) ; // casting #define GB_CASTING(z, aij) \ float z = (float) 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_LNOT || GxB_NO_FP32 || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_fp32_int16 ( float *Cx, // Cx and Ax may be aliased 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++) { 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_fp32_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_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
SplineC2CAdoptor.h
////////////////////////////////////////////////////////////////////////////////////// // This file is distributed under the University of Illinois/NCSA Open Source License. // See LICENSE file in top directory for details. // // Copyright (c) 2016 Jeongnim Kim and QMCPACK developers. // // File developed by: // // File created by: Jeongnim Kim, jeongnim.kim@intel.com, Intel Corp. ////////////////////////////////////////////////////////////////////////////////////// /** @file * * Adoptor classes to handle complex-to-(real,complex) with arbitrary precision */ #ifndef QMCPLUSPLUS_EINSPLINE_C2C_SOA_ADOPTOR_H #define QMCPLUSPLUS_EINSPLINE_C2C_SOA_ADOPTOR_H #include <memory> #include <OhmmsSoA/Container.h> #include <spline2/MultiBspline.hpp> #include <spline2/MultiBsplineEval.hpp> #include "QMCWaveFunctions/BsplineFactory/SplineAdoptorBase.h" #include "QMCWaveFunctions/BsplineFactory/contraction_helper.hpp" #include "Utilities/FairDivide.h" namespace qmcplusplus { /** adoptor class to match std::complex<ST> spline with std::complex<TT> SPOs * @tparam ST precision of spline * @tparam TT precision of SPOs * @tparam D dimension * * Requires temporage storage and multiplication of phase vectors * Internal storage use double sized arrays of ST type, aligned and padded. */ template<typename ST, typename TT> struct SplineC2CSoA : public SplineAdoptorBase<ST, 3> { static const int D = 3; using Base = SplineAdoptorBase<ST, 3>; using SplineType = typename bspline_traits<ST, 3>::SplineType; using BCType = typename bspline_traits<ST, 3>::BCType; using DataType = ST; using PointType = typename Base::PointType; using SingleSplineType = typename Base::SingleSplineType; using ComplexT = typename std::complex<TT>; using vContainer_type = Vector<ST, aligned_allocator<ST>>; using gContainer_type = VectorSoaContainer<ST, 3>; using hContainer_type = VectorSoaContainer<ST, 6>; using ghContainer_type = VectorSoaContainer<ST, 10>; using Base::first_spo; using Base::GGt; using Base::kPoints; using Base::last_spo; using Base::MakeTwoCopies; using Base::offset; using Base::PrimLattice; ///multi bspline set std::shared_ptr<MultiBspline<ST>> SplineInst; vContainer_type mKK; VectorSoaContainer<ST, 3> myKcart; vContainer_type myV; vContainer_type myL; gContainer_type myG; hContainer_type myH; ghContainer_type mygH; ///thread private ratios for reduction when using nested threading, numVP x numThread Matrix<ComplexT> ratios_private; SplineC2CSoA() : Base() { this->is_complex = true; this->is_soa_ready = true; this->AdoptorName = "SplineC2CSoAAdoptor"; this->KeyWord = "SplineC2CSoA"; } inline void resizeStorage(size_t n, size_t nvals) { Base::init_base(n); size_t npad = getAlignedSize<ST>(2 * n); myV.resize(npad); myG.resize(npad); myL.resize(npad); myH.resize(npad); mygH.resize(npad); } void bcast_tables(Communicate* comm) { chunked_bcast(comm, SplineInst->getSplinePtr()); } void gather_tables(Communicate* comm) { if (comm->size() == 1) return; const int Nbands = kPoints.size(); const int Nbandgroups = comm->size(); offset.resize(Nbandgroups + 1, 0); FairDivideLow(Nbands, Nbandgroups, offset); for (size_t ib = 0; ib < offset.size(); ib++) offset[ib] *= 2; gatherv(comm, SplineInst->getSplinePtr(), SplineInst->getSplinePtr()->z_stride, offset); } template<typename GT, typename BCT> void create_spline(GT& xyz_g, BCT& xyz_bc) { resize_kpoints(); SplineInst = std::make_shared<MultiBspline<ST>>(); SplineInst->create(xyz_g, xyz_bc, myV.size()); app_log() << "MEMORY " << SplineInst->sizeInByte() / (1 << 20) << " MB allocated " << "for the coefficients in 3D spline orbital representation" << std::endl; } inline void flush_zero() { SplineInst->flush_zero(); } /** remap kPoints to pack the double copy */ inline void resize_kpoints() { const size_t nk = kPoints.size(); mKK.resize(nk); myKcart.resize(nk); for (size_t i = 0; i < nk; ++i) { mKK[i] = -dot(kPoints[i], kPoints[i]); myKcart(i) = kPoints[i]; } } inline void set_spline(SingleSplineType* spline_r, SingleSplineType* spline_i, int twist, int ispline, int level) { SplineInst->copy_spline(spline_r, 2 * ispline); SplineInst->copy_spline(spline_i, 2 * ispline + 1); } bool read_splines(hdf_archive& h5f) { std::ostringstream o; o << "spline_" << SplineAdoptorBase<ST, D>::MyIndex; einspline_engine<SplineType> bigtable(SplineInst->getSplinePtr()); return h5f.readEntry(bigtable, o.str().c_str()); //"spline_0"); } bool write_splines(hdf_archive& h5f) { std::ostringstream o; o << "spline_" << SplineAdoptorBase<ST, D>::MyIndex; einspline_engine<SplineType> bigtable(SplineInst->getSplinePtr()); return h5f.writeEntry(bigtable, o.str().c_str()); //"spline_0"); } template<typename VV> inline void assign_v(const PointType& r, const vContainer_type& myV, VV& psi, int first, int last) const { // protect last last = last > kPoints.size() ? kPoints.size() : last; const ST x = r[0], y = r[1], z = r[2]; const ST* restrict kx = myKcart.data(0); const ST* restrict ky = myKcart.data(1); const ST* restrict kz = myKcart.data(2); #pragma omp simd for (size_t j = first; j < last; ++j) { ST s, c; const ST val_r = myV[2 * j]; const ST val_i = myV[2 * j + 1]; sincos(-(x * kx[j] + y * ky[j] + z * kz[j]), &s, &c); psi[j + first_spo] = ComplexT(val_r * c - val_i * s, val_i * c + val_r * s); } } template<typename VV> inline void evaluate_v(const ParticleSet& P, const int iat, VV& psi) { const PointType& r = P.activeR(iat); PointType ru(PrimLattice.toUnit_floor(r)); #pragma omp parallel { int first, last; FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last); spline2::evaluate3d(SplineInst->getSplinePtr(), ru, myV, first, last); assign_v(r, myV, psi, first / 2, last / 2); } } template<typename VV, typename RT> inline void evaluateDetRatios(const VirtualParticleSet& VP, VV& psi, const VV& psiinv, std::vector<RT>& ratios) { const bool need_resize = ratios_private.rows() < VP.getTotalNum(); #pragma omp parallel { int tid = omp_get_thread_num(); // initialize thread private ratios if (need_resize) { if (tid == 0) // just like #pragma omp master, but one fewer call to the runtime ratios_private.resize(VP.getTotalNum(), omp_get_num_threads()); #pragma omp barrier } int first, last; FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), tid, first, last); const int first_cplx = first / 2; const int last_cplx = kPoints.size() < last / 2 ? kPoints.size() : last / 2; for (int iat = 0; iat < VP.getTotalNum(); ++iat) { const PointType& r = VP.activeR(iat); PointType ru(PrimLattice.toUnit_floor(r)); spline2::evaluate3d(SplineInst->getSplinePtr(), ru, myV, first, last); assign_v(r, myV, psi, first_cplx, last_cplx); ratios_private[iat][tid] = simd::dot(psi.data() + first_cplx, psiinv.data() + first_cplx, last_cplx - first_cplx); } } // do the reduction manually for (int iat = 0; iat < VP.getTotalNum(); ++iat) { ratios[iat] = ComplexT(0); for (int tid = 0; tid < ratios_private.cols(); tid++) ratios[iat] += ratios_private[iat][tid]; } } /** assign_vgl */ template<typename VV, typename GV> inline void assign_vgl(const PointType& r, VV& psi, GV& dpsi, VV& d2psi, int first, int last) const { // protect last last = last > kPoints.size() ? kPoints.size() : last; constexpr ST zero(0); constexpr ST two(2); const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3), g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7), g22 = PrimLattice.G(8); const ST x = r[0], y = r[1], z = r[2]; const ST symGG[6] = {GGt[0], GGt[1] + GGt[3], GGt[2] + GGt[6], GGt[4], GGt[5] + GGt[7], GGt[8]}; const ST* restrict k0 = myKcart.data(0); const ST* restrict k1 = myKcart.data(1); const ST* restrict k2 = myKcart.data(2); const ST* restrict g0 = myG.data(0); const ST* restrict g1 = myG.data(1); const ST* restrict g2 = myG.data(2); const ST* restrict h00 = myH.data(0); const ST* restrict h01 = myH.data(1); const ST* restrict h02 = myH.data(2); const ST* restrict h11 = myH.data(3); const ST* restrict h12 = myH.data(4); const ST* restrict h22 = myH.data(5); #pragma omp simd for (size_t j = first; j < last; ++j) { const size_t jr = j << 1; const size_t ji = jr + 1; const ST kX = k0[j]; const ST kY = k1[j]; const ST kZ = k2[j]; const ST val_r = myV[jr]; const ST val_i = myV[ji]; //phase ST s, c; sincos(-(x * kX + y * kY + z * kZ), &s, &c); //dot(PrimLattice.G,myG[j]) const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr]; const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr]; const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr]; const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji]; const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji]; const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji]; // \f$\nabla \psi_r + {\bf k}\psi_i\f$ const ST gX_r = dX_r + val_i * kX; const ST gY_r = dY_r + val_i * kY; const ST gZ_r = dZ_r + val_i * kZ; const ST gX_i = dX_i - val_r * kX; const ST gY_i = dY_i - val_r * kY; const ST gZ_i = dZ_i - val_r * kZ; const ST lcart_r = SymTrace(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], symGG); const ST lcart_i = SymTrace(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], symGG); const ST lap_r = lcart_r + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i); const ST lap_i = lcart_i + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r); const size_t psiIndex = j + first_spo; psi[psiIndex] = ComplexT(c * val_r - s * val_i, c * val_i + s * val_r); dpsi[psiIndex][0] = ComplexT(c * gX_r - s * gX_i, c * gX_i + s * gX_r); dpsi[psiIndex][1] = ComplexT(c * gY_r - s * gY_i, c * gY_i + s * gY_r); dpsi[psiIndex][2] = ComplexT(c * gZ_r - s * gZ_i, c * gZ_i + s * gZ_r); d2psi[psiIndex] = ComplexT(c * lap_r - s * lap_i, c * lap_i + s * lap_r); } } /** assign_vgl_from_l can be used when myL is precomputed and myV,myG,myL in cartesian */ template<typename VV, typename GV> inline void assign_vgl_from_l(const PointType& r, VV& psi, GV& dpsi, VV& d2psi) { constexpr ST two(2); const ST x = r[0], y = r[1], z = r[2]; const ST* restrict k0 = myKcart.data(0); const ST* restrict k1 = myKcart.data(1); const ST* restrict k2 = myKcart.data(2); const ST* restrict g0 = myG.data(0); const ST* restrict g1 = myG.data(1); const ST* restrict g2 = myG.data(2); const size_t N = last_spo - first_spo; #pragma omp simd for (size_t j = 0; j < N; ++j) { const size_t jr = j << 1; const size_t ji = jr + 1; const ST kX = k0[j]; const ST kY = k1[j]; const ST kZ = k2[j]; const ST val_r = myV[jr]; const ST val_i = myV[ji]; //phase ST s, c; sincos(-(x * kX + y * kY + z * kZ), &s, &c); //dot(PrimLattice.G,myG[j]) const ST dX_r = g0[jr]; const ST dY_r = g1[jr]; const ST dZ_r = g2[jr]; const ST dX_i = g0[ji]; const ST dY_i = g1[ji]; const ST dZ_i = g2[ji]; // \f$\nabla \psi_r + {\bf k}\psi_i\f$ const ST gX_r = dX_r + val_i * kX; const ST gY_r = dY_r + val_i * kY; const ST gZ_r = dZ_r + val_i * kZ; const ST gX_i = dX_i - val_r * kX; const ST gY_i = dY_i - val_r * kY; const ST gZ_i = dZ_i - val_r * kZ; const ST lap_r = myL[jr] + mKK[j] * val_r + two * (kX * dX_i + kY * dY_i + kZ * dZ_i); const ST lap_i = myL[ji] + mKK[j] * val_i - two * (kX * dX_r + kY * dY_r + kZ * dZ_r); const size_t psiIndex = j + first_spo; psi[psiIndex] = ComplexT(c * val_r - s * val_i, c * val_i + s * val_r); dpsi[psiIndex][0] = ComplexT(c * gX_r - s * gX_i, c * gX_i + s * gX_r); dpsi[psiIndex][1] = ComplexT(c * gY_r - s * gY_i, c * gY_i + s * gY_r); dpsi[psiIndex][2] = ComplexT(c * gZ_r - s * gZ_i, c * gZ_i + s * gZ_r); d2psi[psiIndex] = ComplexT(c * lap_r - s * lap_i, c * lap_i + s * lap_r); } } template<typename VV, typename GV> inline void evaluate_vgl(const ParticleSet& P, const int iat, VV& psi, GV& dpsi, VV& d2psi) { const PointType& r = P.activeR(iat); PointType ru(PrimLattice.toUnit_floor(r)); #pragma omp parallel { int first, last; FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last); spline2::evaluate3d_vgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, first, last); assign_vgl(r, psi, dpsi, d2psi, first / 2, last / 2); } } template<typename VV, typename GV> inline void mw_evaluate_vgl(const std::vector<SplineC2CSoA*>& sa_list, const std::vector<ParticleSet*>& P_list, int iat, const std::vector<VV*>& psi_v_list, const std::vector<GV*>& dpsi_v_list, const std::vector<VV*>& d2psi_v_list) { #pragma omp parallel for for (int iw = 0; iw < sa_list.size(); iw++) sa_list[iw]->evaluate_vgl(*P_list[iw], iat, *psi_v_list[iw], *dpsi_v_list[iw], *d2psi_v_list[iw]); } template<typename VV, typename GV, typename GGV> void assign_vgh(const PointType& r, VV& psi, GV& dpsi, GGV& grad_grad_psi, int first, int last) const { // protect last last = last > kPoints.size() ? kPoints.size() : last; const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3), g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7), g22 = PrimLattice.G(8); const ST x = r[0], y = r[1], z = r[2]; const ST* restrict k0 = myKcart.data(0); const ST* restrict k1 = myKcart.data(1); const ST* restrict k2 = myKcart.data(2); const ST* restrict g0 = myG.data(0); const ST* restrict g1 = myG.data(1); const ST* restrict g2 = myG.data(2); const ST* restrict h00 = myH.data(0); const ST* restrict h01 = myH.data(1); const ST* restrict h02 = myH.data(2); const ST* restrict h11 = myH.data(3); const ST* restrict h12 = myH.data(4); const ST* restrict h22 = myH.data(5); #pragma omp simd for (size_t j = first; j < last; ++j) { int jr = j << 1; int ji = jr + 1; const ST kX = k0[j]; const ST kY = k1[j]; const ST kZ = k2[j]; const ST val_r = myV[jr]; const ST val_i = myV[ji]; //phase ST s, c; sincos(-(x * kX + y * kY + z * kZ), &s, &c); //dot(PrimLattice.G,myG[j]) const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr]; const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr]; const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr]; const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji]; const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji]; const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji]; // \f$\nabla \psi_r + {\bf k}\psi_i\f$ const ST gX_r = dX_r + val_i * kX; const ST gY_r = dY_r + val_i * kY; const ST gZ_r = dZ_r + val_i * kZ; const ST gX_i = dX_i - val_r * kX; const ST gY_i = dY_i - val_r * kY; const ST gZ_i = dZ_i - val_r * kZ; const size_t psiIndex = j + first_spo; psi[psiIndex] = ComplexT(c * val_r - s * val_i, c * val_i + s * val_r); dpsi[psiIndex][0] = ComplexT(c * gX_r - s * gX_i, c * gX_i + s * gX_r); dpsi[psiIndex][1] = ComplexT(c * gY_r - s * gY_i, c * gY_i + s * gY_r); dpsi[psiIndex][2] = ComplexT(c * gZ_r - s * gZ_i, c * gZ_i + s * gZ_r); const ST h_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02) + kX * (gX_i + dX_i); const ST h_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12) + kX * (gY_i + dY_i); const ST h_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22) + kX * (gZ_i + dZ_i); const ST h_yx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g00, g01, g02) + kY * (gX_i + dX_i); const ST h_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12) + kY * (gY_i + dY_i); const ST h_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22) + kY * (gZ_i + dZ_i); const ST h_zx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g00, g01, g02) + kZ * (gX_i + dX_i); const ST h_zy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g10, g11, g12) + kZ * (gY_i + dY_i); const ST h_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22) + kZ * (gZ_i + dZ_i); const ST h_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02) - kX * (gX_r + dX_r); const ST h_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12) - kX * (gY_r + dY_r); const ST h_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22) - kX * (gZ_r + dZ_r); const ST h_yx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g00, g01, g02) - kY * (gX_r + dX_r); const ST h_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12) - kY * (gY_r + dY_r); const ST h_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22) - kY * (gZ_r + dZ_r); const ST h_zx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g00, g01, g02) - kZ * (gX_r + dX_r); const ST h_zy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g10, g11, g12) - kZ * (gY_r + dY_r); const ST h_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22) - kZ * (gZ_r + dZ_r); grad_grad_psi[psiIndex][0] = ComplexT(c * h_xx_r - s * h_xx_i, c * h_xx_i + s * h_xx_r); grad_grad_psi[psiIndex][1] = ComplexT(c * h_xy_r - s * h_xy_i, c * h_xy_i + s * h_xy_r); grad_grad_psi[psiIndex][2] = ComplexT(c * h_xz_r - s * h_xz_i, c * h_xz_i + s * h_xz_r); grad_grad_psi[psiIndex][3] = ComplexT(c * h_yx_r - s * h_yx_i, c * h_yx_i + s * h_yx_r); grad_grad_psi[psiIndex][4] = ComplexT(c * h_yy_r - s * h_yy_i, c * h_yy_i + s * h_yy_r); grad_grad_psi[psiIndex][5] = ComplexT(c * h_yz_r - s * h_yz_i, c * h_yz_i + s * h_yz_r); grad_grad_psi[psiIndex][6] = ComplexT(c * h_zx_r - s * h_zx_i, c * h_zx_i + s * h_zx_r); grad_grad_psi[psiIndex][7] = ComplexT(c * h_zy_r - s * h_zy_i, c * h_zy_i + s * h_zy_r); grad_grad_psi[psiIndex][8] = ComplexT(c * h_zz_r - s * h_zz_i, c * h_zz_i + s * h_zz_r); } } template<typename VV, typename GV, typename GGV, typename GGGV> void assign_vghgh(const PointType& r, VV& psi, GV& dpsi, GGV& grad_grad_psi, GGGV& grad_grad_grad_psi, int first = 0, int last = -1) const { // protect last last = last < 0 ? kPoints.size() : (last > kPoints.size() ? kPoints.size() : last); const ST g00 = PrimLattice.G(0), g01 = PrimLattice.G(1), g02 = PrimLattice.G(2), g10 = PrimLattice.G(3), g11 = PrimLattice.G(4), g12 = PrimLattice.G(5), g20 = PrimLattice.G(6), g21 = PrimLattice.G(7), g22 = PrimLattice.G(8); const ST x = r[0], y = r[1], z = r[2]; const ST* restrict k0 = myKcart.data(0); const ST* restrict k1 = myKcart.data(1); const ST* restrict k2 = myKcart.data(2); const ST* restrict g0 = myG.data(0); const ST* restrict g1 = myG.data(1); const ST* restrict g2 = myG.data(2); const ST* restrict h00 = myH.data(0); const ST* restrict h01 = myH.data(1); const ST* restrict h02 = myH.data(2); const ST* restrict h11 = myH.data(3); const ST* restrict h12 = myH.data(4); const ST* restrict h22 = myH.data(5); const ST* restrict gh000 = mygH.data(0); const ST* restrict gh001 = mygH.data(1); const ST* restrict gh002 = mygH.data(2); const ST* restrict gh011 = mygH.data(3); const ST* restrict gh012 = mygH.data(4); const ST* restrict gh022 = mygH.data(5); const ST* restrict gh111 = mygH.data(6); const ST* restrict gh112 = mygH.data(7); const ST* restrict gh122 = mygH.data(8); const ST* restrict gh222 = mygH.data(9); //SIMD doesn't work quite right yet. Comment out until further debugging. #pragma omp simd for (size_t j = first; j < last; ++j) { int jr = j << 1; int ji = jr + 1; const ST kX = k0[j]; const ST kY = k1[j]; const ST kZ = k2[j]; const ST val_r = myV[jr]; const ST val_i = myV[ji]; //phase ST s, c; sincos(-(x * kX + y * kY + z * kZ), &s, &c); //dot(PrimLattice.G,myG[j]) const ST dX_r = g00 * g0[jr] + g01 * g1[jr] + g02 * g2[jr]; const ST dY_r = g10 * g0[jr] + g11 * g1[jr] + g12 * g2[jr]; const ST dZ_r = g20 * g0[jr] + g21 * g1[jr] + g22 * g2[jr]; const ST dX_i = g00 * g0[ji] + g01 * g1[ji] + g02 * g2[ji]; const ST dY_i = g10 * g0[ji] + g11 * g1[ji] + g12 * g2[ji]; const ST dZ_i = g20 * g0[ji] + g21 * g1[ji] + g22 * g2[ji]; // \f$\nabla \psi_r + {\bf k}\psi_i\f$ const ST gX_r = dX_r + val_i * kX; const ST gY_r = dY_r + val_i * kY; const ST gZ_r = dZ_r + val_i * kZ; const ST gX_i = dX_i - val_r * kX; const ST gY_i = dY_i - val_r * kY; const ST gZ_i = dZ_i - val_r * kZ; const size_t psiIndex = j + first_spo; psi[psiIndex] = ComplexT(c * val_r - s * val_i, c * val_i + s * val_r); dpsi[psiIndex][0] = ComplexT(c * gX_r - s * gX_i, c * gX_i + s * gX_r); dpsi[psiIndex][1] = ComplexT(c * gY_r - s * gY_i, c * gY_i + s * gY_r); dpsi[psiIndex][2] = ComplexT(c * gZ_r - s * gZ_i, c * gZ_i + s * gZ_r); //intermediates for computation of hessian. \partial_i \partial_j phi in cartesian coordinates. const ST f_xx_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g00, g01, g02); const ST f_xy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g10, g11, g12); const ST f_xz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g00, g01, g02, g20, g21, g22); const ST f_yy_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g10, g11, g12); const ST f_yz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g10, g11, g12, g20, g21, g22); const ST f_zz_r = v_m_v(h00[jr], h01[jr], h02[jr], h11[jr], h12[jr], h22[jr], g20, g21, g22, g20, g21, g22); const ST f_xx_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g00, g01, g02); const ST f_xy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g10, g11, g12); const ST f_xz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g00, g01, g02, g20, g21, g22); const ST f_yy_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g10, g11, g12); const ST f_yz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g10, g11, g12, g20, g21, g22); const ST f_zz_i = v_m_v(h00[ji], h01[ji], h02[ji], h11[ji], h12[ji], h22[ji], g20, g21, g22, g20, g21, g22); const ST h_xx_r = f_xx_r + 2 * kX * dX_i - kX * kX * val_r; const ST h_xy_r = f_xy_r + (kX * dY_i + kY * dX_i) - kX * kY * val_r; const ST h_xz_r = f_xz_r + (kX * dZ_i + kZ * dX_i) - kX * kZ * val_r; const ST h_yy_r = f_yy_r + 2 * kY * dY_i - kY * kY * val_r; const ST h_yz_r = f_yz_r + (kY * dZ_i + kZ * dY_i) - kY * kZ * val_r; const ST h_zz_r = f_zz_r + 2 * kZ * dZ_i - kZ * kZ * val_r; const ST h_xx_i = f_xx_i - 2 * kX * dX_r - kX * kX * val_i; const ST h_xy_i = f_xy_i - (kX * dY_r + kY * dX_r) - kX * kY * val_i; const ST h_xz_i = f_xz_i - (kX * dZ_r + kZ * dX_r) - kX * kZ * val_i; const ST h_yy_i = f_yy_i - 2 * kY * dY_r - kY * kY * val_i; const ST h_yz_i = f_yz_i - (kZ * dY_r + kY * dZ_r) - kZ * kY * val_i; const ST h_zz_i = f_zz_i - 2 * kZ * dZ_r - kZ * kZ * val_i; grad_grad_psi[psiIndex][0] = ComplexT(c * h_xx_r - s * h_xx_i, c * h_xx_i + s * h_xx_r); grad_grad_psi[psiIndex][1] = ComplexT(c * h_xy_r - s * h_xy_i, c * h_xy_i + s * h_xy_r); grad_grad_psi[psiIndex][2] = ComplexT(c * h_xz_r - s * h_xz_i, c * h_xz_i + s * h_xz_r); grad_grad_psi[psiIndex][3] = ComplexT(c * h_xy_r - s * h_xy_i, c * h_xy_i + s * h_xy_r); grad_grad_psi[psiIndex][4] = ComplexT(c * h_yy_r - s * h_yy_i, c * h_yy_i + s * h_yy_r); grad_grad_psi[psiIndex][5] = ComplexT(c * h_yz_r - s * h_yz_i, c * h_yz_i + s * h_yz_r); grad_grad_psi[psiIndex][6] = ComplexT(c * h_xz_r - s * h_xz_i, c * h_xz_i + s * h_xz_r); grad_grad_psi[psiIndex][7] = ComplexT(c * h_yz_r - s * h_yz_i, c * h_yz_i + s * h_yz_r); grad_grad_psi[psiIndex][8] = ComplexT(c * h_zz_r - s * h_zz_i, c * h_zz_i + s * h_zz_r); //These are the real and imaginary components of the third SPO derivative. _xxx denotes // third derivative w.r.t. x, _xyz, a derivative with resepect to x,y, and z, and so on. const ST f3_xxx_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g00, g01, g02); const ST f3_xxy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g10, g11, g12); const ST f3_xxz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g00, g01, g02, g20, g21, g22); const ST f3_xyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g10, g11, g12); const ST f3_xyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g10, g11, g12, g20, g21, g22); const ST f3_xzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g00, g01, g02, g20, g21, g22, g20, g21, g22); const ST f3_yyy_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g10, g11, g12); const ST f3_yyz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g10, g11, g12, g20, g21, g22); const ST f3_yzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g10, g11, g12, g20, g21, g22, g20, g21, g22); const ST f3_zzz_r = t3_contract(gh000[jr], gh001[jr], gh002[jr], gh011[jr], gh012[jr], gh022[jr], gh111[jr], gh112[jr], gh122[jr], gh222[jr], g20, g21, g22, g20, g21, g22, g20, g21, g22); const ST f3_xxx_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g00, g01, g02); const ST f3_xxy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g10, g11, g12); const ST f3_xxz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g00, g01, g02, g20, g21, g22); const ST f3_xyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g10, g11, g12); const ST f3_xyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g10, g11, g12, g20, g21, g22); const ST f3_xzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g00, g01, g02, g20, g21, g22, g20, g21, g22); const ST f3_yyy_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g10, g11, g12); const ST f3_yyz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g10, g11, g12, g20, g21, g22); const ST f3_yzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g10, g11, g12, g20, g21, g22, g20, g21, g22); const ST f3_zzz_i = t3_contract(gh000[ji], gh001[ji], gh002[ji], gh011[ji], gh012[ji], gh022[ji], gh111[ji], gh112[ji], gh122[ji], gh222[ji], g20, g21, g22, g20, g21, g22, g20, g21, g22); //Here is where we build up the components of the physical hessian gradient, namely, d^3/dx^3(e^{-ik*r}\phi(r) const ST gh_xxx_r = f3_xxx_r + 3 * kX * f_xx_i - 3 * kX * kX * dX_r - kX * kX * kX * val_i; const ST gh_xxx_i = f3_xxx_i - 3 * kX * f_xx_r - 3 * kX * kX * dX_i + kX * kX * kX * val_r; const ST gh_xxy_r = f3_xxy_r + (kY * f_xx_i + 2 * kX * f_xy_i) - (kX * kX * dY_r + 2 * kX * kY * dX_r) - kX * kX * kY * val_i; const ST gh_xxy_i = f3_xxy_i - (kY * f_xx_r + 2 * kX * f_xy_r) - (kX * kX * dY_i + 2 * kX * kY * dX_i) + kX * kX * kY * val_r; const ST gh_xxz_r = f3_xxz_r + (kZ * f_xx_i + 2 * kX * f_xz_i) - (kX * kX * dZ_r + 2 * kX * kZ * dX_r) - kX * kX * kZ * val_i; const ST gh_xxz_i = f3_xxz_i - (kZ * f_xx_r + 2 * kX * f_xz_r) - (kX * kX * dZ_i + 2 * kX * kZ * dX_i) + kX * kX * kZ * val_r; const ST gh_xyy_r = f3_xyy_r + (2 * kY * f_xy_i + kX * f_yy_i) - (2 * kX * kY * dY_r + kY * kY * dX_r) - kX * kY * kY * val_i; const ST gh_xyy_i = f3_xyy_i - (2 * kY * f_xy_r + kX * f_yy_r) - (2 * kX * kY * dY_i + kY * kY * dX_i) + kX * kY * kY * val_r; const ST gh_xyz_r = f3_xyz_r + (kX * f_yz_i + kY * f_xz_i + kZ * f_xy_i) - (kX * kY * dZ_r + kY * kZ * dX_r + kZ * kX * dY_r) - kX * kY * kZ * val_i; const ST gh_xyz_i = f3_xyz_i - (kX * f_yz_r + kY * f_xz_r + kZ * f_xy_r) - (kX * kY * dZ_i + kY * kZ * dX_i + kZ * kX * dY_i) + kX * kY * kZ * val_r; const ST gh_xzz_r = f3_xzz_r + (2 * kZ * f_xz_i + kX * f_zz_i) - (2 * kX * kZ * dZ_r + kZ * kZ * dX_r) - kX * kZ * kZ * val_i; const ST gh_xzz_i = f3_xzz_i - (2 * kZ * f_xz_r + kX * f_zz_r) - (2 * kX * kZ * dZ_i + kZ * kZ * dX_i) + kX * kZ * kZ * val_r; const ST gh_yyy_r = f3_yyy_r + 3 * kY * f_yy_i - 3 * kY * kY * dY_r - kY * kY * kY * val_i; const ST gh_yyy_i = f3_yyy_i - 3 * kY * f_yy_r - 3 * kY * kY * dY_i + kY * kY * kY * val_r; const ST gh_yyz_r = f3_yyz_r + (kZ * f_yy_i + 2 * kY * f_yz_i) - (kY * kY * dZ_r + 2 * kY * kZ * dY_r) - kY * kY * kZ * val_i; const ST gh_yyz_i = f3_yyz_i - (kZ * f_yy_r + 2 * kY * f_yz_r) - (kY * kY * dZ_i + 2 * kY * kZ * dY_i) + kY * kY * kZ * val_r; const ST gh_yzz_r = f3_yzz_r + (2 * kZ * f_yz_i + kY * f_zz_i) - (2 * kY * kZ * dZ_r + kZ * kZ * dY_r) - kY * kZ * kZ * val_i; const ST gh_yzz_i = f3_yzz_i - (2 * kZ * f_yz_r + kY * f_zz_r) - (2 * kY * kZ * dZ_i + kZ * kZ * dY_i) + kY * kZ * kZ * val_r; const ST gh_zzz_r = f3_zzz_r + 3 * kZ * f_zz_i - 3 * kZ * kZ * dZ_r - kZ * kZ * kZ * val_i; const ST gh_zzz_i = f3_zzz_i - 3 * kZ * f_zz_r - 3 * kZ * kZ * dZ_i + kZ * kZ * kZ * val_r; grad_grad_grad_psi[psiIndex][0][0] = ComplexT(c * gh_xxx_r - s * gh_xxx_i, c * gh_xxx_i + s * gh_xxx_r); grad_grad_grad_psi[psiIndex][0][1] = ComplexT(c * gh_xxy_r - s * gh_xxy_i, c * gh_xxy_i + s * gh_xxy_r); grad_grad_grad_psi[psiIndex][0][2] = ComplexT(c * gh_xxz_r - s * gh_xxz_i, c * gh_xxz_i + s * gh_xxz_r); grad_grad_grad_psi[psiIndex][0][3] = ComplexT(c * gh_xxy_r - s * gh_xxy_i, c * gh_xxy_i + s * gh_xxy_r); grad_grad_grad_psi[psiIndex][0][4] = ComplexT(c * gh_xyy_r - s * gh_xyy_i, c * gh_xyy_i + s * gh_xyy_r); grad_grad_grad_psi[psiIndex][0][5] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][0][6] = ComplexT(c * gh_xxz_r - s * gh_xxz_i, c * gh_xxz_i + s * gh_xxz_r); grad_grad_grad_psi[psiIndex][0][7] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][0][8] = ComplexT(c * gh_xzz_r - s * gh_xzz_i, c * gh_xzz_i + s * gh_xzz_r); grad_grad_grad_psi[psiIndex][1][0] = ComplexT(c * gh_xxy_r - s * gh_xxy_i, c * gh_xxy_i + s * gh_xxy_r); grad_grad_grad_psi[psiIndex][1][1] = ComplexT(c * gh_xyy_r - s * gh_xyy_i, c * gh_xyy_i + s * gh_xyy_r); grad_grad_grad_psi[psiIndex][1][2] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][1][3] = ComplexT(c * gh_xyy_r - s * gh_xyy_i, c * gh_xyy_i + s * gh_xyy_r); grad_grad_grad_psi[psiIndex][1][4] = ComplexT(c * gh_yyy_r - s * gh_yyy_i, c * gh_yyy_i + s * gh_yyy_r); grad_grad_grad_psi[psiIndex][1][5] = ComplexT(c * gh_yyz_r - s * gh_yyz_i, c * gh_yyz_i + s * gh_yyz_r); grad_grad_grad_psi[psiIndex][1][6] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][1][7] = ComplexT(c * gh_yyz_r - s * gh_yyz_i, c * gh_yyz_i + s * gh_yyz_r); grad_grad_grad_psi[psiIndex][1][8] = ComplexT(c * gh_yzz_r - s * gh_yzz_i, c * gh_yzz_i + s * gh_yzz_r); grad_grad_grad_psi[psiIndex][2][0] = ComplexT(c * gh_xxz_r - s * gh_xxz_i, c * gh_xxz_i + s * gh_xxz_r); grad_grad_grad_psi[psiIndex][2][1] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][2][2] = ComplexT(c * gh_xzz_r - s * gh_xzz_i, c * gh_xzz_i + s * gh_xzz_r); grad_grad_grad_psi[psiIndex][2][3] = ComplexT(c * gh_xyz_r - s * gh_xyz_i, c * gh_xyz_i + s * gh_xyz_r); grad_grad_grad_psi[psiIndex][2][4] = ComplexT(c * gh_yyz_r - s * gh_yyz_i, c * gh_yyz_i + s * gh_yyz_r); grad_grad_grad_psi[psiIndex][2][5] = ComplexT(c * gh_yzz_r - s * gh_yzz_i, c * gh_yzz_i + s * gh_yzz_r); grad_grad_grad_psi[psiIndex][2][6] = ComplexT(c * gh_xzz_r - s * gh_xzz_i, c * gh_xzz_i + s * gh_xzz_r); grad_grad_grad_psi[psiIndex][2][7] = ComplexT(c * gh_yzz_r - s * gh_yzz_i, c * gh_yzz_i + s * gh_yzz_r); grad_grad_grad_psi[psiIndex][2][8] = ComplexT(c * gh_zzz_r - s * gh_zzz_i, c * gh_zzz_i + s * gh_zzz_r); } } template<typename VV, typename GV, typename GGV> void evaluate_vgh(const ParticleSet& P, const int iat, VV& psi, GV& dpsi, GGV& grad_grad_psi) { const PointType& r = P.activeR(iat); PointType ru(PrimLattice.toUnit_floor(r)); #pragma omp parallel { int first, last; FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last); spline2::evaluate3d_vgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, first, last); assign_vgh(r, psi, dpsi, grad_grad_psi, first / 2, last / 2); } } template<typename VV, typename GV, typename GGV, typename GGGV> void evaluate_vghgh(const ParticleSet& P, const int iat, VV& psi, GV& dpsi, GGV& grad_grad_psi, GGGV& grad_grad_grad_psi) { const PointType& r = P.activeR(iat); PointType ru(PrimLattice.toUnit_floor(r)); #pragma omp parallel { int first, last; FairDivideAligned(myV.size(), getAlignment<ST>(), omp_get_num_threads(), omp_get_thread_num(), first, last); spline2::evaluate3d_vghgh(SplineInst->getSplinePtr(), ru, myV, myG, myH, mygH, first, last); assign_vghgh(r, psi, dpsi, grad_grad_psi, grad_grad_grad_psi, first / 2, last / 2); } } }; } // namespace qmcplusplus #endif
serial_tree_learner.h
/*! * Copyright (c) 2016 Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See LICENSE file in the project root for license information. */ #ifndef LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #define LIGHTGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_ #include <LightGBM/dataset.h> #include <LightGBM/tree.h> #include <LightGBM/tree_learner.h> #include <LightGBM/utils/array_args.h> #include <LightGBM/utils/json11.h> #include <LightGBM/utils/random.h> #include <string> #include <cmath> #include <cstdio> #include <memory> #include <random> #include <vector> #include "col_sampler.hpp" #include "data_partition.hpp" #include "feature_histogram.hpp" #include "leaf_splits.hpp" #include "monotone_constraints.hpp" #include "split_info.hpp" #ifdef USE_GPU // Use 4KBytes aligned allocator for ordered gradients and ordered hessians when GPU is enabled. // This is necessary to pin the two arrays in memory and make transferring faster. #include <boost/align/aligned_allocator.hpp> #endif namespace LightGBM { using json11::Json; /*! \brief forward declaration */ class CostEfficientGradientBoosting; /*! * \brief Used for learning a tree by single machine */ class SerialTreeLearner: public TreeLearner { public: friend CostEfficientGradientBoosting; explicit SerialTreeLearner(const Config* config); ~SerialTreeLearner(); void Init(const Dataset* train_data, bool is_constant_hessian) override; void ResetTrainingData(const Dataset* train_data, bool is_constant_hessian) override { ResetTrainingDataInner(train_data, is_constant_hessian, true); } void ResetIsConstantHessian(bool is_constant_hessian) override { share_state_->is_constant_hessian = is_constant_hessian; } virtual void ResetTrainingDataInner(const Dataset* train_data, bool is_constant_hessian, bool reset_multi_val_bin); void ResetConfig(const Config* config) override; inline void SetForcedSplit(const Json* forced_split_json) override { if (forced_split_json != nullptr && !forced_split_json->is_null()) { forced_split_json_ = forced_split_json; } else { forced_split_json_ = nullptr; } } Tree* Train(const score_t* gradients, const score_t *hessians) override; Tree* FitByExistingTree(const Tree* old_tree, const score_t* gradients, const score_t* hessians) const override; Tree* FitByExistingTree(const Tree* old_tree, const std::vector<int>& leaf_pred, const score_t* gradients, const score_t* hessians) override; void SetBaggingData(const Dataset* subset, const data_size_t* used_indices, data_size_t num_data) override { if (subset == nullptr) { data_partition_->SetUsedDataIndices(used_indices, num_data); share_state_->is_use_subrow = false; } else { ResetTrainingDataInner(subset, share_state_->is_constant_hessian, false); share_state_->is_use_subrow = true; share_state_->is_subrow_copied = false; share_state_->bagging_use_indices = used_indices; share_state_->bagging_indices_cnt = num_data; } } void AddPredictionToScore(const Tree* tree, double* out_score) const override { if (tree->num_leaves() <= 1) { return; } CHECK_LE(tree->num_leaves(), data_partition_->num_leaves()); #pragma omp parallel for schedule(static, 1) for (int i = 0; i < tree->num_leaves(); ++i) { double output = static_cast<double>(tree->LeafOutput(i)); data_size_t cnt_leaf_data = 0; auto tmp_idx = data_partition_->GetIndexOnLeaf(i, &cnt_leaf_data); for (data_size_t j = 0; j < cnt_leaf_data; ++j) { out_score[tmp_idx[j]] += output; } } } void RenewTreeOutput(Tree* tree, const ObjectiveFunction* obj, std::function<double(const label_t*, int)> residual_getter, data_size_t total_num_data, const data_size_t* bag_indices, data_size_t bag_cnt) const override; protected: void ComputeBestSplitForFeature(FeatureHistogram* histogram_array_, int feature_index, int real_fidx, bool is_feature_used, int num_data, const LeafSplits* leaf_splits, SplitInfo* best_split); void GetShareStates(const Dataset* dataset, bool is_constant_hessian, bool is_first_time); void RecomputeBestSplitForLeaf(int leaf, SplitInfo* split); /*! * \brief Some initial works before training */ virtual void BeforeTrain(); /*! * \brief Some initial works before FindBestSplit */ virtual bool BeforeFindBestSplit(const Tree* tree, int left_leaf, int right_leaf); virtual void FindBestSplits(const Tree* tree); virtual void ConstructHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract); virtual void FindBestSplitsFromHistograms(const std::vector<int8_t>& is_feature_used, bool use_subtract, const Tree*); /*! * \brief Partition tree and data according best split. * \param tree Current tree, will be splitted on this function. * \param best_leaf The index of leaf that will be splitted. * \param left_leaf The index of left leaf after splitted. * \param right_leaf The index of right leaf after splitted. */ inline virtual void Split(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf) { SplitInner(tree, best_leaf, left_leaf, right_leaf, true); } void SplitInner(Tree* tree, int best_leaf, int* left_leaf, int* right_leaf, bool update_cnt); /* Force splits with forced_split_json dict and then return num splits forced.*/ int32_t ForceSplits(Tree* tree, int* left_leaf, int* right_leaf, int* cur_depth); /*! * \brief Get the number of data in a leaf * \param leaf_idx The index of leaf * \return The number of data in the leaf_idx leaf */ inline virtual data_size_t GetGlobalDataCountInLeaf(int leaf_idx) const; /*! \brief number of data */ data_size_t num_data_; /*! \brief number of features */ int num_features_; /*! \brief training data */ const Dataset* train_data_; /*! \brief gradients of current iteration */ const score_t* gradients_; /*! \brief hessians of current iteration */ const score_t* hessians_; /*! \brief training data partition on leaves */ std::unique_ptr<DataPartition> data_partition_; /*! \brief pointer to histograms array of parent of current leaves */ FeatureHistogram* parent_leaf_histogram_array_; /*! \brief pointer to histograms array of smaller leaf */ FeatureHistogram* smaller_leaf_histogram_array_; /*! \brief pointer to histograms array of larger leaf */ FeatureHistogram* larger_leaf_histogram_array_; /*! \brief store best split points for all leaves */ std::vector<SplitInfo> best_split_per_leaf_; /*! \brief store best split per feature for all leaves */ std::vector<SplitInfo> splits_per_leaf_; /*! \brief stores minimum and maximum constraints for each leaf */ std::unique_ptr<LeafConstraintsBase> constraints_; /*! \brief stores best thresholds for all feature for smaller leaf */ std::unique_ptr<LeafSplits> smaller_leaf_splits_; /*! \brief stores best thresholds for all feature for larger leaf */ std::unique_ptr<LeafSplits> larger_leaf_splits_; #ifdef USE_GPU /*! \brief gradients of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized, aligned to 4K page */ std::vector<score_t, boost::alignment::aligned_allocator<score_t, 4096>> ordered_hessians_; #else /*! \brief gradients of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_gradients_; /*! \brief hessians of current iteration, ordered for cache optimized */ std::vector<score_t, Common::AlignmentAllocator<score_t, kAlignedSize>> ordered_hessians_; #endif /*! \brief used to cache historical histogram to speed up*/ HistogramPool histogram_pool_; /*! \brief config of tree learner*/ const Config* config_; ColSampler col_sampler_; const Json* forced_split_json_; std::unique_ptr<TrainingShareStates> share_state_; std::unique_ptr<CostEfficientGradientBoosting> cegb_; }; inline data_size_t SerialTreeLearner::GetGlobalDataCountInLeaf(int leaf_idx) const { if (leaf_idx >= 0) { return data_partition_->leaf_count(leaf_idx); } else { return 0; } } } // namespace LightGBM #endif // LightGBM_TREELEARNER_SERIAL_TREE_LEARNER_H_
knucleotide.c
// The Computer Language Benchmarks Game // http://benchmarksgame.alioth.debian.org/ // // Contributed by Jeremy Zerfas // This controls the maximum length for each set of oligonucleotide frequencies // and each oligonucleotide count output by this program. #define MAXIMUM_OUTPUT_LENGTH 4096 #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <khash.h> // Define a custom hash function to use instead of khash's default hash // function. This custom hash function uses a simpler bit shift and XOR which // results in several percent faster performance compared to when khash's // default hash function is used. #define CUSTOM_HASH_FUNCTION(key) ((key) ^ (key)>>7) KHASH_INIT(oligonucleotide, uint64_t, uint32_t, 1, CUSTOM_HASH_FUNCTION , kh_int64_hash_equal) // intptr_t should be the native integer type on most sane systems. typedef intptr_t intnative_t; typedef struct { uint64_t key; uint32_t value; } element; // Macro to convert a nucleotide character to a code. Note that upper and lower // case ASCII letters only differ in the fifth bit from the right and we only // need the three least significant bits to differentiate the letters 'A', 'C', // 'G', and 'T'. Spaces in this array/string will never be used as long as // characters other than 'A', 'C', 'G', and 'T' aren't used. #define code_For_Nucleotide(nucleotide) (" \0 \1\3 \2"[nucleotide & 0x7]) // And one more macro to convert the codes back to nucleotide characters. #define nucleotide_For_Code(code) ("ACGT"[code & 0x3]) // Function to use when sorting elements with qsort() later. Elements with // larger values will come first and in cases of identical values then elements // with smaller keys will come first. static int element_Compare(const element * const left_Element , const element * const right_Element){ // Sort based on element values. if(left_Element->value < right_Element->value) return 1; if(left_Element->value > right_Element->value) return -1; // If we got here then both items have the same value so then sort based on // key. return left_Element->key > right_Element->key ? 1 : -1; } // Generate frequencies for all oligonucleotides in polynucleotide that are of // desired_Length_For_Oligonucleotides and then save it to output. static void generate_Frequencies_For_Desired_Length_Oligonucleotides( const char * const polynucleotide, const intnative_t polynucleotide_Length , const intnative_t desired_Length_For_Oligonucleotides, char * const output){ khash_t(oligonucleotide) * hash_Table=kh_init(oligonucleotide); uint64_t key=0; const uint64_t mask=((uint64_t)1<<2*desired_Length_For_Oligonucleotides)-1; // For the first several nucleotides we only need to append them to key in // preparation for the insertion of complete oligonucleotides to hash_Table. for(intnative_t i=0; i<desired_Length_For_Oligonucleotides-1; i++) key=(key<<2 & mask) | polynucleotide[i]; // Add all the complete oligonucleotides of // desired_Length_For_Oligonucleotides to hash_Table and update the count // for each oligonucleotide. for(intnative_t i=desired_Length_For_Oligonucleotides-1 ; i<polynucleotide_Length; i++){ key=(key<<2 & mask) | polynucleotide[i]; int element_Was_Unused; const khiter_t k=kh_put(oligonucleotide, hash_Table, key , &element_Was_Unused); // If the element_Was_Unused, then initialize the count to 1, otherwise // increment the count. if(element_Was_Unused) kh_value(hash_Table, k)=1; else kh_value(hash_Table, k)++; } // Create an array of elements from hash_Table. intnative_t elements_Array_Size=kh_size(hash_Table), i=0; element * elements_Array=malloc(elements_Array_Size*sizeof(element)); uint32_t value; kh_foreach(hash_Table, key, value , elements_Array[i++]=((element){key, value})); kh_destroy(oligonucleotide, hash_Table); // Sort elements_Array. qsort(elements_Array, elements_Array_Size, sizeof(element) , (int (*)(const void *, const void *)) element_Compare); // Print the frequencies for each oligonucleotide. for(intnative_t output_Position=0, i=0; i<elements_Array_Size; i++){ // Convert the key for the oligonucleotide to a string. char oligonucleotide[desired_Length_For_Oligonucleotides+1]; for(intnative_t j=desired_Length_For_Oligonucleotides-1; j>-1; j--){ oligonucleotide[j]=nucleotide_For_Code(elements_Array[i].key); elements_Array[i].key>>=2; } oligonucleotide[desired_Length_For_Oligonucleotides]='\0'; // Output the frequency for oligonucleotide to output. output_Position+=snprintf(output+output_Position , MAXIMUM_OUTPUT_LENGTH-output_Position, "%s %.3f\n", oligonucleotide , 100.0f*elements_Array[i].value /(polynucleotide_Length-desired_Length_For_Oligonucleotides+1)); } free(elements_Array); } // Generate a count for the number of times oligonucleotide appears in // polynucleotide and then save it to output. static void generate_Count_For_Oligonucleotide( const char * const polynucleotide, const intnative_t polynucleotide_Length , const char * const oligonucleotide, char * const output){ const intnative_t oligonucleotide_Length=strlen(oligonucleotide); khash_t(oligonucleotide) * const hash_Table=kh_init(oligonucleotide); uint64_t key=0; const uint64_t mask=((uint64_t)1<<2*oligonucleotide_Length)-1; // For the first several nucleotides we only need to append them to key in // preparation for the insertion of complete oligonucleotides to hash_Table. for(intnative_t i=0; i<oligonucleotide_Length-1; i++) key=(key<<2 & mask) | polynucleotide[i]; // Add all the complete oligonucleotides of oligonucleotide_Length to // hash_Table and update the count for each oligonucleotide. for(intnative_t i=oligonucleotide_Length-1; i<polynucleotide_Length; i++){ key=(key<<2 & mask) | polynucleotide[i]; int element_Was_Unused; const khiter_t k=kh_put(oligonucleotide, hash_Table, key , &element_Was_Unused); // If the element_Was_Unused, then initialize the count to 1, otherwise // increment the count. if(element_Was_Unused) kh_value(hash_Table, k)=1; else kh_value(hash_Table, k)++; } // Generate the key for oligonucleotide. key=0; for(intnative_t i=0; i<oligonucleotide_Length; i++) key=(key<<2) | code_For_Nucleotide(oligonucleotide[i]); // Output the count for oligonucleotide to output. khiter_t k=kh_get(oligonucleotide, hash_Table, key); uintmax_t count=k==kh_end(hash_Table) ? 0 : kh_value(hash_Table, k); snprintf(output, MAXIMUM_OUTPUT_LENGTH, "%ju\t%s", count, oligonucleotide); kh_destroy(oligonucleotide, hash_Table); } int main(){ char buffer[4096]; // Find the start of the third polynucleotide. while(fgets(buffer, sizeof(buffer), stdin) && memcmp(">THREE", buffer , sizeof(">THREE")-1)); // Start with 1 MB of storage for reading in the polynucleotide and grow // geometrically. intnative_t polynucleotide_Capacity=1048576; intnative_t polynucleotide_Length=0; char * polynucleotide=malloc(polynucleotide_Capacity); // Start reading and encoding the third polynucleotide. while(fgets(buffer, sizeof(buffer), stdin) && buffer[0]!='>'){ for(intnative_t i=0; buffer[i]!='\0'; i++) if(buffer[i]!='\n') polynucleotide[polynucleotide_Length++] =code_For_Nucleotide(buffer[i]); // Make sure we still have enough memory allocated for any potential // nucleotides in the next line. if(polynucleotide_Capacity-polynucleotide_Length<sizeof(buffer)) polynucleotide=realloc(polynucleotide, polynucleotide_Capacity*=2); } // Free up any leftover memory. polynucleotide=realloc(polynucleotide, polynucleotide_Length); char output_Buffer[7][MAXIMUM_OUTPUT_LENGTH]; // Do the following functions in parallel. #pragma omp parallel sections { #pragma omp section generate_Count_For_Oligonucleotide(polynucleotide , polynucleotide_Length, "GGTATTTTAATTTATAGT", output_Buffer[6]); #pragma omp section generate_Count_For_Oligonucleotide(polynucleotide , polynucleotide_Length, "GGTATTTTAATT", output_Buffer[5]); #pragma omp section generate_Count_For_Oligonucleotide(polynucleotide , polynucleotide_Length, "GGTATT", output_Buffer[4]); #pragma omp section generate_Count_For_Oligonucleotide(polynucleotide , polynucleotide_Length, "GGTA", output_Buffer[3]); #pragma omp section generate_Count_For_Oligonucleotide(polynucleotide , polynucleotide_Length, "GGT", output_Buffer[2]); #pragma omp section generate_Frequencies_For_Desired_Length_Oligonucleotides(polynucleotide , polynucleotide_Length, 2, output_Buffer[1]); #pragma omp section generate_Frequencies_For_Desired_Length_Oligonucleotides(polynucleotide , polynucleotide_Length, 1, output_Buffer[0]); } // Output the results to stdout. for(intnative_t i=0; i<7; printf("%s\n", output_Buffer[i++])); free(polynucleotide); return 0; } /* NOTES: 64-bit Ubuntu quad core gcc (Ubuntu 6.3.0-12ubuntu2) 6.3.0 20170406 Fri, 14 Apr 2017 17:26:27 GMT MAKE: /usr/bin/gcc -pipe -Wall -O3 -fomit-frame-pointer -march=native -fopenmp -std=c99 -IInclude knucleotide.c -o knucleotide.gcc_run rm knucleotide.c 0.41s to complete and log all make actions COMMAND LINE: ./knucleotide.gcc_run 0 < knucleotide-input25000000.txt PROGRAM OUTPUT: A 30.295 T 30.151 C 19.800 G 19.754 AA 9.177 TA 9.132 AT 9.131 TT 9.091 CA 6.002 AC 6.001 AG 5.987 GA 5.984 CT 5.971 TC 5.971 GT 5.957 TG 5.956 CC 3.917 GC 3.911 CG 3.909 GG 3.902 1471758 GGT 446535 GGTA 47336 GGTATT 893 GGTATTTTAATT 893 GGTATTTTAATTTATAGT */
teams_host.c
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <omp.h> #define N 128 #define THRESHOLD 127 int main() { static float x[N],y[N] __attribute__ ((aligned(64))); float s=2.0; int return_code = 0 ; /// How can we set number of teams to number numa domains and what is the mapping? #pragma omp teams num_teams(32) { printf("teams:%d num_teams%d threads:%d ishost:%d\n",omp_get_num_teams(), omp_get_team_num(), omp_get_num_threads(), omp_is_initial_device()); } return 0; }
filterCutoutOMP.c
/* * Copyright 2014 NeuroData (http://neurodata.io) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include<stdio.h> #include<stdint.h> #include<omp.h> #include<stdbool.h> void filterCutoutOMP32 ( uint32_t * cutout, int cutoutsize, uint32_t * filterlist, int listsize) { int i,j; bool equal; //printf("MAX THREADS: %d",omp_get_max_threads()); #pragma omp parallel num_threads(omp_get_max_threads()) { #pragma omp for private(i,j,equal) schedule(dynamic) for ( i=0; i<cutoutsize; i++) { equal = false; for( j=0; j<listsize; j++) { if( cutout[i] == filterlist[j] ) { equal = true; break; } } if( !equal || cutout[i] > filterlist[j] ) cutout[i] = 0; } int ID = omp_get_thread_num(); //printf("THREAD ID: %d",ID); } } void filterCutoutOMP64 ( uint64_t * cutout, int cutoutsize, uint64_t * filterlist, int listsize) { int i,j; bool equal; //printf("MAX THREADS: %d",omp_get_max_threads()); #pragma omp parallel num_threads(omp_get_max_threads()) { #pragma omp for private(i,j,equal) schedule(dynamic) for ( i=0; i<cutoutsize; i++) { equal = false; for( j=0; j<listsize; j++) { if( cutout[i] == filterlist[j] ) { equal = true; break; } } if( !equal || cutout[i] > filterlist[j] ) cutout[i] = 0; } int ID = omp_get_thread_num(); //printf("THREAD ID: %d",ID); } }
GB_binop__lxor_fp64.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_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__lxor_fp64 // A.*B function (eWiseMult): GB_AemultB__lxor_fp64 // A*D function (colscale): GB_AxD__lxor_fp64 // D*A function (rowscale): GB_DxB__lxor_fp64 // C+=B function (dense accum): GB_Cdense_accumB__lxor_fp64 // C+=b function (dense accum): GB_Cdense_accumb__lxor_fp64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__lxor_fp64 // C=scalar+B GB_bind1st__lxor_fp64 // C=scalar+B' GB_bind1st_tran__lxor_fp64 // C=A+scalar GB_bind2nd__lxor_fp64 // C=A'+scalar GB_bind2nd_tran__lxor_fp64 // C type: double // A type: double // B,b type: double // BinaryOp: cij = ((aij != 0) != (bij != 0)) #define GB_ATYPE \ double #define GB_BTYPE \ double #define GB_CTYPE \ double // 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) \ double aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ double bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ double t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = ((x != 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_LXOR || GxB_NO_FP64 || GxB_NO_LXOR_FP64) //------------------------------------------------------------------------------ // 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__lxor_fp64 ( 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__lxor_fp64 ( 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__lxor_fp64 ( 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 double double bwork = (*((double *) 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__lxor_fp64 ( 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 double *GB_RESTRICT Cx = (double *) 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__lxor_fp64 ( 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 double *GB_RESTRICT Cx = (double *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ #undef GB_FREE_ALL #define GB_FREE_ALL \ { \ GB_ek_slice_free (&pstart_Mslice, &kfirst_Mslice, &klast_Mslice) ; \ GB_ek_slice_free (&pstart_Aslice, &kfirst_Aslice, &klast_Aslice) ; \ GB_ek_slice_free (&pstart_Bslice, &kfirst_Bslice, &klast_Bslice) ; \ } GrB_Info GB_AaddB__lxor_fp64 ( 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 *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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_add_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB_AemultB__lxor_fp64 ( 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 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 C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t *pstart_Mslice = NULL, *kfirst_Mslice = NULL, *klast_Mslice = NULL ; int64_t *pstart_Aslice = NULL, *kfirst_Aslice = NULL, *klast_Aslice = NULL ; int64_t *pstart_Bslice = NULL, *kfirst_Bslice = NULL, *klast_Bslice = NULL ; #include "GB_emult_template.c" GB_FREE_ALL ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB_bind1st__lxor_fp64 ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *GB_RESTRICT Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double *Cx = (double *) Cx_output ; double x = (*((double *) x_input)) ; double *Bx = (double *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; double 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__lxor_fp64 ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *GB_RESTRICT Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; double *Cx = (double *) Cx_output ; double *Ax = (double *) Ax_input ; double y = (*((double *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; double 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 typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ double aij = Ax [pA] ; \ Cx [pC] = ((x != 0) != (aij != 0)) ; \ } GrB_Info GB_bind1st_tran__lxor_fp64 ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_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 \ double #if GB_DISABLE return (GrB_NO_VALUE) ; #else double x = (*((const double *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ double } //------------------------------------------------------------------------------ // 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) \ { \ double aij = Ax [pA] ; \ Cx [pC] = ((aij != 0) != (y != 0)) ; \ } GrB_Info GB_bind2nd_tran__lxor_fp64 ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *GB_RESTRICT *Workspaces, const int64_t *GB_RESTRICT A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else double y = (*((const double *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_uint16_bool.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__identity_uint16_bool) // op(A') function: GB (_unop_tran__identity_uint16_bool) // C type: uint16_t // A type: bool // cast: uint16_t cij = (uint16_t) aij // unaryop: cij = aij #define GB_ATYPE \ bool #define GB_CTYPE \ uint16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ bool aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint16_t z = (uint16_t) aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ bool aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint16_t z = (uint16_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_UINT16 || GxB_NO_BOOL) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint16_bool) ( uint16_t *Cx, // Cx and Ax may be aliased const bool *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++) { bool aij = Ax [p] ; uint16_t z = (uint16_t) aij ; Cx [p] = 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 ; bool aij = Ax [p] ; uint16_t z = (uint16_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_uint16_bool) ( 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