source
stringlengths
3
92
c
stringlengths
26
2.25M
GB_unop__ainv_fc64_fc64.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__ainv_fc64_fc64) // op(A') function: GB (_unop_tran__ainv_fc64_fc64) // C type: GxB_FC64_t // A type: GxB_FC64_t // cast: GxB_FC64_t cij = aij // unaryop: cij = GB_FC64_ainv (aij) #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = GB_FC64_ainv (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC64_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC64_t z = aij ; \ Cx [pC] = GB_FC64_ainv (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_AINV || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__ainv_fc64_fc64) ( GxB_FC64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_FC64_ainv (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; GxB_FC64_t z = aij ; Cx [p] = GB_FC64_ainv (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__ainv_fc64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
piCalc.c
#include <stdio.h> #include <omp.h> #include <stdlib.h> #include <math.h> #define MARGIN 1e-12 void Usage(char* prog_name); int sequential(long long points); int noWorkshare(long long points); int glob_sum_seq; int glob_sum_par; int main(){ printf("\n\n1000000 points"); printf("\nSEQUENTIAL\n"); sequential(1000000); printf("\nPARALLEL\n"); noWorkshare(1000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n10000000 points"); printf("\nSEQUENTIAL\n"); sequential(10000000); printf("\nPARALLEL\n"); noWorkshare(10000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n100000000 points"); printf("\nSEQUENTIAL\n"); sequential(100000000); printf("\nPARALLEL\n"); noWorkshare(100000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n1000000000 points"); printf("\nSEQUENTIAL\n"); sequential(1000000000); printf("\nPARALLEL\n"); noWorkshare(1000000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); printf("\n\n10000000000 points"); printf("\nSEQUENTIAL\n"); sequential(10000000000); printf("\nPARALLEL\n"); noWorkshare(10000000000); if(abs(glob_sum_seq - glob_sum_par) <= MARGIN) printf("\nTest PASSED \n"); else printf("\nTest FAILED \n"); } int sequential(long long points) { long long n,i,nthreads,myid; double factor; double sum = 0.0; n = points; double timeStart = omp_get_wtime(); printf("Before for loop, factor = %f.\n", factor); for (i = 0; i < n; i++) { factor = (i % 2 == 0) ? 1.0 : -1.0; sum += factor/(2*i+1); } printf("After for loop, factor = %f.\n", factor); sum = 4.0*sum; printf("With n = %lld terms\n", n); printf(" Our estimate of pi = %.14f\n", sum); printf(" Ref estimate of pi = %.14f\n", 4.0*atan(1.0)); double timeStop = omp_get_wtime(); printf("Elapsed time: %f", timeStop - timeStart); glob_sum_seq = sum; return 0; } int noWorkshare(long long points) { long long n,i,nthreads,myid; double factor; double sum = 0.0; n = points; double timeStart = omp_get_wtime(); printf("Before for loop, factor = %f.\n", factor); #pragma omp parallel \ default(none)\ private(i, myid, factor)\ shared(n, nthreads)\ reduction(+:sum) { nthreads = omp_get_num_threads(); myid = omp_get_thread_num(); for (i = myid; i < n; i+=nthreads) { factor = (i % 2 == 0) ? 1.0 : -1.0; sum += factor/(2*i+1); } } printf("After for loop, factor = %f.\n", factor); sum = 4.0*sum; printf("With n = %lld terms\n", n); printf(" Our estimate of pi = %.14f\n", sum); printf(" Ref estimate of pi = %.14f\n", 4.0*atan(1.0)); double timeStop = omp_get_wtime(); printf("Elapsed time: %f", timeStop - timeStart); glob_sum_par = sum; return 0; } void Usage(char* prog_name) { fprintf(stderr, "usage: %s <thread_count> <n>\n", prog_name); fprintf(stderr, " n is the number of terms and should be >= 1\n"); exit(0); }
parallelfor.c
#include <omp.h> #define N 10 int main (int argc, char *argv[]) { double a[N], b[N]; int i, sum; // This omp construct is completely eliminated /* #pragma omp parallel for for (i=0; i < N-1; i++) b[i+1] = a[i+1] + 2*i; */ // These nested omp constructs are completely eliminated #pragma omp parallel { #pragma omp for for (i=0; i < N-1; i++) b[i+1] = a[i+1] + 2*i; } /* #pragma omp parallel for for (i=0; i < N; i++) { a[i] = 0.0; b[i] = a[i]; b[i] = a[i] + b[i]; } #pragma omp parallel for for (i=0; i < N-1; i++) a[i+1] = a[1+i] + 1; //a[i+2-1] = a[(-2*3) + 2*i - i + 7] + 1; #pragma omp parallel for private(sum) for (i=0; i < N; i++) sum = sum + i; #pragma omp parallel for for (i=0; i < N; i++) sum = sum + i; */ }
GB_binop__isge_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 Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__isge_uint64) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__isge_uint64) // A.*B function (eWiseMult): GB (_AemultB_03__isge_uint64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_uint64) // A*D function (colscale): GB (_AxD__isge_uint64) // D*A function (rowscale): GB (_DxB__isge_uint64) // C+=B function (dense accum): GB (_Cdense_accumB__isge_uint64) // C+=b function (dense accum): GB (_Cdense_accumb__isge_uint64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_uint64) // C=scalar+B GB (_bind1st__isge_uint64) // C=scalar+B' GB (_bind1st_tran__isge_uint64) // C=A+scalar GB (_bind2nd__isge_uint64) // C=A'+scalar GB (_bind2nd_tran__isge_uint64) // C type: uint64_t // A type: uint64_t // B,b type: uint64_t // BinaryOp: cij = (aij >= bij) #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) \ uint64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint64_t bij = Bx [pB] // 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) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISGE || GxB_NO_UINT64 || GxB_NO_ISGE_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__isge_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__isge_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__isge_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 //------------------------------------------------------------------------------ GrB_Info GB (_AxD__isge_uint64) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isge_uint64) ( 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_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_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 or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__isge_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_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__isge_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_03__isge_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_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__isge_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__isge_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 anz, 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; uint64_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__isge_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 = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint64_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__isge_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 = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__isge_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
SpatialAveragePooling.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialAveragePooling.c" #else static inline void THNN_(SpatialAveragePooling_shapeCheck)( THTensor *input, THTensor *gradOutput, int kH, int kW, int dH, int dW, int padH, int padW, bool ceil_mode) { THArgCheck(kW > 0 && kH > 0, 5, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); THArgCheck(dW > 0 && dH > 0, 8, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); int ndim = input->dim(); int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } THNN_ARGCHECK(!input->is_empty() && (ndim == 3 || ndim == 4), 2, input, "non-empty 3D or 4D input tensor expected but got: %s"); THArgCheck(kW/2 >= padW && kH/2 >= padH, 2, "pad should be smaller than half of kernel size, but got " "padW = %d, padH = %d, kW = %d, kH = %d", padW, padH, kW, kH); int64_t nInputPlane = input->size(dimh-1); int64_t inputHeight = input->size(dimh); int64_t inputWidth = input->size(dimw); int64_t outputHeight, outputWidth; int64_t nOutputPlane = nInputPlane; if(ceil_mode) { outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1; outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1; } else { outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1; outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1; } if (padW || padH) { // ensure that the last pooling starts inside the image // needed to avoid problems in ceil mode if ((outputHeight - 1)*dH >= inputHeight + padH) --outputHeight; if ((outputWidth - 1)*dW >= inputWidth + padW) --outputWidth; } if (outputWidth < 1 || outputHeight < 1) THError("Given input size: (%dx%dx%d). " "Calculated output size: (%dx%dx%d). Output size is too small", nInputPlane,inputHeight,inputWidth,nInputPlane,outputHeight,outputWidth); if (gradOutput != NULL) { THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimf, nOutputPlane); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); } } void THNN_(SpatialAveragePooling_updateOutput)( THNNState *state, THTensor *input, THTensor *output, int kW, int kH, int dW, int dH, int padW, int padH, bool ceil_mode, bool count_include_pad) { real *output_data; real *input_data; int dimw = 2; int dimh = 1; int dimc = 0; int64_t nbatch = 1; int64_t inputWidth; int64_t inputHeight; int64_t outputWidth; int64_t outputHeight; int64_t nInputPlane; // number of channels (or colors) int64_t k; THNN_(SpatialAveragePooling_shapeCheck) (input, NULL, kH, kW, dH, dW, padH, padW, ceil_mode); if (input->dim() == 4) { nbatch = input->size(0); dimw++; dimh++; dimc++; } inputWidth = input->size(dimw); inputHeight = input->size(dimh); nInputPlane = input->size(dimc); if(ceil_mode) { outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1; outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1; } else { outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1; outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1; } if (padW || padH) { // ensure that the last pooling starts inside the image // needed to avoid problems in ceil mode if ((outputHeight - 1)*dH >= inputHeight + padH) --outputHeight; if ((outputWidth - 1)*dW >= inputWidth + padW) --outputWidth; } if (input->dim() == 3) THTensor_(resize3d)(output, nInputPlane, outputHeight, outputWidth); else THTensor_(resize4d)(output, input->size(0), nInputPlane, outputHeight, outputWidth); input = THTensor_(newContiguous)(input); THArgCheck(THTensor_(isContiguous)(output), 3, "output must be contiguous"); input_data = THTensor_(data)(input); output_data = THTensor_(data)(output); #pragma omp parallel for private(k) for(k = 0; k < nInputPlane; k++) { int64_t p; for(p = 0; p < nbatch; p++) { int64_t xx, yy; /* For all output pixels... */ real *ptr_output = output_data + p*nInputPlane*outputWidth*outputHeight + k*outputWidth*outputHeight; real *ptr_input = input_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; int64_t i; for(i = 0; i < outputWidth*outputHeight; i++) ptr_output[i] = 0; for(yy = 0; yy < outputHeight; yy++) { for(xx = 0; xx < outputWidth; xx++) { /* Compute the mean of the input image... */ int64_t hstart = yy * dH - padH; int64_t wstart = xx * dW - padW; int64_t hend = fminf(hstart + kH, inputHeight + padH); int64_t wend = fminf(wstart + kW, inputWidth + padW); int pool_size = (hend - hstart) * (wend - wstart); hstart = fmaxf(hstart, 0); wstart = fmaxf(wstart, 0); hend = fminf(hend, inputHeight); wend = fminf(wend, inputWidth); real sum = 0; int divide_factor; if(count_include_pad) divide_factor = pool_size; else divide_factor = (hend - hstart) * (wend - wstart); int64_t kx, ky; for(ky = hstart; ky < hend; ky++) { for(kx = wstart; kx < wend; kx++) sum += ptr_input[ky*inputWidth + kx]; } /* Update output */ *ptr_output++ += sum/divide_factor; } } } } THTensor_(free)(input); } void THNN_(SpatialAveragePooling_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, int kW, int kH, int dW, int dH, int padW, int padH, bool ceil_mode, bool count_include_pad) { int dimw = 2; int dimh = 1; int dimc = 0; int64_t nbatch = 1; int64_t ndim = 3; int64_t inputWidth; int64_t inputHeight; int64_t outputWidth; int64_t outputHeight; int64_t nInputPlane; // number of channels (or colors) real *gradOutput_data; real *gradInput_data; int64_t k; THNN_(SpatialAveragePooling_shapeCheck) (input, gradOutput, kH, kW, dH, dW, padH, padW, ceil_mode); if (input->dim() == 4) { nbatch = input->size(0); dimw++; dimh++; dimc++; ndim = 4; } inputWidth = input->size(dimw); inputHeight = input->size(dimh); nInputPlane = input->size(dimc); if(ceil_mode) { outputWidth = (int64_t)(ceil((float)(inputWidth - kW + 2*padW) / dW)) + 1; outputHeight = (int64_t)(ceil((float)(inputHeight - kH + 2*padH) / dH)) + 1; } else { outputWidth = (int64_t)(floor((float)(inputWidth - kW + 2*padW) / dW)) + 1; outputHeight = (int64_t)(floor((float)(inputHeight - kH + 2*padH) / dH)) + 1; } if (padW || padH) { // ensure that the last pooling starts inside the image // needed to avoid problems in ceil mode if ((outputHeight - 1)*dH >= inputHeight + padH) --outputHeight; if ((outputWidth - 1)*dW >= inputWidth + padW) --outputWidth; } THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); THTensor_(resizeAs)(gradInput, input); gradOutput = THTensor_(newContiguous)(gradOutput); THArgCheck(THTensor_(isContiguous)(gradInput), 4, "gradInput must be contiguous"); gradInput_data = THTensor_(data)(gradInput); gradOutput_data = THTensor_(data)(gradOutput); #pragma omp parallel for private(k) for(k = 0; k < nInputPlane; k++) { int64_t p; for(p = 0; p < nbatch; p++) { real *ptr_gradOutput = gradOutput_data + p*nInputPlane*outputHeight*outputWidth + k*outputWidth*outputHeight; int64_t xx, yy; real* ptr_gi = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; real *ptr_gradInput = gradInput_data + p*nInputPlane*inputWidth*inputHeight + k*inputWidth*inputHeight; int64_t i; for(i=0; i<inputWidth*inputHeight; i++) ptr_gi[i] = 0.0; for(yy = 0; yy < outputHeight; yy++) { for(xx = 0; xx < outputWidth; xx++) { int64_t hstart = yy * dH - padH; int64_t wstart = xx * dW - padW; int64_t hend = fminf(hstart + kH, inputHeight + padH); int64_t wend = fminf(wstart + kW, inputWidth + padW); int pool_size = (hend - hstart) * (wend - wstart); hstart = fmaxf(hstart, 0); wstart = fmaxf(wstart, 0); hend = fminf(hend, inputHeight); wend = fminf(wend, inputWidth); real z = *ptr_gradOutput++; int divide_factor; if(count_include_pad) divide_factor = pool_size; else divide_factor = (hend - hstart) * (wend - wstart); int64_t kx, ky; for(ky = hstart ; ky < hend; ky++) { for(kx = wstart; kx < wend; kx++) ptr_gradInput[ky*inputWidth + kx] += z/divide_factor; } } } } } THTensor_(free)(gradOutput); } #endif
convolution_3x3.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // 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 conv3x3s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 2; Mat out0 = top_blob.channel(p); Mat out1 = top_blob.channel(p+1); const float bias0 = bias ? bias[p] : 0.f; const float bias1 = bias ? bias[p+1] : 0.f; out0.fill(bias0); out1.fill(bias1); const float* k0 = kernel + p*inch*9; const float* k1 = kernel + (p+1)*inch*9; for (int q=0; q<inch; q++) { float* outptr0 = out0; float* outptr1 = out1; float* outptr0n = outptr0 + outw; float* outptr1n = outptr1 + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; #if __ARM_NEON float32x4_t _k00 = vld1q_f32(k0); float32x4_t _k03 = vld1q_f32(k0+3); float32x4_t _k06 = vld1q_f32(k0+6); float32x4_t _k10 = vld1q_f32(k1); float32x4_t _k13 = vld1q_f32(k1+3); float32x4_t _k16 = vld1q_f32(k1+6); #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum0 = vld1q_f32(outptr0); float32x4_t _sum1 = vld1q_f32(outptr1); float32x4_t _sum0n = vld1q_f32(outptr0n); float32x4_t _sum1n = vld1q_f32(outptr1n); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r00, _k00, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r01, _k00, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r02, _k00, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r10, _k03, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r11, _k03, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r12, _k03, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r20, _k06, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r21, _k06, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r22, _k06, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k10, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r01, _k10, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k10, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r10, _k13, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k13, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r12, _k13, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k16, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r21, _k16, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k16, 2); _sum0n = vfmaq_laneq_f32(_sum0n, _r10, _k00, 0); _sum0n = vfmaq_laneq_f32(_sum0n, _r11, _k00, 1); _sum0n = vfmaq_laneq_f32(_sum0n, _r12, _k00, 2); _sum0n = vfmaq_laneq_f32(_sum0n, _r20, _k03, 0); _sum0n = vfmaq_laneq_f32(_sum0n, _r21, _k03, 1); _sum0n = vfmaq_laneq_f32(_sum0n, _r22, _k03, 2); _sum0n = vfmaq_laneq_f32(_sum0n, _r30, _k06, 0); _sum0n = vfmaq_laneq_f32(_sum0n, _r31, _k06, 1); _sum0n = vfmaq_laneq_f32(_sum0n, _r32, _k06, 2); _sum1n = vfmaq_laneq_f32(_sum1n, _r10, _k10, 0); _sum1n = vfmaq_laneq_f32(_sum1n, _r11, _k10, 1); _sum1n = vfmaq_laneq_f32(_sum1n, _r12, _k10, 2); _sum1n = vfmaq_laneq_f32(_sum1n, _r20, _k13, 0); _sum1n = vfmaq_laneq_f32(_sum1n, _r21, _k13, 1); _sum1n = vfmaq_laneq_f32(_sum1n, _r22, _k13, 2); _sum1n = vfmaq_laneq_f32(_sum1n, _r30, _k16, 0); _sum1n = vfmaq_laneq_f32(_sum1n, _r31, _k16, 1); _sum1n = vfmaq_laneq_f32(_sum1n, _r32, _k16, 2); vst1q_f32(outptr0, _sum0); vst1q_f32(outptr1, _sum1); vst1q_f32(outptr0n, _sum0n); vst1q_f32(outptr1n, _sum1n); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr0 += 4; outptr1 += 4; outptr0n += 4; outptr1n += 4; } #else if (nn > 0) { asm volatile( "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5 :64] \n"// r0 "add %5, #16 \n" "pld [%8, #192] \n" "vld1.f32 {d28-d31}, [%8] \n"// r3 "add %8, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q14, q15, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1 :64] \n"// _sum0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2 :64] \n"// _sum1 "vmla.f32 q6, q8, %e18[0] \n" "vmla.f32 q7, q8, %e21[0] \n" "pld [%3, #128] \n" "vld1.f32 {d24-d25}, [%3] \n"// _sum0n "pld [%4, #128] \n" "vld1.f32 {d26-d27}, [%4] \n"// _sum1n "vmla.f32 q12, q14, %e20[0] \n" "vmla.f32 q13, q14, %e23[0] \n" "vext.32 q8, q8, q9, #2 \n" "vext.32 q9, q14, q15, #1 \n" "vmla.f32 q6, q10, %e18[1] \n" "vmla.f32 q7, q10, %e21[1] \n" "vmla.f32 q12, q11, %f20[0] \n" "vmla.f32 q13, q11, %f23[0] \n" "pld [%6, #192] \n" "vld1.f32 {d28-d31}, [%6] \n"// r1 "add %6, #16 \n" "vmla.f32 q6, q8, %f18[0] \n" "vmla.f32 q7, q8, %f21[0] \n" "vmla.f32 q12, q9, %e20[1] \n" "vmla.f32 q13, q9, %e23[1] \n" "vext.32 q10, q14, q15, #1 \n" "vmla.f32 q6, q14, %e19[0] \n" "vmla.f32 q7, q14, %e22[0] \n" "vmla.f32 q12, q14, %e18[0] \n" "vmla.f32 q13, q14, %e21[0] \n" "vext.32 q11, q14, q15, #2 \n" "vmla.f32 q6, q10, %e19[1] \n" "vmla.f32 q7, q10, %e22[1] \n" "vmla.f32 q12, q10, %e18[1] \n" "vmla.f32 q13, q10, %e21[1] \n" "pld [%7, #192] \n" "vld1.f32 {d16-d18}, [%7 :64] \n"// r2 "add %7, #16 \n" "vmla.f32 q6, q11, %f19[0] \n" "vmla.f32 q7, q11, %f22[0] \n" "vmla.f32 q12, q11, %f18[0] \n" "vmla.f32 q13, q11, %f21[0] \n" "vext.32 q10, q8, q9, #1 \n" "vmla.f32 q6, q8, %e20[0] \n" "vmla.f32 q7, q8, %e23[0] \n" "vmla.f32 q12, q8, %e19[0] \n" "vmla.f32 q13, q8, %e22[0] \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e20[1] \n" "vmla.f32 q7, q10, %e23[1] \n" "vmla.f32 q12, q10, %e19[1] \n" "vmla.f32 q13, q10, %e22[1] \n" "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5 :64] \n"// r0 "add %5, #16 \n" "vmla.f32 q6, q11, %f20[0] \n" "vmla.f32 q7, q11, %f23[0] \n" "vmla.f32 q12, q11, %f19[0] \n" "vmla.f32 q13, q11, %f22[0] \n" "pld [%8, #192] \n" "vld1.f32 {d28-d31}, [%8] \n"// r3 "add %8, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vst1.f32 {d12-d13}, [%1 : 64]!\n" "vst1.f32 {d14-d15}, [%2 : 64]!\n" "vext.32 q11, q14, q15, #2 \n" "vst1.f32 {d24-d25}, [%3]! \n" "vst1.f32 {d26-d27}, [%4]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %5, #16 \n" "sub %8, #16 \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(outptr0n), // %3 "=r"(outptr1n), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(outptr0n), "4"(outptr1n), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k00), // %18 "w"(_k03), // %19 "w"(_k06), // %20 "w"(_k10), // %21 "w"(_k13), // %22 "w"(_k16) // %23 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum0 = vmulq_f32(_r00, _k00); float32x4_t _sum1 = vmulq_f32(_r00, _k10); _sum0 = vmlaq_f32(_sum0, _r10, _k03); _sum1 = vmlaq_f32(_sum1, _r10, _k13); _sum0 = vmlaq_f32(_sum0, _r20, _k06); _sum1 = vmlaq_f32(_sum1, _r20, _k16); float32x4_t _sum0n = vmulq_f32(_r10, _k00); float32x4_t _sum1n = vmulq_f32(_r10, _k10); _sum0n = vmlaq_f32(_sum0n, _r20, _k03); _sum1n = vmlaq_f32(_sum1n, _r20, _k13); _sum0n = vmlaq_f32(_sum0n, _r30, _k06); _sum1n = vmlaq_f32(_sum1n, _r30, _k16); _sum0 = vsetq_lane_f32(*outptr0, _sum0, 3); _sum1 = vsetq_lane_f32(*outptr1, _sum1, 3); _sum0n = vsetq_lane_f32(*outptr0n, _sum0n, 3); _sum1n = vsetq_lane_f32(*outptr1n, _sum1n, 3); #if __aarch64__ *outptr0 = vaddvq_f32(_sum0); *outptr1 = vaddvq_f32(_sum1); *outptr0n = vaddvq_f32(_sum0n); *outptr1n = vaddvq_f32(_sum1n); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1)); float32x2_t _ss0n = vadd_f32(vget_low_f32(_sum0n), vget_high_f32(_sum0n)); float32x2_t _ss1n = vadd_f32(vget_low_f32(_sum1n), vget_high_f32(_sum1n)); float32x2_t _ss01 = vpadd_f32(_ss0, _ss1); float32x2_t _ss01n = vpadd_f32(_ss0n, _ss1n); *outptr0 = vget_lane_f32(_ss01, 0); *outptr1 = vget_lane_f32(_ss01, 1); *outptr0n = vget_lane_f32(_ss01n, 0); *outptr1n = vget_lane_f32(_ss01n, 1); #endif // __aarch64__ #else float sum0 = 0.f; float sum0n = 0.f; float sum1 = 0.f; float sum1n = 0.f; sum0 += r0[0] * k0[0]; sum0 += r0[1] * k0[1]; sum0 += r0[2] * k0[2]; sum0 += r1[0] * k0[3]; sum0 += r1[1] * k0[4]; sum0 += r1[2] * k0[5]; sum0 += r2[0] * k0[6]; sum0 += r2[1] * k0[7]; sum0 += r2[2] * k0[8]; sum1 += r0[0] * k1[0]; sum1 += r0[1] * k1[1]; sum1 += r0[2] * k1[2]; sum1 += r1[0] * k1[3]; sum1 += r1[1] * k1[4]; sum1 += r1[2] * k1[5]; sum1 += r2[0] * k1[6]; sum1 += r2[1] * k1[7]; sum1 += r2[2] * k1[8]; sum0n += r1[0] * k0[0]; sum0n += r1[1] * k0[1]; sum0n += r1[2] * k0[2]; sum0n += r2[0] * k0[3]; sum0n += r2[1] * k0[4]; sum0n += r2[2] * k0[5]; sum0n += r3[0] * k0[6]; sum0n += r3[1] * k0[7]; sum0n += r3[2] * k0[8]; sum1n += r1[0] * k1[0]; sum1n += r1[1] * k1[1]; sum1n += r1[2] * k1[2]; sum1n += r2[0] * k1[3]; sum1n += r2[1] * k1[4]; sum1n += r2[2] * k1[5]; sum1n += r3[0] * k1[6]; sum1n += r3[1] * k1[7]; sum1n += r3[2] * k1[8]; *outptr0 += sum0; *outptr1 += sum1; *outptr0n += sum0n; *outptr1n += sum1n; #endif // __ARM_NEON r0++; r1++; r2++; r3++; outptr0++; outptr1++; outptr0n++; outptr1n++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr0 += outw; outptr1 += outw; outptr0n += outw; outptr1n += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum0 = vld1q_f32(outptr0); float32x4_t _sum1 = vld1q_f32(outptr1); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r00, _k00, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r01, _k00, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r02, _k00, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r10, _k03, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r11, _k03, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r12, _k03, 2); _sum0 = vfmaq_laneq_f32(_sum0, _r20, _k06, 0); _sum0 = vfmaq_laneq_f32(_sum0, _r21, _k06, 1); _sum0 = vfmaq_laneq_f32(_sum0, _r22, _k06, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k10, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r01, _k10, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k10, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r10, _k13, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k13, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r12, _k13, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k16, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r21, _k16, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k16, 2); vst1q_f32(outptr0, _sum0); vst1q_f32(outptr1, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr0 += 4; outptr1 += 4; } #else if (nn > 0) { asm volatile( "0: \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r0 "add %3, #16 \n" "pld [%1, #128] \n" "vld1.f32 {d12-d13}, [%1] \n"// _sum0 "pld [%2, #128] \n" "vld1.f32 {d14-d15}, [%2] \n"// _sum1 "vmul.f32 q14, q8, %e12[0] \n" "vmul.f32 q15, q8, %e15[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e12[1] \n" "vmla.f32 q7, q10, %e15[1] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q14, q11, %f12[0] \n" "vmla.f32 q15, q11, %f15[0] \n" "vmla.f32 q6, q8, %e13[0] \n" "vmla.f32 q7, q8, %e16[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q14, q10, %e13[1] \n" "vmla.f32 q15, q10, %e16[1] \n" "pld [%5, #192] \n" "vld1.f32 {d16-d18}, [%5] \n"// r2 "add %5, #16 \n" "vmla.f32 q6, q11, %f13[0] \n" "vmla.f32 q7, q11, %f16[0] \n" "vmla.f32 q14, q8, %e14[0] \n" "vmla.f32 q15, q8, %e17[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q6, q10, %e14[1] \n" "vmla.f32 q7, q10, %e17[1] \n" "vmla.f32 q14, q11, %f14[0] \n" "vmla.f32 q15, q11, %f17[0] \n" "vadd.f32 q6, q6, q14 \n" "vadd.f32 q7, q7, q15 \n" "vst1.f32 {d12-d13}, [%1]! \n" "vst1.f32 {d14-d15}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(outptr0), // %1 "=r"(outptr1), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2) // %5 : "0"(nn), "1"(outptr0), "2"(outptr1), "3"(r0), "4"(r1), "5"(r2), "w"(_k00), // %12 "w"(_k03), // %13 "w"(_k06), // %14 "w"(_k10), // %15 "w"(_k13), // %16 "w"(_k16) // %17 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum0 = vmulq_f32(_r00, _k00); float32x4_t _sum1 = vmulq_f32(_r00, _k10); _sum0 = vmlaq_f32(_sum0, _r10, _k03); _sum1 = vmlaq_f32(_sum1, _r10, _k13); _sum0 = vmlaq_f32(_sum0, _r20, _k06); _sum1 = vmlaq_f32(_sum1, _r20, _k16); _sum0 = vsetq_lane_f32(*outptr0, _sum0, 3); _sum1 = vsetq_lane_f32(*outptr1, _sum1, 3); #if __aarch64__ *outptr0 = vaddvq_f32(_sum0); *outptr1 = vaddvq_f32(_sum1); #else float32x2_t _ss0 = vadd_f32(vget_low_f32(_sum0), vget_high_f32(_sum0)); float32x2_t _ss1 = vadd_f32(vget_low_f32(_sum1), vget_high_f32(_sum1)); float32x2_t _ss01 = vpadd_f32(_ss0, _ss1); *outptr0 = vget_lane_f32(_ss01, 0); *outptr1 = vget_lane_f32(_ss01, 1); #endif // __aarch64__ #else float sum0 = 0.f; float sum1 = 0.f; sum0 += r0[0] * k0[0]; sum0 += r0[1] * k0[1]; sum0 += r0[2] * k0[2]; sum0 += r1[0] * k0[3]; sum0 += r1[1] * k0[4]; sum0 += r1[2] * k0[5]; sum0 += r2[0] * k0[6]; sum0 += r2[1] * k0[7]; sum0 += r2[2] * k0[8]; sum1 += r0[0] * k1[0]; sum1 += r0[1] * k1[1]; sum1 += r0[2] * k1[2]; sum1 += r1[0] * k1[3]; sum1 += r1[1] * k1[4]; sum1 += r1[2] * k1[5]; sum1 += r2[0] * k1[6]; sum1 += r2[1] * k1[7]; sum1 += r2[2] * k1[8]; *outptr0 += sum0; *outptr1 += sum1; #endif // __ARM_NEON r0++; r1++; r2++; outptr0++; outptr1++; } r0 += 2; r1 += 2; r2 += 2; } k0 += 9; k1 += 9; } } #pragma omp parallel for for (int p=remain_outch_start; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; float* outptr2 = outptr + outw; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* r3 = img0 + w*3; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(kernel0); float32x4_t _k3456 = vld1q_f32(kernel0+3); float32x4_t _k6789 = vld1q_f32(kernel0+6); #else const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #endif // __ARM_NEON int i = 0; for (; i+1 < outh; i+=2) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _sum3 = vld1q_f32(outptr2); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _r30n = vld1q_f32(r3 + 4); float32x4_t _r31 = vextq_f32(_r30, _r30n, 1); float32x4_t _r32 = vextq_f32(_r30, _r30n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); float32x4_t _sum2 = vmulq_laneq_f32(_r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r10, _k0123, 0); float32x4_t _sum4 = vmulq_laneq_f32(_r11, _k0123, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r12, _k0123, 2); _sum4 = vfmaq_laneq_f32(_sum4, _r20, _k3456, 0); _sum3 = vfmaq_laneq_f32(_sum3, _r21, _k3456, 1); _sum4 = vfmaq_laneq_f32(_sum4, _r22, _k3456, 2); _sum3 = vfmaq_laneq_f32(_sum3, _r30, _k6789, 0); _sum4 = vfmaq_laneq_f32(_sum4, _r31, _k6789, 1); _sum3 = vfmaq_laneq_f32(_sum3, _r32, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); _sum3 = vaddq_f32(_sum3, _sum4); vst1q_f32(outptr, _sum1); vst1q_f32(outptr2, _sum3); r0 += 4; r1 += 4; r2 += 4; r3 += 4; outptr += 4; outptr2 += 4; } #else if (nn > 0) { asm volatile( "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "add %3, #16 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1 :64] \n"// _sum "vmla.f32 q7, q9, %e14[0] \n" "vmul.f32 q6, q11, %e14[1] \n" "vmul.f32 q13, q12, %f14[0] \n" "pld [%4, #192] \n" "vld1.f32 {d18-d20}, [%4] \n"// r1 "add %4, #16 \n" "vmla.f32 q7, q9, %e15[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e15[1] \n" "vmla.f32 q13, q12, %f15[0] \n" "pld [%2, #128] \n" "vld1.f32 {d16-d17}, [%2] \n"// _sum2 "vmla.f32 q8, q9, %e14[0] \n" "vmul.f32 q14, q11, %e14[1] \n" "vmul.f32 q15, q12, %f14[0] \n" "pld [%5, #192] \n" "vld1.f32 {d18-d20}, [%5 :64] \n"// r2 "add %5, #16 \n" "vmla.f32 q7, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q6, q11, %e16[1] \n" "vmla.f32 q13, q12, %f16[0] \n" "vmla.f32 q8, q9, %e15[0] \n" "vmla.f32 q14, q11, %e15[1] \n" "vmla.f32 q15, q12, %f15[0] \n" "pld [%6, #192] \n" "vld1.f32 {d18-d20}, [%6] \n"// r3 "add %6, #16 \n" "vmla.f32 q8, q9, %e16[0] \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "vmla.f32 q14, q11, %e16[1] \n" "vmla.f32 q15, q12, %f16[0] \n" "vadd.f32 q7, q7, q6 \n" "pld [%3, #192] \n" "vld1.f32 {d18-d20}, [%3 :64] \n"// r0 "vadd.f32 q8, q8, q14 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q8, q8, q15 \n" "vext.32 q11, q9, q10, #1 \n" "vext.32 q12, q9, q10, #2 \n" "add %3, #16 \n" "vst1.f32 {d14-d15}, [%1]! \n" "vst1.f32 {d16-d17}, [%2]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %3, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(outptr2), // %2 "=r"(r0), // %3 "=r"(r1), // %4 "=r"(r2), // %5 "=r"(r3) // %6 : "0"(nn), "1"(outptr), "2"(outptr2), "3"(r0), "4"(r1), "5"(r2), "6"(r3), "w"(_k0123), // %14 "w"(_k3456), // %15 "w"(_k6789) // %16 : "cc", "memory", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r30 = vld1q_f32(r3); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); float32x4_t _sum2 = vmulq_f32(_r10, _k0123); _sum2 = vmlaq_f32(_sum2, _r20, _k3456); _sum2 = vmlaq_f32(_sum2, _r30, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); _sum2 = vsetq_lane_f32(*outptr2, _sum2, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); *outptr2 = vaddvq_f32(_sum2); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); float32x2_t _ss2 = vadd_f32(vget_low_f32(_sum2), vget_high_f32(_sum2)); float32x2_t _sss2 = vpadd_f32(_ss, _ss2); *outptr = vget_lane_f32(_sss2, 0); *outptr2 = vget_lane_f32(_sss2, 1); #endif // __aarch64__ #else float sum = 0; float sum2 = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; sum2 += r1[0] * k0[0]; sum2 += r1[1] * k0[1]; sum2 += r1[2] * k0[2]; sum2 += r2[0] * k1[0]; sum2 += r2[1] * k1[1]; sum2 += r2[2] * k1[2]; sum2 += r3[0] * k2[0]; sum2 += r3[1] * k2[1]; sum2 += r3[2] * k2[2]; *outptr += sum; *outptr2 += sum2; #endif r0++; r1++; r2++; r3++; outptr++; outptr2++; } r0 += 2 + w; r1 += 2 + w; r2 += 2 + w; r3 += 2 + w; outptr += outw; outptr2 += outw; } for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _sum1 = vld1q_f32(outptr); float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r00n = vld1q_f32(r0 + 4); float32x4_t _r01 = vextq_f32(_r00, _r00n, 1); float32x4_t _r02 = vextq_f32(_r00, _r00n, 2); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r10n = vld1q_f32(r1 + 4); float32x4_t _r11 = vextq_f32(_r10, _r10n, 1); float32x4_t _r12 = vextq_f32(_r10, _r10n, 2); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _r20n = vld1q_f32(r2 + 4); float32x4_t _r21 = vextq_f32(_r20, _r20n, 1); float32x4_t _r22 = vextq_f32(_r20, _r20n, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r00, _k0123, 0); float32x4_t _sum2 = vmulq_laneq_f32(_r01, _k0123, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r02, _k0123, 2); _sum2 = vfmaq_laneq_f32(_sum2, _r10, _k3456, 0); _sum1 = vfmaq_laneq_f32(_sum1, _r11, _k3456, 1); _sum2 = vfmaq_laneq_f32(_sum2, _r12, _k3456, 2); _sum1 = vfmaq_laneq_f32(_sum1, _r20, _k6789, 0); _sum2 = vfmaq_laneq_f32(_sum2, _r21, _k6789, 1); _sum1 = vfmaq_laneq_f32(_sum1, _r22, _k6789, 2); _sum1 = vaddq_f32(_sum1, _sum2); vst1q_f32(outptr, _sum1); r0 += 4; r1 += 4; r2 += 4; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d14-d15}, [%1] \n"// _sum "vmla.f32 q7, q8, %e10[0] \n" "vmul.f32 q13, q10, %e10[1] \n" "vmul.f32 q14, q11, %f10[0] \n" "pld [%3, #192] \n" "vld1.f32 {d16-d18}, [%3] \n"// r1 "add %3, #16 \n" "vmla.f32 q7, q8, %e11[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e11[1] \n" "vmla.f32 q14, q11, %f11[0] \n" "pld [%4, #192] \n" "vld1.f32 {d16-d18}, [%4] \n"// r2 "add %4, #16 \n" "vmla.f32 q7, q8, %e12[0] \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vmla.f32 q13, q10, %e12[1] \n" "vmla.f32 q14, q11, %f12[0] \n" "pld [%2, #192] \n" "vld1.f32 {d16-d18}, [%2] \n"// r0 "add %2, #16 \n" "vadd.f32 q7, q7, q13 \n" "vadd.f32 q7, q7, q14 \n" "vext.32 q10, q8, q9, #1 \n" "vext.32 q11, q8, q9, #2 \n" "vst1.f32 {d14-d15}, [%1]! \n" "subs %0, #1 \n" "bne 0b \n" "sub %2, #16 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif r0++; r1++; r2++; outptr++; } r0 += 2; r1 += 2; r2 += 2; } kernel0 += 9; } } } static void conv3x3s1_winograd64_transform_kernel_neon(const Mat& kernel, Mat& kernel_tm, int inch, int outch) { kernel_tm.create(8*8, inch, outch); const float ktm[8][3] = { { 1.0f, 0.0f, 0.0f}, {-2.0f/9, -2.0f/9, -2.0f/9}, {-2.0f/9, 2.0f/9, -2.0f/9}, {1.0f/90, 1.0f/45, 2.0f/45}, {1.0f/90, -1.0f/45, 2.0f/45}, {1.0f/45, 1.0f/90, 1.0f/180}, {1.0f/45, -1.0f/90, 1.0f/180}, { 0.0f, 0.0f, 1.0f} }; #pragma omp parallel for for (int p = 0; p<outch; p++) { for (int q = 0; q<inch; q++) { const float* kernel0 = (const float*)kernel + p*inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i=0; i<8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j=0; j<8; j++) { float* tmpp = &tmp[j][0]; for (int i=0; i<8; i++) { kernel_tm0[j*8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } } static void conv3x3s1_winograd64_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, 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; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8*8, w_tm/8 * h_tm/8, inch); // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm = img0_tm.row(i * w_tm/8 + j); // TODO neon optimize for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; r0_tm += 8; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8*8, w_tm/8 * h_tm/8, outch); int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); Mat out2_tm = top_blob_tm.channel(p+2); Mat out3_tm = top_blob_tm.channel(p+3); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); const Mat kernel2_tm = kernel_tm.channel(p+2); const Mat kernel3_tm = kernel_tm.channel(p+3); out0_tm.fill(0.f); out1_tm.fill(0.f); out2_tm.fill(0.f); out3_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k00 = kernel0_tm.row(q); const float* k10 = kernel1_tm.row(q); const float* k20 = kernel2_tm.row(q); const float* k30 = kernel3_tm.row(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output2_tm = vld1q_f32(output2_tm); float32x4_t _output3_tm = vld1q_f32(output3_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k00 = vld1q_f32(k00); k00 += 64; float32x4_t _k01 = vld1q_f32(k00); k00 += 64; float32x4_t _k02 = vld1q_f32(k00); k00 += 64; float32x4_t _k03 = vld1q_f32(k00); k00 += 64; k00 -= 64*4; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k02); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k03); float32x4_t _k10 = vld1q_f32(k10); k10 += 64; float32x4_t _k11 = vld1q_f32(k10); k10 += 64; float32x4_t _k12 = vld1q_f32(k10); k10 += 64; float32x4_t _k13 = vld1q_f32(k10); k10 += 64; k10 -= 64*4; _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tm = vmlaq_f32(_output1_tm, _r2, _k12); _output1_tm = vmlaq_f32(_output1_tm, _r3, _k13); float32x4_t _k20 = vld1q_f32(k20); k20 += 64; float32x4_t _k21 = vld1q_f32(k20); k20 += 64; float32x4_t _k22 = vld1q_f32(k20); k20 += 64; float32x4_t _k23 = vld1q_f32(k20); k20 += 64; k20 -= 64*4; _output2_tm = vmlaq_f32(_output2_tm, _r0, _k20); _output2_tm = vmlaq_f32(_output2_tm, _r1, _k21); _output2_tm = vmlaq_f32(_output2_tm, _r2, _k22); _output2_tm = vmlaq_f32(_output2_tm, _r3, _k23); float32x4_t _k30 = vld1q_f32(k30); k30 += 64; float32x4_t _k31 = vld1q_f32(k30); k30 += 64; float32x4_t _k32 = vld1q_f32(k30); k30 += 64; float32x4_t _k33 = vld1q_f32(k30); k30 += 64; k30 -= 64*4; _output3_tm = vmlaq_f32(_output3_tm, _r0, _k30); _output3_tm = vmlaq_f32(_output3_tm, _r1, _k31); _output3_tm = vmlaq_f32(_output3_tm, _r2, _k32); _output3_tm = vmlaq_f32(_output3_tm, _r3, _k33); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output2_tm, _output2_tm); vst1q_f32(output3_tm, _output3_tm); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k00 += 4; k10 += 4; k20 += 4; k30 += 4; float32x4_t _output0_tmn = vld1q_f32(output0_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm); float32x4_t _output2_tmn = vld1q_f32(output2_tm); float32x4_t _output3_tmn = vld1q_f32(output3_tm); float32x4_t _r0n = vld1q_f32(r0); float32x4_t _r1n = vld1q_f32(r1); float32x4_t _r2n = vld1q_f32(r2); float32x4_t _r3n = vld1q_f32(r3); float32x4_t _k00n = vld1q_f32(k00); k00 += 64; float32x4_t _k01n = vld1q_f32(k00); k00 += 64; float32x4_t _k02n = vld1q_f32(k00); k00 += 64; float32x4_t _k03n = vld1q_f32(k00); k00 += 64; k00 -= 64*4; _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output0_tmn = vmlaq_f32(_output0_tmn, _r2n, _k02n); _output0_tmn = vmlaq_f32(_output0_tmn, _r3n, _k03n); float32x4_t _k10n = vld1q_f32(k10); k10 += 64; float32x4_t _k11n = vld1q_f32(k10); k10 += 64; float32x4_t _k12n = vld1q_f32(k10); k10 += 64; float32x4_t _k13n = vld1q_f32(k10); k10 += 64; k10 -= 64*4; _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); _output1_tmn = vmlaq_f32(_output1_tmn, _r2n, _k12n); _output1_tmn = vmlaq_f32(_output1_tmn, _r3n, _k13n); float32x4_t _k20n = vld1q_f32(k20); k20 += 64; float32x4_t _k21n = vld1q_f32(k20); k20 += 64; float32x4_t _k22n = vld1q_f32(k20); k20 += 64; float32x4_t _k23n = vld1q_f32(k20); k20 += 64; k20 -= 64*4; _output2_tmn = vmlaq_f32(_output2_tmn, _r0n, _k20n); _output2_tmn = vmlaq_f32(_output2_tmn, _r1n, _k21n); _output2_tmn = vmlaq_f32(_output2_tmn, _r2n, _k22n); _output2_tmn = vmlaq_f32(_output2_tmn, _r3n, _k23n); float32x4_t _k30n = vld1q_f32(k30); k30 += 64; float32x4_t _k31n = vld1q_f32(k30); k30 += 64; float32x4_t _k32n = vld1q_f32(k30); k30 += 64; float32x4_t _k33n = vld1q_f32(k30); k30 += 64; k30 -= 64*4; _output3_tmn = vmlaq_f32(_output3_tmn, _r0n, _k30n); _output3_tmn = vmlaq_f32(_output3_tmn, _r1n, _k31n); _output3_tmn = vmlaq_f32(_output3_tmn, _r2n, _k32n); _output3_tmn = vmlaq_f32(_output3_tmn, _r3n, _k33n); vst1q_f32(output0_tm, _output0_tmn); vst1q_f32(output1_tm, _output1_tmn); vst1q_f32(output2_tm, _output2_tmn); vst1q_f32(output3_tm, _output3_tmn); output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k00 += 4; k10 += 4; k20 += 4; k30 += 4; } #else // __aarch64__ asm volatile( "mov r4, #8 \n" "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]\n"//q8 q9 = _output0_tm "0: \n" "pld [%4, #256] \n" "vld1.f32 {d0-d3}, [%4 :128]! \n"//q0 q1 = _r0 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k00 "add %8, %8, #256 \n" "vmla.f32 q8, q0, q10 \n" "vmla.f32 q9, q1, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]\n"//q12 q13 = _output1_tm "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k10 "add %9, %9, #256 \n" "vmla.f32 q12, q0, q14 \n" "vmla.f32 q13, q1, q15 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n"//q2 q3 = _r1 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k01 "add %8, %8, #256 \n" "vmla.f32 q8, q2, q10 \n" "vmla.f32 q9, q3, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k11 "add %9, %9, #256 \n" "vmla.f32 q12, q2, q14 \n" "vmla.f32 q13, q3, q15 \n" "pld [%6, #256] \n" "vld1.f32 {d8-d11}, [%6 :128]!\n"//q4 q5 = _r2 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k02 "add %8, %8, #256 \n" "vmla.f32 q8, q4, q10 \n" "vmla.f32 q9, q5, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k12 "add %9, %9, #256 \n" "vmla.f32 q12, q4, q14 \n" "vmla.f32 q13, q5, q15 \n" "pld [%7, #256] \n" "vld1.f32 {d12-d15}, [%7 :128]!\n"//q6 q7 = _r3 "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]\n"//q10 q11 = _k03 "sub %8, %8, #736 \n" "vmla.f32 q8, q6, q10 \n" "vmla.f32 q9, q7, q11 \n" "pld [%9, #256] \n" "vld1.f32 {d28-d31}, [%9 :128]\n"//q14 q15 = _k13 "sub %9, %9, #736 \n" "vmla.f32 q12, q6, q14 \n" "vmla.f32 q13, q7, q15 \n" "vst1.f32 {d16-d19}, [%0 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]\n"//q8 q9 = _output2_tm "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k20 "add %10, %10, #256 \n" "vmla.f32 q8, q0, q10 \n" "vmla.f32 q9, q1, q11 \n" "vst1.f32 {d24-d27}, [%1 :128]!\n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]\n"//q12 q13 = _output3_tm "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k30 "add %11, %11, #256 \n" "vmla.f32 q12, q0, q14 \n" "vmla.f32 q13, q1, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k21 "add %10, %10, #256 \n" "vmla.f32 q8, q2, q10 \n" "vmla.f32 q9, q3, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k31 "add %11, %11, #256 \n" "vmla.f32 q12, q2, q14 \n" "vmla.f32 q13, q3, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k22 "add %10, %10, #256 \n" "vmla.f32 q8, q4, q10 \n" "vmla.f32 q9, q5, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k32 "add %11, %11, #256 \n" "vmla.f32 q12, q4, q14 \n" "vmla.f32 q13, q5, q15 \n" "pld [%10, #256] \n" "vld1.f32 {d20-d23}, [%10 :128]\n"//q10 q11 = _k23 "sub %10, %10, #736 \n" "vmla.f32 q8, q6, q10 \n" "vmla.f32 q9, q7, q11 \n" "pld [%11, #256] \n" "vld1.f32 {d28-d31}, [%11 :128]\n"//q14 q15 = _k33 "sub %11, %11, #736 \n" "vmla.f32 q12, q6, q14 \n" "vmla.f32 q13, q7, q15 \n" "vst1.f32 {d16-d19}, [%2 :128]!\n" "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]\n"//q8 q9 = _output0_tm "subs r4, r4, #1 \n" "vst1.f32 {d24-d27}, [%3 :128]!\n" "bne 0b \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1), // %5 "=r"(r2), // %6 "=r"(r3), // %7 "=r"(k00), // %8 "=r"(k10), // %9 "=r"(k20), // %10 "=r"(k30) // %11 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "6"(r2), "7"(r3), "8"(k00), "9"(k10), "10"(k20), "11"(k30) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k00 -= 64; k10 -= 64; k20 -= 64; k30 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k00[m]; k00 += 64; output0_tm[m] += r1[m] * k00[m]; k00 += 64; output0_tm[m] += r2[m] * k00[m]; k00 += 64; output0_tm[m] += r3[m] * k00[m]; k00 += 64; k00 -= 64 * 4; output1_tm[m] += r0[m] * k10[m]; k10 += 64; output1_tm[m] += r1[m] * k10[m]; k10 += 64; output1_tm[m] += r2[m] * k10[m]; k10 += 64; output1_tm[m] += r3[m] * k10[m]; k10 += 64; k10 -= 64 * 4; output2_tm[m] += r0[m] * k20[m]; k20 += 64; output2_tm[m] += r1[m] * k20[m]; k20 += 64; output2_tm[m] += r2[m] * k20[m]; k20 += 64; output2_tm[m] += r3[m] * k20[m]; k20 += 64; k20 -= 64 * 4; output3_tm[m] += r0[m] * k30[m]; k30 += 64; output3_tm[m] += r1[m] * k30[m]; k30 += 64; output3_tm[m] += r2[m] * k30[m]; k30 += 64; output3_tm[m] += r3[m] * k30[m]; k30 += 64; k30 -= 64 * 4; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; output1_tm += 64; output2_tm += 64; output3_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel1_tm.row(q); const float* k2 = kernel2_tm.row(q); const float* k3 = kernel3_tm.row(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output1_tm[m] += r0[m] * k1[m]; output2_tm[m] += r0[m] * k2[m]; output3_tm[m] += r0[m] * k3[m]; } r0 += 64; output0_tm += 64; output1_tm += 64; output2_tm += 64; output3_tm += 64; } } } #pragma omp parallel for for (int p=remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+3<inch; q+=4) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* r2 = bottom_blob_tm.channel(q+2); const float* r3 = bottom_blob_tm.channel(q+3); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); const float* k2 = kernel0_tm.row(q+2); const float* k3 = kernel0_tm.row(q+3); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { #if __ARM_NEON #if __aarch64__ for (int m=0; m+7<64; m+=8) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r2 = vld1q_f32(r2); float32x4_t _r3 = vld1q_f32(r3); float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k2 = vld1q_f32(k2); float32x4_t _k3 = vld1q_f32(k3); _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tm = vmlaq_f32(_output0_tm, _r2, _k2); _output0_tm = vmlaq_f32(_output0_tm, _r3, _k3); vst1q_f32(output0_tm, _output0_tm); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; float32x4_t _output0_tmn = vld1q_f32(output0_tm); float32x4_t _r0n = vld1q_f32(r0); float32x4_t _r1n = vld1q_f32(r1); float32x4_t _r2n = vld1q_f32(r2); float32x4_t _r3n = vld1q_f32(r3); float32x4_t _k0n = vld1q_f32(k0); float32x4_t _k1n = vld1q_f32(k1); float32x4_t _k2n = vld1q_f32(k2); float32x4_t _k3n = vld1q_f32(k3); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); _output0_tmn = vmlaq_f32(_output0_tmn, _r2n, _k2n); _output0_tmn = vmlaq_f32(_output0_tmn, _r3n, _k3n); vst1q_f32(output0_tm, _output0_tmn); output0_tm += 4; r0 += 4; r1 += 4; r2 += 4; r3 += 4; k0 += 4; k1 += 4; k2 += 4; k3 += 4; } #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "mov r4, %0 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d24-d27}, [%0 :128]!\n"//q12 q13 = output0_tm "vmla.f32 q15, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q12, q0, q2 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q13, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q12, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q13, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q12, q8, q10 \n" "pld [%0, #256] \n" "vld1.f32 {d28-d31}, [%0 :128]!\n"//q14 q15 = output0_tm "vmla.f32 q13, q9, q11 \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128]! \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q14, q0, q2 \n" "vst1.f32 {d24-d27}, [r4 :128]!\n" "pld [%2, #256] \n" "vld1.f32 {d16-d19}, [%2 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%6, #256] \n" "vld1.f32 {d20-d23}, [%6 :128]!\n" "vmla.f32 q14, q8, q10 \n" "pld [%3, #256] \n" "vld1.f32 {d0-d3}, [%3 :128]! \n" "vmla.f32 q15, q9, q11 \n" "pld [%7, #256] \n" "vld1.f32 {d4-d7}, [%7 :128]! \n" "vmla.f32 q14, q0, q2 \n" "pld [%4, #256] \n" "vld1.f32 {d16-d19}, [%4 :128]!\n" "vmla.f32 q15, q1, q3 \n" "pld [%8, #256] \n" "vld1.f32 {d20-d23}, [%8 :128]!\n" "vmla.f32 q14, q8, q10 \n" "vmla.f32 q15, q9, q11 \n" "vst1.f32 {d28-d31}, [r4 :128]!\n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1), // %2 "=r"(r2), // %3 "=r"(r3), // %4 "=r"(k0), // %5 "=r"(k1), // %6 "=r"(k2), // %7 "=r"(k3) // %8 : "0"(output0_tm), "1"(r0), "2"(r1), "3"(r2), "4"(r3), "5"(k0), "6"(k1), "7"(k2), "8"(k3) : "cc", "memory", "r4", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ k0 -= 64; k1 -= 64; k2 -= 64; k3 -= 64; #else for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; output0_tm[m] += r2[m] * k2[m]; output0_tm[m] += r3[m] * k3[m]; } r0 += 64; r1 += 64; r2 += 64; r3 += 64; output0_tm += 64; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; // tile for (int i=0; i<h_tm/8 * w_tm/8; i++) { // TODO neon optimize for (int m=0; m<64; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 64; output0_tm += 64; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm = out0_tm.row(i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; // TODO neon optimize for (int m=0; m<8; m++) { float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; output0_tm += 8; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s1_winograd64_neon2(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, 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; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, inch); const int tiles = w_tm/8 * h_tm/8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm01 = img0_tm.row(i * w_tm/8 + j); float* r0_tm23 = img0_tm.row(tiles + i * w_tm/8 + j); float* r0_tm45 = img0_tm.row(tiles * 2 + i * w_tm/8 + j); float* r0_tm67 = img0_tm.row(tiles * 3 + i * w_tm/8 + j); for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tms[4] = { r0_tm01, r0_tm23, r0_tm45, r0_tm67 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm = r0_tms[m/2] + (m%2) * 8; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(2*8, 4 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k0 = kernel0_tm.row(q); const float* k1 = kernel0_tm.row(q+1); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); float32x4_t _k1 = vld1q_f32(k1); float32x4_t _k1n = vld1q_f32(k1+4); float32x4_t _k1nn = vld1q_f32(k1+8); float32x4_t _k1nnn = vld1q_f32(k1+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; float32x4_t _k1; float32x4_t _k1n; float32x4_t _k1nn; float32x4_t _k1nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "pld [%1, #512] \n" "vld1.f32 {%e4-%f4}, [%1 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e5-%f5}, [%1 :128]! \n" "vld1.f32 {%e6-%f6}, [%0 :128]! \n" "vld1.f32 {%e8-%f8}, [%1 :128]! \n" "vld1.f32 {%e7-%f7}, [%0 :128]! \n" "vld1.f32 {%e9-%f9}, [%1 :128]! \n" : "=r"(k0), // %0 "=r"(k1), // %1 "=w"(_k0), // %2 "=w"(_k0n), // %3 "=w"(_k1), // %4 "=w"(_k1n), // %5 "=w"(_k0nn), // %6 "=w"(_k0nnn), // %7 "=w"(_k1nn), // %8 "=w"(_k1nnn) // %9 : "0"(k0), "1"(k1) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; } #else if (nn > 0) { asm volatile( "mov r4, %1 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "0: \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d20-d23}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128]! \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [r4 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "subs %0, #1 \n" "vst1.f32 {d20-d23}, [r4 :128]! \n" "bne 0b \n" "sub %1, #32 \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(r1), "w"(_k0), // %8 "w"(_k0n), // %9 "w"(_k1), // %10 "w"(_k1n), // %11 "w"(_k0nn), // %12 "w"(_k0nnn), // %13 "w"(_k1nn), // %14 "w"(_k1nnn) // %15 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k1nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k1nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q9, q13, %q7 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "vmla.f32 q8, q14, %q8 \n" "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q9, q15, %q9 \n" "vmla.f32 q10, q12, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q10, q14, %q12 \n" "vmla.f32 q11, q15, %q13 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1) // %2 : "0"(output0_tm), "1"(r0), "2"(r1), "w"(_k0), // %6 "w"(_k0n), // %7 "w"(_k1), // %8 "w"(_k1n), // %9 "w"(_k0nn), // %10 "w"(_k0nnn), // %11 "w"(_k1nn), // %12 "w"(_k1nnn) // %13 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; output0_tm[m] += r1[m] * k1[m]; } r0 += 16; r1 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; k1 += 16; #endif // __aarch64__ #else k0 += 16; k1 += 16; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k0 = kernel0_tm.row(q); float* output0_tm = out0_tm; for (int r=0; r<4; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k0 = vld1q_f32(k0); float32x4_t _k0n = vld1q_f32(k0+4); float32x4_t _k0nn = vld1q_f32(k0+8); float32x4_t _k0nnn = vld1q_f32(k0+12); #else float32x4_t _k0; float32x4_t _k0n; float32x4_t _k0nn; float32x4_t _k0nnn; asm volatile( "pld [%0, #512] \n" "vld1.f32 {%e1-%f1}, [%0 :128]! \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e4-%f4}, [%0 :128]! \n" : "=r"(k0), // %0 "=w"(_k0), // %1 "=w"(_k0n), // %2 "=w"(_k0nn), // %3 "=w"(_k0nnn) // %4 : "0"(k0) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k0nn); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k0nnn); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "mov r4, %0 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128]! \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q4 \n" "vmla.f32 q9, q13, %q5 \n" "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d20-d23}, [%0 :128] \n"// q10 q11 = _output0_tm "vmla.f32 q10, q12, %q6 \n" "vst1.f32 {d16-d19}, [r4 :128] \n" "vmla.f32 q11, q13, %q7 \n" "vst1.f32 {d20-d23}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k0), // %4 "w"(_k0n), // %5 "w"(_k0nn), // %6 "w"(_k0nnn) // %7 : "cc", "memory", "r4", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<16; m++) { output0_tm[m] += r0[m] * k0[m]; } r0 += 16; output0_tm += 16; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k0 += 16; #endif // __aarch64__ #else k0 += 16; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm/8 * h_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm01 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm23 = out0_tm.row(tiles + i * w_tm/8 + j); const float* output0_tm45 = out0_tm.row(tiles * 2 + i * w_tm/8 + j); const float* output0_tm67 = out0_tm.row(tiles * 3 + i * w_tm/8 + j); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms[4] = { output0_tm01, output0_tm23, output0_tm45, output0_tm67 }; for (int m=0; m<8; m++) { const float* output0_tm = output0_tms[m/2] + (m%2) * 8; float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s1_winograd64_neon3(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, 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; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, 0, 0.f); const float* bias = _bias; // BEGIN transform input Mat bottom_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; bottom_blob_tm.create(8, 8 * w_tm/8 * h_tm/8, inch); const int tiles = w_tm/8 * h_tm/8; // const float itm[8][8] = { // {1.0f, 0.0f, -5.25f, 0.00f, 5.25f, 0.00f, -1.0f, 0.0f}, // // {0.0f, 1.0f, 1.00f, -4.25f, -4.25f, 1.00f, 1.0f, 0.0f}, // {0.0f, -1.0f, 1.00f, 4.25f, -4.25f, -1.00f, 1.0f, 0.0f}, // // {0.0f, 0.5f, 0.25f, -2.50f, -1.25f, 2.00f, 1.0f, 0.0f}, // {0.0f, -0.5f, 0.25f, 2.50f, -1.25f, -2.00f, 1.0f, 0.0f}, // // {0.0f, 2.0f, 4.00f, -2.50f, -5.00f, 0.50f, 1.0f, 0.0f}, // {0.0f, -2.0f, 4.00f, 2.50f, -5.00f, -0.50f, 1.0f, 0.0f}, // // {0.0f, -1.0f, 0.00f, 5.25f, 0.00f, -5.25f, 0.0f, 1.0f} // }; // 0 = r00 - r06 + (r04 - r02) * 5.25 // 7 = r07 - r01 + (r03 - r05) * 5.25 // 1 = (r02 + r06 - r04 * 4.25) + (r01 - r03 * 4.25 + r05) // 2 = (r02 + r06 - r04 * 4.25) - (r01 - r03 * 4.25 + r05) // 3 = (r06 + r02 * 0.25 - r04 * 1.25) + (r01 * 0.5 - r03 * 2.5 + r05 * 2) // 4 = (r06 + r02 * 0.25 - r04 * 1.25) - (r01 * 0.5 - r03 * 2.5 + r05 * 2) // reuse r04 * 1.25 // reuse r03 * 2.5 // 5 = (r06 + (r02 - r04 * 1.25) * 4) + (r01 * 2 - r03 * 2.5 + r05 * 0.5) // 6 = (r06 + (r02 - r04 * 1.25) * 4) - (r01 * 2 - r03 * 2.5 + r05 * 0.5) #pragma omp parallel for for (int q = 0; q<inch; q++) { const Mat img0 = bottom_blob_bordered.channel(q); Mat img0_tm = bottom_blob_tm.channel(q); float tmp[8][8]; // tile for (int i=0; i<h_tm/8; i++) { for (int j=0; j<w_tm/8; j++) { const float* r0 = img0.row(i * 6) + j * 6; float* r0_tm0 = img0_tm.row(i * w_tm/8 + j); float* r0_tm1 = img0_tm.row(i * w_tm/8 + j + tiles); float* r0_tm2 = img0_tm.row(i * w_tm/8 + j + tiles * 2); float* r0_tm3 = img0_tm.row(i * w_tm/8 + j + tiles * 3); float* r0_tm4 = img0_tm.row(i * w_tm/8 + j + tiles * 4); float* r0_tm5 = img0_tm.row(i * w_tm/8 + j + tiles * 5); float* r0_tm6 = img0_tm.row(i * w_tm/8 + j + tiles * 6); float* r0_tm7 = img0_tm.row(i * w_tm/8 + j + tiles * 7); for (int m=0; m<8; m++) { tmp[0][m] = r0[0] - r0[6] + (r0[4] - r0[2]) * 5.25; tmp[7][m] = r0[7] - r0[1] + (r0[3] - r0[5]) * 5.25; float tmp12a = (r0[2] + r0[6] - r0[4] * 4.25); float tmp12b = (r0[1] + r0[5] - r0[3] * 4.25); tmp[1][m] = tmp12a + tmp12b; tmp[2][m] = tmp12a - tmp12b; float tmp34a = (r0[6] + r0[2] * 0.25 - r0[4] * 1.25); float tmp34b = (r0[1] * 0.5 - r0[3] * 2.5 + r0[5] * 2); tmp[3][m] = tmp34a + tmp34b; tmp[4][m] = tmp34a - tmp34b; float tmp56a = (r0[6] + (r0[2] - r0[4] * 1.25) * 4); float tmp56b = (r0[1] * 2 - r0[3] * 2.5 + r0[5] * 0.5); tmp[5][m] = tmp56a + tmp56b; tmp[6][m] = tmp56a - tmp56b; r0 += w; } float* r0_tms[8] = { r0_tm0, r0_tm1, r0_tm2, r0_tm3, r0_tm4, r0_tm5, r0_tm6, r0_tm7 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm = r0_tms[m]; r0_tm[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm[7] = tmp0[7] - tmp0[1] + (tmp0[3] - tmp0[5]) * 5.25; float tmp12a = (tmp0[2] + tmp0[6] - tmp0[4] * 4.25); float tmp12b = (tmp0[1] - tmp0[3] * 4.25 + tmp0[5]); r0_tm[1] = tmp12a + tmp12b; r0_tm[2] = tmp12a - tmp12b; float tmp34a = (tmp0[6] + tmp0[2] * 0.25 - tmp0[4] * 1.25); float tmp34b = (tmp0[1] * 0.5 - tmp0[3] * 2.5 + tmp0[5] * 2); r0_tm[3] = tmp34a + tmp34b; r0_tm[4] = tmp34a - tmp34b; float tmp56a = (tmp0[6] + (tmp0[2] - tmp0[4] * 1.25) * 4); float tmp56b = (tmp0[1] * 2 - tmp0[3] * 2.5 + tmp0[5] * 0.5); r0_tm[5] = tmp56a + tmp56b; r0_tm[6] = tmp56a - tmp56b; } } } } } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; top_blob_tm.create(8, 8 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; int nn_outch = outch >> 1; int remain_outch_start = nn_outch << 1; #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 2; Mat out0_tm = top_blob_tm.channel(p); Mat out1_tm = top_blob_tm.channel(p+1); const Mat kernel0_tm = kernel_tm.channel(p); const Mat kernel1_tm = kernel_tm.channel(p+1); out0_tm.fill(0.f); out1_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q+1); const float* k10 = kernel1_tm.row(q); const float* k11 = kernel1_tm.row(q+1); float* output0_tm = out0_tm; float* output1_tm = out1_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); float32x4_t _k01 = vld1q_f32(k01); float32x4_t _k01n = vld1q_f32(k01+4); float32x4_t _k10 = vld1q_f32(k10); float32x4_t _k10n = vld1q_f32(k10+4); float32x4_t _k11 = vld1q_f32(k11); float32x4_t _k11n = vld1q_f32(k11+4); #else float32x4_t _k00; float32x4_t _k00n; float32x4_t _k01; float32x4_t _k01n; float32x4_t _k10; float32x4_t _k10n; float32x4_t _k11; float32x4_t _k11n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e4-%f4}, [%0 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {%e6-%f6}, [%1 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {%e8-%f8}, [%2 :128]! \n" "pld [%3, #256] \n" "vld1.f32 {%e10-%f10}, [%3 :128]! \n" "vld1.f32 {%e5-%f5}, [%0 :128]! \n" "vld1.f32 {%e7-%f7}, [%1 :128]! \n" "vld1.f32 {%e9-%f9}, [%2 :128]! \n" "vld1.f32 {%e11-%f11}, [%3 :128]! \n" : "=r"(k00), // %0 "=r"(k01), // %1 "=r"(k10), // %2 "=r"(k11), // %3 "=w"(_k00), // %4 "=w"(_k00n), // %5 "=w"(_k01), // %6 "=w"(_k01n), // %7 "=w"(_k10), // %8 "=w"(_k10n), // %9 "=w"(_k11), // %10 "=w"(_k11n) // %11 : "0"(k00), "1"(k01), "2"(k10), "3"(k11) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _output1_tm = vld1q_f32(output1_tm); _output1_tmn = vld1q_f32(output1_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; } #else if (nn > 0) { asm volatile( "0: \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :128]! \n"// q12 q13 = _r0 "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "vmla.f32 q9, q13, %q11 \n" "pld [%4, #256] \n" "vld1.f32 {d28-d31}, [%4 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q12 \n" "vmla.f32 q9, q15, %q13 \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q14 \n" "vmla.f32 q11, q13, %q15 \n" "vmla.f32 q10, q14, %q16 \n" "vmla.f32 q11, q15, %q17 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "vst1.f32 {d20-d23}, [%2 :128]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(r0), // %3 "=r"(r1) // %4 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "4"(r1), "w"(_k00), // %10 "w"(_k00n), // %11 "w"(_k01), // %12 "w"(_k01n), // %13 "w"(_k10), // %14 "w"(_k10n), // %15 "w"(_k11), // %16 "w"(_k11n) // %17 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _output1_tm = vld1q_f32(output1_tm); float32x4_t _output1_tmn = vld1q_f32(output1_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); _output1_tm = vmlaq_f32(_output1_tm, _r1, _k11); _output1_tmn = vmlaq_f32(_output1_tmn, _r1n, _k11n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); vst1q_f32(output1_tm, _output1_tm); vst1q_f32(output1_tm+4, _output1_tmn); output0_tm += 8; output1_tm += 8; #else asm volatile( "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q12 \n" "vmla.f32 q11, q13, %q13 \n" "vmla.f32 q10, q14, %q14 \n" "vmla.f32 q11, q15, %q15 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" "vst1.f32 {d20-d23}, [%1 :128]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(output0_tm), "1"(output1_tm), "2"(r0), "3"(r1), "w"(_k00), // %8 "w"(_k00n), // %9 "w"(_k01), // %10 "w"(_k01n), // %11 "w"(_k10), // %12 "w"(_k10n), // %13 "w"(_k11), // %14 "w"(_k11n) // %15 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; output0_tm[m] += r1[m] * k01[m]; output1_tm[m] += r0[m] * k10[m]; output1_tm[m] += r1[m] * k11[m]; } r0 += 8; r1 += 8; output0_tm += 8; output1_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; k01 += 8; k10 += 8; k11 += 8; #endif // __aarch64__ #else k00 += 8; k01 += 8; k10 += 8; k11 += 8; #endif // __ARM_NEON } } } #pragma omp parallel for for (int p = remain_outch_start; p<outch; p++) { Mat out0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); out0_tm.fill(0.f); int q = 0; for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q+1); float* output0_tm = out0_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); float32x4_t _k01 = vld1q_f32(k01); float32x4_t _k01n = vld1q_f32(k01+4); #else float32x4_t _k00; float32x4_t _k00n; float32x4_t _k01; float32x4_t _k01n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {%e4-%f4}, [%1 :128]! \n" "vld1.f32 {%e3-%f3}, [%0 :128]! \n" "vld1.f32 {%e5-%f5}, [%1 :128]! \n" : "=r"(k00), // %0 "=r"(k01), // %1 "=w"(_k00), // %2 "=w"(_k00n), // %3 "=w"(_k01), // %4 "=w"(_k01n) // %5 : "0"(k00), "1"(k01) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile #if __ARM_NEON int nn = tiles >> 2; int remain = tiles & 3; #else int remain = tiles; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; _output0_tm = vld1q_f32(output0_tm); _output0_tmn = vld1q_f32(output0_tm+4); _r0 = vld1q_f32(r0); _r0n = vld1q_f32(r0+4); _r1 = vld1q_f32(r1); _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; } #else if (nn > 0) { asm volatile( "0: \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "pld [%2, #256] \n" "vld1.f32 {d24-d27}, [%2 :128]! \n"// q12 q13 = _r0 "vst1.f32 {d16-d19}, [%1 :128]! \n" "pld [%1, #256] \n" "vld1.f32 {d16-d19}, [%1 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%3, #256] \n" "vld1.f32 {d28-d31}, [%3 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q10 \n" "vmla.f32 q9, q15, %q11 \n" "vst1.f32 {d16-d19}, [%1 :128]! \n" "subs %0, #1 \n" "bne 0b \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(r0), // %2 "=r"(r1) // %3 : "0"(nn), "1"(output0_tm), "2"(r0), "3"(r1), "w"(_k00), // %8 "w"(_k00n), // %9 "w"(_k01), // %10 "w"(_k01n) // %11 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); float32x4_t _r1 = vld1q_f32(r1); float32x4_t _r1n = vld1q_f32(r1+4); r0 += 8; r1 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output0_tm = vmlaq_f32(_output0_tm, _r1, _k01); _output0_tmn = vmlaq_f32(_output0_tmn, _r1n, _k01n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q6 \n" "vmla.f32 q9, q13, %q7 \n" "pld [%2, #256] \n" "vld1.f32 {d28-d31}, [%2 :128]! \n"// q14 q15 = _r1 "vmla.f32 q8, q14, %q8 \n" "vmla.f32 q9, q15, %q9 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0), // %1 "=r"(r1) // %2 : "0"(output0_tm), "1"(r0), "2"(r1), "w"(_k00), // %6 "w"(_k00n), // %7 "w"(_k01), // %8 "w"(_k01n) // %9 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; output0_tm[m] += r1[m] * k01[m]; } r0 += 8; r1 += 8; output0_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; k01 += 8; #endif // __aarch64__ #else k00 += 8; k01 += 8; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k00 = kernel0_tm.row(q); float* output0_tm = out0_tm; for (int r=0; r<8; r++) { #if __ARM_NEON #if __aarch64__ float32x4_t _k00 = vld1q_f32(k00); float32x4_t _k00n = vld1q_f32(k00+4); #else float32x4_t _k00; float32x4_t _k00n; asm volatile( "pld [%0, #256] \n" "vld1.f32 {%e1-%f1}, [%0 :128]! \n" "vld1.f32 {%e2-%f2}, [%0 :128]! \n" : "=r"(k00), // %0 "=w"(_k00), // %1 "=w"(_k00n) // %2 : "0"(k00) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ float32x4_t _output0_tm = vld1q_f32(output0_tm); float32x4_t _output0_tmn = vld1q_f32(output0_tm+4); float32x4_t _r0 = vld1q_f32(r0); float32x4_t _r0n = vld1q_f32(r0+4); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); vst1q_f32(output0_tm, _output0_tm); vst1q_f32(output0_tm+4, _output0_tmn); output0_tm += 8; #else asm volatile( "pld [%1, #256] \n" "vld1.f32 {d24-d27}, [%1 :128]! \n"// q12 q13 = _r0 "pld [%0, #256] \n" "vld1.f32 {d16-d19}, [%0 :128] \n"// q8 q9 = _output0_tm "vmla.f32 q8, q12, %q4 \n" "vmla.f32 q9, q13, %q5 \n" "vst1.f32 {d16-d19}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00), // %4 "w"(_k00n) // %5 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; } r0 += 8; output0_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; #endif // __aarch64__ #else k00 += 8; #endif // __ARM_NEON } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; top_blob_bordered.create(outw, outh, outch); { // const float otm[6][8] = { // {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 32.0f, 32.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 2.0f, -2.0f, 16.0f,-16.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 4.0f, 4.0f, 8.0f, 8.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 8.0f, -8.0f, 4.0f, -4.0f, 0.0f}, // {0.0f, 1.0f, 1.0f, 16.0f, 16.0f, 2.0f, 2.0f, 0.0f}, // {0.0f, 1.0f, -1.0f, 32.0f, -32.0f, 1.0f, -1.0f, 1.0f} // }; // 0 = r0 + (r1 + r2) + (r3 + r4) + (r5 + r6) * 32 // 1 = (r1 - r2) + (r3 - r4) * 2 + (r5 - r6) * 16 // 2 = (r1 + r2) + (r3 + r4) * 4 + (r5 + r6) * 8 // 3 = (r1 - r2) + (r3 - r4) * 8 + (r5 - r6) * 4 // 4 = (r1 + r2) + (r3 + r4) * 16+ (r5 + r6) * 2 // 5 = r7 + (r1 - r2) + (r3 - r4) * 32+ (r5 - r6) int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = w_tm/8 * h_tm/8; #pragma omp parallel for for (int p = 0; p<outch; p++) { const Mat out0_tm = top_blob_tm.channel(p); Mat out0 = top_blob_bordered.channel(p); const float bias0 = bias ? bias[p] : 0.f; float tmp[6][8]; // tile for (int i=0; i<outh/6; i++) { for (int j=0; j<outw/6; j++) { const float* output0_tm0 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm1 = out0_tm.row(i * w_tm/8 + j + tiles); const float* output0_tm2 = out0_tm.row(i * w_tm/8 + j + tiles * 2); const float* output0_tm3 = out0_tm.row(i * w_tm/8 + j + tiles * 3); const float* output0_tm4 = out0_tm.row(i * w_tm/8 + j + tiles * 4); const float* output0_tm5 = out0_tm.row(i * w_tm/8 + j + tiles * 5); const float* output0_tm6 = out0_tm.row(i * w_tm/8 + j + tiles * 6); const float* output0_tm7 = out0_tm.row(i * w_tm/8 + j + tiles * 7); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms[8] = { output0_tm0, output0_tm1, output0_tm2, output0_tm3, output0_tm4, output0_tm5, output0_tm6, output0_tm7 }; for (int m=0; m<8; m++) { const float* output0_tm = output0_tms[m]; float tmp024a = output0_tm[1] + output0_tm[2]; float tmp135a = output0_tm[1] - output0_tm[2]; float tmp024b = output0_tm[3] + output0_tm[4]; float tmp135b = output0_tm[3] - output0_tm[4]; float tmp024c = output0_tm[5] + output0_tm[6]; float tmp135c = output0_tm[5] - output0_tm[6]; tmp[0][m] = output0_tm[0] + tmp024a + tmp024b + tmp024c * 32; tmp[2][m] = tmp024a + tmp024b * 4 + tmp024c * 8; tmp[4][m] = tmp024a + tmp024b * 16 + tmp024c + tmp024c; tmp[1][m] = tmp135a + tmp135b + tmp135b + tmp135c * 16; tmp[3][m] = tmp135a + tmp135b * 8 + tmp135c * 4; tmp[5][m] = output0_tm[7] + tmp135a + tmp135b * 32 + tmp135c; } for (int m=0; m<6; m++) { const float* tmp0 = tmp[m]; float tmp024a = tmp0[1] + tmp0[2]; float tmp135a = tmp0[1] - tmp0[2]; float tmp024b = tmp0[3] + tmp0[4]; float tmp135b = tmp0[3] - tmp0[4]; float tmp024c = tmp0[5] + tmp0[6]; float tmp135c = tmp0[5] - tmp0[6]; output0[0] = bias0 + tmp0[0] + tmp024a + tmp024b + tmp024c * 32; output0[2] = bias0 + tmp024a + tmp024b * 4 + tmp024c * 8; output0[4] = bias0 + tmp024a + tmp024b * 16 + tmp024c + tmp024c; output0[1] = bias0 + tmp135a + tmp135b + tmp135b + tmp135c * 16; output0[3] = bias0 + tmp135a + tmp135b * 8 + tmp135c * 4; output0[5] = bias0 + tmp0[7] + tmp135a + tmp135b * 32 + tmp135c; output0 += outw; } } } } } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w); } static void conv3x3s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); const float* kernel0 = kernel + p*inch*9; for (int q=0; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* r0 = img0; const float* r1 = img0 + w; const float* r2 = img0 + w*2; const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; #if __ARM_NEON float32x4_t _k0123 = vld1q_f32(k0); float32x4_t _k3456 = vld1q_f32(k1); float32x4_t _k6789 = vld1q_f32(k2); #endif // __ARM_NEON int i = 0; for (; i < outh; i++) { #if __ARM_NEON int nn = outw >> 2; int remain = outw & 3; #else int remain = outw; #endif // __ARM_NEON #if __ARM_NEON #if __aarch64__ for (; nn>0; nn--) { float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _r0 = vld2q_f32(r0); float32x4x2_t _r0n = vld2q_f32(r0+8); float32x4_t _r00 = _r0.val[0];// 0 2 4 6 float32x4_t _r01 = _r0.val[1];// 1 3 5 7 float32x4_t _r02 = vextq_f32(_r00, _r0n.val[0], 1);// 2 4 6 8 _outp = vfmaq_laneq_f32(_outp, _r00, _k0123, 0); _outp = vfmaq_laneq_f32(_outp, _r01, _k0123, 1); _outp = vfmaq_laneq_f32(_outp, _r02, _k0123, 2); float32x4x2_t _r1 = vld2q_f32(r1); float32x4x2_t _r1n = vld2q_f32(r1+8); float32x4_t _r10 = _r1.val[0]; float32x4_t _r11 = _r1.val[1]; float32x4_t _r12 = vextq_f32(_r10, _r1n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r10, _k3456, 0); _outp = vfmaq_laneq_f32(_outp, _r11, _k3456, 1); _outp = vfmaq_laneq_f32(_outp, _r12, _k3456, 2); float32x4x2_t _r2 = vld2q_f32(r2); float32x4x2_t _r2n = vld2q_f32(r2+8); float32x4_t _r20 = _r2.val[0]; float32x4_t _r21 = _r2.val[1]; float32x4_t _r22 = vextq_f32(_r20, _r2n.val[0], 1); _outp = vfmaq_laneq_f32(_outp, _r20, _k6789, 0); _outp = vfmaq_laneq_f32(_outp, _r21, _k6789, 1); _outp = vfmaq_laneq_f32(_outp, _r22, _k6789, 2); vst1q_f32(outptr, _outp); r0 += 8; r1 += 8; r2 += 8; outptr += 4; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "0: \n" "pld [%1, #128] \n" "vld1.f32 {d0-d1}, [%1] \n" "vmla.f32 q0, q2, %e10[0] \n" "vmul.f32 q10, q3, %e10[1] \n" "pld [%2, #128] \n" "vld2.f32 {d16-d17}, [%2] \n" "vext.32 q1, q2, q8, #1 \n" "vmul.f32 q11, q1, %f10[0] \n" "pld [%3, #256] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vmla.f32 q0, q2, %e11[0] \n" "vmla.f32 q10, q3, %e11[1] \n" "pld [%3, #128] \n" "vld2.f32 {d16-d17}, [%3] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f11[0] \n" "pld [%4, #256] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vmla.f32 q0, q2, %e12[0] \n" "vmla.f32 q10, q3, %e12[1] \n" "pld [%4, #128] \n" "vld2.f32 {d16-d17}, [%4] \n" "vext.32 q1, q2, q8, #1 \n" "vmla.f32 q11, q1, %f12[0] \n" "pld [%2, #256] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vadd.f32 q0, q0, q10 \n" "vadd.f32 q0, q0, q11 \n" "subs %0, #1 \n" "vst1.f32 {d0-d1}, [%1]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2) // %4 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "w"(_k0123), // %10 "w"(_k3456), // %11 "w"(_k6789) // %12 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON float32x4_t _r00 = vld1q_f32(r0); float32x4_t _r10 = vld1q_f32(r1); float32x4_t _r20 = vld1q_f32(r2); float32x4_t _sum = vmulq_f32(_r00, _k0123); _sum = vmlaq_f32(_sum, _r10, _k3456); _sum = vmlaq_f32(_sum, _r20, _k6789); _sum = vsetq_lane_f32(*outptr, _sum, 3); #if __aarch64__ *outptr = vaddvq_f32(_sum); #else float32x2_t _ss = vadd_f32(vget_low_f32(_sum), vget_high_f32(_sum)); _ss = vpadd_f32(_ss, _ss); *outptr = vget_lane_f32(_ss, 0); #endif // __aarch64__ #else float sum = 0; sum += r0[0] * k0[0]; sum += r0[1] * k0[1]; sum += r0[2] * k0[2]; sum += r1[0] * k1[0]; sum += r1[1] * k1[1]; sum += r1[2] * k1[2]; sum += r2[0] * k2[0]; sum += r2[1] * k2[1]; sum += r2[2] * k2[2]; *outptr += sum; #endif // __ARM_NEON r0 += 2; r1 += 2; r2 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; } kernel0 += 9; } } }
taskgroup.c
// RUN: %libomp-compile-and-run | %sort-threads | FileCheck %s // REQUIRES: ompt // UNSUPPORTED: gcc-4, gcc-5, gcc-6, gcc-7, gcc-8 #include "callback.h" #include <unistd.h> #include <stdio.h> int main() { int condition=0; int x=0; #pragma omp parallel num_threads(2) { #pragma omp master { #pragma omp taskgroup { print_current_address(1); #pragma omp task { #pragma omp atomic x++; } } print_current_address(2); } } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_master' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_create' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_task_schedule' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_cancel' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_thread_begin' // CHECK: {{^}}0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_taskgroup_begin: parallel_id=[[PARALLEL_ID:[0-9]+]], task_id=[[TASK_ID:[0-9]+]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]] // CHECK-NEXT: {{^}}[[MASTER_ID]]: current_address={{.*}}[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_taskgroup_begin: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]], codeptr_ra=[[RETURN_ADDRESS:0x[0-f]+]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_wait_taskgroup_end: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]], codeptr_ra=[[RETURN_ADDRESS]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_taskgroup_end: parallel_id=[[PARALLEL_ID]], task_id=[[TASK_ID]], codeptr_ra=[[RETURN_ADDRESS]] // CHECK-NEXT: {{^}}[[MASTER_ID]]: current_address={{.*}}[[RETURN_ADDRESS]] return 0; }
GB_AxB_dot2_template.c
//------------------------------------------------------------------------------ // GB_AxB_dot2_template: C=A'B, C<!M>=A'*B, or C<M>=A'*B via dot products //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // A and B are sparse, bitmap, or full; never hypersparse. If the input // matrices A and/or B are hypersparse, they are packed into sparse matrices, // and C is unpacked from bitmap to sparse/hypersparse when done. #if ( !GB_A_IS_HYPER && !GB_B_IS_HYPER ) { //-------------------------------------------------------------------------- // C=A'*B, C<M>=A'*B, or C<!M>=A'*B where C is bitmap //-------------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:cnvals) for (tid = 0 ; tid < ntasks ; tid++) { //---------------------------------------------------------------------- // get the task descriptor //---------------------------------------------------------------------- const int a_tid = tid / nbslice ; const int b_tid = tid % nbslice ; const int64_t kA_start = A_slice [a_tid] ; const int64_t kA_end = A_slice [a_tid+1] ; const int64_t kB_start = B_slice [b_tid] ; const int64_t kB_end = B_slice [b_tid+1] ; int64_t task_cnvals = 0 ; //---------------------------------------------------------------------- // C=A'*B, C<M>=A'*B, or C<!M>=A'*B via dot products //---------------------------------------------------------------------- for (int64_t j = kB_start ; j < kB_end ; j++) { //------------------------------------------------------------------ // get B(:,j) and C(:,j) //------------------------------------------------------------------ const int64_t pC_start = j * cvlen ; #if GB_B_IS_SPARSE // B is sparse (never hypersparse) const int64_t pB_start = Bp [j] ; const int64_t pB_end = Bp [j+1] ; const int64_t bjnz = pB_end - pB_start ; if (bjnz == 0) { // no work to do if B(:,j) is empty, except to clear Cb memset (&Cb [pC_start + kA_start], 0, kA_end - kA_start) ; continue ; } #if GB_A_IS_SPARSE // Both A and B are sparse; get first and last in B(:,j) const int64_t ib_first = Bi [pB_start] ; const int64_t ib_last = Bi [pB_end-1] ; #endif #else // B is bitmap or full const int64_t pB_start = j * vlen ; #endif //------------------------------------------------------------------ // C(:,j)<#M(:,j)> = A'*B(:,j), or C(:,j) = A'*B(:,j) if no mask //------------------------------------------------------------------ for (int64_t i = kA_start ; i < kA_end ; i++) { //-------------------------------------------------------------- // get C(i,j), M(i,j), and clear the C(i,j) bitmap //-------------------------------------------------------------- int64_t pC = pC_start + i ; // C is bitmap #if defined ( GB_ANY_SPECIALIZED ) // M is bitmap and structural; Mask_comp true Cb [pC] = 0 ; if (!Mb [pC]) #elif defined ( GB_MASK_IS_PRESENT ) bool mij ; if (M_is_bitmap) { // M is bitmap mij = Mb [pC] && GB_mcast (Mx, pC, msize) ; } else if (M_is_full) { // M is full mij = GB_mcast (Mx, pC, msize) ; } else // M is sparse or hyper { // M has been scattered into the C bitmap mij = (Cb [pC] > 1) ; } Cb [pC] = 0 ; if (mij ^ Mask_comp) #else // M is not present Cb [pC] = 0 ; #endif { //---------------------------------------------------------- // the mask allows C(i,j) to be computed //---------------------------------------------------------- #if GB_A_IS_SPARSE // A is sparse int64_t pA = Ap [i] ; const int64_t pA_end = Ap [i+1] ; const int64_t ainz = pA_end - pA ; if (ainz > 0) #else // A is bitmap or full const int64_t pA = i * vlen ; #endif { // C(i,j) = A(:,i)'*B(:,j) bool cij_exists = false ; GB_CIJ_DECLARE (cij) ; #include "GB_AxB_dot_cij.c" } } } } cnvals += task_cnvals ; } } #endif #undef GB_A_IS_SPARSE #undef GB_A_IS_HYPER #undef GB_A_IS_BITMAP #undef GB_A_IS_FULL #undef GB_B_IS_SPARSE #undef GB_B_IS_HYPER #undef GB_B_IS_BITMAP #undef GB_B_IS_FULL
ht_bottom_up.c
#include <stdint.h> #include <stdio.h> #include <omp.h> #define ONE 0x0000000000000001 #define ZERO 0 #define COPROC_XADJ_SIZE uint32_t #define DEBUG 0 extern int __htc_get_unit_count(); #pragma rhomp max_phys_threads(9) #pragma omp declare target // These functions will be compiled for the coprocessor // ---------------------------------------------------------------------- uint8_t bufp(uint32_t vertex, uint64_t xoff[], COPROC_XADJ_SIZE xadj[], uint64_t bfs_tree[], uint64_t bmapOldAddr[], uint8_t xadj_index_shift) { uint8_t updated = 1; uint64_t xoff0 = xoff[2*vertex]; uint64_t xoff1 = xoff[2*vertex+1]; /* if ( (xoff1 - vso) <= 0 ) { // clear done ones // BMAP_UPD: bit_working = bit_working & ( (one << bitCnt) ^ one64); updated = 1; return updated; } */ // updated = (xoff1 - vso) <= 0; // each pipe does for loop for (xoff0 = xoff0; xoff0 < xoff1; ++xoff0) { COPROC_XADJ_SIZE neighbor = xadj[xoff0 << xadj_index_shift]; // XADJ_LD uint32_t bmapIdx = neighbor >> 6; uint64_t oldAddr = bmapOldAddr[bmapIdx]; // Careful ordering of bmapBitIdx after reading bmapOldAddr allows // bmapBitIdx to be a temp and not allocated as part of private // state. uint8_t bmapBitIdx = neighbor & 0x3f; // is neighbor in frontier? // check old bit map instead of level updated = 0; if (((oldAddr >> bmapBitIdx) & ONE) == ZERO) { updated = 1; // moved before next stmt to save a state bfs_tree[vertex] = neighbor; // have each pipe write this break; } } return updated; } #define BFS_PACKED_X(k) (bfsPackedAddr[2*k]) #define VLIST_X(k) (bfsPackedAddr[2*k+1]) #pragma omp end declare target enum CommandType { INIT, SCATTER, BFS }; void bottom_up_ctl(uint8_t function, uint64_t *bfsAddr, /* bfs_tree */ uint64_t *bfsPackedAddr, /* bfs_packed */ uint64_t *bmapOldAddr, /* bfs_tree_bit */ uint64_t *bmapNewAddr, /* bfs_tree_bit_new */ uint64_t *xoff, COPROC_XADJ_SIZE *xadj, /* CTL parameters */ uint32_t ub1, uint64_t *update_count ) { // coprocessor entry point uint8_t unitCnt = __htc_get_unit_count(); uint32_t chunk = (uint32_t)((ub1 / unitCnt) + 1); #pragma omp target teams num_teams(unitCnt) { uint8_t unit = omp_get_team_num(); uint64_t lb = (uint64_t)(unit*chunk); uint64_t ub = lb + chunk; if (ub > ub1) { ub = ub1; } uint32_t nt = ub-lb+1; uint32_t my_update_count = 0; if (nt > 512) nt = 512; #pragma omp parallel num_threads(nt) { switch (function) { case INIT: { { #pragma omp for nowait schedule(static,1) for (uint32_t k=lb; k<ub; k++) { bfsAddr[k] = 0xffffffffffffffffULL; } } } break; case SCATTER: { { #pragma omp for nowait schedule(static, 1) for (uint32_t k=lb; k<ub; k++) { bfsAddr[VLIST_X(k)] = BFS_PACKED_X(k); } } } break; case BFS: { //#pragma omp for nowait schedule(static, 1) reduction(+:my_update_count) #pragma omp for nowait schedule(static, 1) for (uint32_t index = lb; index < ub; index ++) { uint64_t mask; uint8_t bitCnt = 0; uint8_t bmapUpdCnt = 0; mask = bmapOldAddr[index]; if (mask != 0) { for (bitCnt = bitCnt; bitCnt < 64; bitCnt++) { if ( ((mask >> bitCnt) & ONE) == ONE) { // call bufp uint32_t vertex = (uint32_t)(index*64) + bitCnt; if (bufp(vertex, xoff, xadj, bfsAddr, bmapOldAddr, (uint8_t) (((uint64_t)bfsPackedAddr) & 0x1) /* xadj_index_shift */) & 0x1){ mask = mask & ~(1ULL << bitCnt); bmapUpdCnt++; } } else { uint16_t tmask = (uint16_t)(mask >> (bitCnt+1)); uint16_t skip = 0; if ((tmask & 0xff) == 0) { skip = 8; tmask >>= 8; } if ((tmask & 0x0f) == 0) { skip += 4; tmask >>= 4; } if ((tmask & 0x03) == 0) { skip += 2; tmask >>= 2; } skip += (1-(tmask & 0x1)); bitCnt += skip; } // // if ((bitCnt > 63) || (mask <= (1ULL < bitCnt))) { // bitCnt = 63; // no more higher // } // break state with comment } } if (bmapUpdCnt) { my_update_count += bmapUpdCnt; } bmapNewAddr[index] = mask; } *update_count = (uint64_t)my_update_count; } break; } } /* end of parallel */ if (function==BFS) { update_count[unit] = (uint64_t)my_update_count; } } /* pragma omp target */ } /* extern "C" */ void pers_init_bfs_tree (int64_t nv, uint64_t *bfs_tree) { #if DEBUG int unitCnt = __htc_get_unit_count(); fprintf(stderr, "pers_init_bfs_tree: #AUs = %d\n", unitCnt); #endif uint64_t ub1 = (uint64_t) nv; #if DEBUG printf("in pers_init_bfs_tree num_threads is %d\n", omp_get_num_threads()); #endif bottom_up_ctl(INIT, bfs_tree, /* bfsAddr */ 0, /* bfs_packed */ 0, /* bfs_tree_bit */ 0, /* bfs_tree_bit_new */ 0, /* xoff */ 0, /* xadj */ ub1, 0); #if DEBUG fprintf(stderr, "pers_init_bfs_tree: all units returned\n"); #endif } /* extern "C" */ void pers_scatter_bfs (uint64_t *k2, uint64_t *bfs_tree, uint64_t *bfs_packed) { #if DEBUG int unitCnt = __htc_get_unit_count(); fprintf(stderr, "pers_scatter_bfs: #AUs = %d\n", unitCnt); #endif // BFS_SIZE used for K2 on scatter instruction uint64_t S_bfsSize = *k2; #if DEBUG fprintf(stderr,"bfsSize is %ld\n", S_bfsSize); #endif uint64_t ub1 = S_bfsSize; #if DEBUG printf("in scatter num_threads is %d\n", omp_get_num_threads()); #endif bottom_up_ctl(SCATTER, bfs_tree, /* bfsAddr */ bfs_packed, /* bfs_packed */ 0, /* bfs_tree_bit */ 0, /* bfs_tree_bit_new */ 0, /* xoff */ 0, /* xadj */ ub1, 0); #if DEBUG fprintf(stderr, "pers_scatter_bfs: all units returned\n"); #endif } /* extern "C" */ void pers_bottom_up ( int64_t g500_ctl, int64_t nv, uint64_t *bfs_tree, uint64_t *bfs_packed_cp, COPROC_XADJ_SIZE *xadj, uint64_t *xoff, uint64_t **bfs_tree_bit, uint64_t **bfs_tree_bit_new, uint64_t *k1, uint64_t *k2, uint64_t *oldk2) { #if DEBUG fprintf(stderr, "pers_bottom_up: start \n"); #endif int unitCnt = __htc_get_unit_count(); uint64_t bfsSize = (uint64_t) nv; uint64_t ub1 = (bfsSize + 63) >> 6; /* bfsSize / 64 */ while (*k1 != *k2) { *oldk2 = *k2; #if DEBUG fprintf(stderr, "pers_bottom_up: #AUs = %d\n", unitCnt); #endif uint64_t updCnt = 0; int unit; uint64_t update_count[64]; //#pragma omp parallel num_threads(unitCnt) reduction(+:updCnt) //#pragma omp for nowait schedule(static , 1) private(unit) for (unit = 0; unit < unitCnt; unit++) { update_count[unit] = 0; } bottom_up_ctl(BFS, bfs_tree, /* bfsAddr */ (uint64_t *) ((g500_ctl & 0xFFFFFF) == 64), /* xadj_index_shift passed in bfs_packed slot */ *bfs_tree_bit, /* bfs_tree_bit */ *bfs_tree_bit_new, /* bfs_tree_bit_new */ xoff, /* xoff */ xadj, /* xadj */ ub1, /* ub */ &update_count[0]); for (uint8_t unit = 0; unit < unitCnt; unit++) { updCnt += update_count[unit]; } #if DEBUG fprintf(stderr, "pers_bottom_up: all units returned, updCnt = %lld\n", (long long)updCnt); #endif *k2 += updCnt; *k1 = *oldk2; // flip addresses for next iteration uint64_t *temp; temp = *bfs_tree_bit; *bfs_tree_bit = *bfs_tree_bit_new; *bfs_tree_bit_new = temp; } /* while (*k1 != *k2) */ }
kinFoodWeb_kry_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Ting Yan @ SMU * Based on kinFoodWeb_kry.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2019, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example (serial): * * This example solves a nonlinear system that arises from a system * of partial differential equations. The PDE system is a food web * population model, with predator-prey interaction and diffusion * on the unit square in two dimensions. The dependent variable * vector is the following: * * 1 2 ns * c = (c , c , ..., c ) (denoted by the variable cc) * * and the PDE's are as follows: * * i i * 0 = d(i)*(c + c ) + f (x,y,c) (i=1,...,ns) * xx yy i * * where * * i ns j * f (x,y,c) = c * (b(i) + sum a(i,j)*c ) * i j=1 * * The number of species is ns = 2 * np, with the first np being * prey and the last np being predators. The number np is both the * number of prey and predator species. The coefficients a(i,j), * b(i), d(i) are: * * a(i,i) = -AA (all i) * a(i,j) = -GG (i <= np , j > np) * a(i,j) = EE (i > np, j <= np) * b(i) = BB * (1 + alpha * x * y) (i <= np) * b(i) =-BB * (1 + alpha * x * y) (i > np) * d(i) = DPREY (i <= np) * d(i) = DPRED ( i > np) * * The various scalar parameters are set using define's or in * routine InitUserData. * * The boundary conditions are: normal derivative = 0, and the * initial guess is constant in x and y, but the final solution * is not. * * The PDEs are discretized by central differencing on an MX by * MY mesh. * * The nonlinear system is solved by KINSOL using the method * specified in the local variable globalstrat. * * The preconditioner matrix is a block-diagonal matrix based on * the partial derivatives of the interaction terms f only. * * Constraints are imposed to make all components of the solution * positive. * * Optionally, we can set the number of threads with an environment * variable or from the command line. To check the current value * for number of threads set by the environment variable: * % echo $OMP_NUM_THREADS * * Execution: * * If the user wants to use the default value or the number of * threads set by the environment variable use * % ./kinFoodWeb_kry_omp * If the user wants to specify the number of threads to use * % ./kinFoodWeb_kry_omp num_threads * where num_threads is the number of threads the user wants to use * * ----------------------------------------------------------------- * References: * * 1. Peter N. Brown and Youcef Saad, * Hybrid Krylov Methods for Nonlinear Systems of Equations * LLNL report UCRL-97645, November 1987. * * 2. Peter N. Brown and Alan C. Hindmarsh, * Reduced Storage Matrix Methods in Stiff ODE systems, * Lawrence Livermore National Laboratory Report UCRL-95088, * Rev. 1, June 1987, and Journal of Applied Mathematics and * Computation, Vol. 31 (May 1989), pp. 40-91. (Presents a * description of the time-dependent version of this test * problem.) * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <kinsol/kinsol.h> /* access to KINSOL func., consts. */ #include <nvector/nvector_openmp.h> /* access to OpenMP N_Vector */ #include <sunlinsol/sunlinsol_spgmr.h> /* access to SPGMR SUNLinearSolver */ #include <sundials/sundials_dense.h> /* use generic dense solver in precond. */ #include <sundials/sundials_types.h> /* defs. of realtype, sunindextype */ #ifdef _OPENMP #include <omp.h> #endif /* helpful macros */ #ifndef MAX #define MAX(A, B) ((A) > (B) ? (A) : (B)) #endif /* Problem Constants */ #define NUM_SPECIES 6 /* must equal 2*(number of prey or predators) number of prey = number of predators */ #define PI RCONST(3.1415926535898) /* pi */ #define MX 8 /* MX = number of x mesh points */ #define MY 8 /* MY = number of y mesh points */ #define NSMX (NUM_SPECIES * MX) #define NEQ (NSMX * MY) /* number of equations in the system */ #define AA RCONST(1.0) /* value of coefficient AA in above eqns */ #define EE RCONST(10000.) /* value of coefficient EE in above eqns */ #define GG RCONST(0.5e-6) /* value of coefficient GG in above eqns */ #define BB RCONST(1.0) /* value of coefficient BB in above eqns */ #define DPREY RCONST(1.0) /* value of coefficient dprey above */ #define DPRED RCONST(0.5) /* value of coefficient dpred above */ #define ALPHA RCONST(1.0) /* value of coefficient alpha above */ #define AX RCONST(1.0) /* total range of x variable */ #define AY RCONST(1.0) /* total range of y variable */ #define FTOL RCONST(1.e-7) /* ftol tolerance */ #define STOL RCONST(1.e-13) /* stol tolerance */ #define THOUSAND RCONST(1000.0) /* one thousand */ #define ZERO RCONST(0.0) /* 0. */ #define ONE RCONST(1.0) /* 1. */ #define TWO RCONST(2.0) /* 2. */ #define PREYIN RCONST(1.0) /* initial guess for prey concentrations. */ #define PREDIN RCONST(30000.0)/* initial guess for predator concs. */ /* User-defined vector access macro: IJ_Vptr */ /* IJ_Vptr is defined in order to translate from the underlying 3D structure of the dependent variable vector to the 1D storage scheme for an N-vector. IJ_Vptr(vv,i,j) returns a pointer to the location in vv corresponding to indices is = 0, jx = i, jy = j. */ #define IJ_Vptr(vv,i,j) (&NV_Ith_OMP(vv, i*NUM_SPECIES + j*NSMX)) /* Type : UserData contains preconditioner blocks, pivot arrays, and problem constants */ typedef struct { realtype **P[MX][MY]; sunindextype *pivot[MX][MY]; realtype **acoef, *bcoef; N_Vector rates; realtype *cox, *coy; realtype ax, ay, dx, dy; realtype uround, sqruround; sunindextype mx, my, ns, np; int nthreads; } *UserData; /* Functions Called by the KINSOL Solver */ static int func(N_Vector cc, N_Vector fval, void *user_data); static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data); static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data); /* Private Helper Functions */ static UserData AllocUserData(void); static void InitUserData(UserData data); static void FreeUserData(UserData data); static void SetInitialProfiles(N_Vector cc, N_Vector sc); static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol); static void PrintOutput(N_Vector cc); static void PrintFinalStats(void *kmem); static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data); static realtype DotProd(sunindextype size, realtype *x1, realtype *x2); static int check_flag(void *flagvalue, const char *funcname, int opt); /* *-------------------------------------------------------------------- * MAIN PROGRAM *-------------------------------------------------------------------- */ int main(int argc, char *argv[]) { int globalstrategy; realtype fnormtol, scsteptol; N_Vector cc, sc, constraints; UserData data; int flag, maxl, maxlrst; void *kmem; SUNLinearSolver LS; int num_threads; cc = sc = constraints = NULL; kmem = NULL; LS = NULL; data = NULL; /* Allocate memory, and set problem data, initial values, tolerances */ globalstrategy = KIN_NONE; /* Set the number of threads to use */ num_threads = 1; /* default value*/ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrithe with command line value, if supplied */ num_threads = (int) strtol(argv[1], NULL, 0); data = AllocUserData(); if (check_flag((void *)data, "AllocUserData", 2)) return(1); InitUserData(data); data->nthreads = num_threads; /* Create serial vectors of length NEQ */ cc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)cc, "N_VNew_OpenMP", 0)) return(1); sc = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)sc, "N_VNew_OpenMP", 0)) return(1); data->rates = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)data->rates, "N_VNew_OpenMP", 0)) return(1); constraints = N_VNew_OpenMP(NEQ, num_threads); if (check_flag((void *)constraints, "N_VNew_OpenMP", 0)) return(1); N_VConst(TWO, constraints); SetInitialProfiles(cc, sc); fnormtol=FTOL; scsteptol=STOL; /* Call KINCreate/KINInit to initialize KINSOL. A pointer to KINSOL problem memory is returned and stored in kmem. */ kmem = KINCreate(); if (check_flag((void *)kmem, "KINCreate", 0)) return(1); /* Vector cc passed as template vector. */ flag = KINInit(kmem, func, cc); if (check_flag(&flag, "KINInit", 1)) return(1); flag = KINSetUserData(kmem, data); if (check_flag(&flag, "KINSetUserData", 1)) return(1); flag = KINSetConstraints(kmem, constraints); if (check_flag(&flag, "KINSetConstraints", 1)) return(1); flag = KINSetFuncNormTol(kmem, fnormtol); if (check_flag(&flag, "KINSetFuncNormTol", 1)) return(1); flag = KINSetScaledStepTol(kmem, scsteptol); if (check_flag(&flag, "KINSetScaledStepTol", 1)) return(1); /* We no longer need the constraints vector since KINSetConstraints creates a private copy for KINSOL to use. */ N_VDestroy(constraints); /* Create SUNLinSol_SPGMR object with right preconditioning and the maximum Krylov dimension maxl */ maxl = 15; LS = SUNLinSol_SPGMR(cc, PREC_RIGHT, maxl); if(check_flag((void *)LS, "SUNLinSol_SPGMR", 0)) return(1); /* Attach the linear solver to KINSOL */ flag = KINSetLinearSolver(kmem, LS, NULL); if (check_flag(&flag, "KINSetLinearSolver", 1)) return 1; /* Set the maximum number of restarts */ maxlrst = 2; flag = SUNLinSol_SPGMRSetMaxRestarts(LS, maxlrst); if (check_flag(&flag, "SUNLinSol_SPGMRSetMaxRestarts", 1)) return(1); /* Specify the preconditioner setup and solve routines */ flag = KINSetPreconditioner(kmem, PrecSetupBD, PrecSolveBD); if (check_flag(&flag, "KINSetPreconditioner", 1)) return(1); /* Print out the problem size, solution parameters, initial guess. */ PrintHeader(globalstrategy, maxl, maxlrst, fnormtol, scsteptol); /* Call KINSol and print output concentration profile */ flag = KINSol(kmem, /* KINSol memory block */ cc, /* initial guess on input; solution vector */ globalstrategy, /* global strategy choice */ sc, /* scaling vector for the variable cc */ sc); /* scaling vector for function values fval */ if (check_flag(&flag, "KINSol", 1)) return(1); printf("\n\nComputed equilibrium species concentrations:\n"); PrintOutput(cc); /* Print final statistics and free memory */ PrintFinalStats(kmem); printf("num_threads = %i\n", num_threads); N_VDestroy(cc); N_VDestroy(sc); KINFree(&kmem); SUNLinSolFree(LS); FreeUserData(data); return(0); } /* Readability definitions used in other routines below */ #define acoef (data->acoef) #define bcoef (data->bcoef) #define cox (data->cox) #define coy (data->coy) /* *-------------------------------------------------------------------- * FUNCTIONS CALLED BY KINSOL *-------------------------------------------------------------------- */ /* * System function for predator-prey system */ static int func(N_Vector cc, N_Vector fval, void *user_data) { realtype xx, yy, delx, dely, *cxy, *rxy, *fxy, dcyli, dcyui, dcxli, dcxri; sunindextype jx, jy, is, idyu, idyl, idxr, idxl; UserData data; data = (UserData)user_data; delx = data->dx; dely = data->dy; /* Loop over all mesh points, evaluating rate array at each point*/ for (jy = 0; jy < MY; jy++) { yy = dely*jy; /* Set lower/upper index shifts, special at boundaries. */ idyl = (jy != 0 ) ? NSMX : -NSMX; idyu = (jy != MY-1) ? NSMX : -NSMX; for (jx = 0; jx < MX; jx++) { xx = delx*jx; /* Set left/right index shifts, special at boundaries. */ idxl = (jx != 0 ) ? NUM_SPECIES : -NUM_SPECIES; idxr = (jx != MX-1) ? NUM_SPECIES : -NUM_SPECIES; cxy = IJ_Vptr(cc,jx,jy); rxy = IJ_Vptr(data->rates,jx,jy); fxy = IJ_Vptr(fval,jx,jy); /* Get species interaction rate array at (xx,yy) */ WebRate(xx, yy, cxy, rxy, user_data); for(is = 0; is < NUM_SPECIES; is++) { /* Differencing in x direction */ dcyli = *(cxy+is) - *(cxy - idyl + is) ; dcyui = *(cxy + idyu + is) - *(cxy+is); /* Differencing in y direction */ dcxli = *(cxy+is) - *(cxy - idxl + is); dcxri = *(cxy + idxr +is) - *(cxy+is); /* Compute the total rate value at (xx,yy) */ fxy[is] = (coy)[is] * (dcyui - dcyli) + (cox)[is] * (dcxri - dcxli) + rxy[is]; } /* end of is loop */ } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner setup routine. Generate and preprocess P. */ static int PrecSetupBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, void *user_data) { realtype r, r0, uround, sqruround, xx, yy, delx, dely, csave, fac; realtype *cxy, *scxy, **Pxy, *ratesxy, *Pxycol, perturb_rates[NUM_SPECIES]; sunindextype i, j, jx, jy, ret; UserData data; data = (UserData) user_data; delx = data->dx; dely = data->dy; uround = data->uround; sqruround = data->sqruround; fac = N_VWL2Norm(fval, fscale); r0 = THOUSAND * uround * fac * NEQ; if(r0 == ZERO) r0 = ONE; /* Loop over spatial points; get size NUM_SPECIES Jacobian block at each */ for (jy = 0; jy < MY; jy++) { yy = jy*dely; for (jx = 0; jx < MX; jx++) { xx = jx*delx; Pxy = (data->P)[jx][jy]; cxy = IJ_Vptr(cc,jx,jy); scxy= IJ_Vptr(cscale,jx,jy); ratesxy = IJ_Vptr((data->rates),jx,jy); /* Compute difference quotients of interaction rate fn. */ for (j = 0; j < NUM_SPECIES; j++) { csave = cxy[j]; /* Save the j,jx,jy element of cc */ r = MAX(sqruround*fabs(csave), r0/scxy[j]); cxy[j] += r; /* Perturb the j,jx,jy element of cc */ fac = ONE/r; WebRate(xx, yy, cxy, perturb_rates, data); /* Restore j,jx,jy element of cc */ cxy[j] = csave; /* Load the j-th column of difference quotients */ Pxycol = Pxy[j]; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) Pxycol[i] = (perturb_rates[i] - ratesxy[i]) * fac; } /* end of j loop */ /* Do LU decomposition of size NUM_SPECIES preconditioner block */ ret = denseGETRF(Pxy, NUM_SPECIES, NUM_SPECIES, (data->pivot)[jx][jy]); if (ret != 0) return(1); } /* end of jx loop */ } /* end of jy loop */ return(0); } /* * Preconditioner solve routine */ static int PrecSolveBD(N_Vector cc, N_Vector cscale, N_Vector fval, N_Vector fscale, N_Vector vv, void *user_data) { realtype **Pxy, *vxy; sunindextype *piv, jx, jy; UserData data; data = (UserData)user_data; #pragma omp parallel for collapse(2) default(shared) private(jx, jy, Pxy, piv, vxy) schedule(static) for (jx=0; jx<MX; jx++) { for (jy=0; jy<MY; jy++) { /* For each (jx,jy), solve a linear system of size NUM_SPECIES. vxy is the address of the corresponding portion of the vector vv; Pxy is the address of the corresponding block of the matrix P; piv is the address of the corresponding block of the array pivot. */ vxy = IJ_Vptr(vv,jx,jy); Pxy = (data->P)[jx][jy]; piv = (data->pivot)[jx][jy]; denseGETRS(Pxy, NUM_SPECIES, piv, vxy); } /* end of jy loop */ } /* end of jx loop */ return(0); } /* * Interaction rate function routine */ static void WebRate(realtype xx, realtype yy, realtype *cxy, realtype *ratesxy, void *user_data) { sunindextype i; realtype fac; UserData data; data = (UserData)user_data; for (i = 0; i<NUM_SPECIES; i++) ratesxy[i] = DotProd(NUM_SPECIES, cxy, acoef[i]); fac = ONE + ALPHA * xx * yy; #pragma omp parallel for default(shared) private(i) for (i = 0; i < NUM_SPECIES; i++) ratesxy[i] = cxy[i] * ( bcoef[i] * fac + ratesxy[i] ); } /* * Dot product routine for realtype arrays */ static realtype DotProd(sunindextype size, realtype *x1, realtype *x2) { sunindextype i; realtype *xx1, *xx2, temp = ZERO; xx1 = x1; xx2 = x2; for (i = 0; i < size; i++) temp += (*xx1++) * (*xx2++); return(temp); } /* *-------------------------------------------------------------------- * PRIVATE FUNCTIONS *-------------------------------------------------------------------- */ /* * Allocate memory for data structure of type UserData */ static UserData AllocUserData(void) { int jx, jy; UserData data; data = (UserData) malloc(sizeof *data); for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { (data->P)[jx][jy] = newDenseMat(NUM_SPECIES, NUM_SPECIES); (data->pivot)[jx][jy] = newIndexArray(NUM_SPECIES); } } acoef = newDenseMat(NUM_SPECIES, NUM_SPECIES); bcoef = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); cox = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); coy = (realtype *)malloc(NUM_SPECIES * sizeof(realtype)); return(data); } /* * Load problem constants in data */ static void InitUserData(UserData data) { sunindextype i, j, np; realtype *a1,*a2, *a3, *a4, dx2, dy2; data->mx = MX; data->my = MY; data->ns = NUM_SPECIES; data->np = NUM_SPECIES/2; data->ax = AX; data->ay = AY; data->dx = (data->ax)/(MX-1); data->dy = (data->ay)/(MY-1); data->uround = UNIT_ROUNDOFF; data->sqruround = sqrt(data->uround); /* Set up the coefficients a and b plus others found in the equations */ np = data->np; dx2=(data->dx)*(data->dx); dy2=(data->dy)*(data->dy); for (i = 0; i < np; i++) { a1= &(acoef[i][np]); a2= &(acoef[i+np][0]); a3= &(acoef[i][0]); a4= &(acoef[i+np][np]); /* Fill in the portion of acoef in the four quadrants, row by row */ for (j = 0; j < np; j++) { *a1++ = -GG; *a2++ = EE; *a3++ = ZERO; *a4++ = ZERO; } /* and then change the diagonal elements of acoef to -AA */ acoef[i][i]=-AA; acoef[i+np][i+np] = -AA; bcoef[i] = BB; bcoef[i+np] = -BB; cox[i]=DPREY/dx2; cox[i+np]=DPRED/dx2; coy[i]=DPREY/dy2; coy[i+np]=DPRED/dy2; } } /* * Free data memory */ static void FreeUserData(UserData data) { int jx, jy; for (jx=0; jx < MX; jx++) { for (jy=0; jy < MY; jy++) { destroyMat((data->P)[jx][jy]); destroyArray((data->pivot)[jx][jy]); } } destroyMat(acoef); free(bcoef); free(cox); free(coy); N_VDestroy(data->rates); free(data); } /* * Set initial conditions in cc */ static void SetInitialProfiles(N_Vector cc, N_Vector sc) { int i, jx, jy; realtype *cloc, *sloc; realtype ctemp[NUM_SPECIES], stemp[NUM_SPECIES]; /* Initialize arrays ctemp and stemp used in the loading process */ for (i = 0; i < NUM_SPECIES/2; i++) { ctemp[i] = PREYIN; stemp[i] = ONE; } for (i = NUM_SPECIES/2; i < NUM_SPECIES; i++) { ctemp[i] = PREDIN; stemp[i] = RCONST(0.00001); } /* Load initial profiles into cc and sc vector from ctemp and stemp. */ for (jy = 0; jy < MY; jy++) { for (jx = 0; jx < MX; jx++) { cloc = IJ_Vptr(cc,jx,jy); sloc = IJ_Vptr(sc,jx,jy); for (i = 0; i < NUM_SPECIES; i++) { cloc[i] = ctemp[i]; sloc[i] = stemp[i]; } } } } /* * Print first lines of output (problem description) */ static void PrintHeader(int globalstrategy, int maxl, int maxlrst, realtype fnormtol, realtype scsteptol) { printf("\nPredator-prey test problem -- KINSol (OpenMP version)\n\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Number of species = %d\n", NUM_SPECIES); printf("Total system size = %d\n\n", NEQ); printf("Flag globalstrategy = %d (0 = None, 1 = Linesearch)\n", globalstrategy); printf("Linear solver is SPGMR with maxl = %d, maxlrst = %d\n", maxl, maxlrst); printf("Preconditioning uses interaction-only block-diagonal matrix\n"); printf("Positivity constraints imposed on all components \n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: fnormtol = %Lg scsteptol = %Lg\n", fnormtol, scsteptol); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #else printf("Tolerance parameters: fnormtol = %g scsteptol = %g\n", fnormtol, scsteptol); #endif printf("\nInitial profile of concentration\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At all mesh points: %Lg %Lg %Lg %Lg %Lg %Lg\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #else printf("At all mesh points: %g %g %g %g %g %g\n", PREYIN, PREYIN, PREYIN, PREDIN, PREDIN, PREDIN); #endif } /* * Print sampled values of current cc */ static void PrintOutput(N_Vector cc) { int is, jx, jy; realtype *ct; jy = 0; jx = 0; ct = IJ_Vptr(cc,jx,jy); printf("\nAt bottom left:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++){ if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } jy = MY-1; jx = MX-1; ct = IJ_Vptr(cc,jx,jy); printf("\n\nAt top right:"); /* Print out lines with up to 6 values per line */ for (is = 0; is < NUM_SPECIES; is++) { if ((is%6)*6 == is) printf("\n"); #if defined(SUNDIALS_EXTENDED_PRECISION) printf(" %Lg",ct[is]); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf(" %g",ct[is]); #else printf(" %g",ct[is]); #endif } printf("\n\n"); } /* * Print final statistics contained in iopt */ static void PrintFinalStats(void *kmem) { long int nni, nfe, nli, npe, nps, ncfl, nfeSG; int flag; flag = KINGetNumNonlinSolvIters(kmem, &nni); check_flag(&flag, "KINGetNumNonlinSolvIters", 1); flag = KINGetNumFuncEvals(kmem, &nfe); check_flag(&flag, "KINGetNumFuncEvals", 1); flag = KINGetNumLinIters(kmem, &nli); check_flag(&flag, "KINGetNumLinIters", 1); flag = KINGetNumPrecEvals(kmem, &npe); check_flag(&flag, "KINGetNumPrecEvals", 1); flag = KINGetNumPrecSolves(kmem, &nps); check_flag(&flag, "KINGetNumPrecSolves", 1); flag = KINGetNumLinConvFails(kmem, &ncfl); check_flag(&flag, "KINGetNumLinConvFails", 1); flag = KINGetNumLinFuncEvals(kmem, &nfeSG); check_flag(&flag, "KINGetNumLinFuncEvals", 1); printf("Final Statistics.. \n"); printf("nni = %5ld nli = %5ld\n", nni, nli); printf("nfe = %5ld nfeSG = %5ld\n", nfe, nfeSG); printf("nps = %5ld npe = %5ld ncfl = %5ld\n", nps, npe, ncfl); } /* * Check function return value... * opt == 0 means SUNDIALS function allocates memory so check if * returned NULL pointer * opt == 1 means SUNDIALS function returns a flag so check if * flag >= 0 * opt == 2 means function allocates memory so check if returned * NULL pointer */ static int check_flag(void *flagvalue, const char *funcname, int opt) { int *errflag; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && flagvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if flag < 0 */ else if (opt == 1) { errflag = (int *) flagvalue; if (*errflag < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with flag = %d\n\n", funcname, *errflag); return(1); } } /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && flagvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
compression.h
/* * compression.h * * Created on: Oct 28, 2013 * Author: lemire */ #ifndef COMPRESSION_H_ #define COMPRESSION_H_ #include "bpacking.h" #include "util.h" /** * Compresses "length" values from "in" to "out" and return a pointer to the end of the compressed stream. * The format is "number of values, minimal value, maximal value, followed by packed data". */ inline uint32_t * compress(uint32_t * in, uint32_t length, uint32_t * out) { out[0] = length; ++out; if(length == 0) return out; uint32_t m = in[0]; uint32_t M = in[0]; for(uint32_t i = 1; i < length; ++i) { if(in[i]>M) M=in[i]; if(in[i]<m) m=in[i]; } int b = bits(static_cast<uint32_t>(M-m)); out[0] = m; ++out; out[0] = M; ++out; uint32_t k = 0; for(; k+32<=length; k+=32,in+=32) { out = pack32[b](m,in,out); } for(; k+16<=length; k+=16,in+=16) { out = pack16[b](m,in,out); } for(; k+8<=length; k+=8,in+=8) { out = pack8[b](m,in,out); } // we could pack the rest, but we don't bother for(; k<length; ++k,in++,out++) { out[0] = in [0]; } return out; } /* * uncompress FOR data found in "in". * The format is "number of values, minimal value, maximal value, followed by packed data". * The 'nvalue' variable receives the number of decoded values (initial value is ignored) * The values are stored in "out". * We return a pointer to the end of the compressed input stream. */ inline uint32_t * uncompress(uint32_t * in, uint32_t * out, uint32_t & nvalue) { nvalue = in[0]; ++in; if(nvalue == 0) return in; uint32_t m = in[0]; ++in; uint32_t M = in[0]; ++in; int b = bits(static_cast<uint32_t>(M-m)); #ifdef _OPENMP #pragma omp parallel for #endif for(uint32_t k = 0; k<nvalue/32; ++k) { unpack32[b](m,in+b*k,out+32*k); } out = out + nvalue/32*32; in = in + nvalue/32*b; for(uint32_t k=nvalue/32*32; k+16<=nvalue; k+=16,out+=16) { in = unpack16[b](m,in,out); } for(uint32_t k=nvalue/16*16; k+8<=nvalue; k+=8,out+=8) { in = unpack8[b](m,in,out); } // we could pack the rest, but we don't bother for(uint32_t k=nvalue/8*8; k<nvalue; ++k,in++,out++) { out[0] = in [0]; } return in; } #endif /* COMPRESSION_H_ */
csr_matvec.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision: 2.18 $ ***********************************************************************EHEADER*/ /****************************************************************************** * * Matvec functions for hypre_CSRMatrix class. * *****************************************************************************/ #include "seq_mv.h" #include <assert.h> /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvec( double alpha, hypre_CSRMatrix *A, hypre_Vector *x, double beta, hypre_Vector *y ) { double *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); HYPRE_Int *A_rownnz = hypre_CSRMatrixRownnz(A); HYPRE_Int num_rownnz = hypre_CSRMatrixNumRownnz(A); double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); double temp, tempx; HYPRE_Int i, j, jj; HYPRE_Int m; double xpar=0.7; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); if (num_cols != x_size) ierr = 1; if (num_rows != y_size) ierr = 2; if (num_cols != x_size && num_rows != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ /* use rownnz pointer to do the A*x multiplication when num_rownnz is smaller than num_rows */ if (num_rownnz < xpar*(num_rows)) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj,m,tempx) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rownnz; i++) { m = A_rownnz[i]; /* * for (jj = A_i[m]; jj < A_i[m+1]; jj++) * { * j = A_j[jj]; * y_data[m] += A_data[jj] * x_data[j]; * } */ if ( num_vectors==1 ) { tempx = 0.0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[A_j[jj]]; y_data[m] += tempx; } else for ( j=0; j<num_vectors; ++j ) { tempx = 0.0; for (jj = A_i[m]; jj < A_i[m+1]; jj++) tempx += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; y_data[ j*vecstride_y + m*idxstride_y] += tempx; } } } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj,temp) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { if ( num_vectors==1 ) { temp = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] += temp; } else for ( j=0; j<num_vectors; ++j ) { temp = 0.0; for (jj = A_i[i]; jj < A_i[i+1]; jj++) { temp += A_data[jj] * x_data[ j*vecstride_x + A_j[jj]*idxstride_x ]; } y_data[ j*vecstride_y + i*idxstride_y ] += temp; } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows*num_vectors; i++) y_data[i] *= alpha; } return ierr; } #if 0 /* AHB: 10/2009- not using this one anymore because of threading scheme */ /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvecT * * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvecT( double alpha, hypre_CSRMatrix *A, hypre_Vector *x, double beta, hypre_Vector *y ) { double *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); double temp; HYPRE_Int i, i1, j, jv, jj, ns, ne, size, rest; HYPRE_Int num_threads; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ num_threads = hypre_NumThreads(); if (num_threads > 1) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i, i1,jj,j,ns,ne,size,rest) HYPRE_SMP_SCHEDULE #endif for (i1 = 0; i1 < num_threads; i1++) { size = num_cols/num_threads; rest = num_cols - size*num_threads; if (i1 < rest) { ns = i1*size+i1-1; ne = (i1+1)*size+i1+1; } else { ns = i1*size+rest-1; ne = (i1+1)*size+rest; } if ( num_vectors==1 ) { for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; if (j > ns && j < ne) y_data[j] += A_data[jj] * x_data[i]; } } } else { for (i = 0; i < num_rows; i++) { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; if (j > ns && j < ne) y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x]; } } } } } } else { for (i = 0; i < num_rows; i++) { if ( num_vectors==1 ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[j] += A_data[jj] * x_data[i]; } } else { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x ]; } } } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= alpha; } return ierr; } #else /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvecT * * This version is using a different (more efficient) threading scheme * Performs y <- alpha * A^T * x + beta * y * * From Van Henson's modification of hypre_CSRMatrixMatvec. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvecT( double alpha, hypre_CSRMatrix *A, hypre_Vector *x, double beta, hypre_Vector *y ) { double *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); HYPRE_Int num_vectors = hypre_VectorNumVectors(x); HYPRE_Int idxstride_y = hypre_VectorIndexStride(y); HYPRE_Int vecstride_y = hypre_VectorVectorStride(y); HYPRE_Int idxstride_x = hypre_VectorIndexStride(x); HYPRE_Int vecstride_x = hypre_VectorVectorStride(x); double temp; double *y_data_expand; HYPRE_Int my_thread_num = 0, offset = 0; HYPRE_Int i, j, jv, jj; HYPRE_Int num_threads; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. MatvecT returns ierr = 1 if * length of X doesn't equal the number of rows of A, * ierr = 2 if the length of Y doesn't equal the number of * columns of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in MatvecT, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ hypre_assert( num_vectors == hypre_VectorNumVectors(y) ); if (num_rows != x_size) ierr = 1; if (num_cols != y_size) ierr = 2; if (num_rows != x_size && num_cols != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A^T*x *-----------------------------------------------------------------*/ num_threads = hypre_NumThreads(); if (num_threads > 1) { y_data_expand = hypre_CTAlloc(double, num_threads*y_size); if ( num_vectors==1 ) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel private(i,jj,j,my_thread_num,offset) #endif { my_thread_num = hypre_GetThreadNum(); offset = y_size*my_thread_num; #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data_expand[offset + j] += A_data[jj] * x_data[i]; } } /* implied barrier (for threads)*/ #ifdef HYPRE_USING_OPENMP #pragma omp for HYPRE_SMP_SCHEDULE #endif for (i = 0; i < y_size; i++) { for (j = 0; j < num_threads; j++) { y_data[i] += y_data_expand[j*y_size + i]; } } } /* end parallel threaded region */ } else { /* multiple vector case is not threaded */ for (i = 0; i < num_rows; i++) { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x]; } } } } hypre_TFree(y_data_expand); } else { for (i = 0; i < num_rows; i++) { if ( num_vectors==1 ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[j] += A_data[jj] * x_data[i]; } } else { for ( jv=0; jv<num_vectors; ++jv ) { for (jj = A_i[i]; jj < A_i[i+1]; jj++) { j = A_j[jj]; y_data[ j*idxstride_y + jv*vecstride_y ] += A_data[jj] * x_data[ i*idxstride_x + jv*vecstride_x ]; } } } } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_cols*num_vectors; i++) y_data[i] *= alpha; } return ierr; } #endif /*-------------------------------------------------------------------------- * hypre_CSRMatrixMatvec_FF *--------------------------------------------------------------------------*/ HYPRE_Int hypre_CSRMatrixMatvec_FF( double alpha, hypre_CSRMatrix *A, hypre_Vector *x, double beta, hypre_Vector *y, HYPRE_Int *CF_marker_x, HYPRE_Int *CF_marker_y, HYPRE_Int fpt ) { double *A_data = hypre_CSRMatrixData(A); HYPRE_Int *A_i = hypre_CSRMatrixI(A); HYPRE_Int *A_j = hypre_CSRMatrixJ(A); HYPRE_Int num_rows = hypre_CSRMatrixNumRows(A); HYPRE_Int num_cols = hypre_CSRMatrixNumCols(A); double *x_data = hypre_VectorData(x); double *y_data = hypre_VectorData(y); HYPRE_Int x_size = hypre_VectorSize(x); HYPRE_Int y_size = hypre_VectorSize(y); double temp; HYPRE_Int i, jj; HYPRE_Int ierr = 0; /*--------------------------------------------------------------------- * Check for size compatibility. Matvec returns ierr = 1 if * length of X doesn't equal the number of columns of A, * ierr = 2 if the length of Y doesn't equal the number of rows * of A, and ierr = 3 if both are true. * * Because temporary vectors are often used in Matvec, none of * these conditions terminates processing, and the ierr flag * is informational only. *--------------------------------------------------------------------*/ if (num_cols != x_size) ierr = 1; if (num_rows != y_size) ierr = 2; if (num_cols != x_size && num_rows != y_size) ierr = 3; /*----------------------------------------------------------------------- * Do (alpha == 0.0) computation - RDF: USE MACHINE EPS *-----------------------------------------------------------------------*/ if (alpha == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= beta; return ierr; } /*----------------------------------------------------------------------- * y = (beta/alpha)*y *-----------------------------------------------------------------------*/ temp = beta / alpha; if (temp != 1.0) { if (temp == 0.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] = 0.0; } else { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= temp; } } /*----------------------------------------------------------------- * y += A*x *-----------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,jj) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) { if (CF_marker_x[i] == fpt) { temp = y_data[i]; for (jj = A_i[i]; jj < A_i[i+1]; jj++) if (CF_marker_y[A_j[jj]] == fpt) temp += A_data[jj] * x_data[A_j[jj]]; y_data[i] = temp; } } /*----------------------------------------------------------------- * y = alpha*y *-----------------------------------------------------------------*/ if (alpha != 1.0) { #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < num_rows; i++) if (CF_marker_x[i] == fpt) y_data[i] *= alpha; } return ierr; }
8.c
#include <stdio.h> #include <stdlib.h> #include <omp.h> #include <time.h> #define N 500000 #define MAX_ITER 100 /* Элементы массива a инициализируются 0, массива b[0]...b[n-1] – случайными числами от 0 до n-1. Распараллелить цикл for (i=0; i<n; i++) a[b[i]]++; */ int main() { srand(0); int a[N], b[N], prior[N]; float full_time = 0.; struct timeval start_s, end_s; for (int iter = 0; iter < MAX_ITER; iter++){ for (int i = 0; i < N; i++){ a[i] = prior[i] = 0; b[i] = (int)((rand() >> 15) % N); } gettimeofday(&start_s, NULL); #pragma omp parallel for for (int i = 0; i < N; i++){ #pragma omp atomic a[b[i]]++; } gettimeofday(&end_s, NULL); for (int i = 0; i < N; i++){ prior[b[i]]++; } for (int i = 0; i < N; i++){ if (a[b[i]] != prior[b[i]]){ printf("Raise condition detected, index #%d (%d, %d)\n", i, a[b[i]], prior[b[i]]); return 1; } } full_time += ((end_s.tv_sec - start_s.tv_sec) * 1000000u + end_s.tv_usec - start_s.tv_usec) / 1.e6; } printf("time: %f sec\n", full_time / MAX_ITER); }
mxEvaluateStrongFormEdgeRHS.c
#ifdef _OPENMP #include <omp.h> #endif #include "mex.h" #include "blas.h" // #if !defined(_WIN32) // #define dgemm dgemm_ // #endif #define DEBUG 0 #define NRHS 8 #define NLHS 1 void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* check input & output */ if (nrhs != NRHS) { mexPrintf("Matlab:%s:InvalidNumberInput,\n", __FILE__); mexPrintf("%d inputs required.\n", NRHS); } if (nlhs != NLHS) { mexPrintf("Matlab:%s:InvalidNumberOutput,\n", __FILE__); mexPrintf("%d inputs required.\n", NLHS); } double *invM = mxGetPr(prhs[0]); double *Mb = mxGetPr(prhs[1]); double *FToE = mxGetPr(prhs[2]); double *FToN1 = mxGetPr(prhs[3]); double *Js = mxGetPr(prhs[4]); double *J = mxGetPr(prhs[5]); double *fluxM = mxGetPr(prhs[6]); double *fluxS = mxGetPr(prhs[7]); // dims = mxGetDimensions(prhs[6]); const int Np = mxGetM(prhs[5]); // num of interp nodes const int K = mxGetN(prhs[5]); // num of elements const mwSize *dims = mxGetDimensions(prhs[6]); const int Nfp = dims[0]; const int Ne = dims[1]; // num of edges int Nfield; if (mxGetNumberOfDimensions(prhs[6]) > 2) { Nfield = dims[2]; } else { Nfield = 1; // fluxM is a 2D matrix } const size_t ndimOut = 3; const mwSize dimOut[3] = {Np, K, Nfield}; plhs[0] = mxCreateNumericArray(ndimOut, dimOut, mxDOUBLE_CLASS, mxREAL); double *frhs = mxGetPr(plhs[0]); char *chn = "N"; double one = 1.0, zero = 0.0; ptrdiff_t oneI = 1; ptrdiff_t np = Np; #ifdef _OPENMP #pragma omp parallel for num_threads(DG_THREADS) #endif for (int fld = 0; fld < Nfield; fld++) { double *rhs = frhs + Np * K * fld; double *fluxM_ = fluxM + Nfp * Ne * fld; // double *fluxP_ = fluxP + Nfp * Ne * fld; double *fluxS_ = fluxS + Nfp * Ne * fld; for (int k = 0; k < Ne; k++) { // evaluate rhs on each edge const int e1 = (int)FToE[2 * k] - 1; // const int e2 = (int)FToE[2 * k + 1] - 1; const int ind1 = e1 * Np - 1; // const int ind2 = e2 * Np - 1; const int ind = k * Nfp; double rhsM[Nfp]; // rhsP[Nfp]; for (int n = 0; n < Nfp; n++) { rhsM[n] = 0; // rhsP[n] = 0; } for (int n = 0; n < Nfp; n++) { const int sk = n + ind; double dfM = fluxM_[sk] - fluxS_[sk]; // double dfP = fluxP_[sk] - fluxS_[sk]; double j = Js[sk]; double *mb = Mb + n * Nfp; for (int m = 0; m < Nfp; m++) { rhsM[m] += mb[m] * j * dfM; // rhsP[m] -= mb[m] * j * dfP; } } for (int n = 0; n < Nfp; n++) { const int sk = n + ind; const int m1 = (int)FToN1[sk] + ind1; // const int m2 = (int)FToN2[sk] + ind2; rhs[m1] += rhsM[n]; // rhs[m2] += rhsP[n]; } } double temp[Np]; for (int k = 0; k < K; k++) { double *rhs_ = rhs + k * Np; double *j = J + k * Np; dgemm(chn, chn, &np, &oneI, &np, &one, invM, &np, rhs_, &np, &zero, temp, &np); // copy rhs for (int n = 0; n < Np; n++) { rhs_[n] = temp[n] / j[n]; } } } return; }
irbuilder_for_unsigned_down.c
// NOTE: Assertions have been autogenerated by utils/update_cc_test_checks.py UTC_ARGS: --function-signature --include-generated-funcs // RUN: %clang_cc1 -no-opaque-pointers -fopenmp-enable-irbuilder -verify -fopenmp -fopenmp-version=45 -x c++ -triple x86_64-unknown-unknown -emit-llvm %s -o - | FileCheck %s // expected-no-diagnostics #ifndef HEADER #define HEADER // CHECK-LABEL: define {{.*}}@workshareloop_unsigned_down( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[A_ADDR:.+]] = alloca float*, align 8 // CHECK-NEXT: %[[I:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[AGG_CAPTURED:.+]] = alloca %struct.anon, align 8 // CHECK-NEXT: %[[AGG_CAPTURED1:.+]] = alloca %struct.anon.0, align 4 // CHECK-NEXT: %[[DOTCOUNT_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LASTITER:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_LOWERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_UPPERBOUND:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[P_STRIDE:.+]] = alloca i32, align 4 // CHECK-NEXT: store float* %[[A:.+]], float** %[[A_ADDR]], align 8 // CHECK-NEXT: store i32 32000000, i32* %[[I]], align 4 // CHECK-NEXT: %[[TMP0:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[AGG_CAPTURED]], i32 0, i32 0 // CHECK-NEXT: store i32* %[[I]], i32** %[[TMP0]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[AGG_CAPTURED1]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: store i32 %[[TMP2]], i32* %[[TMP1]], align 4 // CHECK-NEXT: call void @__captured_stmt(i32* %[[DOTCOUNT_ADDR]], %struct.anon* %[[AGG_CAPTURED]]) // CHECK-NEXT: %[[DOTCOUNT:.+]] = load i32, i32* %[[DOTCOUNT_ADDR]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_PREHEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_PREHEADER]]: // CHECK-NEXT: store i32 0, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = sub i32 %[[DOTCOUNT]], 1 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: store i32 1, i32* %[[P_STRIDE]], align 4 // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_for_static_init_4u(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]], i32 34, i32* %[[P_LASTITER]], i32* %[[P_LOWERBOUND]], i32* %[[P_UPPERBOUND]], i32* %[[P_STRIDE]], i32 1, i32 0) // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[P_LOWERBOUND]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[P_UPPERBOUND]], align 4 // CHECK-NEXT: %[[TMP6:.+]] = sub i32 %[[TMP5]], %[[TMP4]] // CHECK-NEXT: %[[TMP7:.+]] = add i32 %[[TMP6]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_HEADER]]: // CHECK-NEXT: %[[OMP_LOOP_IV:.+]] = phi i32 [ 0, %[[OMP_LOOP_PREHEADER]] ], [ %[[OMP_LOOP_NEXT:.+]], %[[OMP_LOOP_INC:.+]] ] // CHECK-NEXT: br label %[[OMP_LOOP_COND:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_COND]]: // CHECK-NEXT: %[[OMP_LOOP_CMP:.+]] = icmp ult i32 %[[OMP_LOOP_IV]], %[[TMP7]] // CHECK-NEXT: br i1 %[[OMP_LOOP_CMP]], label %[[OMP_LOOP_BODY:.+]], label %[[OMP_LOOP_EXIT:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_BODY]]: // CHECK-NEXT: %[[TMP8:.+]] = add i32 %[[OMP_LOOP_IV]], %[[TMP4]] // CHECK-NEXT: call void @__captured_stmt.1(i32* %[[I]], i32 %[[TMP8]], %struct.anon.0* %[[AGG_CAPTURED1]]) // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[CONV:.+]] = uitofp i32 %[[TMP9]] to float // CHECK-NEXT: %[[TMP10:.+]] = load float*, float** %[[A_ADDR]], align 8 // CHECK-NEXT: %[[TMP11:.+]] = load i32, i32* %[[I]], align 4 // CHECK-NEXT: %[[IDXPROM:.+]] = zext i32 %[[TMP11]] to i64 // CHECK-NEXT: %[[ARRAYIDX:.+]] = getelementptr inbounds float, float* %[[TMP10]], i64 %[[IDXPROM]] // CHECK-NEXT: store float %[[CONV]], float* %[[ARRAYIDX]], align 4 // CHECK-NEXT: br label %[[OMP_LOOP_INC]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_INC]]: // CHECK-NEXT: %[[OMP_LOOP_NEXT]] = add nuw i32 %[[OMP_LOOP_IV]], 1 // CHECK-NEXT: br label %[[OMP_LOOP_HEADER]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_EXIT]]: // CHECK-NEXT: call void @__kmpc_for_static_fini(%struct.ident_t* @1, i32 %[[OMP_GLOBAL_THREAD_NUM]]) // CHECK-NEXT: %[[OMP_GLOBAL_THREAD_NUM2:.+]] = call i32 @__kmpc_global_thread_num(%struct.ident_t* @1) // CHECK-NEXT: call void @__kmpc_barrier(%struct.ident_t* @2, i32 %[[OMP_GLOBAL_THREAD_NUM2]]) // CHECK-NEXT: br label %[[OMP_LOOP_AFTER:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[OMP_LOOP_AFTER]]: // CHECK-NEXT: ret void // CHECK-NEXT: } extern "C" void workshareloop_unsigned_down(float *a) { #pragma omp for for (unsigned i = 32000000; i > 33; i -= 7) { a[i] = i; } } #endif // HEADER // // // // // // CHECK-LABEL: define {{.*}}@__captured_stmt( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[DISTANCE_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon*, align 8 // CHECK-NEXT: %[[DOTSTART:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTOP:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[DOTSTEP:.+]] = alloca i32, align 4 // CHECK-NEXT: store i32* %[[DISTANCE:.+]], i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store %struct.anon* %[[__CONTEXT:.+]], %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon*, %struct.anon** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon, %struct.anon* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32*, i32** %[[TMP1]], align 8 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[TMP2]], align 4 // CHECK-NEXT: store i32 %[[TMP3]], i32* %[[DOTSTART]], align 4 // CHECK-NEXT: store i32 33, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: store i32 -7, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[TMP4:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP5:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[CMP:.+]] = icmp ugt i32 %[[TMP4]], %[[TMP5]] // CHECK-NEXT: br i1 %[[CMP]], label %[[COND_TRUE:.+]], label %[[COND_FALSE:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_TRUE]]: // CHECK-NEXT: %[[TMP6:.+]] = load i32, i32* %[[DOTSTART]], align 4 // CHECK-NEXT: %[[TMP7:.+]] = load i32, i32* %[[DOTSTOP]], align 4 // CHECK-NEXT: %[[SUB:.+]] = sub i32 %[[TMP6]], %[[TMP7]] // CHECK-NEXT: %[[TMP8:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB1:.+]] = sub nsw i32 0, %[[TMP8]] // CHECK-NEXT: %[[SUB2:.+]] = sub i32 %[[SUB1]], 1 // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[SUB]], %[[SUB2]] // CHECK-NEXT: %[[TMP9:.+]] = load i32, i32* %[[DOTSTEP]], align 4 // CHECK-NEXT: %[[SUB3:.+]] = sub nsw i32 0, %[[TMP9]] // CHECK-NEXT: %[[DIV:.+]] = udiv i32 %[[ADD]], %[[SUB3]] // CHECK-NEXT: br label %[[COND_END:.+]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_FALSE]]: // CHECK-NEXT: br label %[[COND_END]] // CHECK-EMPTY: // CHECK-NEXT: [[COND_END]]: // CHECK-NEXT: %[[COND:.+]] = phi i32 [ %[[DIV]], %[[COND_TRUE]] ], [ 0, %[[COND_FALSE]] ] // CHECK-NEXT: %[[TMP10:.+]] = load i32*, i32** %[[DISTANCE_ADDR]], align 8 // CHECK-NEXT: store i32 %[[COND]], i32* %[[TMP10]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define {{.*}}@__captured_stmt.1( // CHECK-NEXT: [[ENTRY:.*]]: // CHECK-NEXT: %[[LOOPVAR_ADDR:.+]] = alloca i32*, align 8 // CHECK-NEXT: %[[LOGICAL_ADDR:.+]] = alloca i32, align 4 // CHECK-NEXT: %[[__CONTEXT_ADDR:.+]] = alloca %struct.anon.0*, align 8 // CHECK-NEXT: store i32* %[[LOOPVAR:.+]], i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[LOGICAL:.+]], i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: store %struct.anon.0* %[[__CONTEXT:.+]], %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP0:.+]] = load %struct.anon.0*, %struct.anon.0** %[[__CONTEXT_ADDR]], align 8 // CHECK-NEXT: %[[TMP1:.+]] = getelementptr inbounds %struct.anon.0, %struct.anon.0* %[[TMP0]], i32 0, i32 0 // CHECK-NEXT: %[[TMP2:.+]] = load i32, i32* %[[TMP1]], align 4 // CHECK-NEXT: %[[TMP3:.+]] = load i32, i32* %[[LOGICAL_ADDR]], align 4 // CHECK-NEXT: %[[MUL:.+]] = mul i32 -7, %[[TMP3]] // CHECK-NEXT: %[[ADD:.+]] = add i32 %[[TMP2]], %[[MUL]] // CHECK-NEXT: %[[TMP4:.+]] = load i32*, i32** %[[LOOPVAR_ADDR]], align 8 // CHECK-NEXT: store i32 %[[ADD]], i32* %[[TMP4]], align 4 // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK: ![[META0:[0-9]+]] = !{i32 1, !"wchar_size", i32 4} // CHECK: ![[META1:[0-9]+]] = !{i32 7, !"openmp", i32 45} // CHECK: ![[META2:[0-9]+]] =
yolov2_forward_network_quantized.c
#include "additionally.h" // some definitions from: im2col.h, blas.h, list.h, utils.h, activations.h, tree.h, layer.h, network.h // softmax_layer.h, reorg_layer.h, route_layer.h, region_layer.h, maxpool_layer.h, convolutional_layer.h #define GEMMCONV //#define SSE41 //#undef AVX #define W_MAX_VAL (256/2 - 1) // 7-bit (1-bit sign) #define I_MAX_VAL (256/2 - 1) // 7-bit (1-bit sign) #define R_MAX_VAL (256*256/2 - 1) // 31-bit (1-bit sign) #define R_MULT (32) // 4 - 32 /* // from: box.h typedef struct { float x, y, w, h; } box; */ int max_abs(int src, int max_val) { if (abs(src) > abs(max_val)) src = (src > 0) ? max_val : -max_val; return src; } short int max_abs_short(short int src, short int max_val) { if (abs(src) > abs(max_val)) src = (src > 0) ? max_val : -max_val; return src; } int * get_distribution(float *arr_ptr, int arr_size, int number_of_ranges, float start_range) { //const int number_of_ranges = 32; //const float start_range = 1.F / 65536; int *count = calloc(number_of_ranges, sizeof(int)); float min_val = 10000, max_val = 0; int i, j; for (i = 0; i < arr_size; ++i) { float w = arr_ptr[i]; float cur_range = start_range; for (j = 0; j < number_of_ranges; ++j) { if (fabs(cur_range) <= w && w < fabs(cur_range * 2)) count[j]++;// , printf("found \n"); cur_range *= 2; //printf("%f, ", w); } } return count; } float get_multiplier(float *arr_ptr, int arr_size, int bits_length) { const int number_of_ranges = 32; const float start_range = 1.F / 65536; int i, j; int *count = get_distribution(arr_ptr, arr_size, number_of_ranges, start_range); int max_count_range = 0; int index_max_count = 0; for (j = 0; j < number_of_ranges; ++j) { int counter = 0; for (i = j; i < (j + bits_length) && i < number_of_ranges; ++i) { counter += count[i]; //counter += log2(count[i]); } if (max_count_range < counter) { max_count_range = counter; index_max_count = j; } } //index_max_count = index_max_count + 2; // optimal shift multipler float multiplier = 1 / (start_range * powf(2., (float)index_max_count)); //printf(" max_count_range = %d, index_max_count = %d, multiplier = %g \n", // max_count_range, index_max_count, multiplier); free(count); return multiplier; } #ifdef OPENCV #include <opencv2/core/fast_math.hpp> #include "opencv2/highgui/highgui_c.h" #include "opencv2/core/core_c.h" #include "opencv2/core/version.hpp" void draw_distribution(float *arr_ptr, int arr_size, char *name) { int img_w = 1200, img_h = 800; const int number_of_ranges = 32; const float start_range = 1.F / 65536; //int *count = calloc(number_of_ranges, sizeof(int)); //float min_val = 100, max_val = 0; int i, j; int *count = get_distribution(arr_ptr, arr_size, number_of_ranges, start_range); float multiplier = get_multiplier(arr_ptr, arr_size, 8); int max_count_range = 0; for (j = 0; j < number_of_ranges; ++j) { count[j] = log2(count[j]); if (max_count_range < count[j]) max_count_range = count[j]; } cvNamedWindow("Wights", CV_WINDOW_NORMAL); cvResizeWindow("Wights", img_w, img_h); IplImage *img = cvCreateImage(cvSize(img_w, img_h), IPL_DEPTH_8U, 3); if (max_count_range > 0) { for (j = 0; j < number_of_ranges; ++j) { //printf("count[j] = %d, max_count_range = %d, img_w = %d, img_h = %d, j = %d, number_of_ranges = %d \n", // count[j], max_count_range, img_w, img_h, j, number_of_ranges); CvPoint pt1, pt2; pt1.x = j*img_w / number_of_ranges; pt2.x = (j + 1)*img_w / number_of_ranges; pt1.y = img_h; pt2.y = img_h - img_h*count[j] / max_count_range; //printf("pt1.x = %d, pt1.y = %d, pt2.x = %d, pt2.y = %d \n", pt1.x, pt1.y, pt2.x, pt2.y); //if(pt2.y < pt1.y) cvRectangle(img, pt1, pt2, CV_RGB(128, 64, 32), CV_FILLED, 8, 0); cvRectangle(img, pt1, pt2, CV_RGB(32, 32, 32), 1, 8, 0); } } int index_multiplier = log2(1 / (multiplier*start_range)); int x_coord_multiplier = index_multiplier*img_w / number_of_ranges; cvLine(img, cvPoint(x_coord_multiplier, 0), cvPoint(x_coord_multiplier, img_h), CV_RGB(255, 32, 32), 1, 8, 0); char buff[256]; //sprintf(buff, "[%g - %g]", min_val, max_val); sprintf(buff, "optimal multiplier = %g", multiplier); //printf("[%g - %g]", min_val, max_val); CvFont font; cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 1, 1, 0, 2, 8); cvPutText(img, buff, cvPoint(100, 50), &font, CV_RGB(32, 64, 128)); if (name) cvPutText(img, name, cvPoint(0, 20), &font, CV_RGB(32, 64, 128)); float cur_range = start_range; cvInitFont(&font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0, 1, 8); for (j = 0; j < number_of_ranges; ++j) { CvPoint pt_text = cvPoint(j*img_w / number_of_ranges, img_h - 50); int lg = log2(cur_range); sprintf(buff, "%d", lg); cvPutText(img, buff, pt_text, &font, CV_RGB(32, 64, 128)); cur_range *= 2; } cvPutText(img, "X and Y are log2", cvPoint(img_w / 2 - 100, img_h - 10), &font, CV_RGB(32, 64, 128)); cvShowImage("Wights", img); cvWaitKey(0); free(count); } #endif // OPENCV // im2col.c int8_t im2col_get_pixel_int8(int8_t *im, int height, int width, int channels, int row, int col, int channel, int pad) { row -= pad; col -= pad; if (row < 0 || col < 0 || row >= height || col >= width) return 0; return im[col + width*(row + height*channel)]; } // im2col.c //From Berkeley Vision's Caffe! //https://github.com/BVLC/caffe/blob/master/LICENSE void im2col_cpu_int8(int8_t* data_im, int channels, int height, int width, int ksize, int stride, int pad, int8_t* data_col) { int c, h, w; int height_col = (height + 2 * pad - ksize) / stride + 1; int width_col = (width + 2 * pad - ksize) / stride + 1; int channels_col = channels * ksize * ksize; for (c = 0; c < channels_col; ++c) { int w_offset = c % ksize; int h_offset = (c / ksize) % ksize; int c_im = c / ksize / ksize; for (h = 0; h < height_col; ++h) { for (w = 0; w < width_col; ++w) { int im_row = h_offset + h * stride; int im_col = w_offset + w * stride; int col_index = (c * height_col + h) * width_col + w; data_col[col_index] = im2col_get_pixel_int8(data_im, height, width, channels, im_row, im_col, c_im, pad); } } } } // Use to enable AVX or SSE41 //#define AVX // 1.35 sec (0.8 FPS) 2.3x - GCC -mavx -mavx2 -mfma -ffp-contract=fast //#define SSE41 // 1.55 sec (0.7 FPS) 2x // default 3.10 sec (0.3 FPS) #if defined(AVX) || defined(SSE41) #ifdef _WIN64 #include <intrin.h> #else #include <x86intrin.h> #endif #include <ammintrin.h> #include <immintrin.h> #include <smmintrin.h> #include <emmintrin.h> // https://software.intel.com/sites/landingpage/IntrinsicsGuide/#text=broad&expand=561 #endif // AVX or SSE41 #if defined(AVX) __m256i _mm256_div_epi16(const __m256i va, const int b) { __m256i vb = _mm256_set1_epi16(32768 / b); return _mm256_mulhrs_epi16(va, vb); } #define INTERMEDIATE_MULT 15 // 8 or 15 #define FINAL_MULT (R_MULT / INTERMEDIATE_MULT) // 0.89 sec void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m256i res; __m256i a, b, d; __m128i tmp128; __m256i div256 = _mm256_set1_epi16(INTERMEDIATE_MULT); int16_t *c_tmp = calloc(N, sizeof(int16_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm256_set1_epi16(A_PART); for (j = 0; j < N - 32; j += 32) { int index = k*ldb + j; d = _mm256_loadu_si256((__m256i*)&B[index]); tmp128 = _mm256_extractf128_si256(d, 0);// get low 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 b = _mm256_mullo_epi16(a, b); // B = A * B b = _mm256_div_epi16(b, INTERMEDIATE_MULT); // B = (A * B) / INTERMEDIATE_MULL res = _mm256_loadu_si256(&c_tmp[j]); // load temp C res = _mm256_add_epi16(b, res); // (A*B) + C _mm256_storeu_si256(&c_tmp[j], res); // store temp C tmp128 = _mm256_extractf128_si256(d, 1);// get high 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 (for low 8 bytes) b = _mm256_mullo_epi16(a, b); // B = A * B b = _mm256_div_epi16(b, INTERMEDIATE_MULT); // B = (A * B) / INTERMEDIATE_MULL res = _mm256_loadu_si256(&c_tmp[j + 16]); // Load next temp C res = _mm256_add_epi16(b, res); // (A*B) + C _mm256_storeu_si256(&c_tmp[j + 16], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (INTERMEDIATE_MULL), (256 * 128 - 1)); } int prev_end = (N % 32 == 0) ? (N - 32) : (N / 32) * 32; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j] / (INTERMEDIATE_MULT); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += (c_tmp[j] / FINAL_MULT); c_tmp[j] = 0; } } free(c_tmp); } // 1.15 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m256i multyplied_i32, res; __m256i a, b, d; __m128i tmp128; int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm256_set1_epi16(A_PART); for (j = 0; j < N - 32; j += 32) { int index = k*ldb + j; d = _mm256_loadu_si256((__m256i*)&B[index]); tmp128 = _mm256_extractf128_si256(d, 0);// get low 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 b = _mm256_mullo_epi16(a, b); // B = A * B tmp128 = _mm256_extractf128_si256(b, 0); // get low 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j]); // load temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j], res); // store temp C tmp128 = _mm256_extractf128_si256(b, 1); // get high 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 8]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 8], res); // store temp C tmp128 = _mm256_extractf128_si256(d, 1);// get high 128 bit b = _mm256_cvtepi8_epi16(tmp128); // int8 -> int16 (for low 8 bytes) b = _mm256_mullo_epi16(a, b); // B = A * B tmp128 = _mm256_extractf128_si256(b, 0); // get low 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 16]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 16], res); // store temp C tmp128 = _mm256_extractf128_si256(b, 1); // get high 128 bit multyplied_i32 = _mm256_cvtepi16_epi32(tmp128); // int16 -> int32 res = _mm256_loadu_si256(&c_tmp[j + 24]); // Load next temp C res = _mm256_add_epi32(multyplied_i32, res);// (A*B) + C _mm256_storeu_si256(&c_tmp[j + 24], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (32), (256 * 128 - 1)); } int prev_end = (N % 32 == 0) ? (N - 32) : (N / 32) * 32; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } //for (j = 0; j < N; ++j) C[i*ldc + j] += c_tmp[j] / (R_MULT); } free(c_tmp); } #elif defined(SSE41) // 1.3 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { __m128i multyplied_i32, res; __m128i a, b, d; //c = _mm_set1_epi16(32); int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; a = _mm_set1_epi16(A_PART); for (j = 0; j < N - 16; j += 16) { int index = k*ldb + j; d = _mm_loadu_si128((__m128i*)&B[index]); b = _mm_cvtepi8_epi16(d); // int8 -> int16 b = _mm_mullo_epi16(a, b); // B = A * B multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j]); // load temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j], res); // store temp C b = _mm_srli_si128(b, 8); // Shift Right -> 8 bytes multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 4]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 4], res); // store temp C d = _mm_srli_si128(d, 8); // Shift Right -> 8 bytes b = _mm_cvtepi8_epi16(d); // int8 -> int16 (for low 8 bytes) b = _mm_mullo_epi16(a, b); // B = A * B multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 8]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 8], res); // store temp C b = _mm_srli_si128(b, 8); // Shift Right -> 8 bytes multyplied_i32 = _mm_cvtepi16_epi32(b); // int16 -> int32 res = _mm_loadu_si128(&c_tmp[j + 12]); // Load next temp C res = _mm_add_epi32(multyplied_i32, res);// (A*B) + C _mm_store_si128(&c_tmp[j + 12], res); // store temp C //c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (32), (256 * 128 - 1)); } int prev_end = (N % 16 == 0) ? (N - 16) : (N / 16) * 16; for (j = prev_end; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } //for (j = 0; j < N; ++j) C[i*ldc + j] += c_tmp[j] / (R_MULT); } free(c_tmp); } void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { printf(" gemm_nn_int8_int16_conv16() isn't implemented for SSE4.1 \n"); } #else // 2.9 sec void gemm_nn_int8_int16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; //#pragma simd parallel for for (j = 0; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (R_MULT), (256 * 128 - 1)); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } } free(c_tmp); } void gemm_nn_int8_int32(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int32_t *C, int ldc) { int32_t *c_tmp = calloc(N, sizeof(int32_t)); int i, j, k; for (i = 0; i < M; ++i) { for (k = 0; k < K; ++k) { register int16_t A_PART = ALPHA*A[i*lda + k]; //#pragma simd parallel for for (j = 0; j < N; ++j) { c_tmp[j] += A_PART*B[k*ldb + j]; //C[i*ldc + j] += max_abs(A_PART*B[k*ldb + j] / (R_MULT), (256 * 128 - 1)); } } for (j = 0; j < N; ++j) { C[i*ldc + j] += max_abs(c_tmp[j] / (R_MULT), (256 * 128 - 1)); c_tmp[j] = 0; } } free(c_tmp); } void gemm_nn_int8_int16_conv16(int M, int N, int K, int8_t ALPHA, int8_t *A, int lda, int8_t *B, int ldb, int16_t *C, int ldc) { printf(" gemm_nn_int8_int16_conv16() isn't implemented \n"); } #endif // SSE41 or AVX void forward_convolutional_layer_q(layer l, network_state state) { int out_h = (l.h + 2 * l.pad - l.size) / l.stride + 1; // output_height=input_height for stride=1 and pad=1 int out_w = (l.w + 2 * l.pad - l.size) / l.stride + 1; // output_width=input_width for stride=1 and pad=1 int i, f, j; int const out_size = out_h*out_w; size_t const weights_size = l.size*l.size*l.c*l.n; // fill zero (ALPHA) //for (i = 0; i < l.outputs; ++i) l.output[i] = 0; // l.n - number of filters on this layer // l.c - channels of input-array // l.h - height of input-array // l.w - width of input-array // l.size - width and height of filters (the same size for all filters) //draw_distribution(l.weights, weights_size, NULL); //draw_distribution(state.input, l.inputs, NULL); typedef int16_t conv_t; // l.output conv_t *output_q = calloc(l.outputs, sizeof(conv_t)); state.input_int8 = (int *)calloc(l.inputs, sizeof(int)); int z; for (z = 0; z < l.inputs; ++z) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[z] * l.input_quant_multipler; state.input_int8[z] = max_abs(src, I_MAX_VAL); } //////////////////////////////////// // cudnnConvolutionBiasActivationForward() // y = act ( alpha1 * conv(x) + alpha2 * z + bias ) // int8 = activation( float * conv(int8) + float * int8 + float ) // int8 = activation( conv(input_int8) + bias_float ) // X_INT8x4 or X_INT8 // https://docs.nvidia.com/deeplearning/sdk/cudnn-developer-guide/index.html#cudnnConvolutionBiasActivationForward /////////////////////////////////// // 1. Convolution !!! int fil; // cuDNN: y = conv(x) int m = l.n; int k = l.size*l.size*l.c; int n = out_h*out_w; int8_t *a = l.weights_int8; int8_t *b = (int8_t *)state.workspace; conv_t *c = output_q; // int16_t // convolution as GEMM (as part of BLAS) //for (i = 0; i < l.batch; ++i) { im2col_cpu_int8(state.input_int8, l.c, l.h, l.w, l.size, l.stride, l.pad, b); // here //gemm_nn_int8_int16(m, n, k, 1, a, k, b, n, c, n); // single-thread gemm int t; // multi-thread gemm #pragma omp parallel for for (t = 0; t < m; ++t) { gemm_nn_int8_int16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int16_conv16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int32(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); conv_t should be int32_t } //} free(state.input_int8); float ALPHA1 = R_MULT / (l.input_quant_multipler * l.weights_quant_multipler); // cuDNN: y = alpha1 * conv(x) for (i = 0; i < l.outputs; ++i) { l.output[i] = output_q[i] * ALPHA1; // cuDNN: alpha1 } //for (fil = 0; fil < l.n; ++fil) { // for (j = 0; j < out_size; ++j) { // l.output[fil*out_size + j] = l.output[fil*out_size + j] * ALPHA1; // } //} // cuDNN: y = alpha1 * conv(x) + bias for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { l.output[fil*out_size + j] += l.biases[fil]; } } //draw_distribution(l.output, l.outputs, "output"); // cuDNN: y = act ( alpha1 * conv(x) + bias ) // bias is always FLOAT if (l.activation == LEAKY) { for (i = 0; i < l.n*out_size; ++i) { l.output[i] = (l.output[i]>0) ? l.output[i] : l.output[i] / 10; //leaky_activate(l.output[i]); } } free(output_q); } // 4 layers in 1: convolution, batch-normalization, BIAS and activation void forward_convolutional_layer_q_old(layer l, network_state state, int return_float) { int out_h = (l.h + 2 * l.pad - l.size) / l.stride + 1; // output_height=input_height for stride=1 and pad=1 int out_w = (l.w + 2 * l.pad - l.size) / l.stride + 1; // output_width=input_width for stride=1 and pad=1 int i, f, j; int const out_size = out_h*out_w; size_t const weights_size = l.size*l.size*l.c*l.n; // fill zero (ALPHA) //for (i = 0; i < l.outputs; ++i) l.output[i] = 0; // l.n - number of filters on this layer // l.c - channels of input-array // l.h - height of input-array // l.w - width of input-array // l.size - width and height of filters (the same size for all filters) //draw_distribution(l.weights, weights_size, NULL); //draw_distribution(state.input, l.inputs, NULL); typedef int16_t conv_t; // l.output conv_t *output_q = calloc(l.outputs, sizeof(conv_t)); //////////////////////////////////// // cudnnConvolutionBiasActivationForward() // y = act ( alpha1 * conv(x) + alpha2 * z + bias ) // int8 = activation( float * conv(int8) + float * int8 + float ) // int8 = activation( conv(input_int8) + bias_float ) // X_INT8x4 or X_INT8 // https://docs.nvidia.com/deeplearning/sdk/cudnn-developer-guide/index.html#cudnnConvolutionBiasActivationForward /////////////////////////////////// // 1. Convolution !!! #ifndef GEMMCONV int fil; // filter index #pragma omp parallel for // "omp parallel for" - automatic parallelization of loop by using OpenMP for (fil = 0; fil < l.n; ++fil) { int chan, y, x, f_y, f_x; // channel index for (chan = 0; chan < l.c; ++chan) // input - y for (y = 0; y < l.h; ++y) // input - x for (x = 0; x < l.w; ++x) { int const output_index = fil*l.w*l.h + y*l.w + x; int const weights_pre_index = fil*l.c*l.size*l.size + chan*l.size*l.size; int const input_pre_index = chan*l.w*l.h; //float sum = 0; //int16_t sum = 0; int32_t sum = 0; //conv_t sum = 0; // filter - y for (f_y = 0; f_y < l.size; ++f_y) { int input_y = y + f_y - l.pad; // filter - x for (f_x = 0; f_x < l.size; ++f_x) { int input_x = x + f_x - l.pad; if (input_y < 0 || input_x < 0 || input_y >= l.h || input_x >= l.w) continue; int input_index = input_pre_index + input_y*l.w + input_x; int weights_index = weights_pre_index + f_y*l.size + f_x; //sum += state.input[input_index] * l.weights[weights_index]; // int16 += int8 * int8; sum += (int32_t)state.input_int8[input_index] * (int32_t)l.weights_int8[weights_index]; } } // l.output[filters][width][height] += // state.input[channels][width][height] * // l.weights[filters][channels][filter_width][filter_height]; //output_q[output_index] += max_abs(sum, R_MAX_VAL); output_q[output_index] += max_abs(sum / R_MULT, R_MAX_VAL); //output_q[output_index] += sum / R_MULT; //if (fabs(output_q[output_index]) > 65535) printf(" fabs(output_q[output_index]) > 65535 \n"); } } #else int fil; // cuDNN: y = conv(x) int m = l.n; int k = l.size*l.size*l.c; int n = out_h*out_w; int8_t *a = l.weights_int8; int8_t *b = (int8_t *)state.workspace; conv_t *c = output_q; // int16_t // convolution as GEMM (as part of BLAS) //for (i = 0; i < l.batch; ++i) { im2col_cpu_int8(state.input_int8, l.c, l.h, l.w, l.size, l.stride, l.pad, b); // here //gemm_nn_int8_int16(m, n, k, 1, a, k, b, n, c, n); // single-thread gemm int t; // multi-thread gemm #pragma omp parallel for for (t = 0; t < m; ++t) { gemm_nn_int8_int16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int16_conv16(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); //gemm_nn_int8_int32(1, n, k, 1, a + t*k, k, b, n, c + t*n, n); conv_t should be int32_t } //} #endif // cuDNN: y = alpha1 * conv(x) //for (i = 0; i < l.outputs; ++i) { // output_q[i] = output_q[i] * l.output_multipler; // cuDNN: alpha1 //} for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { output_q[fil*out_size + j] = output_q[fil*out_size + j] * l.output_multipler; } } // cuDNN: y = alpha1 * conv(x) + bias for (fil = 0; fil < l.n; ++fil) { for (j = 0; j < out_size; ++j) { output_q[fil*out_size + j] += l.biases_quant[fil]; } } //for (i = 0; i < l.inputs; ++i) state.input[i] = state.input_int8[i]; //char buff[1024]; //sprintf(buff, "inputs - filters %d", l.n); //draw_distribution(state.input, l.inputs, buff); //for (i = 0; i < l.outputs; ++i) l.output[i] = (float)output_q[i]; //draw_distribution(l.output, l.outputs, "output"); // cuDNN: y = act ( alpha1 * conv(x) + bias ) // bias is always FLOAT if (l.activation == LEAKY) { for (i = 0; i < l.n*out_size; ++i) { output_q[i] = (output_q[i]>0) ? output_q[i] : output_q[i] / 10; //leaky_activate(l.output[i]); } } // cuDNN: y = act ( alpha1 * conv(x) + alpha2 * z + bias ), where: alpha2=0, z=NULL if (return_float) { // y - FLOAT, x,w - X_INT8 / X_INT8x4 for (i = 0; i < l.outputs; ++i) { l.output[i] = (float)output_q[i] / 16.F; // /8 // float32 // 15.769 } } else { // y - X_INT8 / X_INT8x4, x,w - X_INT8 / X_INT8x4 for (i = 0; i < l.outputs; ++i) { l.output_int8[i] = max_abs(output_q[i], I_MAX_VAL); // int8 } } free(output_q); } #define MIN_INT8 -128 // MAX pooling layer void forward_maxpool_layer_q(const layer l, network_state state) { int b, i, j, k, m, n; int w_offset = -l.pad; int h_offset = -l.pad; int h = l.out_h; int w = l.out_w; int c = l.c; // batch index for (b = 0; b < l.batch; ++b) { // channel index for (k = 0; k < c; ++k) { // y - input for (i = 0; i < h; ++i) { // x - input for (j = 0; j < w; ++j) { int out_index = j + w*(i + h*(k + c*b)); int8_t max = MIN_INT8; int max_i = -1; // pooling x-index for (n = 0; n < l.size; ++n) { // pooling y-index for (m = 0; m < l.size; ++m) { int cur_h = h_offset + i*l.stride + n; int cur_w = w_offset + j*l.stride + m; int index = cur_w + l.w*(cur_h + l.h*(k + b*l.c)); int valid = (cur_h >= 0 && cur_h < l.h && cur_w >= 0 && cur_w < l.w); int8_t val = (valid != 0) ? state.input_int8[index] : MIN_INT8; max_i = (val > max) ? index : max_i; // get max index max = (val > max) ? val : max; // get max value } } //l.output[out_index] = max; // store max value l.output_int8[out_index] = max; // store max value l.indexes[out_index] = max_i; // store max index } } } } } // Route layer - just copy 1 or more layers into the current layer void forward_route_layer_q(const layer l, network_state state) { int i, j; int offset = 0; // number of merged layers for (i = 0; i < l.n; ++i) { int index = l.input_layers[i]; // source layer index //float *input = state.net.layers[index].output; // source layer output ptr int8_t *input = state.net.layers[index].output_int8; // source layer output ptr int input_size = l.input_sizes[i]; // source layer size // batch index for (j = 0; j < l.batch; ++j) { memcpy(l.output_int8 + offset + j*l.outputs, input + j*input_size, input_size * sizeof(int8_t)); } offset += input_size; } } // Reorg layer - just change dimension sizes of the previous layer (some dimension sizes are increased by decreasing other) void forward_reorg_layer_q(const layer l, network_state state) { //float *out = l.output; //float *x = state.input; int8_t *out = l.output_int8; int8_t *x = state.input_int8; int out_w = l.out_w; int out_h = l.out_h; int out_c = l.out_c; int batch = l.batch; int stride = l.stride; int b, i, j, k; int in_c = out_c / (stride*stride); int out_w_X_stride = out_w*stride; int out_h_X_stride = out_h*stride; //printf("\n out_c = %d, out_w = %d, out_h = %d, stride = %d, forward = %d \n", out_c, out_w, out_h, stride, forward); //printf(" in_c = %d, in_w = %d, in_h = %d \n", in_c, out_w*stride, out_h*stride); // batch for (b = 0; b < batch; ++b) { // channel for (k = 0; k < out_c; ++k) { int c2 = k % in_c; int pre_out_index = out_h_X_stride*(c2 + in_c*b); int offset = k / in_c; int offset_mod_stride = offset % stride; int offset_div_stride = offset / stride; // y for (j = 0; j < out_h; ++j) { int pre_in_index = out_w*(j + out_h*(k + out_c*b)); // x for (i = 0; i < out_w; ++i) { int in_index = i + pre_in_index; int w2 = i*stride + offset_mod_stride; int h2 = j*stride + offset_div_stride; int out_index = w2 + out_w_X_stride*(h2 + pre_out_index); out[in_index] = x[out_index]; } } } } } // ---- region layer ---- static void softmax_q(float *input, int n, float temp, float *output) { int i; float sum = 0; float largest = -FLT_MAX; for (i = 0; i < n; ++i) { if (input[i] > largest) largest = input[i]; } for (i = 0; i < n; ++i) { float e = expf(input[i] / temp - largest / temp); sum += e; output[i] = e; } for (i = 0; i < n; ++i) { output[i] /= sum; } } static void softmax_tree(float *input, int batch, int inputs, float temp, tree *hierarchy, float *output) { int b; for (b = 0; b < batch; ++b) { int i; int count = 0; for (i = 0; i < hierarchy->groups; ++i) { int group_size = hierarchy->group_size[i]; softmax_q(input + b*inputs + count, group_size, temp, output + b*inputs + count); count += group_size; } } } // --- // Region layer - just change places of array items, then do logistic_activate and softmax void forward_region_layer_q(const layer l, network_state state) { int i, b; int size = l.coords + l.classes + 1; // 4 Coords(x,y,w,h) + Classes + 1 Probability-t0 //printf("\n l.coords = %d \n", l.coords); memcpy(l.output, state.input, l.outputs*l.batch * sizeof(float)); //flatten(l.output, l.w*l.h, size*l.n, l.batch, 1); // convert many channels to the one channel (depth=1) // (each grid cell will have a number of float-variables equal = to the initial number of channels) { float *x = l.output; int layer_size = l.w*l.h; // W x H - size of layer int layers = size*l.n; // number of channels (where l.n = number of anchors) int batch = l.batch; float *swap = calloc(layer_size*layers*batch, sizeof(float)); int i, c, b; // batch index for (b = 0; b < batch; ++b) { // channel index for (c = 0; c < layers; ++c) { // layer grid index for (i = 0; i < layer_size; ++i) { int i1 = b*layers*layer_size + c*layer_size + i; int i2 = b*layers*layer_size + i*layers + c; swap[i2] = x[i1]; } } } memcpy(x, swap, layer_size*layers*batch * sizeof(float)); free(swap); } // logistic activation only for: t0 (where is t0 = Probability * IoU(box, object)) for (b = 0; b < l.batch; ++b) { // for each item (x, y, anchor-index) for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; float x = l.output[index + 4]; l.output[index + 4] = 1.0F / (1.0F + expf(-x)); // logistic_activate_q(l.output[index + 4]); } } if (l.softmax_tree) { // Yolo 9000 for (b = 0; b < l.batch; ++b) { for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; softmax_tree(l.output + index + 5, 1, 0, 1, l.softmax_tree, l.output + index + 5); } } } else if (l.softmax) { // Yolo v2 // softmax activation only for Classes probability for (b = 0; b < l.batch; ++b) { // for each item (x, y, anchor-index) //#pragma omp parallel for for (i = 0; i < l.h*l.w*l.n; ++i) { int index = size*i + b*l.outputs; softmax_q(l.output + index + 5, l.classes, 1, l.output + index + 5); } } } } void yolov2_forward_network_q(network net, network_state state) { state.workspace = net.workspace; int i, k; for (i = 0; i < net.n; ++i) { state.index = i; layer l = net.layers[i]; if (l.type == CONVOLUTIONAL) { if (i >= 1 && l.activation != LINEAR) forward_convolutional_layer_q(l, state); else forward_convolutional_layer_cpu(l, state); //printf("\n %d - CONVOLUTIONAL \t\t l.size = %d \n", i, l.size); } else if (l.type == MAXPOOL) { forward_maxpool_layer_cpu(l, state); //printf("\n MAXPOOL \t\t l.size = %d \n", l.size); } else if (l.type == ROUTE) { forward_route_layer_cpu(l, state); //printf("\n ROUTE \t\t\t l.n = %d \n", l.n); } else if (l.type == REORG) { forward_reorg_layer_cpu(l, state); //printf("\n REORG \n"); } else if (l.type == UPSAMPLE) { forward_upsample_layer_cpu(l, state); //printf("\n UPSAMPLE \n"); } else if (l.type == SHORTCUT) { forward_shortcut_layer_cpu(l, state); //printf("\n SHORTCUT \n"); } else if (l.type == YOLO) { forward_yolo_layer_cpu(l, state); //printf("\n YOLO \n"); } else if (l.type == REGION) { forward_region_layer_cpu(l, state); //printf("\n REGION \n"); } else { printf("\n layer: %d \n", l.type); } state.input = l.output; //state.input_int8 = l.output_int8; /* if (i == 0) { //draw_distribution(state.input, l.outputs, NULL); int k; for (k = 0; k < l.out_w*l.out_h*l.out_c; ++k) { int16_t src = state.input[k] * 3.88677;// *net.layers[2].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); //printf(" %d, ", src); } } */ } } void yolov2_forward_network_q_old(network net, network_state state) { state.workspace = net.workspace; int i, k; for (i = 0; i < net.n; ++i) { state.index = i; layer l = net.layers[i]; if (l.type == CONVOLUTIONAL) { int return_float = (net.layers[i+1].activation == LINEAR); // if next layer has LINEAR activation if (i >= 1 && l.activation != LINEAR) forward_convolutional_layer_q_old(l, state, return_float); else forward_convolutional_layer_cpu(l, state); //printf("\n %d - CONVOLUTIONAL \t\t l.size = %d \n", i, l.size); } else if (l.type == MAXPOOL) { forward_maxpool_layer_q(l, state); //printf("\n MAXPOOL \t\t l.size = %d \n", l.size); } else if (l.type == ROUTE) { forward_route_layer_q(l, state); //printf("\n ROUTE \t\t\t l.n = %d \n", l.n); } else if (l.type == REORG) { forward_reorg_layer_q(l, state); //printf("\n REORG \n"); } /* else if (l.type == UPSAMPLE) { forward_upsample_layer_cpu(l, state); //printf("\n UPSAMPLE \n"); } else if (l.type == SHORTCUT) { forward_shortcut_layer_cpu(l, state); //printf("\n SHORTCUT \n"); } else if (l.type == YOLO) { forward_yolo_layer_cpu(l, state); //printf("\n YOLO \n"); } */ else if (l.type == REGION) { forward_region_layer_q(l, state); //printf("\n REGION \n"); } else { printf("\n layer: %d \n", l.type); } state.input = l.output; state.input_int8 = l.output_int8; if (i == 0) { //draw_distribution(state.input, l.outputs, NULL); int k; for (k = 0; k < l.out_w*l.out_h*l.out_c; ++k) { int16_t src = state.input[k] * 3.88677;// *net.layers[2].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); //printf(" %d, ", src); } } } } // detect on CPU float *network_predict_quantized(network net, float *input) { network_state state; state.net = net; state.index = 0; state.input = input; //state.input_int8 = calloc(net.w*net.h*net.c, sizeof(int8_t)); state.truth = 0; state.train = 0; state.delta = 0; /*/ int k; for (k = 0; k < net.w*net.h*net.c; ++k) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[k] * net.layers[0].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); } */ yolov2_forward_network_q(net, state); // network on CPU //float *out = get_network_output(net); int i; for (i = net.n - 1; i > 0; --i) if (net.layers[i].type != COST) break; //free(state.input_int8); return net.layers[i].output; } // detect on CPU float *network_predict_quantized_old(network net, float *input) { network_state state; state.net = net; state.index = 0; state.input = input; state.input_int8 = calloc(net.w*net.h*net.c, sizeof(int8_t)); state.truth = 0; state.train = 0; state.delta = 0; int k; for (k = 0; k < net.w*net.h*net.c; ++k) { //int16_t src = lround(state.input[k] * net.layers[0].input_quant_multipler); int16_t src = state.input[k] * net.layers[0].input_quant_multipler; state.input_int8[k] = max_abs(src, I_MAX_VAL); } yolov2_forward_network_q_old(net, state); // network on CPU //float *out = get_network_output(net); int i; for (i = net.n - 1; i > 0; --i) if (net.layers[i].type != COST) break; free(state.input_int8); return net.layers[i].output; } // -------------------- // x - last conv-layer output // biases - anchors from cfg-file // n - number of anchors from cfg-file box get_region_box_q(float *x, float *biases, int n, int index, int i, int j, int w, int h) { box b; b.x = (i + logistic_activate(x[index + 0])) / w; // (col + 1./(1. + exp(-x))) / width_last_layer b.y = (j + logistic_activate(x[index + 1])) / h; // (row + 1./(1. + exp(-x))) / height_last_layer b.w = expf(x[index + 2]) * biases[2 * n] / w; // exp(x) * anchor_w / width_last_layer b.h = expf(x[index + 3]) * biases[2 * n + 1] / h; // exp(x) * anchor_h / height_last_layer return b; } // get prediction boxes void get_region_boxes_q(layer l, int w, int h, float thresh, float **probs, box *boxes, int only_objectness, int *map) { int i, j, n; float *predictions = l.output; // grid index for (i = 0; i < l.w*l.h; ++i) { int row = i / l.w; int col = i % l.w; // anchor index for (n = 0; n < l.n; ++n) { int index = i*l.n + n; // index for each grid-cell & anchor int p_index = index * (l.classes + 5) + 4; float scale = predictions[p_index]; // scale = t0 = Probability * IoU(box, object) if (l.classfix == -1 && scale < .5) scale = 0; // if(t0 < 0.5) t0 = 0; int box_index = index * (l.classes + 5); boxes[index] = get_region_box_q(predictions, l.biases, n, box_index, col, row, l.w, l.h); boxes[index].x *= w; boxes[index].y *= h; boxes[index].w *= w; boxes[index].h *= h; int class_index = index * (l.classes + 5) + 5; // Yolo 9000 or Yolo v2 if (l.softmax_tree) { // Yolo 9000 hierarchy_predictions(predictions + class_index, l.classes, l.softmax_tree, 0); int found = 0; if (map) { for (j = 0; j < 200; ++j) { float prob = scale*predictions[class_index + map[j]]; probs[index][j] = (prob > thresh) ? prob : 0; } } else { for (j = l.classes - 1; j >= 0; --j) { if (!found && predictions[class_index + j] > .5) { found = 1; } else { predictions[class_index + j] = 0; } float prob = predictions[class_index + j]; probs[index][j] = (scale > thresh) ? prob : 0; } } } else { // Yolo v2 for (j = 0; j < l.classes; ++j) { float prob = scale*predictions[class_index + j]; // prob = IoU(box, object) = t0 * class-probability probs[index][j] = (prob > thresh) ? prob : 0; // if (IoU < threshold) IoU = 0; } } if (only_objectness) { probs[index][0] = scale; } } } } float entropy_calibration(float *src_arr, const size_t size, const float bin_width, const int max_bin) { //const float bin_width = 1.0 / 4096;// 1.0F / 64.0F; //const int max_bin = 2048*2;// 2048; const int max_global_val = max_bin * bin_width; // 1024 // 32 float *m_array = (float*)calloc(max_bin, sizeof(float)); float *H_histogram = (float*)calloc(max_bin, sizeof(float)); float *P_array = (float*)calloc(max_bin, sizeof(float)); float *Q_array = (float*)calloc(max_bin, sizeof(float)); float *quant_Q_array = (float*)calloc(128, sizeof(float)); // 128 for INT8 uint64_t *quant_Q_array_count = (uint64_t*)calloc(128, sizeof(uint64_t)); // 128 for INT8 int i, j; { //uint64_t outliers = 0; const int last_bin = max_bin - 1; for (j = 0; j <= last_bin; ++j) P_array[j] = 0; for (j = 0; j < size; ++j) { int bin_num = lround(fabs(src_arr[j]) / bin_width); int bin_num_saturated = (bin_num >= last_bin) ? last_bin : bin_num; H_histogram[bin_num_saturated]++; //if (bin_num > last_bin) outliers++; //else H_histogram[bin_num]++; } } for (i = 128; i < max_bin; ++i) { // [1/64; 1024] // [1/64; 32] //if (i > max_bin) printf(" i > max_bin = %d, ", i); //printf(" %d \r", i); // calculate bin histogram uint64_t outliers = 0; const int last_bin = i - 1; for (j = 0; j <= last_bin; ++j) P_array[j] = 0; /*for (j = 0; j < size; ++j) { int bin_num = lround(fabs(src_arr[j]) / bin_width); //int bin_num_saturated = (bin_num >= last_bin) ? last_bin : bin_num; if (bin_num > last_bin) outliers++; else P_array[bin_num]++; }*/ for (j = 0; j < max_bin; ++j) { if (j <= last_bin) P_array[j] = H_histogram[j]; else outliers += H_histogram[j]; } // quantinization P-i-bins to Q-128-bins const float quant_expand_width = i / 128.0F; for (j = 0; j < 128; ++j) quant_Q_array[j] = 0, quant_Q_array_count[j] = 0; for (j = 0; j < i; ++j) { int quant_bin = lround(j / quant_expand_width); if (quant_bin > 127) quant_bin = 127; // printf(" quant_bin > 127 = %d \n", quant_bin); quant_Q_array[quant_bin] += P_array[j]; if (P_array[j] != 0) quant_Q_array_count[quant_bin]++; } // expand 128-bins to i-bins for (j = 0; j < i; ++j) Q_array[j] = 0; for (j = 0; j < i; ++j) { int quant_bin = lround(j / quant_expand_width); if (quant_bin > 127) quant_bin = 127;// printf(" quant_bin > 127 = %d \n", quant_bin); //Q_array[j] = llround(quant_Q_array[quant_bin] / quant_expand_width); if (P_array[j] != 0) // preserve empty bins from original P Q_array[j] = quant_Q_array[quant_bin] / quant_Q_array_count[quant_bin]; //printf(" quant_bin = %d, Q[j] = %f = q_Q %f / q_w %f, P = %f \n", quant_bin, Q_array[j], quant_Q_array[quant_bin], quant_expand_width, P_array[j]); } P_array[last_bin] += outliers; // saturation // P /= SUM(P); Q /= SUM(Q); float sum_P = 0, sum_Q = 0, quant_sum_Q = 0; for (j = 0; j < 128; ++j) quant_sum_Q += quant_Q_array[j]; for (j = 0; j < i; ++j) { sum_P += P_array[j]; sum_Q += Q_array[j]; //printf(" P_array = %f, Q_array = %f \n", P_array[j], Q_array[j]); } for (j = 0; j < i; ++j) { P_array[j] /= sum_P; Q_array[j] /= sum_Q; } // KL_divergence(P, Q); for (j = 0; j < i; ++j) { m_array[i] += P_array[j] * (log((P_array[j] + FLT_MIN) / (Q_array[j] + FLT_MIN))); //printf(" p = %f, q = %f, p/q = %f, log(p/q) = %f, m = %f \n", P_array[j], Q_array[j], P_array[j] / Q_array[j], log((P_array[j] + FLT_MIN) / (Q_array[j] + FLT_MIN)), m_array[i]); } //printf("\n i = %d, size = %zu, sum_P = %f, sum_Q = %f, q_sum_Q = %f, q_e_width = %f, m = %f \n", i, size, sum_P, sum_Q, quant_sum_Q, quant_expand_width, m_array[i]); //getchar(); } float m_index = 128, min_m = FLT_MAX; for (i = 128; i < max_bin; ++i) { if (m_array[i] < min_m) { min_m = m_array[i]; m_index = i; } } float threshold = (m_index + 0.5) * bin_width; float multiplier = 127 / threshold; printf(" mult = %g, threshold = %g, min_m = %g, m_index = %g \n", multiplier, threshold, min_m, m_index); free(H_histogram); free(P_array); free(Q_array); free(quant_Q_array); free(quant_Q_array_count); free(m_array); //getchar(); return multiplier; } // Quantinization and get multiplers for convolutional weights for quantinization void quantinization_and_get_multipliers(network net) { // ----------- entropy_calibration(,, 1.0 / 16, 4096); - FULL ---------------------- //float input_mult[] = { 256, 4,32,64,32,32,32,32,32,64,64,64,64,64,128,64,128,128,64,128,64,128,128 }; // divided 4 - full works int counter = 0; //const int input_mult_size = sizeof(input_mult) / sizeof(float); int j; for (j = 0; j < net.n; ++j) { layer *l = &net.layers[j]; if (l->type == CONVOLUTIONAL) { size_t const weights_size = l->size*l->size*l->c*l->n; size_t const filter_size = l->size*l->size*l->c; int i, k, fil; // get optimal multipliers - for Weights //float *weights_multiplier = (float *)calloc(l->n, sizeof(float)); //l->output_multipler = (float *)calloc(l->n, sizeof(float)); //float weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / (2048), (2048)); //float weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / 4096, 4096) / 2; //if (j == 0) weights_multiplier_single = entropy_calibration(l->weights, weights_size, 1.0 / 2, 2048); float old_weight_mult = get_multiplier(l->weights, weights_size, 8) / 4; // good [2 - 8], best 4 float weights_multiplier_single = old_weight_mult; //float old_weight_mult = get_multiplier(l->weights, weights_size, 7) / 4; printf(" old_weight_mult = %f, weights_multiplier_single = %f \n\n", old_weight_mult, weights_multiplier_single); //weights_multiplier_single = old_weight_mult; l->weights_quant_multipler = weights_multiplier_single; for (fil = 0; fil < l->n; ++fil) { for (i = 0; i < filter_size; ++i) { float w = l->weights[fil*filter_size + i] * l->weights_quant_multipler;// [fil]; l->weights_int8[fil*filter_size + i] = max_abs(w, W_MAX_VAL); //l->weights_int8[fil*filter_size + i] = max_abs(lround(w), W_MAX_VAL); } } if (counter >= net.input_calibration_size) { printf("\n Warning: input_calibration= in the cfg-file has less values %d than convolutional layers %d \n", net.input_calibration_size, counter); } //l->input_quant_multipler = 40;//(counter < net.input_calibration_size) ? net.input_calibration[counter] : 16; // best 40 l->input_quant_multipler = (counter < net.input_calibration_size) ? net.input_calibration[counter] : 40; ++counter; //float current_input_mult = 40;//(counter < net.input_calibration_size) ? net.input_calibration[counter] : 16; float current_input_mult = (counter < net.input_calibration_size) ? net.input_calibration[counter] : 40; for (fil = 0; fil < l->n; ++fil) { if (counter == 1) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); if (counter == 2) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); else if (counter >= 2) l->output_multipler = current_input_mult / (l->weights_quant_multipler * l->input_quant_multipler / R_MULT); } // quantinization Biases for (fil = 0; fil < l->n; ++fil) { // calculate optimal multipliers - for Biases float biases_multipler = (l->output_multipler * l->weights_quant_multipler * l->input_quant_multipler / R_MULT); l->biases_quant[fil] = l->biases[fil] * biases_multipler; } printf(" Multiplers: weights %g, input %g, output %g \n", l->weights_quant_multipler, l->input_quant_multipler, l->output_multipler); } else { printf(" Skip layer: %d \n", l->type); } } #ifdef GPU // init weights and cuDNN for quantized IINT8x4 init_gpu_int8x4(net); #endif //GPU }
threshold.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % TTTTT H H RRRR EEEEE SSSSS H H OOO L DDDD % % T H H R R E SS H H O O L D D % % T HHHHH RRRR EEE SSS HHHHH O O L D D % % T H H R R E SS H H O O L D D % % T H H R R EEEEE SSSSS H H OOO LLLLL DDDD % % % % % % MagickCore Image Threshold Methods % % % % Software Design % % John Cristy % % October 1996 % % % % % % Copyright 1999-2011 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/property.h" #include "magick/blob.h" #include "magick/cache-view.h" #include "magick/color.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/configure.h" #include "magick/constitute.h" #include "magick/decorate.h" #include "magick/draw.h" #include "magick/enhance.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/effect.h" #include "magick/fx.h" #include "magick/gem.h" #include "magick/geometry.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/memory_.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/montage.h" #include "magick/option.h" #include "magick/pixel-private.h" #include "magick/quantize.h" #include "magick/quantum.h" #include "magick/random_.h" #include "magick/random-private.h" #include "magick/resize.h" #include "magick/resource_.h" #include "magick/segment.h" #include "magick/shear.h" #include "magick/signature-private.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/thread-private.h" #include "magick/threshold.h" #include "magick/transform.h" #include "magick/xml-tree.h" /* Define declarations. */ #define ThresholdsFilename "thresholds.xml" /* Typedef declarations. */ struct _ThresholdMap { char *map_id, *description; size_t width, height; ssize_t divisor, *levels; }; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A d a p t i v e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AdaptiveThresholdImage() selects an individual threshold for each pixel % based on the range of intensity values in its local neighborhood. This % allows for thresholding of an image whose global intensity histogram % doesn't contain distinctive peaks. % % The format of the AdaptiveThresholdImage method is: % % Image *AdaptiveThresholdImage(const Image *image, % const size_t width,const size_t height, % const ssize_t offset,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o width: the width of the local neighborhood. % % o height: the height of the local neighborhood. % % o offset: the mean offset. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *AdaptiveThresholdImage(const Image *image, const size_t width,const size_t height,const ssize_t offset, ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view, *threshold_view; Image *threshold_image; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket zero; MagickRealType number_pixels; ssize_t y; assert(image != (const Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); threshold_image=CloneImage(image,0,0,MagickTrue,exception); if (threshold_image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(threshold_image,DirectClass) == MagickFalse) { InheritException(exception,&threshold_image->exception); threshold_image=DestroyImage(threshold_image); return((Image *) NULL); } /* Local adaptive threshold. */ status=MagickTrue; progress=0; GetMagickPixelPacket(image,&zero); number_pixels=(MagickRealType) width*height; image_view=AcquireCacheView(image); threshold_view=AcquireCacheView(threshold_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { MagickBooleanType sync; register const IndexPacket *restrict indexes; register const PixelPacket *restrict p; register IndexPacket *restrict threshold_indexes; register ssize_t x; register PixelPacket *restrict q; if (status == MagickFalse) continue; p=GetCacheViewVirtualPixels(image_view,-((ssize_t) width/2L),y-(ssize_t) height/2L,image->columns+width,height,exception); q=GetCacheViewAuthenticPixels(threshold_view,0,y,threshold_image->columns,1, exception); if ((p == (const PixelPacket *) NULL) || (q == (PixelPacket *) NULL)) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(image_view); threshold_indexes=GetCacheViewAuthenticIndexQueue(threshold_view); for (x=0; x < (ssize_t) image->columns; x++) { MagickPixelPacket mean, pixel; register const PixelPacket *r; register ssize_t u; ssize_t v; pixel=zero; mean=zero; r=p; for (v=0; v < (ssize_t) height; v++) { for (u=0; u < (ssize_t) width; u++) { pixel.red+=r[u].red; pixel.green+=r[u].green; pixel.blue+=r[u].blue; pixel.opacity+=r[u].opacity; if (image->colorspace == CMYKColorspace) pixel.index=(MagickRealType) indexes[x+(r-p)+u]; } r+=image->columns+width; } mean.red=(MagickRealType) (pixel.red/number_pixels+offset); mean.green=(MagickRealType) (pixel.green/number_pixels+offset); mean.blue=(MagickRealType) (pixel.blue/number_pixels+offset); mean.opacity=(MagickRealType) (pixel.opacity/number_pixels+offset); if (image->colorspace == CMYKColorspace) mean.index=(MagickRealType) (pixel.index/number_pixels+offset); q->red=(Quantum) (((MagickRealType) q->red <= mean.red) ? 0 : QuantumRange); q->green=(Quantum) (((MagickRealType) q->green <= mean.green) ? 0 : QuantumRange); q->blue=(Quantum) (((MagickRealType) q->blue <= mean.blue) ? 0 : QuantumRange); q->opacity=(Quantum) (((MagickRealType) q->opacity <= mean.opacity) ? 0 : QuantumRange); if (image->colorspace == CMYKColorspace) threshold_indexes[x]=(IndexPacket) (((MagickRealType) threshold_indexes[x] <= mean.index) ? 0 : QuantumRange); p++; q++; } sync=SyncCacheViewAuthenticPixels(threshold_view,exception); if (sync == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_AdaptiveThresholdImage) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } threshold_view=DestroyCacheView(threshold_view); image_view=DestroyCacheView(image_view); if (status == MagickFalse) threshold_image=DestroyImage(threshold_image); return(threshold_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B i l e v e l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BilevelImage() changes the value of individual pixels based on the % intensity of each pixel channel. The result is a high-contrast image. % % More precisely each channel value of the image is 'thresholded' so that if % it is equal to or less than the given value it is set to zero, while any % value greater than that give is set to it maximum or QuantumRange. % % This function is what is used to implement the "-threshold" operator for % the command line API. % % If the default channel setting is given the image is thresholded using just % the gray 'intensity' of the image, rather than the individual channels. % % The format of the BilevelImageChannel method is: % % MagickBooleanType BilevelImage(Image *image,const double threshold) % MagickBooleanType BilevelImageChannel(Image *image, % const ChannelType channel,const double threshold) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % % o threshold: define the threshold values. % % Aside: You can get the same results as operator using LevelImageChannels() % with the 'threshold' value for both the black_point and the white_point. % */ MagickExport MagickBooleanType BilevelImage(Image *image,const double threshold) { MagickBooleanType status; status=BilevelImageChannel(image,DefaultChannels,threshold); return(status); } MagickExport MagickBooleanType BilevelImageChannel(Image *image, const ChannelType channel,const double threshold) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); /* Bilevel threshold image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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); if (channel == DefaultChannels) { for (x=0; x < (ssize_t) image->columns; x++) { q->red=(Quantum) ((MagickRealType) PixelIntensityToQuantum(q) <= threshold ? 0 : QuantumRange); q->green=q->red; q->blue=q->red; q++; } } else for (x=0; x < (ssize_t) image->columns; x++) { if ((channel & RedChannel) != 0) q->red=(Quantum) ((MagickRealType) q->red <= threshold ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) q->green=(Quantum) ((MagickRealType) q->green <= threshold ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) q->blue=(Quantum) ((MagickRealType) q->blue <= threshold ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) { if (image->matte == MagickFalse) q->opacity=(Quantum) ((MagickRealType) q->opacity <= threshold ? 0 : QuantumRange); else q->opacity=(Quantum) ((MagickRealType) q->opacity <= threshold ? OpaqueOpacity : TransparentOpacity); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) indexes[x]=(IndexPacket) ((MagickRealType) indexes[x] <= threshold ? 0 : QuantumRange); 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_BilevelImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % B l a c k T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % BlackThresholdImage() is like ThresholdImage() but forces all pixels below % the threshold into black while leaving all pixels at or above the threshold % unchanged. % % The format of the BlackThresholdImage method is: % % MagickBooleanType BlackThresholdImage(Image *image,const char *threshold) % MagickBooleanType BlackThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType BlackThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=BlackThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType BlackThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); GetMagickPixelPacket(image,&threshold); flags=ParseGeometry(thresholds,&geometry_info); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(QuantumRange/100.0); threshold.green*=(QuantumRange/100.0); threshold.blue*=(QuantumRange/100.0); threshold.opacity*=(QuantumRange/100.0); threshold.index*=(QuantumRange/100.0); } /* Black threshold image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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++) { if (channel != DefaultChannels) { if (PixelIntensity(q) < MagickPixelIntensity(&threshold)) { q->red=(Quantum) 0; q->green=(Quantum) 0; q->blue=(Quantum) 0; if (image->colorspace == CMYKColorspace) indexes[x]=(Quantum) 0; } } else { if (((channel & RedChannel) != 0) && ((MagickRealType) q->red < threshold.red)) q->red=(Quantum) 0; if (((channel & GreenChannel) != 0) && ((MagickRealType) q->green < threshold.green)) q->green=(Quantum) 0; if (((channel & BlueChannel) != 0) && ((MagickRealType) q->blue < threshold.blue)) q->blue=(Quantum) 0; if (((channel & OpacityChannel) != 0) && ((MagickRealType) q->opacity < threshold.opacity)) q->opacity=(Quantum) 0; if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) indexes[x] < threshold.index)) indexes[x]=(Quantum) 0; } q++; } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_BlackThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l a m p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClampImage() restricts the color range from 0 to the quantum depth. % % The format of the ClampImageChannel method is: % % MagickBooleanType ClampImage(Image *image) % MagickBooleanType ClampImageChannel(Image *image, % const ChannelType channel) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel type. % */ static inline Quantum ClampToUnsignedQuantum(const Quantum quantum) { #if defined(MAGICKCORE_HDRI_SUPPORT) if (quantum <= 0) return(0); if (quantum >= QuantumRange) return(QuantumRange); return(quantum); #else return(quantum); #endif } MagickExport MagickBooleanType ClampImage(Image *image) { MagickBooleanType status; status=ClampImageChannel(image,DefaultChannels); return(status); } MagickExport MagickBooleanType ClampImageChannel(Image *image, const ChannelType channel) { #define ClampImageTag "Clamp/Image" CacheView *image_view; ExceptionInfo *exception; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->storage_class == PseudoClass) { register ssize_t i; register PixelPacket *restrict q; q=image->colormap; for (i=0; i < (ssize_t) image->colors; i++) { q->red=ClampToUnsignedQuantum(q->red); q->green=ClampToUnsignedQuantum(q->green); q->blue=ClampToUnsignedQuantum(q->blue); q->opacity=ClampToUnsignedQuantum(q->opacity); q++; } return(SyncImage(image)); } /* Clamp image. */ status=MagickTrue; progress=0; exception=(&image->exception); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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++) { if ((channel & RedChannel) != 0) q->red=ClampToUnsignedQuantum(q->red); if ((channel & GreenChannel) != 0) q->green=ClampToUnsignedQuantum(q->green); if ((channel & BlueChannel) != 0) q->blue=ClampToUnsignedQuantum(q->blue); if ((channel & OpacityChannel) != 0) q->opacity=ClampToUnsignedQuantum(q->opacity); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) indexes[x]=(IndexPacket) ClampToUnsignedQuantum(indexes[x]); 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_ClampImageChannel) #endif proceed=SetImageProgress(image,ClampImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyThresholdMap() de-allocate the given ThresholdMap % % The format of the ListThresholdMaps method is: % % ThresholdMap *DestroyThresholdMap(Threshold *map) % % A description of each parameter follows. % % o map: Pointer to the Threshold map to destroy % */ MagickExport ThresholdMap *DestroyThresholdMap(ThresholdMap *map) { assert(map != (ThresholdMap *) NULL); if (map->map_id != (char *) NULL) map->map_id=DestroyString(map->map_id); if (map->description != (char *) NULL) map->description=DestroyString(map->description); if (map->levels != (ssize_t *) NULL) map->levels=(ssize_t *) RelinquishMagickMemory(map->levels); map=(ThresholdMap *) RelinquishMagickMemory(map); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMapFile() look for a given threshold map name or alias in the % given XML file data, and return the allocated the map when found. % % The format of the ListThresholdMaps method is: % % ThresholdMap *GetThresholdMap(const char *xml,const char *filename, % const char *map_id,ExceptionInfo *exception) % % A description of each parameter follows. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o map_id: ID of the map to look for in XML list. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMapFile(const char *xml, const char *filename,const char *map_id,ExceptionInfo *exception) { const char *attr, *content; double value; ThresholdMap *map; XMLTreeInfo *description, *levels, *threshold, *thresholds; map = (ThresholdMap *)NULL; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *)NULL ) return(map); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *)NULL; threshold = GetNextXMLTreeTag(threshold) ) { attr = GetXMLTreeAttribute(threshold, "map"); if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) ) break; attr = GetXMLTreeAttribute(threshold, "alias"); if ( (attr != (char *)NULL) && (LocaleCompare(map_id,attr) == 0) ) break; } if ( threshold == (XMLTreeInfo *)NULL ) { return(map); } description = GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); return(map); } levels = GetXMLTreeChild(threshold,"levels"); if ( levels == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<levels>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); return(map); } /* The map has been found -- Allocate a Threshold Map to return */ map = (ThresholdMap *)AcquireMagickMemory(sizeof(ThresholdMap)); if ( map == (ThresholdMap *)NULL ) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); map->map_id = (char *)NULL; map->description = (char *)NULL; map->levels = (ssize_t *) NULL; /* Assign Basic Attributes */ attr = GetXMLTreeAttribute(threshold, "map"); if ( attr != (char *)NULL ) map->map_id = ConstantString(attr); content = GetXMLTreeContent(description); if ( content != (char *)NULL ) map->description = ConstantString(content); attr = GetXMLTreeAttribute(levels, "width"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels width>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->width = StringToUnsignedLong(attr); if ( map->width == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels width>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } attr = GetXMLTreeAttribute(levels, "height"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels height>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->height = StringToUnsignedLong(attr); if ( map->height == 0 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels height>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } attr = GetXMLTreeAttribute(levels, "divisor"); if ( attr == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->divisor = (ssize_t) StringToLong(attr); if ( map->divisor < 2 ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute", "<levels divisor>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } /* Allocate theshold levels array */ content = GetXMLTreeContent(levels); if ( content == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<levels>, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } map->levels=(ssize_t *) AcquireQuantumMemory((size_t) map->width,map->height* sizeof(*map->levels)); if ( map->levels == (ssize_t *)NULL ) ThrowFatalException(ResourceLimitFatalError,"UnableToAcquireThresholdMap"); { /* parse levels into integer array */ ssize_t i; char *p; for( i=0; i< (ssize_t) (map->width*map->height); i++) { map->levels[i] = (ssize_t)strtol(content, &p, 10); if ( p == content ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too few values, map \"%s\"", map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } if ( map->levels[i] < 0 || map->levels[i] > map->divisor ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> %.20g out of range, map \"%s\"", (double) map->levels[i],map_id); thresholds = DestroyXMLTree(thresholds); map = DestroyThresholdMap(map); return(map); } content = p; } value=(double) strtol(content,&p,10); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent", "<level> too many values, map \"%s\"", map_id); thresholds=DestroyXMLTree(thresholds); map=DestroyThresholdMap(map); return(map); } } thresholds = DestroyXMLTree(thresholds); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t T h r e s h o l d M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetThresholdMap() load and search one or more threshold map files for the % a map matching the given name or aliase. % % The format of the GetThresholdMap method is: % % ThresholdMap *GetThresholdMap(const char *map_id, % ExceptionInfo *exception) % % A description of each parameter follows. % % o map_id: ID of the map to look for. % % o exception: return any errors or warnings in this structure. % */ MagickExport ThresholdMap *GetThresholdMap(const char *map_id, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; ThresholdMap *map; map=(ThresholdMap *)NULL; options=GetConfigureOptions(ThresholdsFilename,exception); while (( option=(const StringInfo *) GetNextValueInLinkedList(options) ) != (const StringInfo *) NULL && map == (ThresholdMap *)NULL ) map=GetThresholdMapFile((const char *) GetStringInfoDatum(option), GetStringInfoPath(option),map_id,exception); options=DestroyConfigureOptions(options); return(map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + L i s t T h r e s h o l d M a p F i l e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMapFile() lists the threshold maps and their descriptions % in the given XML file data. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,const char*xml, % const char *filename,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o xml: The threshold map list in XML format. % % o filename: The threshold map XML filename. % % o exception: return any errors or warnings in this structure. % */ MagickBooleanType ListThresholdMapFile(FILE *file,const char *xml, const char *filename,ExceptionInfo *exception) { XMLTreeInfo *thresholds,*threshold,*description; const char *map,*alias,*content; assert( xml != (char *)NULL ); assert( file != (FILE *)NULL ); (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading threshold map file \"%s\" ...",filename); thresholds=NewXMLTree(xml,exception); if ( thresholds == (XMLTreeInfo *)NULL ) return(MagickFalse); (void) fprintf(file,"%-16s %-12s %s\n", "Map", "Alias", "Description"); (void) fprintf(file,"----------------------------------------------------\n"); for( threshold = GetXMLTreeChild(thresholds,"threshold"); threshold != (XMLTreeInfo *)NULL; threshold = GetNextXMLTreeTag(threshold) ) { map = GetXMLTreeAttribute(threshold, "map"); if (map == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute", "<map>"); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } alias = GetXMLTreeAttribute(threshold, "alias"); /* alias is optional, no if test needed */ description=GetXMLTreeChild(threshold,"description"); if ( description == (XMLTreeInfo *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } content=GetXMLTreeContent(description); if ( content == (char *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent", "<description>, map \"%s\"", map); thresholds=DestroyXMLTree(thresholds); return(MagickFalse); } (void) fprintf(file,"%-16s %-12s %s\n",map,alias ? alias : "", content); } thresholds=DestroyXMLTree(thresholds); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % L i s t T h r e s h o l d M a p s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ListThresholdMaps() lists the threshold maps and their descriptions % as defined by "threshold.xml" to a file. % % The format of the ListThresholdMaps method is: % % MagickBooleanType ListThresholdMaps(FILE *file,ExceptionInfo *exception) % % A description of each parameter follows. % % o file: An pointer to the output FILE. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType ListThresholdMaps(FILE *file, ExceptionInfo *exception) { const StringInfo *option; LinkedListInfo *options; MagickStatusType status; status=MagickFalse; if ( file == (FILE *)NULL ) file = stdout; options=GetConfigureOptions(ThresholdsFilename,exception); (void) fprintf(file, "\n Threshold Maps for Ordered Dither Operations\n"); while ( ( option=(const StringInfo *) GetNextValueInLinkedList(options) ) != (const StringInfo *) NULL) { (void) fprintf(file,"\nPATH: %s\n\n",GetStringInfoPath(option)); status|=ListThresholdMapFile(file,(const char *) GetStringInfoDatum(option), GetStringInfoPath(option),exception); } options=DestroyConfigureOptions(options); return(status != 0 ? MagickTrue : MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d D i t h e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedDitherImage() uses the ordered dithering technique of reducing color % images to monochrome using positional information to retain as much % information as possible. % % WARNING: This function is deprecated, and is now just a call to % the more more powerful OrderedPosterizeImage(); function. % % The format of the OrderedDitherImage method is: % % MagickBooleanType OrderedDitherImage(Image *image) % MagickBooleanType OrderedDitherImageChannel(Image *image, % const ChannelType channel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedDitherImage(Image *image) { MagickBooleanType status; status=OrderedDitherImageChannel(image,DefaultChannels,&image->exception); return(status); } MagickExport MagickBooleanType OrderedDitherImageChannel(Image *image, const ChannelType channel,ExceptionInfo *exception) { MagickBooleanType status; /* Call the augumented function OrderedPosterizeImage() */ status=OrderedPosterizeImageChannel(image,channel,"o8x8",exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % O r d e r e d P o s t e r i z e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OrderedPosterizeImage() will perform a ordered dither based on a number % of pre-defined dithering threshold maps, but over multiple intensity % levels, which can be different for different channels, according to the % input argument. % % The format of the OrderedPosterizeImage method is: % % MagickBooleanType OrderedPosterizeImage(Image *image, % const char *threshold_map,ExceptionInfo *exception) % MagickBooleanType OrderedPosterizeImageChannel(Image *image, % const ChannelType channel,const char *threshold_map, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold_map: A string containing the name of the threshold dither % map to use, followed by zero or more numbers representing the number % of color levels tho dither between. % % Any level number less than 2 will be equivelent to 2, and means only % binary dithering will be applied to each color channel. % % No numbers also means a 2 level (bitmap) dither will be applied to all % channels, while a single number is the number of levels applied to each % channel in sequence. More numbers will be applied in turn to each of % the color channels. % % For example: "o3x3,6" will generate a 6 level posterization of the % image with a ordered 3x3 diffused pixel dither being applied between % each level. While checker,8,8,4 will produce a 332 colormaped image % with only a single checkerboard hash pattern (50% grey) between each % color level, to basically double the number of color levels with % a bare minimim of dithering. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType OrderedPosterizeImage(Image *image, const char *threshold_map,ExceptionInfo *exception) { MagickBooleanType status; status=OrderedPosterizeImageChannel(image,DefaultChannels,threshold_map, exception); return(status); } MagickExport MagickBooleanType OrderedPosterizeImageChannel(Image *image, const ChannelType channel,const char *threshold_map,ExceptionInfo *exception) { #define DitherImageTag "Dither/Image" CacheView *image_view; LongPixelPacket levels; MagickBooleanType status; MagickOffsetType progress; ssize_t y; ThresholdMap *map; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (threshold_map == (const char *) NULL) return(MagickTrue); { char token[MaxTextExtent]; register const char *p; p=(char *)threshold_map; while (((isspace((int) ((unsigned char) *p)) != 0) || (*p == ',')) && (*p != '\0')) p++; threshold_map=p; while (((isspace((int) ((unsigned char) *p)) == 0) && (*p != ',')) && (*p != '\0')) { if ((p-threshold_map) >= MaxTextExtent) break; token[p-threshold_map] = *p; p++; } token[p-threshold_map] = '\0'; map = GetThresholdMap(token, exception); if ( map == (ThresholdMap *)NULL ) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "InvalidArgument","%s : '%s'","ordered-dither",threshold_map); return(MagickFalse); } } /* Set channel levels from extra comma separated arguments Default to 2, the single value given, or individual channel values */ #if 1 { /* parse directly as a comma separated list of integers */ char *p; p = strchr((char *) threshold_map,','); if ( p != (char *)NULL && isdigit((int) ((unsigned char) *(++p))) ) levels.index = (unsigned int) strtoul(p, &p, 10); else levels.index = 2; levels.red = ((channel & RedChannel ) != 0) ? levels.index : 0; levels.green = ((channel & GreenChannel) != 0) ? levels.index : 0; levels.blue = ((channel & BlueChannel) != 0) ? levels.index : 0; levels.opacity = ((channel & OpacityChannel) != 0) ? levels.index : 0; levels.index = ((channel & IndexChannel) != 0 && (image->colorspace == CMYKColorspace)) ? levels.index : 0; /* if more than a single number, each channel has a separate value */ if ( p != (char *) NULL && *p == ',' ) { p=strchr((char *) threshold_map,','); p++; if ((channel & RedChannel) != 0) levels.red = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & GreenChannel) != 0) levels.green = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & BlueChannel) != 0) levels.blue = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & IndexChannel) != 0 && image->colorspace == CMYKColorspace) levels.index=(unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); if ((channel & OpacityChannel) != 0) levels.opacity = (unsigned int) strtoul(p, &p, 10), (void)(*p == ',' && p++); } } #else /* Parse level values as a geometry */ /* This difficult! * How to map GeometryInfo structure elements into * LongPixelPacket structure elements, but according to channel? * Note the channels list may skip elements!!!! * EG -channel BA -ordered-dither map,2,3 * will need to map g.rho -> l.blue, and g.sigma -> l.opacity * A simpler way is needed, probably converting geometry to a temporary * array, then using channel to advance the index into ssize_t pixel packet. */ #endif #if 0 printf("DEBUG levels r=%u g=%u b=%u a=%u i=%u\n", levels.red, levels.green, levels.blue, levels.opacity, levels.index); #endif { /* Do the posterized ordered dithering of the image */ ssize_t d; /* d = number of psuedo-level divisions added between color levels */ d = map->divisor-1; /* reduce levels to levels - 1 */ levels.red = levels.red ? levels.red-1 : 0; levels.green = levels.green ? levels.green-1 : 0; levels.blue = levels.blue ? levels.blue-1 : 0; levels.opacity = levels.opacity ? levels.opacity-1 : 0; levels.index = levels.index ? levels.index-1 : 0; if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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++) { register ssize_t threshold, t, l; /* Figure out the dither threshold for this pixel This must be a integer from 1 to map->divisor-1 */ threshold = map->levels[(x%map->width) +map->width*(y%map->height)]; /* Dither each channel in the image as appropriate Notes on the integer Math... total number of divisions = (levels-1)*(divisor-1)+1) t1 = this colors psuedo_level = q->red * total_divisions / (QuantumRange+1) l = posterization level 0..levels t = dither threshold level 0..divisor-1 NB: 0 only on last Each color_level is of size QuantumRange / (levels-1) NB: All input levels and divisor are already had 1 subtracted Opacity is inverted so 'off' represents transparent. */ if (levels.red) { t = (ssize_t) (QuantumScale*q->red*(levels.red*d+1)); l = t/d; t = t-l*d; q->red=RoundToQuantum((MagickRealType) ((l+(t >= threshold))* (MagickRealType) QuantumRange/levels.red)); } if (levels.green) { t = (ssize_t) (QuantumScale*q->green*(levels.green*d+1)); l = t/d; t = t-l*d; q->green=RoundToQuantum((MagickRealType) ((l+(t >= threshold))* (MagickRealType) QuantumRange/levels.green)); } if (levels.blue) { t = (ssize_t) (QuantumScale*q->blue*(levels.blue*d+1)); l = t/d; t = t-l*d; q->blue=RoundToQuantum((MagickRealType) ((l+(t >= threshold))* (MagickRealType) QuantumRange/levels.blue)); } if (levels.opacity) { t = (ssize_t) ((1.0-QuantumScale*q->opacity)*(levels.opacity*d+1)); l = t/d; t = t-l*d; q->opacity=RoundToQuantum((MagickRealType) ((1.0-l-(t >= threshold))* (MagickRealType) QuantumRange/levels.opacity)); } if (levels.index) { t = (ssize_t) (QuantumScale*indexes[x]*(levels.index*d+1)); l = t/d; t = t-l*d; indexes[x]=(IndexPacket) RoundToQuantum((MagickRealType) ((l+ (t>=threshold))*(MagickRealType) QuantumRange/levels.index)); } 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_OrderedPosterizeImageChannel) #endif proceed=SetImageProgress(image,DitherImageTag,progress++,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); } map=DestroyThresholdMap(map); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R a n d o m T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RandomThresholdImage() changes the value of individual pixels based on the % intensity of each pixel compared to a random threshold. The result is a % low-contrast, two color image. % % The format of the RandomThresholdImage method is: % % MagickBooleanType RandomThresholdImageChannel(Image *image, % const char *thresholds,ExceptionInfo *exception) % MagickBooleanType RandomThresholdImageChannel(Image *image, % const ChannelType channel,const char *thresholds, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o thresholds: a geometry string containing low,high thresholds. If the % string contains 2x2, 3x3, or 4x4, an ordered dither of order 2, 3, or 4 % is performed instead. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType RandomThresholdImage(Image *image, const char *thresholds,ExceptionInfo *exception) { MagickBooleanType status; status=RandomThresholdImageChannel(image,DefaultChannels,thresholds, exception); return(status); } MagickExport MagickBooleanType RandomThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickStatusType flags; MagickBooleanType status; MagickOffsetType progress; MagickPixelPacket threshold; MagickRealType min_threshold, max_threshold; RandomInfo **restrict random_info; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); if (thresholds == (const char *) NULL) return(MagickTrue); GetMagickPixelPacket(image,&threshold); min_threshold=0.0; max_threshold=(MagickRealType) QuantumRange; flags=ParseGeometry(thresholds,&geometry_info); min_threshold=geometry_info.rho; max_threshold=geometry_info.sigma; if ((flags & SigmaValue) == 0) max_threshold=min_threshold; if (strchr(thresholds,'%') != (char *) NULL) { max_threshold*=(MagickRealType) (0.01*QuantumRange); min_threshold*=(MagickRealType) (0.01*QuantumRange); } else if (((max_threshold == min_threshold) || (max_threshold == 1)) && (min_threshold <= 8)) { /* Backward Compatibility -- ordered-dither -- IM v 6.2.9-6. */ status=OrderedPosterizeImageChannel(image,channel,thresholds,exception); return(status); } /* Random threshold image. */ status=MagickTrue; progress=0; if (channel == AllChannels) { if (AcquireImageColormap(image,2) == MagickFalse) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); random_info=AcquireRandomInfoThreadSet(); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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++) { IndexPacket index; MagickRealType intensity; intensity=(MagickRealType) PixelIntensityToQuantum(q); if (intensity < min_threshold) threshold.index=min_threshold; else if (intensity > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType)(QuantumRange* GetPseudoRandomValue(random_info[id])); index=(IndexPacket) (intensity <= threshold.index ? 0 : 1); indexes[x]=index; *q++=image->colormap[(ssize_t) index]; } 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_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } if (SetImageStorageClass(image,DirectClass) == MagickFalse) { InheritException(exception,&image->exception); return(MagickFalse); } random_info=AcquireRandomInfoThreadSet(); image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *restrict indexes; register PixelPacket *restrict q; register ssize_t x; 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++) { if ((channel & RedChannel) != 0) { if ((MagickRealType) q->red < min_threshold) threshold.red=min_threshold; else if ((MagickRealType) q->red > max_threshold) threshold.red=max_threshold; else threshold.red=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & GreenChannel) != 0) { if ((MagickRealType) q->green < min_threshold) threshold.green=min_threshold; else if ((MagickRealType) q->green > max_threshold) threshold.green=max_threshold; else threshold.green=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & BlueChannel) != 0) { if ((MagickRealType) q->blue < min_threshold) threshold.blue=min_threshold; else if ((MagickRealType) q->blue > max_threshold) threshold.blue=max_threshold; else threshold.blue=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & OpacityChannel) != 0) { if ((MagickRealType) q->opacity < min_threshold) threshold.opacity=min_threshold; else if ((MagickRealType) q->opacity > max_threshold) threshold.opacity=max_threshold; else threshold.opacity=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) { if ((MagickRealType) indexes[x] < min_threshold) threshold.index=min_threshold; else if ((MagickRealType) indexes[x] > max_threshold) threshold.index=max_threshold; else threshold.index=(MagickRealType) (QuantumRange* GetPseudoRandomValue(random_info[id])); } if ((channel & RedChannel) != 0) q->red=(Quantum) ((MagickRealType) q->red <= threshold.red ? 0 : QuantumRange); if ((channel & GreenChannel) != 0) q->green=(Quantum) ((MagickRealType) q->green <= threshold.green ? 0 : QuantumRange); if ((channel & BlueChannel) != 0) q->blue=(Quantum) ((MagickRealType) q->blue <= threshold.blue ? 0 : QuantumRange); if ((channel & OpacityChannel) != 0) q->opacity=(Quantum) ((MagickRealType) q->opacity <= threshold.opacity ? 0 : QuantumRange); if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace)) indexes[x]=(IndexPacket) ((MagickRealType) indexes[x] <= threshold.index ? 0 : QuantumRange); 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_RandomThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); random_info=DestroyRandomInfoThreadSet(random_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W h i t e T h r e s h o l d I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WhiteThresholdImage() is like ThresholdImage() but forces all pixels above % the threshold into white while leaving all pixels at or below the threshold % unchanged. % % The format of the WhiteThresholdImage method is: % % MagickBooleanType WhiteThresholdImage(Image *image,const char *threshold) % MagickBooleanType WhiteThresholdImageChannel(Image *image, % const ChannelType channel,const char *threshold, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o channel: the channel or channels to be thresholded. % % o threshold: Define the threshold value. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType WhiteThresholdImage(Image *image, const char *threshold) { MagickBooleanType status; status=WhiteThresholdImageChannel(image,DefaultChannels,threshold, &image->exception); return(status); } MagickExport MagickBooleanType WhiteThresholdImageChannel(Image *image, const ChannelType channel,const char *thresholds,ExceptionInfo *exception) { #define ThresholdImageTag "Threshold/Image" CacheView *image_view; GeometryInfo geometry_info; MagickBooleanType status; MagickPixelPacket threshold; MagickOffsetType progress; MagickStatusType flags; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (thresholds == (const char *) NULL) return(MagickTrue); if (SetImageStorageClass(image,DirectClass) == MagickFalse) return(MagickFalse); flags=ParseGeometry(thresholds,&geometry_info); GetMagickPixelPacket(image,&threshold); threshold.red=geometry_info.rho; threshold.green=geometry_info.sigma; if ((flags & SigmaValue) == 0) threshold.green=threshold.red; threshold.blue=geometry_info.xi; if ((flags & XiValue) == 0) threshold.blue=threshold.red; threshold.opacity=geometry_info.psi; if ((flags & PsiValue) == 0) threshold.opacity=threshold.red; threshold.index=geometry_info.chi; if ((flags & ChiValue) == 0) threshold.index=threshold.red; if ((flags & PercentValue) != 0) { threshold.red*=(QuantumRange/100.0); threshold.green*=(QuantumRange/100.0); threshold.blue*=(QuantumRange/100.0); threshold.opacity*=(QuantumRange/100.0); threshold.index*=(QuantumRange/100.0); } /* White threshold image. */ status=MagickTrue; progress=0; image_view=AcquireCacheView(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(dynamic,4) shared(progress,status) #endif for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *restrict indexes; register ssize_t x; register PixelPacket *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++) { if (channel != DefaultChannels) { if (PixelIntensity(q) > MagickPixelIntensity(&threshold)) { q->red=(Quantum) QuantumRange; q->green=(Quantum) QuantumRange; q->blue=(Quantum) QuantumRange; if (image->colorspace == CMYKColorspace) indexes[x]=(Quantum) QuantumRange; } } else { if (((channel & RedChannel) != 0) && ((MagickRealType) q->red > threshold.red)) q->red=(Quantum) QuantumRange; if (((channel & GreenChannel) != 0) && ((MagickRealType) q->green > threshold.green)) q->green=(Quantum) QuantumRange; if (((channel & BlueChannel) != 0) && ((MagickRealType) q->blue > threshold.blue)) q->blue=(Quantum) QuantumRange; if (((channel & OpacityChannel) != 0) && ((MagickRealType) q->opacity > threshold.opacity)) q->opacity=(Quantum) QuantumRange; if (((channel & IndexChannel) != 0) && (image->colorspace == CMYKColorspace) && ((MagickRealType) indexes[x] > threshold.index)) indexes[x]=(Quantum) QuantumRange; } 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_WhiteThresholdImageChannel) #endif proceed=SetImageProgress(image,ThresholdImageTag,progress++, image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
pr30494.c
/* PR middle-end/30494 */ /* { dg-do compile } */ /* { dg-require-effective-target alloca } */ int foo (int n) { int i; #pragma omp for for (i = 0; i < 6; i++) { int v[n], w[n * 3 + i]; v[0] = 1; w[0] = 2; } return 0; } int bar (int n) { int i; #pragma parallel omp for for (i = 0; i < 6; i++) { int v[n], w[n * 3 + i]; v[0] = 1; w[0] = 2; } return 0; }
TransformWrapper.h
/* file name : TransformWrapper.h author : Martin Schwartz (martin.schwartz@med.uni-tuebingen.de) version : 1.0 date : 03.01.2015 description : interface for the base transformations. For a detailed description, it is suggested to read p. 57 of the thesis. */ #ifndef TRANSFORMWRAPPER_H #define TRANSFORMWRAPPER_H #include "Gadget.h" #include "GadgetMRIHeaders.h" #include "hoMatrix_util.h" #include "hoNDArray_utils.h" #include "hoNDFFT_CS.h" #include "hoNDDCT.h" #include "hoNDKLT_CS.h" #include "GlobalVar.h" namespace Gadgetron { class TransformWrapper { public: virtual bool KernelFTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) = 0; virtual bool KernelBTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) = 0; }; // interface for the DFT transformation class FFTWrapper : public TransformWrapper { public: // forward transformation virtual bool KernelFTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { hoNDFFT_CS<float>::instance()->ifft(&Array, (unsigned int)dim_to_transform); return GADGET_OK; }; // backward transformation virtual bool KernelBTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { hoNDFFT_CS<float>::instance()->fft(&Array, (unsigned int)dim_to_transform); return GADGET_OK; }; }; // interface for the DCT transformation class DCTWrapper : public TransformWrapper { public: // forward transformation - DCT II virtual bool KernelFTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { // split real and imaginary part for split DCT hoNDArray<float> RealArray(Array.get_dimensions()), ImagArray(Array.get_dimensions()); float *fRealPtr = RealArray.get_data_ptr(), *fImagPtr = ImagArray.get_data_ptr(); std::complex<float> *cArrayPtr = Array.get_data_ptr(); for (size_t i = 0; i < RealArray.get_number_of_elements(); i++) { fRealPtr[i] = cArrayPtr[i].real(); fImagPtr[i] = cArrayPtr[i].imag(); } // transform real part hoNDDCT<float>::instance()->dct(&RealArray, dim_to_transform); // transform imaginary part hoNDDCT<float>::instance()->dct(&ImagArray, dim_to_transform); // put real and imaginary parts into original array #pragma omp parallel for for (size_t i = 0; i < RealArray.get_number_of_elements(); i++) { cArrayPtr[i] = std::complex<float>(fRealPtr[i],fImagPtr[i]); } return GADGET_OK; } // backward transformation - DCT III virtual bool KernelBTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { // split real and imaginary part for split DCT hoNDArray<float> RealArray(Array.get_dimensions()), ImagArray(Array.get_dimensions()); float *fRealPtr = RealArray.get_data_ptr(); float *fImagPtr = ImagArray.get_data_ptr(); std::complex<float> *cArrayPtr = Array.get_data_ptr(); for (size_t i = 0; i < RealArray.get_number_of_elements(); i++) { fRealPtr[i] = cArrayPtr[i].real(); fImagPtr[i] = cArrayPtr[i].imag(); } // transform real part hoNDDCT<float>::instance()->idct(&RealArray, dim_to_transform); // transform imaginary part hoNDDCT<float>::instance()->idct(&ImagArray, dim_to_transform); // put real and imaginary parts into original array #pragma omp parallel for for (size_t i = 0; i < RealArray.get_number_of_elements(); i++) { cArrayPtr[i] = std::complex<float>(fRealPtr[i],fImagPtr[i]); } return GADGET_OK; } }; // interface for the PCA transformation class KLTWrapper : public TransformWrapper { public: // forward transformation virtual bool KernelFTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { // check if transformation was prepared if (GlobalVar::instance()->vbStatPrinc_.at(dim_to_transform) == false) { GWARN("KLTWrapper: KLT transformation not prepared!\n"); GlobalVar::instance()->KLTVec_.at(dim_to_transform)->prepare(Array, (size_t)dim_to_transform, (size_t)0, true); } // transform GlobalVar::instance()->KLTVec_.at(dim_to_transform)->ftransform(Array, Array, dim_to_transform); return GADGET_OK; } // backward transformation virtual bool KernelBTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { // check if transformation was prepared if (GlobalVar::instance()->vbStatPrinc_.at(dim_to_transform) == false) { GWARN("KLTWrapper: KLT transformation not prepared!\n"); } // transform GlobalVar::instance()->KLTVec_.at(dim_to_transform)->btransform(Array, Array, dim_to_transform); return GADGET_OK; } }; // interface for the Wavelet transformation - not further implemented in this version class WaveletWrapper : public TransformWrapper { public: virtual bool KernelFTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { GERROR("not implemented in this version...\n"); return GADGET_OK; } virtual bool KernelBTrafo(hoNDArray<std::complex<float> > &Array, int dim_to_transform) { GERROR("not implemented in this version...\n"); return GADGET_OK; } }; } #endif // TRANSFORMWRAPPER_H
fft.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 */ #include <stdio.h> #include <math.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <unistd.h> #include <sys/time.h> #include <omp.h> #include "BenchmarksUtil.h" #include "fft.h" /* Definitions and operations for complex numbers */ /* * compute the W coefficients (that is, powers of the root of 1) * and store them into an array. */ int size = 32*1024*1024; void compute_w_coefficients(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; #pragma omp task untied compute_w_coefficients(n, a, ab, W); #pragma omp task untied compute_w_coefficients(n, ab + 1, b, W); #pragma omp taskwait } } void compute_w_coefficients_seq(int n, int a, int b, COMPLEX * W) { register double twoPiOverN; register int k; register REAL s, c; if (b - a < 128) { twoPiOverN = 2.0 * 3.1415926535897932384626434 / n; for (k = a; k <= b; ++k) { c = cos(twoPiOverN * k); c_re(W[k]) = c_re(W[n - k]) = c; s = sin(twoPiOverN * k); c_im(W[k]) = -s; c_im(W[n - k]) = s; } } else { int ab = (a + b) / 2; compute_w_coefficients_seq(n, a, ab, W); compute_w_coefficients_seq(n, ab + 1, b, W); } } /* * Determine (in a stupid way) if n is divisible by eight, then by four, else * find the smallest prime factor of n. */ int factor(int n) { int r; if (n < 2) return 1; if (n == 64 || n == 128 || n == 256 || n == 1024 || n == 2048 || n == 4096) return 8; if ((n & 15) == 0) return 16; if ((n & 7) == 0) return 8; if ((n & 3) == 0) return 4; if ((n & 1) == 0) return 2; /* try odd numbers up to n (computing the sqrt may be slower) */ for (r = 3; r < n; r += 2) if (n % r == 0) return r; /* n is prime */ return n; } void unshuffle(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); const COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; #pragma omp task untied unshuffle(a, ab, in, out, r, m); #pragma omp task untied unshuffle(ab, b, in, out, r, m); #pragma omp taskwait } } void unshuffle_seq(int a, int b, COMPLEX * in, COMPLEX * out, int r, int m) { int i, j; int r4 = r & (~0x3); const COMPLEX *ip; COMPLEX *jp; if (b - a < 16) { ip = in + a * r; for (i = a; i < b; ++i) { jp = out + i; for (j = 0; j < r4; j += 4) { jp[0] = ip[0]; jp[m] = ip[1]; jp[2 * m] = ip[2]; jp[3 * m] = ip[3]; jp += 4 * m; ip += 4; } for (; j < r; ++j) { *jp = *ip; ip++; jp += m; } } } else { int ab = (a + b) / 2; unshuffle_seq(a, ab, in, out, r, m); unshuffle_seq(ab, b, in, out, r, m); } } void fft_twiddle_gen1(COMPLEX * in, COMPLEX * out, COMPLEX * W, int r, int m, int nW, int nWdnti, int nWdntm) { int j, k; COMPLEX *jp, *kp; for (k = 0, kp = out; k < r; ++k, kp += m) { REAL r0, i0, rt, it, rw, iw; int l1 = nWdnti + nWdntm * k; int l0; r0 = i0 = 0.0; for (j = 0, jp = in, l0 = 0; j < r; ++j, jp += m) { rw = c_re(W[l0]); iw = c_im(W[l0]); rt = c_re(*jp); it = c_im(*jp); r0 += rt * rw - it * iw; i0 += rt * iw + it * rw; l0 += l1; if (l0 > nW) l0 -= nW; } c_re(*kp) = r0; c_im(*kp) = i0; } } void fft_twiddle_gen(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { #pragma omp task untied fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; #pragma omp task untied fft_twiddle_gen(i, i2, in, out, W, nW, nWdn, r, m); #pragma omp task untied fft_twiddle_gen(i2, i1, in, out, W, nW, nWdn, r, m); } #pragma omp taskwait } void fft_twiddle_gen_seq(int i, int i1, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int r, int m) { if (i == i1 - 1) { fft_twiddle_gen1(in + i, out + i, W, r, m, nW, nWdn * i, nWdn * m); } else { int i2 = (i + i1) / 2; fft_twiddle_gen_seq(i, i2, in, out, W, nW, nWdn, r, m); fft_twiddle_gen_seq(i2, i1, in, out, W, nW, nWdn, r, m); } } /* machine-generated code begins here */ void fft_base_2(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(in[0]); i1_0 = c_im(in[0]); r1_1 = c_re(in[1]); i1_1 = c_im(in[1]); c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[1]) = (r1_0 - r1_1); c_im(out[1]) = (i1_0 - i1_1); } void fft_twiddle_2(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_2(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_2(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; r1_0 = c_re(jp[0 * m]); i1_0 = c_im(jp[0 * m]); wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r1_1 = ((wr * tmpr) - (wi * tmpi)); i1_1 = ((wi * tmpr) + (wr * tmpi)); c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[1 * m]) = (r1_0 - r1_1); c_im(kp[1 * m]) = (i1_0 - i1_1); } } } else { int ab = (a + b) / 2; fft_twiddle_2_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_2_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_2(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_2(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_2(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_2_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 2; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_2_seq(a, ab, in, out, m); fft_unshuffle_2_seq(ab, b, in, out, m); } } void fft_base_4(COMPLEX * in, COMPLEX * out) { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(in[0]); i2_0 = c_im(in[0]); r2_2 = c_re(in[2]); i2_2 = c_im(in[2]); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; r2_1 = c_re(in[1]); i2_1 = c_im(in[1]); r2_3 = c_re(in[3]); i2_3 = c_im(in[3]); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[2]) = (r1_0 - r1_1); c_im(out[2]) = (i1_0 - i1_1); c_re(out[1]) = (r1_2 + i1_3); c_im(out[1]) = (i1_2 - r1_3); c_re(out[3]) = (r1_2 - i1_3); c_im(out[3]) = (i1_2 + r1_3); } void fft_twiddle_4(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_4(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_4(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; { REAL r2_0, i2_0; REAL r2_2, i2_2; r2_0 = c_re(jp[0 * m]); i2_0 = c_im(jp[0 * m]); wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r2_2 = ((wr * tmpr) - (wi * tmpi)); i2_2 = ((wi * tmpr) + (wr * tmpi)); r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_2 = (r2_0 - r2_2); i1_2 = (i2_0 - i2_2); } { REAL r2_1, i2_1; REAL r2_3, i2_3; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r2_1 = ((wr * tmpr) - (wi * tmpi)); i2_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r2_3 = ((wr * tmpr) - (wi * tmpi)); i2_3 = ((wi * tmpr) + (wr * tmpi)); r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_3 = (r2_1 - r2_3); i1_3 = (i2_1 - i2_3); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[2 * m]) = (r1_0 - r1_1); c_im(kp[2 * m]) = (i1_0 - i1_1); c_re(kp[1 * m]) = (r1_2 + i1_3); c_im(kp[1 * m]) = (i1_2 - r1_3); c_re(kp[3 * m]) = (r1_2 - i1_3); c_im(kp[3 * m]) = (i1_2 + r1_3); } } } else { int ab = (a + b) / 2; fft_twiddle_4_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_4_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_4(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_4(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_4(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_4_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 4; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_4_seq(a, ab, in, out, m); fft_unshuffle_4_seq(ab, b, in, out, m); } } void fft_base_8(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(in[0]); i3_0 = c_im(in[0]); r3_4 = c_re(in[4]); i3_4 = c_im(in[4]); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; r3_2 = c_re(in[2]); i3_2 = c_im(in[2]); r3_6 = c_re(in[6]); i3_6 = c_im(in[6]); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; r3_1 = c_re(in[1]); i3_1 = c_im(in[1]); r3_5 = c_re(in[5]); i3_5 = c_im(in[5]); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; r3_3 = c_re(in[3]); i3_3 = c_im(in[3]); r3_7 = c_re(in[7]); i3_7 = c_im(in[7]); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[4]) = (r1_0 - r1_1); c_im(out[4]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[5]) = (r1_2 - tmpr); c_im(out[5]) = (i1_2 - tmpi); c_re(out[2]) = (r1_4 + i1_5); c_im(out[2]) = (i1_4 - r1_5); c_re(out[6]) = (r1_4 - i1_5); c_im(out[6]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 - tmpi); c_re(out[7]) = (r1_6 - tmpr); c_im(out[7]) = (i1_6 + tmpi); } } void fft_twiddle_8(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_8(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_8(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; { REAL r3_0, i3_0; REAL r3_4, i3_4; r3_0 = c_re(jp[0 * m]); i3_0 = c_im(jp[0 * m]); wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r3_4 = ((wr * tmpr) - (wi * tmpi)); i3_4 = ((wi * tmpr) + (wr * tmpi)); r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_4 = (r3_0 - r3_4); i2_4 = (i3_0 - i3_4); } { REAL r3_2, i3_2; REAL r3_6, i3_6; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r3_2 = ((wr * tmpr) - (wi * tmpi)); i3_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r3_6 = ((wr * tmpr) - (wi * tmpi)); i3_6 = ((wi * tmpr) + (wr * tmpi)); r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_6 = (r3_2 - r3_6); i2_6 = (i3_2 - i3_6); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_4 = (r2_0 - r2_2); i1_4 = (i2_0 - i2_2); r1_2 = (r2_4 + i2_6); i1_2 = (i2_4 - r2_6); r1_6 = (r2_4 - i2_6); i1_6 = (i2_4 + r2_6); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; { REAL r3_1, i3_1; REAL r3_5, i3_5; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r3_1 = ((wr * tmpr) - (wi * tmpi)); i3_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r3_5 = ((wr * tmpr) - (wi * tmpi)); i3_5 = ((wi * tmpr) + (wr * tmpi)); r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_5 = (r3_1 - r3_5); i2_5 = (i3_1 - i3_5); } { REAL r3_3, i3_3; REAL r3_7, i3_7; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r3_3 = ((wr * tmpr) - (wi * tmpi)); i3_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r3_7 = ((wr * tmpr) - (wi * tmpi)); i3_7 = ((wi * tmpr) + (wr * tmpi)); r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_7 = (r3_3 - r3_7); i2_7 = (i3_3 - i3_7); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_5 = (r2_1 - r2_3); i1_5 = (i2_1 - i2_3); r1_3 = (r2_5 + i2_7); i1_3 = (i2_5 - r2_7); r1_7 = (r2_5 - i2_7); i1_7 = (i2_5 + r2_7); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[4 * m]) = (r1_0 - r1_1); c_im(kp[4 * m]) = (i1_0 - i1_1); tmpr = (0.707106781187 * (r1_3 + i1_3)); tmpi = (0.707106781187 * (i1_3 - r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[5 * m]) = (r1_2 - tmpr); c_im(kp[5 * m]) = (i1_2 - tmpi); c_re(kp[2 * m]) = (r1_4 + i1_5); c_im(kp[2 * m]) = (i1_4 - r1_5); c_re(kp[6 * m]) = (r1_4 - i1_5); c_im(kp[6 * m]) = (i1_4 + r1_5); tmpr = (0.707106781187 * (i1_7 - r1_7)); tmpi = (0.707106781187 * (r1_7 + i1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 - tmpi); c_re(kp[7 * m]) = (r1_6 - tmpr); c_im(kp[7 * m]) = (i1_6 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_8_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_8_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_8(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_8(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_8(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_8_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 8; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_8_seq(a, ab, in, out, m); fft_unshuffle_8_seq(ab, b, in, out, m); } } void fft_base_16(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(in[0]); i4_0 = c_im(in[0]); r4_8 = c_re(in[8]); i4_8 = c_im(in[8]); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; r4_4 = c_re(in[4]); i4_4 = c_im(in[4]); r4_12 = c_re(in[12]); i4_12 = c_im(in[12]); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; r4_2 = c_re(in[2]); i4_2 = c_im(in[2]); r4_10 = c_re(in[10]); i4_10 = c_im(in[10]); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; r4_6 = c_re(in[6]); i4_6 = c_im(in[6]); r4_14 = c_re(in[14]); i4_14 = c_im(in[14]); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; r4_1 = c_re(in[1]); i4_1 = c_im(in[1]); r4_9 = c_re(in[9]); i4_9 = c_im(in[9]); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; r4_5 = c_re(in[5]); i4_5 = c_im(in[5]); r4_13 = c_re(in[13]); i4_13 = c_im(in[13]); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; r4_3 = c_re(in[3]); i4_3 = c_im(in[3]); r4_11 = c_re(in[11]); i4_11 = c_im(in[11]); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; r4_7 = c_re(in[7]); i4_7 = c_im(in[7]); r4_15 = c_re(in[15]); i4_15 = c_im(in[15]); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[8]) = (r1_0 - r1_1); c_im(out[8]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[9]) = (r1_2 - tmpr); c_im(out[9]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[10]) = (r1_4 - tmpr); c_im(out[10]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[11]) = (r1_6 - tmpr); c_im(out[11]) = (i1_6 - tmpi); c_re(out[4]) = (r1_8 + i1_9); c_im(out[4]) = (i1_8 - r1_9); c_re(out[12]) = (r1_8 - i1_9); c_im(out[12]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 - tmpi); c_re(out[13]) = (r1_10 - tmpr); c_im(out[13]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 - tmpi); c_re(out[14]) = (r1_12 - tmpr); c_im(out[14]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 - tmpi); c_re(out[15]) = (r1_14 - tmpr); c_im(out[15]) = (i1_14 + tmpi); } } void fft_twiddle_16(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_16(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_16(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; { REAL r4_0, i4_0; REAL r4_8, i4_8; r4_0 = c_re(jp[0 * m]); i4_0 = c_im(jp[0 * m]); wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r4_8 = ((wr * tmpr) - (wi * tmpi)); i4_8 = ((wi * tmpr) + (wr * tmpi)); r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_8 = (r4_0 - r4_8); i3_8 = (i4_0 - i4_8); } { REAL r4_4, i4_4; REAL r4_12, i4_12; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r4_4 = ((wr * tmpr) - (wi * tmpi)); i4_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r4_12 = ((wr * tmpr) - (wi * tmpi)); i4_12 = ((wi * tmpr) + (wr * tmpi)); r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_12 = (r4_4 - r4_12); i3_12 = (i4_4 - i4_12); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_8 = (r3_0 - r3_4); i2_8 = (i3_0 - i3_4); r2_4 = (r3_8 + i3_12); i2_4 = (i3_8 - r3_12); r2_12 = (r3_8 - i3_12); i2_12 = (i3_8 + r3_12); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; { REAL r4_2, i4_2; REAL r4_10, i4_10; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r4_2 = ((wr * tmpr) - (wi * tmpi)); i4_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r4_10 = ((wr * tmpr) - (wi * tmpi)); i4_10 = ((wi * tmpr) + (wr * tmpi)); r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_10 = (r4_2 - r4_10); i3_10 = (i4_2 - i4_10); } { REAL r4_6, i4_6; REAL r4_14, i4_14; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r4_6 = ((wr * tmpr) - (wi * tmpi)); i4_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r4_14 = ((wr * tmpr) - (wi * tmpi)); i4_14 = ((wi * tmpr) + (wr * tmpi)); r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_14 = (r4_6 - r4_14); i3_14 = (i4_6 - i4_14); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_10 = (r3_2 - r3_6); i2_10 = (i3_2 - i3_6); r2_6 = (r3_10 + i3_14); i2_6 = (i3_10 - r3_14); r2_14 = (r3_10 - i3_14); i2_14 = (i3_10 + r3_14); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_8 = (r2_0 - r2_2); i1_8 = (i2_0 - i2_2); tmpr = (0.707106781187 * (r2_6 + i2_6)); tmpi = (0.707106781187 * (i2_6 - r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_10 = (r2_4 - tmpr); i1_10 = (i2_4 - tmpi); r1_4 = (r2_8 + i2_10); i1_4 = (i2_8 - r2_10); r1_12 = (r2_8 - i2_10); i1_12 = (i2_8 + r2_10); tmpr = (0.707106781187 * (i2_14 - r2_14)); tmpi = (0.707106781187 * (r2_14 + i2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 - tmpi); r1_14 = (r2_12 - tmpr); i1_14 = (i2_12 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; { REAL r4_1, i4_1; REAL r4_9, i4_9; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r4_1 = ((wr * tmpr) - (wi * tmpi)); i4_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r4_9 = ((wr * tmpr) - (wi * tmpi)); i4_9 = ((wi * tmpr) + (wr * tmpi)); r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_9 = (r4_1 - r4_9); i3_9 = (i4_1 - i4_9); } { REAL r4_5, i4_5; REAL r4_13, i4_13; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r4_5 = ((wr * tmpr) - (wi * tmpi)); i4_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r4_13 = ((wr * tmpr) - (wi * tmpi)); i4_13 = ((wi * tmpr) + (wr * tmpi)); r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_13 = (r4_5 - r4_13); i3_13 = (i4_5 - i4_13); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_9 = (r3_1 - r3_5); i2_9 = (i3_1 - i3_5); r2_5 = (r3_9 + i3_13); i2_5 = (i3_9 - r3_13); r2_13 = (r3_9 - i3_13); i2_13 = (i3_9 + r3_13); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; { REAL r4_3, i4_3; REAL r4_11, i4_11; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r4_3 = ((wr * tmpr) - (wi * tmpi)); i4_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r4_11 = ((wr * tmpr) - (wi * tmpi)); i4_11 = ((wi * tmpr) + (wr * tmpi)); r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_11 = (r4_3 - r4_11); i3_11 = (i4_3 - i4_11); } { REAL r4_7, i4_7; REAL r4_15, i4_15; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r4_7 = ((wr * tmpr) - (wi * tmpi)); i4_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r4_15 = ((wr * tmpr) - (wi * tmpi)); i4_15 = ((wi * tmpr) + (wr * tmpi)); r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_15 = (r4_7 - r4_15); i3_15 = (i4_7 - i4_15); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_11 = (r3_3 - r3_7); i2_11 = (i3_3 - i3_7); r2_7 = (r3_11 + i3_15); i2_7 = (i3_11 - r3_15); r2_15 = (r3_11 - i3_15); i2_15 = (i3_11 + r3_15); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_9 = (r2_1 - r2_3); i1_9 = (i2_1 - i2_3); tmpr = (0.707106781187 * (r2_7 + i2_7)); tmpi = (0.707106781187 * (i2_7 - r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_11 = (r2_5 - tmpr); i1_11 = (i2_5 - tmpi); r1_5 = (r2_9 + i2_11); i1_5 = (i2_9 - r2_11); r1_13 = (r2_9 - i2_11); i1_13 = (i2_9 + r2_11); tmpr = (0.707106781187 * (i2_15 - r2_15)); tmpi = (0.707106781187 * (r2_15 + i2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 - tmpi); r1_15 = (r2_13 - tmpr); i1_15 = (i2_13 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[8 * m]) = (r1_0 - r1_1); c_im(kp[8 * m]) = (i1_0 - i1_1); tmpr = ((0.923879532511 * r1_3) + (0.382683432365 * i1_3)); tmpi = ((0.923879532511 * i1_3) - (0.382683432365 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[9 * m]) = (r1_2 - tmpr); c_im(kp[9 * m]) = (i1_2 - tmpi); tmpr = (0.707106781187 * (r1_5 + i1_5)); tmpi = (0.707106781187 * (i1_5 - r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[10 * m]) = (r1_4 - tmpr); c_im(kp[10 * m]) = (i1_4 - tmpi); tmpr = ((0.382683432365 * r1_7) + (0.923879532511 * i1_7)); tmpi = ((0.382683432365 * i1_7) - (0.923879532511 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[11 * m]) = (r1_6 - tmpr); c_im(kp[11 * m]) = (i1_6 - tmpi); c_re(kp[4 * m]) = (r1_8 + i1_9); c_im(kp[4 * m]) = (i1_8 - r1_9); c_re(kp[12 * m]) = (r1_8 - i1_9); c_im(kp[12 * m]) = (i1_8 + r1_9); tmpr = ((0.923879532511 * i1_11) - (0.382683432365 * r1_11)); tmpi = ((0.923879532511 * r1_11) + (0.382683432365 * i1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 - tmpi); c_re(kp[13 * m]) = (r1_10 - tmpr); c_im(kp[13 * m]) = (i1_10 + tmpi); tmpr = (0.707106781187 * (i1_13 - r1_13)); tmpi = (0.707106781187 * (r1_13 + i1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 - tmpi); c_re(kp[14 * m]) = (r1_12 - tmpr); c_im(kp[14 * m]) = (i1_12 + tmpi); tmpr = ((0.382683432365 * i1_15) - (0.923879532511 * r1_15)); tmpi = ((0.382683432365 * r1_15) + (0.923879532511 * i1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 - tmpi); c_re(kp[15 * m]) = (r1_14 - tmpr); c_im(kp[15 * m]) = (i1_14 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_16_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_16_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_16(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_16(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_16(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_16_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 16; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_16_seq(a, ab, in, out, m); fft_unshuffle_16_seq(ab, b, in, out, m); } } void fft_base_32(COMPLEX * in, COMPLEX * out) { REAL tmpr, tmpi; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(in[0]); i5_0 = c_im(in[0]); r5_16 = c_re(in[16]); i5_16 = c_im(in[16]); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; r5_8 = c_re(in[8]); i5_8 = c_im(in[8]); r5_24 = c_re(in[24]); i5_24 = c_im(in[24]); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; r5_4 = c_re(in[4]); i5_4 = c_im(in[4]); r5_20 = c_re(in[20]); i5_20 = c_im(in[20]); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; r5_12 = c_re(in[12]); i5_12 = c_im(in[12]); r5_28 = c_re(in[28]); i5_28 = c_im(in[28]); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; r5_2 = c_re(in[2]); i5_2 = c_im(in[2]); r5_18 = c_re(in[18]); i5_18 = c_im(in[18]); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; r5_10 = c_re(in[10]); i5_10 = c_im(in[10]); r5_26 = c_re(in[26]); i5_26 = c_im(in[26]); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; r5_6 = c_re(in[6]); i5_6 = c_im(in[6]); r5_22 = c_re(in[22]); i5_22 = c_im(in[22]); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; r5_14 = c_re(in[14]); i5_14 = c_im(in[14]); r5_30 = c_re(in[30]); i5_30 = c_im(in[30]); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; r5_1 = c_re(in[1]); i5_1 = c_im(in[1]); r5_17 = c_re(in[17]); i5_17 = c_im(in[17]); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; r5_9 = c_re(in[9]); i5_9 = c_im(in[9]); r5_25 = c_re(in[25]); i5_25 = c_im(in[25]); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; r5_5 = c_re(in[5]); i5_5 = c_im(in[5]); r5_21 = c_re(in[21]); i5_21 = c_im(in[21]); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; r5_13 = c_re(in[13]); i5_13 = c_im(in[13]); r5_29 = c_re(in[29]); i5_29 = c_im(in[29]); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; r5_3 = c_re(in[3]); i5_3 = c_im(in[3]); r5_19 = c_re(in[19]); i5_19 = c_im(in[19]); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; r5_11 = c_re(in[11]); i5_11 = c_im(in[11]); r5_27 = c_re(in[27]); i5_27 = c_im(in[27]); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; r5_7 = c_re(in[7]); i5_7 = c_im(in[7]); r5_23 = c_re(in[23]); i5_23 = c_im(in[23]); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; r5_15 = c_re(in[15]); i5_15 = c_im(in[15]); r5_31 = c_re(in[31]); i5_31 = c_im(in[31]); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(out[0]) = (r1_0 + r1_1); c_im(out[0]) = (i1_0 + i1_1); c_re(out[16]) = (r1_0 - r1_1); c_im(out[16]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(out[1]) = (r1_2 + tmpr); c_im(out[1]) = (i1_2 + tmpi); c_re(out[17]) = (r1_2 - tmpr); c_im(out[17]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(out[2]) = (r1_4 + tmpr); c_im(out[2]) = (i1_4 + tmpi); c_re(out[18]) = (r1_4 - tmpr); c_im(out[18]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(out[3]) = (r1_6 + tmpr); c_im(out[3]) = (i1_6 + tmpi); c_re(out[19]) = (r1_6 - tmpr); c_im(out[19]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(out[4]) = (r1_8 + tmpr); c_im(out[4]) = (i1_8 + tmpi); c_re(out[20]) = (r1_8 - tmpr); c_im(out[20]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(out[5]) = (r1_10 + tmpr); c_im(out[5]) = (i1_10 + tmpi); c_re(out[21]) = (r1_10 - tmpr); c_im(out[21]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(out[6]) = (r1_12 + tmpr); c_im(out[6]) = (i1_12 + tmpi); c_re(out[22]) = (r1_12 - tmpr); c_im(out[22]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(out[7]) = (r1_14 + tmpr); c_im(out[7]) = (i1_14 + tmpi); c_re(out[23]) = (r1_14 - tmpr); c_im(out[23]) = (i1_14 - tmpi); c_re(out[8]) = (r1_16 + i1_17); c_im(out[8]) = (i1_16 - r1_17); c_re(out[24]) = (r1_16 - i1_17); c_im(out[24]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(out[9]) = (r1_18 + tmpr); c_im(out[9]) = (i1_18 - tmpi); c_re(out[25]) = (r1_18 - tmpr); c_im(out[25]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(out[10]) = (r1_20 + tmpr); c_im(out[10]) = (i1_20 - tmpi); c_re(out[26]) = (r1_20 - tmpr); c_im(out[26]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(out[11]) = (r1_22 + tmpr); c_im(out[11]) = (i1_22 - tmpi); c_re(out[27]) = (r1_22 - tmpr); c_im(out[27]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(out[12]) = (r1_24 + tmpr); c_im(out[12]) = (i1_24 - tmpi); c_re(out[28]) = (r1_24 - tmpr); c_im(out[28]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(out[13]) = (r1_26 + tmpr); c_im(out[13]) = (i1_26 - tmpi); c_re(out[29]) = (r1_26 - tmpr); c_im(out[29]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(out[14]) = (r1_28 + tmpr); c_im(out[14]) = (i1_28 - tmpi); c_re(out[30]) = (r1_28 - tmpr); c_im(out[30]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(out[15]) = (r1_30 + tmpr); c_im(out[15]) = (i1_30 - tmpi); c_re(out[31]) = (r1_30 - tmpr); c_im(out[31]) = (i1_30 + tmpi); } } void fft_twiddle_32(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; #pragma omp task untied fft_twiddle_32(a, ab, in, out, W, nW, nWdn, m); #pragma omp task untied fft_twiddle_32(ab, b, in, out, W, nW, nWdn, m); #pragma omp taskwait } } void fft_twiddle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, COMPLEX * W, int nW, int nWdn, int m) { int l1, i; COMPLEX *jp, *kp; REAL tmpr, tmpi, wr, wi; if ((b - a) < 128) { for (i = a, l1 = nWdn * i, kp = out + i; i < b; i++, l1 += nWdn, kp++) { jp = in + i; { REAL r1_0, i1_0; REAL r1_1, i1_1; REAL r1_2, i1_2; REAL r1_3, i1_3; REAL r1_4, i1_4; REAL r1_5, i1_5; REAL r1_6, i1_6; REAL r1_7, i1_7; REAL r1_8, i1_8; REAL r1_9, i1_9; REAL r1_10, i1_10; REAL r1_11, i1_11; REAL r1_12, i1_12; REAL r1_13, i1_13; REAL r1_14, i1_14; REAL r1_15, i1_15; REAL r1_16, i1_16; REAL r1_17, i1_17; REAL r1_18, i1_18; REAL r1_19, i1_19; REAL r1_20, i1_20; REAL r1_21, i1_21; REAL r1_22, i1_22; REAL r1_23, i1_23; REAL r1_24, i1_24; REAL r1_25, i1_25; REAL r1_26, i1_26; REAL r1_27, i1_27; REAL r1_28, i1_28; REAL r1_29, i1_29; REAL r1_30, i1_30; REAL r1_31, i1_31; { REAL r2_0, i2_0; REAL r2_2, i2_2; REAL r2_4, i2_4; REAL r2_6, i2_6; REAL r2_8, i2_8; REAL r2_10, i2_10; REAL r2_12, i2_12; REAL r2_14, i2_14; REAL r2_16, i2_16; REAL r2_18, i2_18; REAL r2_20, i2_20; REAL r2_22, i2_22; REAL r2_24, i2_24; REAL r2_26, i2_26; REAL r2_28, i2_28; REAL r2_30, i2_30; { REAL r3_0, i3_0; REAL r3_4, i3_4; REAL r3_8, i3_8; REAL r3_12, i3_12; REAL r3_16, i3_16; REAL r3_20, i3_20; REAL r3_24, i3_24; REAL r3_28, i3_28; { REAL r4_0, i4_0; REAL r4_8, i4_8; REAL r4_16, i4_16; REAL r4_24, i4_24; { REAL r5_0, i5_0; REAL r5_16, i5_16; r5_0 = c_re(jp[0 * m]); i5_0 = c_im(jp[0 * m]); wr = c_re(W[16 * l1]); wi = c_im(W[16 * l1]); tmpr = c_re(jp[16 * m]); tmpi = c_im(jp[16 * m]); r5_16 = ((wr * tmpr) - (wi * tmpi)); i5_16 = ((wi * tmpr) + (wr * tmpi)); r4_0 = (r5_0 + r5_16); i4_0 = (i5_0 + i5_16); r4_16 = (r5_0 - r5_16); i4_16 = (i5_0 - i5_16); } { REAL r5_8, i5_8; REAL r5_24, i5_24; wr = c_re(W[8 * l1]); wi = c_im(W[8 * l1]); tmpr = c_re(jp[8 * m]); tmpi = c_im(jp[8 * m]); r5_8 = ((wr * tmpr) - (wi * tmpi)); i5_8 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[24 * l1]); wi = c_im(W[24 * l1]); tmpr = c_re(jp[24 * m]); tmpi = c_im(jp[24 * m]); r5_24 = ((wr * tmpr) - (wi * tmpi)); i5_24 = ((wi * tmpr) + (wr * tmpi)); r4_8 = (r5_8 + r5_24); i4_8 = (i5_8 + i5_24); r4_24 = (r5_8 - r5_24); i4_24 = (i5_8 - i5_24); } r3_0 = (r4_0 + r4_8); i3_0 = (i4_0 + i4_8); r3_16 = (r4_0 - r4_8); i3_16 = (i4_0 - i4_8); r3_8 = (r4_16 + i4_24); i3_8 = (i4_16 - r4_24); r3_24 = (r4_16 - i4_24); i3_24 = (i4_16 + r4_24); } { REAL r4_4, i4_4; REAL r4_12, i4_12; REAL r4_20, i4_20; REAL r4_28, i4_28; { REAL r5_4, i5_4; REAL r5_20, i5_20; wr = c_re(W[4 * l1]); wi = c_im(W[4 * l1]); tmpr = c_re(jp[4 * m]); tmpi = c_im(jp[4 * m]); r5_4 = ((wr * tmpr) - (wi * tmpi)); i5_4 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[20 * l1]); wi = c_im(W[20 * l1]); tmpr = c_re(jp[20 * m]); tmpi = c_im(jp[20 * m]); r5_20 = ((wr * tmpr) - (wi * tmpi)); i5_20 = ((wi * tmpr) + (wr * tmpi)); r4_4 = (r5_4 + r5_20); i4_4 = (i5_4 + i5_20); r4_20 = (r5_4 - r5_20); i4_20 = (i5_4 - i5_20); } { REAL r5_12, i5_12; REAL r5_28, i5_28; wr = c_re(W[12 * l1]); wi = c_im(W[12 * l1]); tmpr = c_re(jp[12 * m]); tmpi = c_im(jp[12 * m]); r5_12 = ((wr * tmpr) - (wi * tmpi)); i5_12 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[28 * l1]); wi = c_im(W[28 * l1]); tmpr = c_re(jp[28 * m]); tmpi = c_im(jp[28 * m]); r5_28 = ((wr * tmpr) - (wi * tmpi)); i5_28 = ((wi * tmpr) + (wr * tmpi)); r4_12 = (r5_12 + r5_28); i4_12 = (i5_12 + i5_28); r4_28 = (r5_12 - r5_28); i4_28 = (i5_12 - i5_28); } r3_4 = (r4_4 + r4_12); i3_4 = (i4_4 + i4_12); r3_20 = (r4_4 - r4_12); i3_20 = (i4_4 - i4_12); r3_12 = (r4_20 + i4_28); i3_12 = (i4_20 - r4_28); r3_28 = (r4_20 - i4_28); i3_28 = (i4_20 + r4_28); } r2_0 = (r3_0 + r3_4); i2_0 = (i3_0 + i3_4); r2_16 = (r3_0 - r3_4); i2_16 = (i3_0 - i3_4); tmpr = (0.707106781187 * (r3_12 + i3_12)); tmpi = (0.707106781187 * (i3_12 - r3_12)); r2_4 = (r3_8 + tmpr); i2_4 = (i3_8 + tmpi); r2_20 = (r3_8 - tmpr); i2_20 = (i3_8 - tmpi); r2_8 = (r3_16 + i3_20); i2_8 = (i3_16 - r3_20); r2_24 = (r3_16 - i3_20); i2_24 = (i3_16 + r3_20); tmpr = (0.707106781187 * (i3_28 - r3_28)); tmpi = (0.707106781187 * (r3_28 + i3_28)); r2_12 = (r3_24 + tmpr); i2_12 = (i3_24 - tmpi); r2_28 = (r3_24 - tmpr); i2_28 = (i3_24 + tmpi); } { REAL r3_2, i3_2; REAL r3_6, i3_6; REAL r3_10, i3_10; REAL r3_14, i3_14; REAL r3_18, i3_18; REAL r3_22, i3_22; REAL r3_26, i3_26; REAL r3_30, i3_30; { REAL r4_2, i4_2; REAL r4_10, i4_10; REAL r4_18, i4_18; REAL r4_26, i4_26; { REAL r5_2, i5_2; REAL r5_18, i5_18; wr = c_re(W[2 * l1]); wi = c_im(W[2 * l1]); tmpr = c_re(jp[2 * m]); tmpi = c_im(jp[2 * m]); r5_2 = ((wr * tmpr) - (wi * tmpi)); i5_2 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[18 * l1]); wi = c_im(W[18 * l1]); tmpr = c_re(jp[18 * m]); tmpi = c_im(jp[18 * m]); r5_18 = ((wr * tmpr) - (wi * tmpi)); i5_18 = ((wi * tmpr) + (wr * tmpi)); r4_2 = (r5_2 + r5_18); i4_2 = (i5_2 + i5_18); r4_18 = (r5_2 - r5_18); i4_18 = (i5_2 - i5_18); } { REAL r5_10, i5_10; REAL r5_26, i5_26; wr = c_re(W[10 * l1]); wi = c_im(W[10 * l1]); tmpr = c_re(jp[10 * m]); tmpi = c_im(jp[10 * m]); r5_10 = ((wr * tmpr) - (wi * tmpi)); i5_10 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[26 * l1]); wi = c_im(W[26 * l1]); tmpr = c_re(jp[26 * m]); tmpi = c_im(jp[26 * m]); r5_26 = ((wr * tmpr) - (wi * tmpi)); i5_26 = ((wi * tmpr) + (wr * tmpi)); r4_10 = (r5_10 + r5_26); i4_10 = (i5_10 + i5_26); r4_26 = (r5_10 - r5_26); i4_26 = (i5_10 - i5_26); } r3_2 = (r4_2 + r4_10); i3_2 = (i4_2 + i4_10); r3_18 = (r4_2 - r4_10); i3_18 = (i4_2 - i4_10); r3_10 = (r4_18 + i4_26); i3_10 = (i4_18 - r4_26); r3_26 = (r4_18 - i4_26); i3_26 = (i4_18 + r4_26); } { REAL r4_6, i4_6; REAL r4_14, i4_14; REAL r4_22, i4_22; REAL r4_30, i4_30; { REAL r5_6, i5_6; REAL r5_22, i5_22; wr = c_re(W[6 * l1]); wi = c_im(W[6 * l1]); tmpr = c_re(jp[6 * m]); tmpi = c_im(jp[6 * m]); r5_6 = ((wr * tmpr) - (wi * tmpi)); i5_6 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[22 * l1]); wi = c_im(W[22 * l1]); tmpr = c_re(jp[22 * m]); tmpi = c_im(jp[22 * m]); r5_22 = ((wr * tmpr) - (wi * tmpi)); i5_22 = ((wi * tmpr) + (wr * tmpi)); r4_6 = (r5_6 + r5_22); i4_6 = (i5_6 + i5_22); r4_22 = (r5_6 - r5_22); i4_22 = (i5_6 - i5_22); } { REAL r5_14, i5_14; REAL r5_30, i5_30; wr = c_re(W[14 * l1]); wi = c_im(W[14 * l1]); tmpr = c_re(jp[14 * m]); tmpi = c_im(jp[14 * m]); r5_14 = ((wr * tmpr) - (wi * tmpi)); i5_14 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[30 * l1]); wi = c_im(W[30 * l1]); tmpr = c_re(jp[30 * m]); tmpi = c_im(jp[30 * m]); r5_30 = ((wr * tmpr) - (wi * tmpi)); i5_30 = ((wi * tmpr) + (wr * tmpi)); r4_14 = (r5_14 + r5_30); i4_14 = (i5_14 + i5_30); r4_30 = (r5_14 - r5_30); i4_30 = (i5_14 - i5_30); } r3_6 = (r4_6 + r4_14); i3_6 = (i4_6 + i4_14); r3_22 = (r4_6 - r4_14); i3_22 = (i4_6 - i4_14); r3_14 = (r4_22 + i4_30); i3_14 = (i4_22 - r4_30); r3_30 = (r4_22 - i4_30); i3_30 = (i4_22 + r4_30); } r2_2 = (r3_2 + r3_6); i2_2 = (i3_2 + i3_6); r2_18 = (r3_2 - r3_6); i2_18 = (i3_2 - i3_6); tmpr = (0.707106781187 * (r3_14 + i3_14)); tmpi = (0.707106781187 * (i3_14 - r3_14)); r2_6 = (r3_10 + tmpr); i2_6 = (i3_10 + tmpi); r2_22 = (r3_10 - tmpr); i2_22 = (i3_10 - tmpi); r2_10 = (r3_18 + i3_22); i2_10 = (i3_18 - r3_22); r2_26 = (r3_18 - i3_22); i2_26 = (i3_18 + r3_22); tmpr = (0.707106781187 * (i3_30 - r3_30)); tmpi = (0.707106781187 * (r3_30 + i3_30)); r2_14 = (r3_26 + tmpr); i2_14 = (i3_26 - tmpi); r2_30 = (r3_26 - tmpr); i2_30 = (i3_26 + tmpi); } r1_0 = (r2_0 + r2_2); i1_0 = (i2_0 + i2_2); r1_16 = (r2_0 - r2_2); i1_16 = (i2_0 - i2_2); tmpr = ((0.923879532511 * r2_6) + (0.382683432365 * i2_6)); tmpi = ((0.923879532511 * i2_6) - (0.382683432365 * r2_6)); r1_2 = (r2_4 + tmpr); i1_2 = (i2_4 + tmpi); r1_18 = (r2_4 - tmpr); i1_18 = (i2_4 - tmpi); tmpr = (0.707106781187 * (r2_10 + i2_10)); tmpi = (0.707106781187 * (i2_10 - r2_10)); r1_4 = (r2_8 + tmpr); i1_4 = (i2_8 + tmpi); r1_20 = (r2_8 - tmpr); i1_20 = (i2_8 - tmpi); tmpr = ((0.382683432365 * r2_14) + (0.923879532511 * i2_14)); tmpi = ((0.382683432365 * i2_14) - (0.923879532511 * r2_14)); r1_6 = (r2_12 + tmpr); i1_6 = (i2_12 + tmpi); r1_22 = (r2_12 - tmpr); i1_22 = (i2_12 - tmpi); r1_8 = (r2_16 + i2_18); i1_8 = (i2_16 - r2_18); r1_24 = (r2_16 - i2_18); i1_24 = (i2_16 + r2_18); tmpr = ((0.923879532511 * i2_22) - (0.382683432365 * r2_22)); tmpi = ((0.923879532511 * r2_22) + (0.382683432365 * i2_22)); r1_10 = (r2_20 + tmpr); i1_10 = (i2_20 - tmpi); r1_26 = (r2_20 - tmpr); i1_26 = (i2_20 + tmpi); tmpr = (0.707106781187 * (i2_26 - r2_26)); tmpi = (0.707106781187 * (r2_26 + i2_26)); r1_12 = (r2_24 + tmpr); i1_12 = (i2_24 - tmpi); r1_28 = (r2_24 - tmpr); i1_28 = (i2_24 + tmpi); tmpr = ((0.382683432365 * i2_30) - (0.923879532511 * r2_30)); tmpi = ((0.382683432365 * r2_30) + (0.923879532511 * i2_30)); r1_14 = (r2_28 + tmpr); i1_14 = (i2_28 - tmpi); r1_30 = (r2_28 - tmpr); i1_30 = (i2_28 + tmpi); } { REAL r2_1, i2_1; REAL r2_3, i2_3; REAL r2_5, i2_5; REAL r2_7, i2_7; REAL r2_9, i2_9; REAL r2_11, i2_11; REAL r2_13, i2_13; REAL r2_15, i2_15; REAL r2_17, i2_17; REAL r2_19, i2_19; REAL r2_21, i2_21; REAL r2_23, i2_23; REAL r2_25, i2_25; REAL r2_27, i2_27; REAL r2_29, i2_29; REAL r2_31, i2_31; { REAL r3_1, i3_1; REAL r3_5, i3_5; REAL r3_9, i3_9; REAL r3_13, i3_13; REAL r3_17, i3_17; REAL r3_21, i3_21; REAL r3_25, i3_25; REAL r3_29, i3_29; { REAL r4_1, i4_1; REAL r4_9, i4_9; REAL r4_17, i4_17; REAL r4_25, i4_25; { REAL r5_1, i5_1; REAL r5_17, i5_17; wr = c_re(W[1 * l1]); wi = c_im(W[1 * l1]); tmpr = c_re(jp[1 * m]); tmpi = c_im(jp[1 * m]); r5_1 = ((wr * tmpr) - (wi * tmpi)); i5_1 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[17 * l1]); wi = c_im(W[17 * l1]); tmpr = c_re(jp[17 * m]); tmpi = c_im(jp[17 * m]); r5_17 = ((wr * tmpr) - (wi * tmpi)); i5_17 = ((wi * tmpr) + (wr * tmpi)); r4_1 = (r5_1 + r5_17); i4_1 = (i5_1 + i5_17); r4_17 = (r5_1 - r5_17); i4_17 = (i5_1 - i5_17); } { REAL r5_9, i5_9; REAL r5_25, i5_25; wr = c_re(W[9 * l1]); wi = c_im(W[9 * l1]); tmpr = c_re(jp[9 * m]); tmpi = c_im(jp[9 * m]); r5_9 = ((wr * tmpr) - (wi * tmpi)); i5_9 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[25 * l1]); wi = c_im(W[25 * l1]); tmpr = c_re(jp[25 * m]); tmpi = c_im(jp[25 * m]); r5_25 = ((wr * tmpr) - (wi * tmpi)); i5_25 = ((wi * tmpr) + (wr * tmpi)); r4_9 = (r5_9 + r5_25); i4_9 = (i5_9 + i5_25); r4_25 = (r5_9 - r5_25); i4_25 = (i5_9 - i5_25); } r3_1 = (r4_1 + r4_9); i3_1 = (i4_1 + i4_9); r3_17 = (r4_1 - r4_9); i3_17 = (i4_1 - i4_9); r3_9 = (r4_17 + i4_25); i3_9 = (i4_17 - r4_25); r3_25 = (r4_17 - i4_25); i3_25 = (i4_17 + r4_25); } { REAL r4_5, i4_5; REAL r4_13, i4_13; REAL r4_21, i4_21; REAL r4_29, i4_29; { REAL r5_5, i5_5; REAL r5_21, i5_21; wr = c_re(W[5 * l1]); wi = c_im(W[5 * l1]); tmpr = c_re(jp[5 * m]); tmpi = c_im(jp[5 * m]); r5_5 = ((wr * tmpr) - (wi * tmpi)); i5_5 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[21 * l1]); wi = c_im(W[21 * l1]); tmpr = c_re(jp[21 * m]); tmpi = c_im(jp[21 * m]); r5_21 = ((wr * tmpr) - (wi * tmpi)); i5_21 = ((wi * tmpr) + (wr * tmpi)); r4_5 = (r5_5 + r5_21); i4_5 = (i5_5 + i5_21); r4_21 = (r5_5 - r5_21); i4_21 = (i5_5 - i5_21); } { REAL r5_13, i5_13; REAL r5_29, i5_29; wr = c_re(W[13 * l1]); wi = c_im(W[13 * l1]); tmpr = c_re(jp[13 * m]); tmpi = c_im(jp[13 * m]); r5_13 = ((wr * tmpr) - (wi * tmpi)); i5_13 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[29 * l1]); wi = c_im(W[29 * l1]); tmpr = c_re(jp[29 * m]); tmpi = c_im(jp[29 * m]); r5_29 = ((wr * tmpr) - (wi * tmpi)); i5_29 = ((wi * tmpr) + (wr * tmpi)); r4_13 = (r5_13 + r5_29); i4_13 = (i5_13 + i5_29); r4_29 = (r5_13 - r5_29); i4_29 = (i5_13 - i5_29); } r3_5 = (r4_5 + r4_13); i3_5 = (i4_5 + i4_13); r3_21 = (r4_5 - r4_13); i3_21 = (i4_5 - i4_13); r3_13 = (r4_21 + i4_29); i3_13 = (i4_21 - r4_29); r3_29 = (r4_21 - i4_29); i3_29 = (i4_21 + r4_29); } r2_1 = (r3_1 + r3_5); i2_1 = (i3_1 + i3_5); r2_17 = (r3_1 - r3_5); i2_17 = (i3_1 - i3_5); tmpr = (0.707106781187 * (r3_13 + i3_13)); tmpi = (0.707106781187 * (i3_13 - r3_13)); r2_5 = (r3_9 + tmpr); i2_5 = (i3_9 + tmpi); r2_21 = (r3_9 - tmpr); i2_21 = (i3_9 - tmpi); r2_9 = (r3_17 + i3_21); i2_9 = (i3_17 - r3_21); r2_25 = (r3_17 - i3_21); i2_25 = (i3_17 + r3_21); tmpr = (0.707106781187 * (i3_29 - r3_29)); tmpi = (0.707106781187 * (r3_29 + i3_29)); r2_13 = (r3_25 + tmpr); i2_13 = (i3_25 - tmpi); r2_29 = (r3_25 - tmpr); i2_29 = (i3_25 + tmpi); } { REAL r3_3, i3_3; REAL r3_7, i3_7; REAL r3_11, i3_11; REAL r3_15, i3_15; REAL r3_19, i3_19; REAL r3_23, i3_23; REAL r3_27, i3_27; REAL r3_31, i3_31; { REAL r4_3, i4_3; REAL r4_11, i4_11; REAL r4_19, i4_19; REAL r4_27, i4_27; { REAL r5_3, i5_3; REAL r5_19, i5_19; wr = c_re(W[3 * l1]); wi = c_im(W[3 * l1]); tmpr = c_re(jp[3 * m]); tmpi = c_im(jp[3 * m]); r5_3 = ((wr * tmpr) - (wi * tmpi)); i5_3 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[19 * l1]); wi = c_im(W[19 * l1]); tmpr = c_re(jp[19 * m]); tmpi = c_im(jp[19 * m]); r5_19 = ((wr * tmpr) - (wi * tmpi)); i5_19 = ((wi * tmpr) + (wr * tmpi)); r4_3 = (r5_3 + r5_19); i4_3 = (i5_3 + i5_19); r4_19 = (r5_3 - r5_19); i4_19 = (i5_3 - i5_19); } { REAL r5_11, i5_11; REAL r5_27, i5_27; wr = c_re(W[11 * l1]); wi = c_im(W[11 * l1]); tmpr = c_re(jp[11 * m]); tmpi = c_im(jp[11 * m]); r5_11 = ((wr * tmpr) - (wi * tmpi)); i5_11 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[27 * l1]); wi = c_im(W[27 * l1]); tmpr = c_re(jp[27 * m]); tmpi = c_im(jp[27 * m]); r5_27 = ((wr * tmpr) - (wi * tmpi)); i5_27 = ((wi * tmpr) + (wr * tmpi)); r4_11 = (r5_11 + r5_27); i4_11 = (i5_11 + i5_27); r4_27 = (r5_11 - r5_27); i4_27 = (i5_11 - i5_27); } r3_3 = (r4_3 + r4_11); i3_3 = (i4_3 + i4_11); r3_19 = (r4_3 - r4_11); i3_19 = (i4_3 - i4_11); r3_11 = (r4_19 + i4_27); i3_11 = (i4_19 - r4_27); r3_27 = (r4_19 - i4_27); i3_27 = (i4_19 + r4_27); } { REAL r4_7, i4_7; REAL r4_15, i4_15; REAL r4_23, i4_23; REAL r4_31, i4_31; { REAL r5_7, i5_7; REAL r5_23, i5_23; wr = c_re(W[7 * l1]); wi = c_im(W[7 * l1]); tmpr = c_re(jp[7 * m]); tmpi = c_im(jp[7 * m]); r5_7 = ((wr * tmpr) - (wi * tmpi)); i5_7 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[23 * l1]); wi = c_im(W[23 * l1]); tmpr = c_re(jp[23 * m]); tmpi = c_im(jp[23 * m]); r5_23 = ((wr * tmpr) - (wi * tmpi)); i5_23 = ((wi * tmpr) + (wr * tmpi)); r4_7 = (r5_7 + r5_23); i4_7 = (i5_7 + i5_23); r4_23 = (r5_7 - r5_23); i4_23 = (i5_7 - i5_23); } { REAL r5_15, i5_15; REAL r5_31, i5_31; wr = c_re(W[15 * l1]); wi = c_im(W[15 * l1]); tmpr = c_re(jp[15 * m]); tmpi = c_im(jp[15 * m]); r5_15 = ((wr * tmpr) - (wi * tmpi)); i5_15 = ((wi * tmpr) + (wr * tmpi)); wr = c_re(W[31 * l1]); wi = c_im(W[31 * l1]); tmpr = c_re(jp[31 * m]); tmpi = c_im(jp[31 * m]); r5_31 = ((wr * tmpr) - (wi * tmpi)); i5_31 = ((wi * tmpr) + (wr * tmpi)); r4_15 = (r5_15 + r5_31); i4_15 = (i5_15 + i5_31); r4_31 = (r5_15 - r5_31); i4_31 = (i5_15 - i5_31); } r3_7 = (r4_7 + r4_15); i3_7 = (i4_7 + i4_15); r3_23 = (r4_7 - r4_15); i3_23 = (i4_7 - i4_15); r3_15 = (r4_23 + i4_31); i3_15 = (i4_23 - r4_31); r3_31 = (r4_23 - i4_31); i3_31 = (i4_23 + r4_31); } r2_3 = (r3_3 + r3_7); i2_3 = (i3_3 + i3_7); r2_19 = (r3_3 - r3_7); i2_19 = (i3_3 - i3_7); tmpr = (0.707106781187 * (r3_15 + i3_15)); tmpi = (0.707106781187 * (i3_15 - r3_15)); r2_7 = (r3_11 + tmpr); i2_7 = (i3_11 + tmpi); r2_23 = (r3_11 - tmpr); i2_23 = (i3_11 - tmpi); r2_11 = (r3_19 + i3_23); i2_11 = (i3_19 - r3_23); r2_27 = (r3_19 - i3_23); i2_27 = (i3_19 + r3_23); tmpr = (0.707106781187 * (i3_31 - r3_31)); tmpi = (0.707106781187 * (r3_31 + i3_31)); r2_15 = (r3_27 + tmpr); i2_15 = (i3_27 - tmpi); r2_31 = (r3_27 - tmpr); i2_31 = (i3_27 + tmpi); } r1_1 = (r2_1 + r2_3); i1_1 = (i2_1 + i2_3); r1_17 = (r2_1 - r2_3); i1_17 = (i2_1 - i2_3); tmpr = ((0.923879532511 * r2_7) + (0.382683432365 * i2_7)); tmpi = ((0.923879532511 * i2_7) - (0.382683432365 * r2_7)); r1_3 = (r2_5 + tmpr); i1_3 = (i2_5 + tmpi); r1_19 = (r2_5 - tmpr); i1_19 = (i2_5 - tmpi); tmpr = (0.707106781187 * (r2_11 + i2_11)); tmpi = (0.707106781187 * (i2_11 - r2_11)); r1_5 = (r2_9 + tmpr); i1_5 = (i2_9 + tmpi); r1_21 = (r2_9 - tmpr); i1_21 = (i2_9 - tmpi); tmpr = ((0.382683432365 * r2_15) + (0.923879532511 * i2_15)); tmpi = ((0.382683432365 * i2_15) - (0.923879532511 * r2_15)); r1_7 = (r2_13 + tmpr); i1_7 = (i2_13 + tmpi); r1_23 = (r2_13 - tmpr); i1_23 = (i2_13 - tmpi); r1_9 = (r2_17 + i2_19); i1_9 = (i2_17 - r2_19); r1_25 = (r2_17 - i2_19); i1_25 = (i2_17 + r2_19); tmpr = ((0.923879532511 * i2_23) - (0.382683432365 * r2_23)); tmpi = ((0.923879532511 * r2_23) + (0.382683432365 * i2_23)); r1_11 = (r2_21 + tmpr); i1_11 = (i2_21 - tmpi); r1_27 = (r2_21 - tmpr); i1_27 = (i2_21 + tmpi); tmpr = (0.707106781187 * (i2_27 - r2_27)); tmpi = (0.707106781187 * (r2_27 + i2_27)); r1_13 = (r2_25 + tmpr); i1_13 = (i2_25 - tmpi); r1_29 = (r2_25 - tmpr); i1_29 = (i2_25 + tmpi); tmpr = ((0.382683432365 * i2_31) - (0.923879532511 * r2_31)); tmpi = ((0.382683432365 * r2_31) + (0.923879532511 * i2_31)); r1_15 = (r2_29 + tmpr); i1_15 = (i2_29 - tmpi); r1_31 = (r2_29 - tmpr); i1_31 = (i2_29 + tmpi); } c_re(kp[0 * m]) = (r1_0 + r1_1); c_im(kp[0 * m]) = (i1_0 + i1_1); c_re(kp[16 * m]) = (r1_0 - r1_1); c_im(kp[16 * m]) = (i1_0 - i1_1); tmpr = ((0.980785280403 * r1_3) + (0.195090322016 * i1_3)); tmpi = ((0.980785280403 * i1_3) - (0.195090322016 * r1_3)); c_re(kp[1 * m]) = (r1_2 + tmpr); c_im(kp[1 * m]) = (i1_2 + tmpi); c_re(kp[17 * m]) = (r1_2 - tmpr); c_im(kp[17 * m]) = (i1_2 - tmpi); tmpr = ((0.923879532511 * r1_5) + (0.382683432365 * i1_5)); tmpi = ((0.923879532511 * i1_5) - (0.382683432365 * r1_5)); c_re(kp[2 * m]) = (r1_4 + tmpr); c_im(kp[2 * m]) = (i1_4 + tmpi); c_re(kp[18 * m]) = (r1_4 - tmpr); c_im(kp[18 * m]) = (i1_4 - tmpi); tmpr = ((0.831469612303 * r1_7) + (0.55557023302 * i1_7)); tmpi = ((0.831469612303 * i1_7) - (0.55557023302 * r1_7)); c_re(kp[3 * m]) = (r1_6 + tmpr); c_im(kp[3 * m]) = (i1_6 + tmpi); c_re(kp[19 * m]) = (r1_6 - tmpr); c_im(kp[19 * m]) = (i1_6 - tmpi); tmpr = (0.707106781187 * (r1_9 + i1_9)); tmpi = (0.707106781187 * (i1_9 - r1_9)); c_re(kp[4 * m]) = (r1_8 + tmpr); c_im(kp[4 * m]) = (i1_8 + tmpi); c_re(kp[20 * m]) = (r1_8 - tmpr); c_im(kp[20 * m]) = (i1_8 - tmpi); tmpr = ((0.55557023302 * r1_11) + (0.831469612303 * i1_11)); tmpi = ((0.55557023302 * i1_11) - (0.831469612303 * r1_11)); c_re(kp[5 * m]) = (r1_10 + tmpr); c_im(kp[5 * m]) = (i1_10 + tmpi); c_re(kp[21 * m]) = (r1_10 - tmpr); c_im(kp[21 * m]) = (i1_10 - tmpi); tmpr = ((0.382683432365 * r1_13) + (0.923879532511 * i1_13)); tmpi = ((0.382683432365 * i1_13) - (0.923879532511 * r1_13)); c_re(kp[6 * m]) = (r1_12 + tmpr); c_im(kp[6 * m]) = (i1_12 + tmpi); c_re(kp[22 * m]) = (r1_12 - tmpr); c_im(kp[22 * m]) = (i1_12 - tmpi); tmpr = ((0.195090322016 * r1_15) + (0.980785280403 * i1_15)); tmpi = ((0.195090322016 * i1_15) - (0.980785280403 * r1_15)); c_re(kp[7 * m]) = (r1_14 + tmpr); c_im(kp[7 * m]) = (i1_14 + tmpi); c_re(kp[23 * m]) = (r1_14 - tmpr); c_im(kp[23 * m]) = (i1_14 - tmpi); c_re(kp[8 * m]) = (r1_16 + i1_17); c_im(kp[8 * m]) = (i1_16 - r1_17); c_re(kp[24 * m]) = (r1_16 - i1_17); c_im(kp[24 * m]) = (i1_16 + r1_17); tmpr = ((0.980785280403 * i1_19) - (0.195090322016 * r1_19)); tmpi = ((0.980785280403 * r1_19) + (0.195090322016 * i1_19)); c_re(kp[9 * m]) = (r1_18 + tmpr); c_im(kp[9 * m]) = (i1_18 - tmpi); c_re(kp[25 * m]) = (r1_18 - tmpr); c_im(kp[25 * m]) = (i1_18 + tmpi); tmpr = ((0.923879532511 * i1_21) - (0.382683432365 * r1_21)); tmpi = ((0.923879532511 * r1_21) + (0.382683432365 * i1_21)); c_re(kp[10 * m]) = (r1_20 + tmpr); c_im(kp[10 * m]) = (i1_20 - tmpi); c_re(kp[26 * m]) = (r1_20 - tmpr); c_im(kp[26 * m]) = (i1_20 + tmpi); tmpr = ((0.831469612303 * i1_23) - (0.55557023302 * r1_23)); tmpi = ((0.831469612303 * r1_23) + (0.55557023302 * i1_23)); c_re(kp[11 * m]) = (r1_22 + tmpr); c_im(kp[11 * m]) = (i1_22 - tmpi); c_re(kp[27 * m]) = (r1_22 - tmpr); c_im(kp[27 * m]) = (i1_22 + tmpi); tmpr = (0.707106781187 * (i1_25 - r1_25)); tmpi = (0.707106781187 * (r1_25 + i1_25)); c_re(kp[12 * m]) = (r1_24 + tmpr); c_im(kp[12 * m]) = (i1_24 - tmpi); c_re(kp[28 * m]) = (r1_24 - tmpr); c_im(kp[28 * m]) = (i1_24 + tmpi); tmpr = ((0.55557023302 * i1_27) - (0.831469612303 * r1_27)); tmpi = ((0.55557023302 * r1_27) + (0.831469612303 * i1_27)); c_re(kp[13 * m]) = (r1_26 + tmpr); c_im(kp[13 * m]) = (i1_26 - tmpi); c_re(kp[29 * m]) = (r1_26 - tmpr); c_im(kp[29 * m]) = (i1_26 + tmpi); tmpr = ((0.382683432365 * i1_29) - (0.923879532511 * r1_29)); tmpi = ((0.382683432365 * r1_29) + (0.923879532511 * i1_29)); c_re(kp[14 * m]) = (r1_28 + tmpr); c_im(kp[14 * m]) = (i1_28 - tmpi); c_re(kp[30 * m]) = (r1_28 - tmpr); c_im(kp[30 * m]) = (i1_28 + tmpi); tmpr = ((0.195090322016 * i1_31) - (0.980785280403 * r1_31)); tmpi = ((0.195090322016 * r1_31) + (0.980785280403 * i1_31)); c_re(kp[15 * m]) = (r1_30 + tmpr); c_im(kp[15 * m]) = (i1_30 - tmpi); c_re(kp[31 * m]) = (r1_30 - tmpr); c_im(kp[31 * m]) = (i1_30 + tmpi); } } } else { int ab = (a + b) / 2; fft_twiddle_32_seq(a, ab, in, out, W, nW, nWdn, m); fft_twiddle_32_seq(ab, b, in, out, W, nW, nWdn, m); } } void fft_unshuffle_32(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; #pragma omp task untied fft_unshuffle_32(a, ab, in, out, m); #pragma omp task untied fft_unshuffle_32(ab, b, in, out, m); #pragma omp taskwait } } void fft_unshuffle_32_seq(int a, int b, COMPLEX * in, COMPLEX * out, int m) { int i; const COMPLEX *ip; COMPLEX *jp; if ((b - a) < 128) { ip = in + a * 32; for (i = a; i < b; ++i) { jp = out + i; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; jp += 2 * m; jp[0] = ip[0]; jp[m] = ip[1]; ip += 2; } } else { int ab = (a + b) / 2; fft_unshuffle_32_seq(a, ab, in, out, m); fft_unshuffle_32_seq(ab, b, in, out, m); } } /* end of machine-generated code */ /* * Recursive complex FFT on the n complex components of the array in: * basic Cooley-Tukey algorithm, with some improvements for * n power of two. The result is placed in the array out. n is arbitrary. * The algorithm runs in time O(n*(r1 + ... + rk)) where r1, ..., rk * are prime numbers, and r1 * r2 * ... * rk = n. * * n: size of the input * in: pointer to input * out: pointer to output * factors: list of factors of n, precomputed * W: twiddle factors * nW: size of W, that is, size of the original transform * */ void fft_aux(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) { #pragma omp task untied fft_unshuffle_32(0, m, in, out, m); } else if (r == 16) { #pragma omp task untied fft_unshuffle_16(0, m, in, out, m); } else if (r == 8) { #pragma omp task untied fft_unshuffle_8(0, m, in, out, m); } else if (r == 4) { #pragma omp task untied fft_unshuffle_4(0, m, in, out, m); } else if (r == 2) { #pragma omp task untied fft_unshuffle_2(0, m, in, out, m); } else unshuffle(0, m, in, out, r, m); #pragma omp taskwait for (k = 0; k < n; k += m) { #pragma omp task untied fft_aux(m, out + k, in + k, factors + 1, W, nW); } #pragma omp taskwait } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) { #pragma omp task untied fft_twiddle_2(0, m, in, out, W, nW, nW / n, m); } else if (r == 4) { #pragma omp task untied fft_twiddle_4(0, m, in, out, W, nW, nW / n, m); } else if (r == 8) { #pragma omp task untied fft_twiddle_8(0, m, in, out, W, nW, nW / n, m); } else if (r == 16) { #pragma omp task untied fft_twiddle_16(0, m, in, out, W, nW, nW / n, m); } else if (r == 32) { #pragma omp task untied fft_twiddle_32(0, m, in, out, W, nW, nW / n, m); } else { #pragma omp task untied fft_twiddle_gen(0, m, in, out, W, nW, nW / n, r, m); } #pragma omp taskwait return; } void fft_aux_seq(int n, COMPLEX * in, COMPLEX * out, int *factors, COMPLEX * W, int nW) { int r, m; int k; /* special cases */ if (n == 32) { fft_base_32(in, out); return; } if (n == 16) { fft_base_16(in, out); return; } if (n == 8) { fft_base_8(in, out); return; } if (n == 4) { fft_base_4(in, out); return; } if (n == 2) { fft_base_2(in, out); return; } /* * the cases n == 3, n == 5, and maybe 7 should be implemented as well */ r = *factors; m = n / r; if (r < n) { /* * split the DFT of length n into r DFTs of length n/r, and * recurse */ if (r == 32) fft_unshuffle_32_seq(0, m, in, out, m); else if (r == 16) fft_unshuffle_16_seq(0, m, in, out, m); else if (r == 8) fft_unshuffle_8_seq(0, m, in, out, m); else if (r == 4) fft_unshuffle_4_seq(0, m, in, out, m); else if (r == 2) fft_unshuffle_2_seq(0, m, in, out, m); else unshuffle_seq(0, m, in, out, r, m); for (k = 0; k < n; k += m) { fft_aux_seq(m, out + k, in + k, factors + 1, W, nW); } } /* * now multiply by the twiddle factors, and perform m FFTs * of length r */ if (r == 2) fft_twiddle_2_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 4) fft_twiddle_4_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 8) fft_twiddle_8_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 16) fft_twiddle_16_seq(0, m, in, out, W, nW, nW / n, m); else if (r == 32) fft_twiddle_32_seq(0, m, in, out, W, nW, nW / n, m); else fft_twiddle_gen_seq(0, m, in, out, W, nW, nW / n, r, m); return; } /* * user interface for fft_aux */ void fft(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; fprintf(stdout,"Computing coefficients "); W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); #pragma omp parallel #pragma omp single #pragma omp task untied compute_w_coefficients(n, 0, n / 2, W); fprintf(stdout," completed!\n"); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fprintf(stdout,"Computing FFT "); #pragma omp parallel #pragma omp single #pragma omp task untied fft_aux(n, in, out, factors, W, n); fprintf(stdout," completed!\n"); free(W); return; } void fft_seq(int n, COMPLEX * in, COMPLEX * out) { int factors[40]; /* allows FFTs up to at least 3^40 */ int *p = factors; int l = n; int r; COMPLEX *W; W = (COMPLEX *) malloc((n + 1) * sizeof(COMPLEX)); compute_w_coefficients_seq(n, 0, n / 2, W); /* * find factors of n, first 8, then 4 and then primes in ascending * order */ do { r = factor(l); *p++ = r; l /= r; } while (l > 1); fft_aux_seq(n, in, out, factors, W, n); free(W); return; } int test_correctness(int n, COMPLEX *out1, COMPLEX *out2) { int i; double a,d,error = 0.0; for (i = 0; i < n; ++i) { a = sqrt((c_re(out1[i]) - c_re(out2[i])) * (c_re(out1[i]) - c_re(out2[i])) + (c_im(out1[i]) - c_im(out2[i])) * (c_im(out1[i]) - c_im(out2[i]))); d = sqrt(c_re(out2[i]) * c_re(out2[i]) + c_im(out2[i]) * c_im(out2[i])); if (d < -1.0e-10 || d > 1.0e-10) a /= d; if (a > error) error = a; } fprintf(stdout,"relative error=%e\n", error); if (error > 1e-3) return 0; else return 1; } void print_usage() { fprintf(stderr, "\n"); fprintf(stderr, "Usage: %s -[options]\n", "FFT"); fprintf(stderr, "\n"); fprintf(stderr, "Where options are:\n"); fprintf(stderr, " -n <size> : Matrix Size (de\n"); fprintf(stderr, " -h : Print program's usage (this help).\n"); fprintf(stdout, "\n"); } int main(int argc, char* argv[]) { int i; for (i=1; i<argc; i++) { if (argv[i][0] == '-') { switch (argv[i][1]) { case 'n': /* read argument size 0 */ argv[i][1] = '*'; i++; if (argc == i) { "Erro\n"; exit(100); } size = atoi(argv[i]); break; case 'h': /* print usage */ argv[i][1] = '*'; print_usage(); exit (100); break; } } } COMPLEX *in, *out1=NULL, *out2=NULL; in = malloc(size * sizeof(COMPLEX)); out1 = malloc(size * sizeof(COMPLEX)); for (i = 0; i < size; ++i) { c_re(in[i]) = 1.0; c_im(in[i]) = 1.0; } double t_start, t_end; t_start = rtclock(); fft(size, in, out1); t_end = rtclock(); fprintf(stdout, "Parallel Runtime: %0.6lfs\n", t_end - t_start); out2 = malloc(size * sizeof(COMPLEX)); for (i = 0; i < size; ++i) { c_re(in[i]) = 1.0; c_im(in[i]) = 1.0; } t_start = rtclock(); fft_seq(size, in, out2); t_end = rtclock(); fprintf(stdout, "Sequential Runtime: %0.6lfs\n", t_end - t_start); if (test_correctness(size, out1, out2)) { fprintf(stdout, "Result: Successful\n"); } else { fprintf(stdout, "Result: Unsuccessful\n"); } }
convolution_pack8_fp16s.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 convolution_pack8_fp16sa_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& weight_data_fp16, const Mat& bias_data_fp16, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, int activation_type, const Mat& activation_params, const Option& opt) { int w = bottom_blob.w; int channels = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int maxk = kernel_w * kernel_h; // kernel offsets std::vector<int> _space_ofs(maxk); int* space_ofs = &_space_ofs[0]; { int p1 = 0; int p2 = 0; int gap = w * dilation_h - kernel_w * dilation_w; for (int i = 0; i < kernel_h; i++) { for (int j = 0; j < kernel_w; j++) { space_ofs[p1] = p2; p1++; p2 += dilation_w; } p2 += gap; } } const __fp16* bias_data_ptr = bias_data_fp16; // num_output #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { __fp16* outptr = top_blob.channel(p); for (int i = 0; i < outh; i++) { for (int j = 0; j < outw; j++) { float16x8_t _sum = vdupq_n_f16((__fp16)0.f); if (bias_data_ptr) { _sum = vld1q_f16(bias_data_ptr + p * 8); } const __fp16* kptr = weight_data_fp16.channel(p); // channels for (int q = 0; q < channels; q++) { const Mat m = bottom_blob.channel(q); const __fp16* sptr = m.row<const __fp16>(i * stride_h) + j * stride_w * 8; for (int k = 0; k < maxk; k++) { float16x8_t _val = vld1q_f16(sptr + space_ofs[k] * 8); float16x8_t _w0 = vld1q_f16(kptr); float16x8_t _w1 = vld1q_f16(kptr + 8); float16x8_t _w2 = vld1q_f16(kptr + 16); float16x8_t _w3 = vld1q_f16(kptr + 24); float16x8_t _w4 = vld1q_f16(kptr + 32); float16x8_t _w5 = vld1q_f16(kptr + 40); float16x8_t _w6 = vld1q_f16(kptr + 48); float16x8_t _w7 = vld1q_f16(kptr + 56); _sum = vfmaq_laneq_f16(_sum, _w0, _val, 0); _sum = vfmaq_laneq_f16(_sum, _w1, _val, 1); _sum = vfmaq_laneq_f16(_sum, _w2, _val, 2); _sum = vfmaq_laneq_f16(_sum, _w3, _val, 3); _sum = vfmaq_laneq_f16(_sum, _w4, _val, 4); _sum = vfmaq_laneq_f16(_sum, _w5, _val, 5); _sum = vfmaq_laneq_f16(_sum, _w6, _val, 6); _sum = vfmaq_laneq_f16(_sum, _w7, _val, 7); kptr += 64; } } _sum = activation_ps(_sum, activation_type, activation_params); vst1q_f16(outptr + j * 8, _sum); } outptr += outw * 8; } } }
zoom.c
// This program is free software: you can use, modify and/or redistribute it // under the terms of the simplified BSD License. You should have received a // copy of this license along this program. If not, see // <http://www.opensource.org/licenses/bsd-license.html>. // // Copyright (C) 2012, Javier Sánchez Pérez <jsanchez@dis.ulpgc.es> // All rights reserved. #ifndef ZOOM_C #define ZOOM_C #include "xmalloc.c" #include "mask.c" #include "bicubic_interpolation.c" #define ZOOM_SIGMA_ZERO 0.6 /** * * Compute the size of a zoomed image from the zoom factor * **/ void zoom_size( int nx, // width of the orignal image int ny, // height of the orignal image int *nxx, // width of the zoomed image int *nyy, // height of the zoomed image float factor // zoom factor between 0 and 1 ) { *nxx = (int)((float) nx * factor + 0.5); *nyy = (int)((float) ny * factor + 0.5); } /** * * Downsample an image * **/ void zoom_out( const float *I, // input image float *Iout, // output image const int nx, // image width const int ny, // image height const float factor // zoom factor between 0 and 1 ) { // temporary working image float *Is = xmalloc(nx * ny * sizeof*Is); for(int i = 0; i < nx * ny; i++) Is[i] = I[i]; // compute the size of the zoomed image int nxx, nyy; zoom_size(nx, ny, &nxx, &nyy, factor); // compute the Gaussian sigma for smoothing const float sigma = ZOOM_SIGMA_ZERO * sqrt(1.0/(factor*factor) - 1.0); // pre-smooth the image gaussian(Is, nx, ny, sigma); // re-sample the image using bicubic interpolation #pragma omp parallel for for (int i1 = 0; i1 < nyy; i1++) for (int j1 = 0; j1 < nxx; j1++) { const float i2 = (float) i1 / factor; const float j2 = (float) j1 / factor; float g = bicubic_interpolation_at(Is, j2, i2, nx, ny, false); Iout[i1 * nxx + j1] = g; } free(Is); } /** * * Function to upsample the image * **/ void zoom_in( const float *I, // input image float *Iout, // output image int nx, // width of the original image int ny, // height of the original image int nxx, // width of the zoomed image int nyy // height of the zoomed image ) { // compute the zoom factor const float factorx = ((float)nxx / nx); const float factory = ((float)nyy / ny); // re-sample the image using bicubic interpolation #pragma omp parallel for for (int i1 = 0; i1 < nyy; i1++) for (int j1 = 0; j1 < nxx; j1++) { float i2 = (float) i1 / factory; float j2 = (float) j1 / factorx; float g = bicubic_interpolation_at(I, j2, i2, nx, ny, false); Iout[i1 * nxx + j1] = g; } } #endif//ZOOM_C
pr34607.c
/* PR c++/34607 */ /* { dg-do compile } */ /* { dg-options "-fopenmp -std=gnu99" } */ void foo () { #pragma omp for for (int i =; i < 2; ++i) /* { dg-error "expected expression before" } */ ; #pragma omp for for (T i = 54; i < 56; i++) /* { dg-error "unknown type name" } */ ; T j; /* { dg-error "unknown type name" } */ #pragma omp for for (j = 1; j < 3; j++) ; }
switch-sbr-2.c
/* { dg-additional-options "-fno-tree-switch-conversion" } */ #pragma omp declare target int foo (unsigned a) { switch (a) { case 1 ... 5: return 1; case 9 ... 11: return a + 3; case 12 ... 13: return a + 3; default: return 44; } } #pragma omp end declare target #define s 100 void __attribute__((noinline, noclone)) verify(int *a) { if (a[0] != 44) __builtin_abort (); for (int i = 1; i <= 5; i++) if (a[i] != 1) __builtin_abort (); for (int i = 6; i <= 8; i++) if (a[i] != 44) __builtin_abort (); for (int i = 9; i <= 13; i++) if (a[i] != i + 3) __builtin_abort (); for (int i = 14; i < s; i++) if (a[i] != 44) __builtin_abort (); } int main(int argc) { int array[s]; #pragma omp target { for (int i = 0; i < s; i++) { int v = foo (i); array[i] = v; } } verify (array); return 0; }
mpncbo.c
/* $Header$ */ /* mpncbo -- netCDF binary operator */ /* Purpose: Compute sum, difference, product, or ratio of specified hyperslabs of specfied variables from two input netCDF files and output them to a single file. */ /* Copyright (C) 1995--present Charlie Zender This file is part of NCO, the netCDF Operators. NCO is free software. You may redistribute and/or modify NCO under the terms of the 3-Clause BSD License. You are permitted to link NCO with the HDF, netCDF, OPeNDAP, and UDUnits libraries and to distribute the resulting executables under the terms of the BSD, but in addition obeying the extra stipulations of the HDF, netCDF, OPeNDAP, and UDUnits licenses. 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 3-Clause BSD License for more details. The original author of this software, Charlie Zender, seeks to improve it with your suggestions, contributions, bug-reports, and patches. Please contact the NCO project at http://nco.sf.net or write to Charlie Zender Department of Earth System Science University of California, Irvine Irvine, CA 92697-3100 */ /* Usage: mpncbo -O -p ~/nco/data in.nc in.nc ~/foo.nc mpncbo -O -v mss_val in.nc in.nc ~/foo.nc mpncbo -p /data/zender/tmp h0001.nc ~/foo.nc mpncbo -p /data/zender/tmp -l /data/zender/tmp/rmt h0001.nc h0002.nc ~/foo.nc mpncbo -p /ZENDER/tmp -l /data/zender/tmp/rmt h0001.nc h0002.nc ~/foo.nc mpncbo -p /ZENDER/tmp -l /usr/tmp/zender h0001.nc h0002.nc ~/foo.nc Test type conversion: ncks -O -C -v float_var in.nc foo1.nc ncrename -v float_var,double_var foo1.nc ncks -O -C -v double_var in.nc foo2.nc mpncbo -O -C -v double_var foo1.nc foo2.nc foo3.nc mpncbo -O -C -v double_var foo2.nc foo1.nc foo4.nc ncks -H -m foo1.nc ncks -H -m foo2.nc ncks -H -m foo3.nc ncks -H -m foo4.nc Test nco_var_cnf_dmn: ncks -O -v scalar_var in.nc ~/foo.nc ; ncrename -v scalar_var,four_dmn_rec_var foo.nc ; mpncbo -O -v four_dmn_rec_var in.nc ~/foo.nc foo2.nc */ #ifdef HAVE_CONFIG_H # include <config.h> /* Autotools tokens */ #endif /* !HAVE_CONFIG_H */ /* Standard C headers */ #include <math.h> /* sin cos cos sin 3.14159 */ #include <stdio.h> /* stderr, FILE, NULL, etc. */ #include <stdlib.h> /* abs, getopt, malloc, strtol */ #include <string.h> /* strcmp() */ #include <sys/stat.h> /* stat() */ #include <time.h> /* machine time */ #include <unistd.h> /* POSIX stuff */ #ifndef HAVE_GETOPT_LONG # include "nco_getopt.h" #else /* HAVE_GETOPT_LONG */ # ifdef HAVE_GETOPT_H # include <getopt.h> # endif /* !HAVE_GETOPT_H */ #endif /* HAVE_GETOPT_LONG */ /* 3rd party vendors */ #include <netcdf.h> /* netCDF definitions and C library */ #ifdef ENABLE_MPI # include <mpi.h> /* MPI definitions */ # include "nco_mpi.h" /* MPI utilities */ #endif /* !ENABLE_MPI */ /* Personal headers */ /* #define MAIN_PROGRAM_FILE MUST precede #include libnco.h */ #define MAIN_PROGRAM_FILE #include "libnco.h" /* netCDF Operator (NCO) library */ int main(int argc,char **argv) { char **fl_lst_abb=NULL; /* Option a */ char **fl_lst_in; char **gaa_arg=NULL; /* [sng] Global attribute arguments */ char **var_lst_in=NULL_CEWI; char *aux_arg[NC_MAX_DIMS]; char *cmd_ln; char *cnk_arg[NC_MAX_DIMS]; char *cnk_map_sng=NULL_CEWI; /* [sng] Chunking map */ char *cnk_plc_sng=NULL_CEWI; /* [sng] Chunking policy */ char *fl_in_1=NULL; /* fl_in_1 is nco_realloc'd when not NULL */ char *fl_in_2=NULL; /* fl_in_2 is nco_realloc'd when not NULL */ char *fl_out=NULL; /* Option o */ char *fl_out_tmp=NULL; /* MPI CEWI */ char *fl_pth=NULL; /* Option p */ char *fl_pth_lcl=NULL; /* Option l */ char *lmt_arg[NC_MAX_DIMS]; char *nco_op_typ_sng=NULL; /* [sng] Operation type */ char *opt_crr=NULL; /* [sng] String representation of current long-option name */ char *optarg_lcl=NULL; /* [sng] Local copy of system optarg */ char *sng_cnv_rcd=NULL_CEWI; /* [sng] strtol()/strtoul() return code */ const char * const CVS_Id="$Id$"; const char * const CVS_Revision="$Revision$"; const char * const opt_sht_lst="34567ACcD:d:FhL:l:Oo:p:rRSt:v:X:xy:-:"; cnk_dmn_sct **cnk_dmn=NULL_CEWI; #if defined(__cplusplus) || defined(PGI_CC) ddra_info_sct ddra_info; ddra_info.flg_ddra=False; #else /* !__cplusplus */ ddra_info_sct ddra_info={.MRV_flg=False,.flg_ddra=False,.lmn_nbr=0LL,.lmn_nbr_avg=0LL,.lmn_nbr_wgt=0LL,.nco_op_typ=nco_op_nil,.rnk_avg=0,.rnk_var=0,.rnk_wgt=0,.tmr_flg=nco_tmr_srt,.var_idx=0,.wgt_brd_flg=False,.wrd_sz=0}; #endif /* !__cplusplus */ dmn_sct **dim_1; dmn_sct **dim_2; dmn_sct **dmn_out; extern char *optarg; extern int optind; /* Using naked stdin/stdout/stderr in parallel region generates warning Copy appropriate filehandle to variable scoped shared in parallel clause */ FILE * const fp_stderr=stderr; /* [fl] stderr filehandle CEWI */ FILE * const fp_stdout=stdout; /* [fl] stdout filehandle CEWI */ int *in_id_1_arr; int *in_id_2_arr; int abb_arg_nbr=0; int aux_nbr=0; /* [nbr] Number of auxiliary coordinate hyperslabs specified */ int cnk_map=nco_cnk_map_nil; /* [enm] Chunking map */ int cnk_nbr=0; /* [nbr] Number of chunk sizes */ int cnk_plc=nco_cnk_plc_nil; /* [enm] Chunking policy */ int dfl_lvl=NCO_DFL_LVL_UNDEFINED; /* [enm] Deflate level */ int fl_idx; int fl_nbr=0; int fl_in_fmt_1; /* [enm] Input file format */ int fl_in_fmt_2; /* [enm] Input file format */ int fl_out_fmt=NCO_FORMAT_UNDEFINED; /* [enm] Output file format */ int fll_md_old; /* [enm] Old fill mode */ int gaa_nbr=0; /* [nbr] Number of global attributes to add */ int idx; int jdx; int dmn_idx; int dmn_jdx; int in_id_1; int in_id_2; int lmt_nbr=0; /* Option d. NB: lmt_nbr gets incremented */ int log_lvl=0; /* [enm] netCDF library debugging verbosity [0..5] */ int md_open; /* [enm] Mode flag for nc_open() call */ int nbr_dmn_fl_1; int nbr_dmn_fl_2; int nbr_dmn_xtr_1; int nbr_dmn_xtr_2; int nbr_var_fix_1; /* nbr_var_fix_1 gets incremented */ int nbr_var_fix_2; /* nbr_var_fix_2 gets incremented */ int nbr_var_fl_1; int nbr_var_fl_2; int nbr_var_prc_1; /* nbr_var_prc_1 gets incremented */ int nbr_var_prc_2; /* nbr_var_prc_2 gets incremented */ int xtr_nbr_1=0; /* xtr_nbr_1 won't otherwise be set for -c with no -v */ int xtr_nbr_2=0; /* xtr_nbr_2 won't otherwise be set for -c with no -v */ int nco_op_typ=nco_op_nil; /* [enm] Operation type */ int opt; int out_id; int rcd=NC_NOERR; /* [rcd] Return code */ int thr_idx; /* [idx] Index of current thread */ int thr_nbr=int_CEWI; /* [nbr] Thread number Option t */ int var_lst_in_nbr=0; lmt_sct **aux=NULL_CEWI; /* Auxiliary coordinate limits */ lmt_sct **lmt=NULL_CEWI; lmt_all_sct **lmt_all_lst=NULL_CEWI; /* List of *lmt_all structures */ cnv_sct *cnv; /* [sct] Convention structure */ nco_bool EXCLUDE_INPUT_LIST=False; /* Option c */ nco_bool EXTRACT_ALL_COORDINATES=False; /* Option c */ nco_bool EXTRACT_ASSOCIATED_COORDINATES=True; /* Option C */ nco_bool FILE_1_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FILE_2_RETRIEVED_FROM_REMOTE_LOCATION; nco_bool FL_LST_IN_FROM_STDIN=False; /* [flg] fl_lst_in comes from stdin */ nco_bool FORCE_APPEND=False; /* Option A */ nco_bool FORCE_OVERWRITE=False; /* Option O */ nco_bool FORTRAN_IDX_CNV=False; /* Option F */ nco_bool HISTORY_APPEND=True; /* Option h */ nco_bool HPSS_TRY=False; /* [flg] Search HPSS for unfound files */ nco_bool MSA_USR_RDR=False; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order*/ nco_bool RAM_CREATE=False; /* [flg] Create file in RAM */ nco_bool RAM_OPEN=False; /* [flg] Open (netCDF3-only) file(s) in RAM */ nco_bool SHARE_CREATE=False; /* [flg] Create (netCDF3-only) file(s) with unbuffered I/O */ nco_bool SHARE_OPEN=False; /* [flg] Open (netCDF3-only) file(s) with unbuffered I/O */ nco_bool RM_RMT_FL_PST_PRC=True; /* Option R */ nco_bool WRT_TMP_FL=True; /* [flg] Write output to temporary file */ nco_bool flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ nco_bool flg_ddra=False; /* [flg] DDRA diagnostics */ nm_id_sct *dmn_lst_1; nm_id_sct *dmn_lst_2; nm_id_sct *xtr_lst_1=NULL; /* xtr_lst_1 may be alloc()'d from NULL with -c option */ nm_id_sct *xtr_lst_2=NULL; /* xtr_lst_2 may be alloc()'d from NULL with -c option */ size_t bfr_sz_hnt=NC_SIZEHINT_DEFAULT; /* [B] Buffer size hint */ size_t cnk_csh_byt=NCO_CNK_CSH_BYT_DFL; /* [B] Chunk cache size */ size_t cnk_min_byt=NCO_CNK_SZ_MIN_BYT_DFL; /* [B] Minimize size of variable to chunk */ size_t cnk_sz_byt=0UL; /* [B] Chunk size in bytes */ size_t cnk_sz_scl=0UL; /* [nbr] Chunk size scalar */ size_t hdr_pad=0UL; /* [B] Pad at end of header section */ var_sct **var_1; var_sct **var_2; var_sct **var_fix_1; var_sct **var_fix_2; var_sct **var_fix_out; var_sct **var_out; var_sct **var_prc_1; var_sct **var_prc_2; var_sct **var_prc_out; #ifdef ENABLE_MPI /* Declare all MPI-specific variables here */ MPI_Status mpi_stt; /* [enm] Status check to decode msg_tag_typ */ nco_bool TKN_WRT_FREE=True; /* [flg] Write-access to output file is available */ int fl_nm_lng; /* [nbr] Output file name length CEWI */ int msg_bfr[msg_bfr_lng]; /* [bfr] Buffer containing var, idx, tkn_wrt_rsp */ int msg_tag_typ; /* [enm] MPI message tag type */ int prc_rnk; /* [idx] Process rank */ int prc_nbr=0; /* [nbr] Number of MPI processes */ int tkn_wrt_rsp; /* [enm] Response to request for write token */ int var_wrt_nbr=0; /* [nbr] Variables written to output file until now */ int rnk_wrk; /* [idx] Worker rank */ int wrk_id_bfr[wrk_id_bfr_lng]; /* [bfr] Buffer for rnk_wrk */ #endif /* !ENABLE_MPI */ static struct option opt_lng[]={ /* Structure ordered by short option key if possible */ /* Long options with no argument, no short option counterpart */ {"clean",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"mmr_cln",no_argument,0,0}, /* [flg] Clean memory prior to exit */ {"drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"dirty",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"mmr_drt",no_argument,0,0}, /* [flg] Allow dirty memory on exit */ {"ddra",no_argument,0,0}, /* [flg] DDRA diagnostics */ {"mdl_cmp",no_argument,0,0}, /* [flg] DDRA diagnostics */ {"msa_usr_rdr",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ {"msa_user_order",no_argument,0,0}, /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ {"ram_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"create_ram",no_argument,0,0}, /* [flg] Create file in RAM */ {"open_ram",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) in RAM */ {"diskless_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) in RAM */ {"share_all",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"create_share",no_argument,0,0}, /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ {"open_share",no_argument,0,0}, /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ {"unbuffered_io",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"uio",no_argument,0,0}, /* [flg] Open and create (netCDF3) file(s) with unbuffered I/O */ {"wrt_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"write_tmp_fl",no_argument,0,0}, /* [flg] Write output to temporary file */ {"no_tmp_fl",no_argument,0,0}, /* [flg] Do not write output to temporary file */ {"version",no_argument,0,0}, {"vrs",no_argument,0,0}, /* Long options with argument, no short option counterpart */ {"bfr_sz_hnt",required_argument,0,0}, /* [B] Buffer size hint */ {"buffer_size_hint",required_argument,0,0}, /* [B] Buffer size hint */ {"cnk_byt",required_argument,0,0}, /* [B] Chunk size in bytes */ {"chunk_byte",required_argument,0,0}, /* [B] Chunk size in bytes */ {"cnk_dmn",required_argument,0,0}, /* [nbr] Chunk size */ {"chunk_dimension",required_argument,0,0}, /* [nbr] Chunk size */ {"cnk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"chunk_map",required_argument,0,0}, /* [nbr] Chunking map */ {"cnk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"chunk_min",required_argument,0,0}, /* [B] Minimize size of variable to chunk */ {"cnk_plc",required_argument,0,0}, /* [nbr] Chunking policy */ {"chunk_policy",required_argument,0,0}, /* [nbr] Chunking policy */ {"cnk_scl",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"chunk_scalar",required_argument,0,0}, /* [nbr] Chunk size scalar */ {"fl_fmt",required_argument,0,0}, {"file_format",required_argument,0,0}, {"gaa",required_argument,0,0}, /* [sng] Global attribute add */ {"glb_att_add",required_argument,0,0}, /* [sng] Global attribute add */ {"hdr_pad",required_argument,0,0}, {"header_pad",required_argument,0,0}, {"log_lvl",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ {"log_level",required_argument,0,0}, /* [enm] netCDF library debugging verbosity [0..5] */ /* Long options with short counterparts */ {"3",no_argument,0,'3'}, {"4",no_argument,0,'4'}, {"netcdf4",no_argument,0,'4'}, {"5",no_argument,0,'5'}, {"64bit_data",no_argument,0,'5'}, {"cdf5",no_argument,0,'5'}, {"pnetcdf",no_argument,0,'5'}, {"64bit_offset",no_argument,0,'6'}, {"7",no_argument,0,'7'}, {"append",no_argument,0,'A'}, {"coords",no_argument,0,'c'}, {"crd",no_argument,0,'c'}, {"xtr_ass_var",no_argument,0,'c'}, {"xcl_ass_var",no_argument,0,'C'}, {"no_coords",no_argument,0,'C'}, {"no_crd",no_argument,0,'C'}, {"dbg_lvl",required_argument,0,'D'}, {"debug",required_argument,0,'D'}, {"nco_dbg_lvl",required_argument,0,'D'}, {"dimension",required_argument,0,'d'}, {"dmn",required_argument,0,'d'}, {"fortran",no_argument,0,'F'}, {"ftn",no_argument,0,'F'}, {"history",no_argument,0,'h'}, {"hst",no_argument,0,'h'}, {"dfl_lvl",required_argument,0,'L'}, /* [enm] Deflate level */ {"deflate",required_argument,0,'L'}, /* [enm] Deflate level */ {"local",required_argument,0,'l'}, {"lcl",required_argument,0,'l'}, {"overwrite",no_argument,0,'O'}, {"ovr",no_argument,0,'O'}, {"path",required_argument,0,'p'}, {"retain",no_argument,0,'R'}, {"rtn",no_argument,0,'R'}, {"revision",no_argument,0,'r'}, {"suspend", no_argument,0,'S'}, {"thr_nbr",required_argument,0,'t'}, {"threads",required_argument,0,'t'}, {"omp_num_threads",required_argument,0,'t'}, {"variable",required_argument,0,'v'}, {"auxiliary",required_argument,0,'X'}, {"exclude",no_argument,0,'x'}, {"xcl",no_argument,0,'x'}, {"operation",required_argument,0,'y'}, {"op_typ",required_argument,0,'y'}, {"help",no_argument,0,'?'}, {"hlp",no_argument,0,'?'}, {0,0,0,0} }; /* end opt_lng */ int opt_idx=0; /* Index of current long option into opt_lng array */ #ifdef ENABLE_MPI /* MPI Initialization */ MPI_Init(&argc,&argv); MPI_Comm_size(MPI_COMM_WORLD,&prc_nbr); MPI_Comm_rank(MPI_COMM_WORLD,&prc_rnk); #endif /* !ENABLE_MPI */ /* Start timer and save command line */ ddra_info.tmr_flg=nco_tmr_srt; rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); ddra_info.tmr_flg=nco_tmr_mtd; cmd_ln=nco_cmd_ln_sng(argc,argv); /* Get program name and set program enum (e.g., nco_prg_id=ncra) */ nco_prg_nm=nco_prg_prs(argv[0],&nco_prg_id); /* Parse command line arguments */ while(1){ /* getopt_long_only() allows one dash to prefix long options */ opt=getopt_long(argc,argv,opt_sht_lst,opt_lng,&opt_idx); /* NB: access to opt_crr is only valid when long_opt is detected */ if(opt == EOF) break; /* Parse positional arguments once getopt_long() returns EOF */ opt_crr=(char *)strdup(opt_lng[opt_idx].name); /* Process long options without short option counterparts */ if(opt == 0){ if(!strcmp(opt_crr,"bfr_sz_hnt") || !strcmp(opt_crr,"buffer_size_hint")){ bfr_sz_hnt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_byt") || !strcmp(opt_crr,"chunk_byte")){ cnk_sz_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_byt */ if(!strcmp(opt_crr,"cnk_min") || !strcmp(opt_crr,"chunk_min")){ cnk_min_byt=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk_min */ if(!strcmp(opt_crr,"cnk_dmn") || !strcmp(opt_crr,"chunk_dimension")){ /* Copy limit argument for later processing */ cnk_arg[cnk_nbr]=(char *)strdup(optarg); cnk_nbr++; } /* endif cnk */ if(!strcmp(opt_crr,"cnk_scl") || !strcmp(opt_crr,"chunk_scalar")){ cnk_sz_scl=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_map") || !strcmp(opt_crr,"chunk_map")){ /* Chunking map */ cnk_map_sng=(char *)strdup(optarg); cnk_map=nco_cnk_map_get(cnk_map_sng); } /* endif cnk */ if(!strcmp(opt_crr,"cnk_plc") || !strcmp(opt_crr,"chunk_policy")){ /* Chunking policy */ cnk_plc_sng=(char *)strdup(optarg); cnk_plc=nco_cnk_plc_get(cnk_plc_sng); } /* endif cnk */ if(!strcmp(opt_crr,"mmr_cln") || !strcmp(opt_crr,"clean")) flg_mmr_cln=True; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"drt") || !strcmp(opt_crr,"mmr_drt") || !strcmp(opt_crr,"dirty")) flg_mmr_cln=False; /* [flg] Clean memory prior to exit */ if(!strcmp(opt_crr,"ddra") || !strcmp(opt_crr,"mdl_cmp")) ddra_info.flg_ddra=flg_ddra=True; /* [flg] DDRA diagnostics */ if(!strcmp(opt_crr,"fl_fmt") || !strcmp(opt_crr,"file_format")) rcd=nco_create_mode_prs(optarg,&fl_out_fmt); if(!strcmp(opt_crr,"gaa") || !strcmp(opt_crr,"glb_att_add")){ gaa_arg=(char **)nco_realloc(gaa_arg,(gaa_nbr+1)*sizeof(char *)); gaa_arg[gaa_nbr++]=(char *)strdup(optarg); } /* endif gaa */ if(!strcmp(opt_crr,"hdr_pad") || !strcmp(opt_crr,"header_pad")){ hdr_pad=strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); } /* endif "hdr_pad" */ if(!strcmp(opt_crr,"log_lvl") || !strcmp(opt_crr,"log_level")){ log_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); nc_set_log_level(log_lvl); } /* !log_lvl */ if(!strcmp(opt_crr,"msa_usr_rdr") || !strcmp(opt_crr,"msa_user_order")) MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"create_ram") || !strcmp(opt_crr,"diskless_all")) RAM_CREATE=True; /* [flg] Create (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"ram_all") || !strcmp(opt_crr,"open_ram") || !strcmp(opt_crr,"diskless_all")) RAM_OPEN=True; /* [flg] Open (netCDF3) file(s) in RAM */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"create_share")) SHARE_CREATE=True; /* [flg] Create (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"share_all") || !strcmp(opt_crr,"unbuffered_io") || !strcmp(opt_crr,"uio") || !strcmp(opt_crr,"open_share")) SHARE_OPEN=True; /* [flg] Open (netCDF3) file(s) with unbuffered I/O */ if(!strcmp(opt_crr,"vrs") || !strcmp(opt_crr,"version")){ (void)nco_vrs_prn(CVS_Id,CVS_Revision); nco_exit(EXIT_SUCCESS); } /* endif "vrs" */ if(!strcmp(opt_crr,"wrt_tmp_fl") || !strcmp(opt_crr,"write_tmp_fl")) WRT_TMP_FL=True; if(!strcmp(opt_crr,"no_tmp_fl")) WRT_TMP_FL=False; } /* opt != 0 */ /* Process short options */ switch(opt){ case 0: /* Long options have already been processed, return */ break; case '3': /* Request netCDF3 output storage format */ fl_out_fmt=NC_FORMAT_CLASSIC; break; case '4': /* Request netCDF4 output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4; break; case '5': /* Request netCDF3 64-bit offset+data storage (i.e., pnetCDF) format */ fl_out_fmt=NC_FORMAT_CDF5; break; case '6': /* Request netCDF3 64-bit offset output storage format */ fl_out_fmt=NC_FORMAT_64BIT_OFFSET; break; case '7': /* Request netCDF4-classic output storage format */ fl_out_fmt=NC_FORMAT_NETCDF4_CLASSIC; break; case 'A': /* Toggle FORCE_APPEND */ FORCE_APPEND=!FORCE_APPEND; break; case 'C': /* Extract all coordinates associated with extracted variables? */ EXTRACT_ASSOCIATED_COORDINATES=False; break; case 'c': EXTRACT_ALL_COORDINATES=True; break; case 'D': /* The debugging level. Default is 0. */ nco_dbg_lvl=(unsigned short int)strtoul(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtoul",sng_cnv_rcd); break; case 'd': /* Copy limit argument for later processing */ lmt_arg[lmt_nbr]=(char *)strdup(optarg); lmt_nbr++; break; case 'F': /* Toggle index convention. Default is 0-based arrays (C-style). */ FORTRAN_IDX_CNV=!FORTRAN_IDX_CNV; break; case 'h': /* Toggle appending to history global attribute */ HISTORY_APPEND=!HISTORY_APPEND; break; case 'L': /* [enm] Deflate level. Default is 0. */ dfl_lvl=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'l': /* Local path prefix for files retrieved from remote file system */ fl_pth_lcl=(char *)strdup(optarg); break; case 'O': /* Toggle FORCE_OVERWRITE */ FORCE_OVERWRITE=!FORCE_OVERWRITE; break; case 'o': /* Name of output file */ fl_out=(char *)strdup(optarg); break; case 'p': /* Common file path */ fl_pth=(char *)strdup(optarg); break; case 'R': /* Toggle removal of remotely-retrieved-files. Default is True. */ RM_RMT_FL_PST_PRC=!RM_RMT_FL_PST_PRC; break; case 'r': /* Print CVS program information and copyright notice */ (void)nco_vrs_prn(CVS_Id,CVS_Revision); (void)nco_lbr_vrs_prn(); (void)nco_cpy_prn(); (void)nco_cnf_prn(); nco_exit(EXIT_SUCCESS); break; #ifdef ENABLE_MPI case 'S': /* Suspend with signal handler to facilitate debugging */ if(signal(SIGUSR1,nco_cnt_run) == SIG_ERR) (void)fprintf(fp_stdout,"%s: ERROR Could not install suspend handler.\n",nco_prg_nm); while(!nco_spn_lck_brk) usleep(nco_spn_lck_us); /* Spinlock. fxm: should probably insert a sched_yield */ break; #endif /* !ENABLE_MPI */ case 't': /* Thread number */ thr_nbr=(int)strtol(optarg,&sng_cnv_rcd,NCO_SNG_CNV_BASE10); if(*sng_cnv_rcd) nco_sng_cnv_err(optarg,"strtol",sng_cnv_rcd); break; case 'v': /* Variables to extract/exclude */ /* Replace commas with hashes when within braces (convert back later) */ optarg_lcl=(char *)strdup(optarg); (void)nco_rx_comma2hash(optarg_lcl); var_lst_in=nco_lst_prs_2D(optarg_lcl,",",&var_lst_in_nbr); optarg_lcl=(char *)nco_free(optarg_lcl); xtr_nbr_1=xtr_nbr_2=var_lst_in_nbr; break; case 'X': /* Copy auxiliary coordinate argument for later processing */ aux_arg[aux_nbr]=(char *)strdup(optarg); aux_nbr++; MSA_USR_RDR=True; /* [flg] Multi-Slab Algorithm returns hyperslabs in user-specified order */ break; case 'x': /* Exclude rather than extract variables specified with -v */ EXCLUDE_INPUT_LIST=True; break; case 'y': /* User-specified operation type overrides invocation default */ nco_op_typ_sng=(char *)strdup(optarg); nco_op_typ=nco_op_typ_get(nco_op_typ_sng); break; case '?': /* Print proper usage */ (void)nco_usg_prn(); nco_exit(EXIT_SUCCESS); break; case '-': /* Long options are not allowed */ (void)fprintf(stderr,"%s: ERROR Long options are not available in this build. Use single letter options instead.\n",nco_prg_nm_get()); nco_exit(EXIT_FAILURE); break; default: /* Print proper usage */ (void)fprintf(stdout,"%s ERROR in command-line syntax/options. Please reformulate command accordingly.\n",nco_prg_nm_get()); (void)nco_usg_prn(); nco_exit(EXIT_FAILURE); break; } /* end switch */ if(opt_crr) opt_crr=(char *)nco_free(opt_crr); } /* end while loop */ /* Process positional arguments and fill-in filenames */ fl_lst_in=nco_fl_lst_mk(argv,argc,optind,&fl_nbr,&fl_out,&FL_LST_IN_FROM_STDIN,FORCE_OVERWRITE); /* Make uniform list of user-specified chunksizes */ if(cnk_nbr > 0) cnk_dmn=nco_cnk_prs(cnk_nbr,cnk_arg); /* Make uniform list of user-specified dimension limits */ lmt=nco_lmt_prs(lmt_nbr,lmt_arg); /* Initialize thread information */ thr_nbr=nco_openmp_ini(thr_nbr); in_id_1_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); in_id_2_arr=(int *)nco_malloc(thr_nbr*sizeof(int)); /* Parse filenames */ fl_idx=0; /* Input file _1 */ fl_in_1=nco_fl_nm_prs(fl_in_1,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"%s: INFO Input file %d is %s",nco_prg_nm_get(),fl_idx,fl_in_1); /* Make sure file is on local system and is readable or die trying */ fl_in_1=nco_fl_mk_lcl(fl_in_1,fl_pth_lcl,&FILE_1_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl && FILE_1_RETRIEVED_FROM_REMOTE_LOCATION) (void)fprintf(stderr,", local file is %s",fl_in_1); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\n"); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_1,md_open,&bfr_sz_hnt,in_id_1_arr+thr_idx); in_id_1=in_id_1_arr[0]; fl_idx=1; /* Input file _2 */ fl_in_2=nco_fl_nm_prs(fl_in_2,fl_idx,&fl_nbr,fl_lst_in,abb_arg_nbr,fl_lst_abb,fl_pth); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"%s: INFO Input file %d is %s",nco_prg_nm_get(),fl_idx,fl_in_2); /* Make sure file is on local system and is readable or die trying */ fl_in_2=nco_fl_mk_lcl(fl_in_2,fl_pth_lcl,&FILE_2_RETRIEVED_FROM_REMOTE_LOCATION); if(nco_dbg_lvl >= nco_dbg_fl && FILE_2_RETRIEVED_FROM_REMOTE_LOCATION) (void)fprintf(stderr,", local file is %s",fl_in_2); if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\n"); /* Open file once per thread to improve caching */ if(RAM_OPEN) md_open=NC_NOWRITE|NC_DISKLESS; else md_open=NC_NOWRITE; if(SHARE_OPEN) md_open=md_open|NC_SHARE; for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) rcd+=nco_fl_open(fl_in_2,md_open,&bfr_sz_hnt,in_id_2_arr+thr_idx); in_id_2=in_id_2_arr[0]; /* Parse auxiliary coordinates */ if(aux_nbr > 0){ int aux_idx_nbr; aux=nco_aux_evl(in_id_1,aux_nbr,aux_arg,&aux_idx_nbr); if(aux_idx_nbr > 0){ lmt=(lmt_sct **)nco_realloc(lmt,(lmt_nbr+aux_idx_nbr)*sizeof(lmt_sct *)); int lmt_nbr_new=lmt_nbr+aux_idx_nbr; int aux_idx=0; for(int lmt_idx=lmt_nbr;lmt_idx<lmt_nbr_new;lmt_idx++) lmt[lmt_idx]=aux[aux_idx++]; lmt_nbr=lmt_nbr_new; } /* endif aux */ } /* endif aux_nbr */ /* Get number of variables and dimensions in file */ (void)nco_inq(in_id_1,&nbr_dmn_fl_1,&nbr_var_fl_1,(int *)NULL,(int *)NULL); (void)nco_inq(in_id_2,&nbr_dmn_fl_2,&nbr_var_fl_2,(int *)NULL,(int *)NULL); (void)nco_inq_format(in_id_1,&fl_in_fmt_1); (void)nco_inq_format(in_id_2,&fl_in_fmt_2); /* Form initial extraction list which may include extended regular expressions */ xtr_lst_1=nco_var_lst_mk(in_id_1,nbr_var_fl_1,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr_1); xtr_lst_2=nco_var_lst_mk(in_id_2,nbr_var_fl_2,var_lst_in,EXCLUDE_INPUT_LIST,EXTRACT_ALL_COORDINATES,&xtr_nbr_2); /* Change included variables to excluded variables */ if(EXCLUDE_INPUT_LIST) xtr_lst_1=nco_var_lst_xcl(in_id_1,nbr_var_fl_1,xtr_lst_1,&xtr_nbr_1); if(EXCLUDE_INPUT_LIST) xtr_lst_2=nco_var_lst_xcl(in_id_2,nbr_var_fl_2,xtr_lst_2,&xtr_nbr_2); /* Determine conventions (ARM/CCM/CCSM/CF/MPAS) for treating file */ cnv=nco_cnv_ini(in_id_1); /* Add all coordinate variables to extraction list */ if(EXTRACT_ALL_COORDINATES) xtr_lst_1=nco_var_lst_crd_add(in_id_1,nbr_dmn_fl_1,nbr_var_fl_1,xtr_lst_1,&xtr_nbr_1,cnv); if(EXTRACT_ALL_COORDINATES) xtr_lst_2=nco_var_lst_crd_add(in_id_2,nbr_dmn_fl_2,nbr_var_fl_2,xtr_lst_2,&xtr_nbr_2,cnv); /* Extract coordinates associated with extracted variables */ if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst_1=nco_var_lst_crd_ass_add(in_id_1,xtr_lst_1,&xtr_nbr_1,cnv); if(EXTRACT_ASSOCIATED_COORDINATES) xtr_lst_2=nco_var_lst_crd_ass_add(in_id_2,xtr_lst_2,&xtr_nbr_2,cnv); /* With fully symmetric 1<->2 ordering, may occasionally find xtr_nbr_2 > xtr_nbr_1 This occurs, e.g., when fl_in_1 contains reduced variables and full coordinates are only in fl_in_2 and so will not appear xtr_lst_1 */ /* Sort extraction list by variable ID for fastest I/O */ if(xtr_nbr_1 > 1) xtr_lst_1=nco_lst_srt_nm_id(xtr_lst_1,xtr_nbr_1,False); if(xtr_nbr_2 > 1) xtr_lst_2=nco_lst_srt_nm_id(xtr_lst_2,xtr_nbr_2,False); /* We now have final list of variables to extract. Phew. */ /* Find coordinate/dimension values associated with user-specified limits NB: nco_lmt_evl() with same nc_id contains OpenMP critical region */ for(idx=0;idx<lmt_nbr;idx++) (void)nco_lmt_evl(in_id_1,lmt[idx],0L,FORTRAN_IDX_CNV); /* Place all dimensions in lmt_all_lst */ lmt_all_lst=(lmt_all_sct **)nco_malloc(nbr_dmn_fl_1*sizeof(lmt_all_sct *)); /* Initialize lmt_all_sct's */ (void)nco_msa_lmt_all_ntl(in_id_1,MSA_USR_RDR,lmt_all_lst,nbr_dmn_fl_1,lmt,lmt_nbr); /* Find dimensions associated with variables to be extracted */ dmn_lst_1=nco_dmn_lst_ass_var(in_id_1,xtr_lst_1,xtr_nbr_1,&nbr_dmn_xtr_1); dmn_lst_2=nco_dmn_lst_ass_var(in_id_2,xtr_lst_2,xtr_nbr_2,&nbr_dmn_xtr_2); /* Fill-in dimension structure for all extracted dimensions */ dim_1=(dmn_sct **)nco_malloc(nbr_dmn_xtr_1*sizeof(dmn_sct *)); dim_2=(dmn_sct **)nco_malloc(nbr_dmn_xtr_2*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr_1;idx++) dim_1[idx]=nco_dmn_fll(in_id_1,dmn_lst_1[idx].id,dmn_lst_1[idx].nm); for(idx=0;idx<nbr_dmn_xtr_2;idx++) dim_2[idx]=nco_dmn_fll(in_id_2,dmn_lst_2[idx].id,dmn_lst_2[idx].nm); /* Dimension lists no longer needed */ dmn_lst_1=nco_nm_id_lst_free(dmn_lst_1,nbr_dmn_xtr_1); dmn_lst_2=nco_nm_id_lst_free(dmn_lst_2,nbr_dmn_xtr_2); /* Check that dims in list 2 are a subset of list 1 and that they are the same size */ (void)nco_dmn_sct_cmp(dim_1,nbr_dmn_xtr_1,dim_2,nbr_dmn_xtr_2,fl_in_1,fl_in_2); /* Duplicate input dimension structures for output dimension structures */ dmn_out=(dmn_sct **)nco_malloc(nbr_dmn_xtr_1*sizeof(dmn_sct *)); for(idx=0;idx<nbr_dmn_xtr_1;idx++){ dmn_out[idx]=nco_dmn_dpl(dim_1[idx]); (void)nco_dmn_xrf(dim_1[idx],dmn_out[idx]); } /* Merge hyperslab limit information into dimension structures */ if(nbr_dmn_fl_1 > 0) (void)nco_dmn_lmt_all_mrg(dmn_out,nbr_dmn_xtr_1,lmt_all_lst,nbr_dmn_fl_1); if(nco_dbg_lvl >= nco_dbg_sbr){ for(idx=0;idx<xtr_nbr_1;idx++) (void)fprintf(stderr,"xtr_lst_1[%d].nm = %s, .id= %d\n",idx,xtr_lst_1[idx].nm,xtr_lst_1[idx].id); } /* end if */ /* Fill-in variable structure list for all extracted variables */ var_1=(var_sct **)nco_malloc(xtr_nbr_1*sizeof(var_sct *)); var_2=(var_sct **)nco_malloc(xtr_nbr_2*sizeof(var_sct *)); var_out=(var_sct **)nco_malloc(xtr_nbr_1*sizeof(var_sct *)); for(idx=0;idx<xtr_nbr_1;idx++){ var_1[idx]=nco_var_fll(in_id_1,xtr_lst_1[idx].id,xtr_lst_1[idx].nm,dim_1,nbr_dmn_xtr_1); var_out[idx]=nco_var_dpl(var_1[idx]); (void)nco_xrf_var(var_1[idx],var_out[idx]); (void)nco_xrf_dmn(var_out[idx]); } /* end loop over idx */ for(idx=0;idx<xtr_nbr_2;idx++) var_2[idx]=nco_var_fll(in_id_2,xtr_lst_2[idx].id,xtr_lst_2[idx].nm,dim_2,nbr_dmn_xtr_2); /* Extraction lists no longer needed */ xtr_lst_1=nco_nm_id_lst_free(xtr_lst_1,xtr_nbr_1); xtr_lst_2=nco_nm_id_lst_free(xtr_lst_2,xtr_nbr_2); /* Die gracefully on unsupported features... */ if(xtr_nbr_1 < xtr_nbr_2){ (void)fprintf(fp_stdout,"%s: WARNING First file has fewer extracted variables than second file (%d < %d). This desired feature is TODO nco581.\n",nco_prg_nm,xtr_nbr_1,xtr_nbr_2); nco_exit(EXIT_FAILURE); } /* endif */ /* Refresh var_out with dim_out data */ (void)nco_var_dmn_refresh(var_out,xtr_nbr_1); /* Change dimensions in dim_2 to dim_out */ for(idx=0;idx<nbr_dmn_xtr_2;idx++){ for(jdx=0;jdx<nbr_dmn_xtr_1;jdx++) if(!strcmp(dim_2[idx]->nm,dmn_out[jdx]->nm)){ /* NB: Copy new dim data but do NOT free original as dimension element is aliased in var_2 array */ (void)nco_dmn_cpy(dim_2[idx],dmn_out[jdx]); break; } /* endif */ /* Dimension not found so die gracefully */ if(jdx==nbr_dmn_xtr_1){ (void)fprintf(fp_stdout,"%s: ERROR dimension \"%s\" in second file %s is not present in first file %s\n",nco_prg_nm,dim_2[idx]->nm,fl_in_2,fl_in_1); nco_exit(EXIT_FAILURE); } /* endif dimension not found */ } /* end loop over dimensions */ /* Refresh var_2 with the new dim_2 data */ (void)nco_var_dmn_refresh(var_2,xtr_nbr_2); /* Divide variable lists into lists of fixed variables and variables to be processed Create lists from file_1 last so those values remain in *_out arrays */ (void)nco_var_lst_dvd(var_2,var_out,xtr_nbr_2,cnv,True,nco_pck_plc_nil,nco_pck_map_nil,(dmn_sct **)NULL,0,&var_fix_2,&var_fix_out,&nbr_var_fix_2,&var_prc_2,&var_prc_out,&nbr_var_prc_2); /* Avoid double-free() condition */ var_fix_out=(var_sct **)nco_free(var_fix_out); var_prc_out=(var_sct **)nco_free(var_prc_out); (void)nco_var_lst_dvd(var_1,var_out,xtr_nbr_1,cnv,True,nco_pck_plc_nil,nco_pck_map_nil,(dmn_sct **)NULL,0,&var_fix_1,&var_fix_out,&nbr_var_fix_1,&var_prc_1,&var_prc_out,&nbr_var_prc_1); /* Die gracefully on unsupported features... */ if(nbr_var_fix_1 < nbr_var_fix_2){ (void)fprintf(fp_stdout,"%s: ERROR First file has fewer fixed variables than second file (%d < %d). This feature is TODO nco581.\n",nco_prg_nm,nbr_var_fix_1,nbr_var_fix_2); nco_exit(EXIT_FAILURE); } /* endif */ /* Merge two variable lists into same order */ rcd=nco_var_lst_mrg(&var_prc_1,&var_prc_2,&nbr_var_prc_1,&nbr_var_prc_2); /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt_1; /* Verify output file format supports requested actions */ (void)nco_fl_fmt_vet(fl_out_fmt,cnk_nbr,dfl_lvl); /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* 20101019 fxm got to here merging ncbo 4.0.5 into mpncbo */ /* Assign zero to start and unity to stride vectors in output variables */ (void)nco_var_srd_srt_set(var_out,xtr_nbr_1); #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ #endif /* !ENABLE_MPI */ /* Make output and input files consanguinous */ if(fl_out_fmt == NCO_FORMAT_UNDEFINED) fl_out_fmt=fl_in_fmt_1; /* Open output file */ fl_out_tmp=nco_fl_out_open(fl_out,&FORCE_APPEND,FORCE_OVERWRITE,fl_out_fmt,&bfr_sz_hnt,RAM_CREATE,RAM_OPEN,SHARE_CREATE,SHARE_OPEN,WRT_TMP_FL,&out_id); /* Copy global attributes */ (void)nco_att_cpy(in_id_1,out_id,NC_GLOBAL,NC_GLOBAL,(nco_bool)True); /* Catenate time-stamped command line to "history" global attribute */ if(HISTORY_APPEND) (void)nco_hst_att_cat(out_id,cmd_ln); if(HISTORY_APPEND && FORCE_APPEND) (void)nco_prv_att_cat(fl_in_1,in_id_1,out_id); if(gaa_nbr > 0) (void)nco_glb_att_add(out_id,gaa_arg,gaa_nbr); if(HISTORY_APPEND) (void)nco_vrs_att_cat(out_id); if(thr_nbr > 1 && HISTORY_APPEND) (void)nco_thr_att_cat(out_id,thr_nbr); #ifdef ENABLE_MPI /* Initialize MPI task information */ if(prc_nbr > 0 && HISTORY_APPEND) (void)nco_mpi_att_cat(out_id,prc_nbr); #endif /* !ENABLE_MPI */ /* Define dimensions in output file */ (void)nco_dmn_dfn(fl_out,out_id,dmn_out,nbr_dmn_xtr_1); /* fxm: TODO 550 put max_dim_sz/list(var_1,var_2) into var_def(var_out) */ /* Define variables in output file, copy their attributes */ (void)nco_var_dfn(in_id_1,fl_out,out_id,var_out,xtr_nbr_1,(dmn_sct **)NULL,(int)0,nco_pck_plc_nil,nco_pck_map_nil,dfl_lvl); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl_1,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); /* Take output file out of define mode */ if(hdr_pad == 0UL){ (void)nco_enddef(out_id); }else{ (void)nco__enddef(out_id,hdr_pad); if(nco_dbg_lvl >= nco_dbg_scl) (void)fprintf(stderr,"%s: INFO Padding header with %lu extra bytes\n",nco_prg_nm_get(),(unsigned long)hdr_pad); } /* hdr_pad */ #ifdef ENABLE_MPI } /* prc_rnk != rnk_mgr */ /* Manager obtains output filename and broadcasts to workers */ if(prc_rnk == rnk_mgr) fl_nm_lng=(int)strlen(fl_out_tmp); MPI_Bcast(&fl_nm_lng,1,MPI_INT,rnk_mgr,MPI_COMM_WORLD); if(prc_rnk != rnk_mgr) fl_out_tmp=(char *)nco_malloc((fl_nm_lng+1)*sizeof(char)); MPI_Bcast(fl_out_tmp,fl_nm_lng+1,MPI_CHAR,rnk_mgr,MPI_COMM_WORLD); if(prc_rnk == rnk_mgr){ /* MPI manager code */ TKN_WRT_FREE=False; #endif /* !ENABLE_MPI */ /* Copy variable data for non-processed variables */ (void)nco_msa_var_val_cpy(in_id_1,out_id,var_fix_1,nbr_var_fix_1,lmt_all_lst,nbr_dmn_fl_1); #ifdef ENABLE_MPI /* Close output file so workers can open it */ nco_close(out_id); TKN_WRT_FREE=True; } /* prc_rnk != rnk_mgr */ #endif /* !ENABLE_MPI */ /* ncbo() code has been similar to nces() (and ncra()) wherever possible Major differences occur where performance would otherwise suffer From now on, however, binary-file and binary-operation nature of ncbo() is too different from nces() paradigm to justify following nces() style. Instead, we adopt symmetric nomenclature (e.g., file_1, file_2), and perform differences variable-by-variable so peak memory usage goes as Order(2*maximum variable size) rather than Order(3*maximum record size) or Order(3*file size) */ /* Perform various error-checks on input file */ if(False) (void)nco_fl_cmp_err_chk(); /* Default operation depends on invocation name */ if(nco_op_typ_sng == NULL) nco_op_typ=nco_op_typ_get(nco_op_typ_sng); /* Timestamp end of metadata setup and disk layout */ rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); ddra_info.tmr_flg=nco_tmr_rgl; #ifdef ENABLE_MPI if(prc_rnk == rnk_mgr){ /* MPI manager code */ /* Compensate for incrementing on each worker's first message */ var_wrt_nbr=-prc_nbr+1; idx=0; /* While variables remain to be processed or written... */ while(var_wrt_nbr < nbr_var_prc_1){ /* Receive message from any worker */ MPI_Recv(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,MPI_ANY_SOURCE,MPI_ANY_TAG,MPI_COMM_WORLD,&mpi_stt); /* Obtain MPI message tag type */ msg_tag_typ=mpi_stt.MPI_TAG; /* Get sender's prc_rnk */ rnk_wrk=wrk_id_bfr[0]; /* Allocate next variable, if any, to worker */ if(msg_tag_typ == msg_tag_wrk_rqs){ var_wrt_nbr++; /* [nbr] Number of variables written */ /* Worker closed output file before sending msg_tag_wrk_rqs */ TKN_WRT_FREE=True; if(idx < nbr_var_prc_1){ /* Tell requesting worker to allocate space for next variable */ msg_bfr[0]=idx; /* [idx] Variable to be processed */ msg_bfr[1]=out_id; /* Output file ID */ msg_bfr[2]=var_prc_out[idx]->id; /* [id] Variable ID in output file */ /* Point to next variable on list */ idx++; }else{ msg_bfr[0]=idx_all_wrk_ass; /* [enm] All variables already assigned */ msg_bfr[1]=out_id; /* Output file ID */ } /* endif idx */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_wrk_rsp,MPI_COMM_WORLD); /* msg_tag_typ != msg_tag_wrk_rqs */ }else if(msg_tag_typ == msg_tag_tkn_wrt_rqs){ /* Allocate token if free, else ask worker to try later */ if(TKN_WRT_FREE){ TKN_WRT_FREE=False; msg_bfr[0]=tkn_wrt_rqs_xcp; /* Accept request for write token */ }else{ msg_bfr[0]=tkn_wrt_rqs_dny; /* Deny request for write token */ } /* !TKN_WRT_FREE */ MPI_Send(msg_bfr,msg_bfr_lng,MPI_INT,rnk_wrk,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD); } /* msg_tag_typ != msg_tag_tkn_wrt_rqs */ } /* end while var_wrt_nbr < nbr_var_prc_1 */ }else{ /* prc_rnk != rnk_mgr, end Manager code begin Worker code */ wrk_id_bfr[0]=prc_rnk; while(1){ /* While work remains... */ /* Send msg_tag_wrk_rqs */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_wrk_rqs,MPI_COMM_WORLD); /* Receive msg_tag_wrk_rsp */ MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,0,msg_tag_wrk_rsp,MPI_COMM_WORLD,&mpi_stt); idx=msg_bfr[0]; out_id=msg_bfr[1]; if(idx == idx_all_wrk_ass) break; else{ var_prc_out[idx]->id=msg_bfr[2]; /* Process this variable same as UP code */ #else /* !ENABLE_MPI */ #ifdef _OPENMP /* OpenMP notes: shared(): msk and wgt are not altered within loop private(): wgt_avg does not need initialization */ #pragma omp parallel for default(none) firstprivate(ddra_info) private(idx,in_id_1,in_id_2,dmn_idx,dmn_jdx) shared(nco_dbg_lvl,dim_1,fl_in_1,fl_in_2,fl_out,flg_ddra,in_id_1_arr,in_id_2_arr,nbr_dmn_xtr_1,nbr_var_prc_1,nbr_var_prc_2,nco_op_typ,out_id,nco_prg_nm,rcd,var_prc_1,var_prc_2,var_prc_out,lmt_all_lst,nbr_dmn_fl_1) #endif /* !_OPENMP */ /* UP and SMP codes main loop over variables */ for(idx=0;idx<nbr_var_prc_1;idx++){ #endif /* ENABLE_MPI */ /* Common code for UP, SMP, and MPI */ int has_mss_val=False; ptr_unn mss_val; if(nco_dbg_lvl >= nco_dbg_var) (void)fprintf(fp_stderr,"%s, ",var_prc_1[idx]->nm); if(nco_dbg_lvl >= nco_dbg_var) (void)fflush(fp_stderr); in_id_1=in_id_1_arr[omp_get_thread_num()]; in_id_2=in_id_2_arr[omp_get_thread_num()]; (void)nco_var_mtd_refresh(in_id_1,var_prc_1[idx]); has_mss_val=var_prc_1[idx]->has_mss_val; (void)nco_msa_var_get(in_id_1,var_prc_1[idx],lmt_all_lst,nbr_dmn_fl_1); /* Find and set variable dmn_nbr, ID, mss_val, type in second file */ (void)nco_var_mtd_refresh(in_id_2,var_prc_2[idx]); /* Read hyperslab from second file */ (void)nco_msa_var_get(in_id_2,var_prc_2[idx],lmt_all_lst,nbr_dmn_fl_1); /* Check that all dims in var_prc_2 are in var_prc_1 */ for(dmn_idx=0;dmn_idx<var_prc_2[idx]->nbr_dim;dmn_idx++){ for(dmn_jdx=0;dmn_jdx<var_prc_1[idx]->nbr_dim;dmn_jdx++) if(!strcmp(var_prc_2[idx]->dim[dmn_idx]->nm,var_prc_1[idx]->dim[dmn_jdx]->nm)) break; if(dmn_jdx==var_prc_1[idx]->nbr_dim){ (void)fprintf(fp_stdout,"%s: ERROR Variables do not conform:\nFile %s variable %s has dimension %s not present in file %s variable %s\n",nco_prg_nm,fl_in_2,var_prc_2[idx]->nm, var_prc_2[idx]->dim[dmn_idx]->nm,fl_in_1,var_prc_1[idx]->nm); nco_exit(EXIT_FAILURE); } /* endif error */ } /* end loop over idx */ /* Die gracefully on unsupported features... */ if(var_prc_1[idx]->nbr_dim < var_prc_2[idx]->nbr_dim){ (void)fprintf(fp_stdout,"%s: ERROR Variable %s has lesser rank in first file than in second file (%d < %d). This feature is NCO TODO 552.\n",nco_prg_nm,var_prc_1[idx]->nm,var_prc_1[idx]->nbr_dim,var_prc_2[idx]->nbr_dim); nco_exit(EXIT_FAILURE); } /* endif */ if(var_prc_1[idx]->nbr_dim > var_prc_2[idx]->nbr_dim) (void)ncap_var_cnf_dmn(&var_prc_out[idx],&var_prc_2[idx]); /* var2 now conforms in size to var1, and is in memory */ /* fxm: TODO 268 allow var1 or var2 to typecast */ /* Make sure var2 conforms to type of var1 */ if(var_prc_1[idx]->type != var_prc_2[idx]->type){ if(nco_dbg_lvl >= nco_dbg_std) (void)fprintf(fp_stderr,"%s: INFO Input variables do not conform in type:\nFile 1 = %s variable %s has type %s\nFile 2 = %s variable %s has type %s\nFile 3 = %s variable %s will have type %s\n",nco_prg_nm,fl_in_1,var_prc_1[idx]->nm,nco_typ_sng(var_prc_1[idx]->type),fl_in_2,var_prc_2[idx]->nm,nco_typ_sng(var_prc_2[idx]->type),fl_out,var_prc_1[idx]->nm,nco_typ_sng(var_prc_1[idx]->type)); } /* endif different type */ var_prc_2[idx]=nco_var_cnf_typ(var_prc_1[idx]->type,var_prc_2[idx]); /* Change missing_value of var_prc_2, if any, to missing_value of var_prc_1, if any */ has_mss_val=nco_mss_val_cnf(var_prc_1[idx],var_prc_2[idx]); /* mss_val in fl_1, if any, overrides mss_val in fl_2 */ if(has_mss_val) mss_val=var_prc_1[idx]->mss_val; /* Perform specified binary operation */ switch(nco_op_typ){ case nco_op_add: /* [enm] Add file_1 to file_2 */ (void)nco_var_add(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,mss_val,var_prc_2[idx]->val,var_prc_1[idx]->val); break; case nco_op_mlt: /* [enm] Multiply file_1 by file_2 */ (void)nco_var_mlt(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,mss_val,var_prc_2[idx]->val,var_prc_1[idx]->val); break; case nco_op_dvd: /* [enm] Divide file_1 by file_2 */ (void)nco_var_dvd(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,mss_val,var_prc_2[idx]->val,var_prc_1[idx]->val); break; case nco_op_sbt: /* [enm] Subtract file_2 from file_1 */ (void)nco_var_sbt(var_prc_1[idx]->type,var_prc_1[idx]->sz,has_mss_val,mss_val,var_prc_2[idx]->val,var_prc_1[idx]->val); break; default: /* Other defined nco_op_typ values are valid for ncra(), ncrcat(), ncwa(), not ncbo() */ (void)fprintf(fp_stdout,"%s: ERROR Illegal nco_op_typ in binary operation\n",nco_prg_nm); nco_exit(EXIT_FAILURE); break; } /* end case */ var_prc_2[idx]->val.vp=nco_free(var_prc_2[idx]->val.vp); #ifdef ENABLE_MPI /* Obtain token and prepare to write */ while(1){ /* Send msg_tag_tkn_wrt_rqs repeatedly until token obtained */ wrk_id_bfr[0]=prc_rnk; MPI_Send(wrk_id_bfr,wrk_id_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rqs,MPI_COMM_WORLD); MPI_Recv(msg_bfr,msg_bfr_lng,MPI_INT,rnk_mgr,msg_tag_tkn_wrt_rsp,MPI_COMM_WORLD,&mpi_stt); tkn_wrt_rsp=msg_bfr[0]; /* Wait then re-send request */ if(tkn_wrt_rsp == tkn_wrt_rqs_dny) sleep(tkn_wrt_rqs_ntv); else break; } /* end while loop waiting for write token */ /* Worker has token---prepare to write */ if(tkn_wrt_rsp == tkn_wrt_rqs_xcp){ if(RAM_OPEN) md_open=NC_WRITE|NC_SHARE|NC_DISKLESS; else md_open=NC_WRITE|NC_SHARE; rcd=nco_fl_open(fl_out_tmp,md_open,&bfr_sz_hnt,&out_id); /* Set chunksize parameters */ if(fl_out_fmt == NC_FORMAT_NETCDF4 || fl_out_fmt == NC_FORMAT_NETCDF4_CLASSIC) (void)nco_cnk_sz_set(out_id,lmt_all_lst,nbr_dmn_fl_1,&cnk_map,&cnk_plc,cnk_sz_scl,cnk_dmn,cnk_nbr); /* Turn-off default filling behavior to enhance efficiency */ nco_set_fill(out_id,NC_NOFILL,&fll_md_old); #else /* !ENABLE_MPI */ #ifdef _OPENMP #pragma omp critical #endif /* !_OPENMP */ #endif /* !ENABLE_MPI */ /* Common code for UP, SMP, and MPI */ { /* begin OpenMP critical */ /* Copy result to output file and free workspace buffer */ if(var_prc_1[idx]->nbr_dim == 0){ (void)nco_put_var1(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_1[idx]->val.vp,var_prc_1[idx]->type); }else{ /* end if variable is scalar */ (void)nco_put_vara(out_id,var_prc_out[idx]->id,var_prc_out[idx]->srt,var_prc_out[idx]->cnt,var_prc_1[idx]->val.vp,var_prc_1[idx]->type); } /* end else */ } /* end OpenMP critical */ var_prc_1[idx]->val.vp=nco_free(var_prc_1[idx]->val.vp); if(flg_ddra){ /* DDRA diagnostics Usage: ncbo -O -C --mdl -p ~/nco/data in.nc in.nc ~/foo.nc ncbo -O -C --mdl -p ${DATA}/nco_bm stl_5km.nc stl_5km.nc ~/foo.nc ncbo -O -C --mdl -p ${DATA}/nco_bm gcm_T85.nc gcm_T85.nc ~/foo.nc */ /* Assign remaining input for DDRA diagnostics */ ddra_info.lmn_nbr=var_prc_1[idx]->sz; /* [nbr] Variable size */ ddra_info.nco_op_typ=nco_op_typ; /* [enm] Operation type */ ddra_info.rnk_var=var_prc_1[idx]->nbr_dim; /* I [nbr] Variable rank (in input file) */ ddra_info.var_idx=idx; /* [enm] Index */ ddra_info.wrd_sz=nco_typ_lng(var_prc_1[idx]->type); /* [B] Bytes per element */ /* DDRA diagnostics */ rcd+=nco_ddra /* [fnc] Count operations */ (var_prc_1[idx]->nm, /* I [sng] Variable name */ (char *)NULL, /* I [sng] Weight name */ &ddra_info); /* I [sct] DDRA information */ } /* !flg_ddra */ #ifdef ENABLE_MPI /* Close output file and increment written counter */ nco_close(out_id); var_wrt_nbr++; } /* endif tkn_wrt_rqs_xcp */ } /* end else !idx_all_wrk_ass */ } /* end while loop requesting work/token */ } /* endif Worker */ #else /* !ENABLE_MPI */ } /* end (OpenMP parallel for) loop over idx */ #endif /* !ENABLE_MPI */ if(nco_dbg_lvl >= nco_dbg_fl) (void)fprintf(stderr,"\n"); /* Close input netCDF files */ for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_1_arr[thr_idx]); for(thr_idx=0;thr_idx<thr_nbr;thr_idx++) nco_close(in_id_2_arr[thr_idx]); #ifdef ENABLE_MPI /* Manager moves output file (closed by workers) from temporary to permanent location */ if(prc_rnk == rnk_mgr) (void)nco_fl_mv(fl_out_tmp,fl_out); #else /* !ENABLE_MPI */ /* Close output file and move it from temporary to permanent location */ (void)nco_fl_out_cls(fl_out,fl_out_tmp,out_id); #endif /* end !ENABLE_MPI */ /* Remove local copy of file */ if(FILE_1_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_1); if(FILE_2_RETRIEVED_FROM_REMOTE_LOCATION && RM_RMT_FL_PST_PRC) (void)nco_fl_rm(fl_in_2); /* Clean memory unless dirty memory allowed */ if(flg_mmr_cln){ /* ncbo-specific memory */ if(fl_in_1) fl_in_1=(char *)nco_free(fl_in_1); if(fl_in_2) fl_in_2=(char *)nco_free(fl_in_2); /* NCO-generic clean-up */ /* Free individual strings/arrays */ for(idx=0;idx<nbr_dmn_fl_1;idx++) for(jdx=0;jdx<lmt_all_lst[idx]->lmt_dmn_nbr;jdx++) lmt_all_lst[idx]->lmt_dmn[jdx]=nco_lmt_free(lmt_all_lst[idx]->lmt_dmn[jdx]); if(nbr_dmn_fl_1 > 0) lmt_all_lst=nco_lmt_all_lst_free(lmt_all_lst,nbr_dmn_fl_1); lmt=(lmt_sct**)nco_free(lmt); if(cmd_ln) cmd_ln=(char *)nco_free(cmd_ln); if(cnk_map_sng) cnk_map_sng=(char *)nco_free(cnk_map_sng); if(cnk_plc_sng) cnk_plc_sng=(char *)nco_free(cnk_plc_sng); if(fl_out) fl_out=(char *)nco_free(fl_out); if(fl_out_tmp) fl_out_tmp=(char *)nco_free(fl_out_tmp); if(fl_pth) fl_pth=(char *)nco_free(fl_pth); if(fl_pth_lcl) fl_pth_lcl=(char *)nco_free(fl_pth_lcl); if(in_id_1_arr) in_id_1_arr=(int *)nco_free(in_id_1_arr); if(in_id_2_arr) in_id_2_arr=(int *)nco_free(in_id_2_arr); /* Free lists of strings */ if(fl_lst_in && fl_lst_abb == NULL) fl_lst_in=nco_sng_lst_free(fl_lst_in,fl_nbr); if(fl_lst_in && fl_lst_abb) fl_lst_in=nco_sng_lst_free(fl_lst_in,1); if(fl_lst_abb) fl_lst_abb=nco_sng_lst_free(fl_lst_abb,abb_arg_nbr); if(gaa_nbr > 0) gaa_arg=nco_sng_lst_free(gaa_arg,gaa_nbr); if(var_lst_in_nbr > 0) var_lst_in=nco_sng_lst_free(var_lst_in,var_lst_in_nbr); /* Free limits */ for(idx=0;idx<lmt_nbr;idx++) lmt_arg[idx]=(char *)nco_free(lmt_arg[idx]); for(idx=0;idx<aux_nbr;idx++) aux_arg[idx]=(char *)nco_free(aux_arg[idx]); if(aux_nbr > 0) aux=(lmt_sct **)nco_free(aux); /* Free chunking information */ for(idx=0;idx<cnk_nbr;idx++) cnk_arg[idx]=(char *)nco_free(cnk_arg[idx]); if(cnk_nbr > 0) cnk_dmn=nco_cnk_lst_free(cnk_dmn,cnk_nbr); /* Free dimension lists */ if(nbr_dmn_xtr_1 > 0) dim_1=nco_dmn_lst_free(dim_1,nbr_dmn_xtr_1); if(nbr_dmn_xtr_2 > 0) dim_2=nco_dmn_lst_free(dim_2,nbr_dmn_xtr_2); if(nbr_dmn_xtr_1 > 0) dmn_out=nco_dmn_lst_free(dmn_out,nbr_dmn_xtr_1); /* Free variable lists Using nco_var_lst_free() to free main var_1 and var_2 lists would fail if ncap_var_prc_dmn() had to broadcast any variables because pointer var_1 and var_2 still contain dangling pointer to old variable. Hence, use nco_var_lst_free() to free prc and fix lists and use nco_free() to free main var_1 and var_2 lists. Dangling pointers in var_1 and var_2 are unsafe: fxm TODO 578 */ if(nbr_var_prc_1 > 0) var_prc_1=nco_var_lst_free(var_prc_1,nbr_var_prc_1); if(nbr_var_fix_1 > 0) var_fix_1=nco_var_lst_free(var_fix_1,nbr_var_fix_1); if(nbr_var_prc_2 > 0) var_prc_2=nco_var_lst_free(var_prc_2,nbr_var_prc_2); if(nbr_var_fix_2 > 0) var_fix_2=nco_var_lst_free(var_fix_2,nbr_var_fix_2); var_1=(var_sct **)nco_free(var_1); var_2=(var_sct **)nco_free(var_2); if(xtr_nbr_1 > 0) var_out=nco_var_lst_free(var_out,xtr_nbr_1); var_prc_out=(var_sct **)nco_free(var_prc_out); var_fix_out=(var_sct **)nco_free(var_fix_out); } /* !flg_mmr_cln */ #ifdef ENABLE_MPI MPI_Finalize(); #endif /* !ENABLE_MPI */ /* End timer */ ddra_info.tmr_flg=nco_tmr_end; /* [enm] Timer flag */ rcd+=nco_ddra((char *)NULL,(char *)NULL,&ddra_info); if(rcd != NC_NOERR) nco_err_exit(rcd,"main"); nco_exit_gracefully(); return EXIT_SUCCESS; } /* end main() */
AUC-hybrid.c
// Program: AUC-hybrid // Author: Jason Regina // Date: 12 November 2015 // Description: This program approximates pi using the Riemann Sum method #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <math.h> #include <mpi.h> #include <omp.h> // This function returns a y-value on a unit circle // centered at the origin, given an x-value double func(double x) { return sqrt(1.0 - (x * x)); } int main( int argc, char** argv ) { // Set number of rectangles int recs = 100000000; int num_threads = 1; // Initialize MPI int rank = 0, procs = 0; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &procs); // Parse command line const char* name = argv[0]; int c; while ((c = getopt(argc, argv, "n:t:")) != -1) { switch(c) { case 'n': recs = atoi(optarg); break; case 't': num_threads = atoi(optarg); break; case '?': default: fprintf(stderr, "Usage: %s -n [NUMBER_OF_RECTANGLES] -t [NUM_OMP_THREADS]\n", name); return -1; } } argc -+ optind; argv += optind; // Calculate rectangle width double width; width = 1.0 / recs; // Determine first and last elements of process int first = 0, last = recs; first = rank * (recs / procs); if (rank != (procs - 1)) last = first + (recs / procs); // Set number of OMP_THREADS omp_set_num_threads(num_threads); // Calculate total area double sum = 0.0; int i = 0; #pragma omp parallel for reduction(+:sum) shared(first,last,width) private(i) for (i = first; i < last; i++) { sum += func(width * i) * width * 4.0; } // Calculate total sum double total_sum = 0.0; MPI_Reduce(&sum, &total_sum, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); // Print result if (rank == 0) { printf(" --- %s --- \n", name); printf("Number of processes: %d\n", procs); printf("Threads per process: %d\n", num_threads); printf("Rectangles : %d\n", recs); printf("pi is approximately: %f\n", total_sum); } // Terminate MPI_Finalize(); return 0; }
hello_par.c
#include <stdio.h> #include <omp.h> int main () { int nthreads = 4; omp_set_num_threads(nthreads); #pragma omp parallel { int id = omp_get_thread_num(); printf("Hello World from thread = %d", id); printf(" with %d threads\n",omp_get_num_threads()); } printf("all done, with hopefully %d threads\n",nthreads); }
GB_unop__tanh_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__tanh_fp32_fp32) // op(A') function: GB (_unop_tran__tanh_fp32_fp32) // C type: float // A type: float // cast: float cij = aij // unaryop: cij = tanhf (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 = tanhf (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] = tanhf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TANH || GxB_NO_FP32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__tanh_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] = tanhf (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] = tanhf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__tanh_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_unop__bnot_uint8_uint8.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__bnot_uint8_uint8) // op(A') function: GB (_unop_tran__bnot_uint8_uint8) // C type: uint8_t // A type: uint8_t // cast: uint8_t cij = aij // unaryop: cij = ~(aij) #define GB_ATYPE \ uint8_t #define GB_CTYPE \ uint8_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_CAST(z, aij) \ uint8_t z = aij ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ uint8_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint8_t z = aij ; \ Cx [pC] = ~(z) ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BNOT || GxB_NO_UINT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__bnot_uint8_uint8) ( uint8_t *Cx, // Cx and Ax may be aliased const uint8_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (uint8_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = ~(z) ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; uint8_t aij = Ax [p] ; uint8_t z = aij ; Cx [p] = ~(z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__bnot_uint8_uint8) ( 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
DeclOpenMP.h
//===- DeclOpenMP.h - Classes for representing OpenMP directives -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines OpenMP nodes for declarative directives. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_DECLOPENMP_H #define LLVM_CLANG_AST_DECLOPENMP_H #include "clang/AST/Decl.h" #include "clang/AST/Expr.h" #include "clang/AST/ExternalASTSource.h" #include "clang/AST/Type.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/Support/TrailingObjects.h" namespace clang { /// \brief This represents '#pragma omp threadprivate ...' directive. /// For example, in the following, both 'a' and 'A::b' are threadprivate: /// /// \code /// int a; /// #pragma omp threadprivate(a) /// struct A { /// static int b; /// #pragma omp threadprivate(b) /// }; /// \endcode /// class OMPThreadPrivateDecl final : public Decl, private llvm::TrailingObjects<OMPThreadPrivateDecl, Expr *> { friend class ASTDeclReader; friend TrailingObjects; unsigned NumVars; virtual void anchor(); OMPThreadPrivateDecl(Kind DK, DeclContext *DC, SourceLocation L) : Decl(DK, DC, L), NumVars(0) { } ArrayRef<const Expr *> getVars() const { return llvm::makeArrayRef(getTrailingObjects<Expr *>(), NumVars); } MutableArrayRef<Expr *> getVars() { return MutableArrayRef<Expr *>(getTrailingObjects<Expr *>(), NumVars); } void setVars(ArrayRef<Expr *> VL); public: static OMPThreadPrivateDecl *Create(ASTContext &C, DeclContext *DC, SourceLocation L, ArrayRef<Expr *> VL); static OMPThreadPrivateDecl *CreateDeserialized(ASTContext &C, unsigned ID, unsigned N); typedef MutableArrayRef<Expr *>::iterator varlist_iterator; typedef ArrayRef<const Expr *>::iterator varlist_const_iterator; typedef llvm::iterator_range<varlist_iterator> varlist_range; typedef llvm::iterator_range<varlist_const_iterator> varlist_const_range; unsigned varlist_size() const { return NumVars; } bool varlist_empty() const { return NumVars == 0; } varlist_range varlists() { return varlist_range(varlist_begin(), varlist_end()); } varlist_const_range varlists() const { return varlist_const_range(varlist_begin(), varlist_end()); } varlist_iterator varlist_begin() { return getVars().begin(); } varlist_iterator varlist_end() { return getVars().end(); } varlist_const_iterator varlist_begin() const { return getVars().begin(); } varlist_const_iterator varlist_end() const { return getVars().end(); } static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == OMPThreadPrivate; } }; /// \brief This represents '#pragma omp declare reduction ...' directive. /// For example, in the following, declared reduction 'foo' for types 'int' and /// 'float': /// /// \code /// #pragma omp declare reduction (foo : int,float : omp_out += omp_in) \ /// initializer (omp_priv = 0) /// \endcode /// /// Here 'omp_out += omp_in' is a combiner and 'omp_priv = 0' is an initializer. class OMPDeclareReductionDecl final : public ValueDecl, public DeclContext { public: enum InitKind { CallInit, // Initialized by function call. DirectInit, // omp_priv(<expr>) CopyInit // omp_priv = <expr> }; private: friend class ASTDeclReader; /// \brief Combiner for declare reduction construct. Expr *Combiner; /// \brief Initializer for declare reduction construct. Expr *Initializer; /// Kind of initializer - function call or omp_priv<init_expr> initializtion. InitKind InitializerKind = CallInit; /// \brief Reference to the previous declare reduction construct in the same /// scope with the same name. Required for proper templates instantiation if /// the declare reduction construct is declared inside compound statement. LazyDeclPtr PrevDeclInScope; virtual void anchor(); OMPDeclareReductionDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName Name, QualType Ty, OMPDeclareReductionDecl *PrevDeclInScope) : ValueDecl(DK, DC, L, Name, Ty), DeclContext(DK), Combiner(nullptr), Initializer(nullptr), InitializerKind(CallInit), PrevDeclInScope(PrevDeclInScope) {} void setPrevDeclInScope(OMPDeclareReductionDecl *Prev) { PrevDeclInScope = Prev; } public: /// \brief Create declare reduction node. static OMPDeclareReductionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, QualType T, OMPDeclareReductionDecl *PrevDeclInScope); /// \brief Create deserialized declare reduction node. static OMPDeclareReductionDecl *CreateDeserialized(ASTContext &C, unsigned ID); /// \brief Get combiner expression of the declare reduction construct. Expr *getCombiner() { return Combiner; } const Expr *getCombiner() const { return Combiner; } /// \brief Set combiner expression for the declare reduction construct. void setCombiner(Expr *E) { Combiner = E; } /// \brief Get initializer expression (if specified) of the declare reduction /// construct. Expr *getInitializer() { return Initializer; } const Expr *getInitializer() const { return Initializer; } /// Get initializer kind. InitKind getInitializerKind() const { return InitializerKind; } /// \brief Set initializer expression for the declare reduction construct. void setInitializer(Expr *E, InitKind IK) { Initializer = E; InitializerKind = IK; } /// \brief Get reference to previous declare reduction construct in the same /// scope with the same name. OMPDeclareReductionDecl *getPrevDeclInScope(); const OMPDeclareReductionDecl *getPrevDeclInScope() const; static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == OMPDeclareReduction; } static DeclContext *castToDeclContext(const OMPDeclareReductionDecl *D) { return static_cast<DeclContext *>(const_cast<OMPDeclareReductionDecl *>(D)); } static OMPDeclareReductionDecl *castFromDeclContext(const DeclContext *DC) { return static_cast<OMPDeclareReductionDecl *>( const_cast<DeclContext *>(DC)); } }; /// Pseudo declaration for capturing expressions. Also is used for capturing of /// non-static data members in non-static member functions. /// /// Clang supports capturing of variables only, but OpenMP 4.5 allows to /// privatize non-static members of current class in non-static member /// functions. This pseudo-declaration allows properly handle this kind of /// capture by wrapping captured expression into a variable-like declaration. class OMPCapturedExprDecl final : public VarDecl { friend class ASTDeclReader; void anchor() override; OMPCapturedExprDecl(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, QualType Type, SourceLocation StartLoc) : VarDecl(OMPCapturedExpr, C, DC, StartLoc, SourceLocation(), Id, Type, nullptr, SC_None) { setImplicit(); } public: static OMPCapturedExprDecl *Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, QualType T, SourceLocation StartLoc); static OMPCapturedExprDecl *CreateDeserialized(ASTContext &C, unsigned ID); SourceRange getSourceRange() const override LLVM_READONLY; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { return classofKind(D->getKind()); } static bool classofKind(Kind K) { return K == OMPCapturedExpr; } }; } // end namespace clang #endif
02_tryout_openmp.c
#include<stdio.h> #include<stdlib.h> #include <omp.h> #include<unistd.h> #include <stdlib.h> #include<time.h> #define NUM_THREADS 12 #define STATIC_CHUNK 10 #define DYNAMIC_CHUNK 10 #define NUM_LOOPS 10 #define SLEEP_EVERY_N 3 void replacecharacters(char dnabig[]); // function to replace characters R and W void countA(char dnabig[]); // function to count the number of A's in the sequence of 10^6 int main(int argc, char *argv[]) // main function { double total_time; // variables to calculate time taken by program clock_t start, end; float nStatic1[NUM_LOOPS], nStaticN[NUM_LOOPS]; float nDynamic1[NUM_LOOPS], nDynamicN[NUM_LOOPS]; float nGuided[NUM_LOOPS]; omp_set_num_threads(NUM_THREADS); char dna[]={'A','G','T','C','R','W'}; // array of 6 character char dnabig[1000000]; // initializing array dnabig to contain combination of all 6 characters int randomnumber; //int len=sizeof(dna); omp_set_num_threads(12); start = clock(); srand(time(NULL)); #pragma omp parallel { #pragma omp for schedule(static, 1) //// case of static with chunk size=1 for (int j = 0 ; j < NUM_LOOPS ; ++j) { for(int i=0;i<1000000; i++) // to randomly fill the dbabig array with 10^6 sequence of dna's { randomnumber = rand() % 6; dnabig[i]=dna[randomnumber]; } replacecharacters(dnabig); countA(dnabig); end = clock(); total_time = ((double) (end - start)) / CLOCKS_PER_SEC; nStatic1[j] = total_time; } #pragma omp for schedule(static, STATIC_CHUNK) //// case of static with chunk size=10 for (int j = 0 ; j < NUM_LOOPS ; ++j) { for(int i=0;i<1000000; i++) // to randomly fill the dbabig array with 10^6 sequence of dna's { randomnumber = rand() % 6; dnabig[i]=dna[randomnumber]; } replacecharacters(dnabig); countA(dnabig); end = clock(); total_time = ((double) (end - start)) / CLOCKS_PER_SEC; nStaticN[j] = total_time; } #pragma omp for schedule(dynamic, 1) //// case of dynamic with chunk size=1 for (int j = 0 ; j < NUM_LOOPS ; ++j) { for(int i=0;i<1000000; i++) // to randomly fill the dbabig array with 10^6 sequence of dna's { randomnumber = rand() % 6; dnabig[i]=dna[randomnumber]; } replacecharacters(dnabig); countA(dnabig); end = clock(); total_time = ((double) (end - start)) / CLOCKS_PER_SEC; nDynamic1[j] = total_time; } #pragma omp for schedule(dynamic, DYNAMIC_CHUNK) //// case of dynamic with chunk size=10 for (int j = 0 ; j < NUM_LOOPS ; ++j) { for(int i=0;i<1000000; i++) // to randomly fill the dbabig array with 10^6 sequence of dna's { randomnumber = rand() % 6; dnabig[i]=dna[randomnumber]; } replacecharacters(dnabig); countA(dnabig); end = clock(); total_time = ((double) (end - start)) / CLOCKS_PER_SEC; nDynamicN[j] = total_time; } #pragma omp for schedule(guided) //// case of guided for (int j = 0 ; j < NUM_LOOPS ; ++j) { for(int i=0;i<1000000; i++) // to randomly fill the dbabig array with 10^6 sequence of dna's { randomnumber = rand() % 6; dnabig[i]=dna[randomnumber]; } replacecharacters(dnabig); countA(dnabig); end = clock(); total_time = ((double) (end - start)) / CLOCKS_PER_SEC; nGuided[j] = total_time; } } printf("------------------------------------------------\n"); printf("| static \t| static \t| dynamic \t| dynamic \t| guided |\n"); printf("| 1 \t| %d \t| 1 \t| %d \t| |\n", STATIC_CHUNK, DYNAMIC_CHUNK); printf("------------------------------------------------\n"); for (int i=0; i<NUM_LOOPS; ++i) { printf("| %f | %f | %f | %f | %f |\n", nStatic1[i], nStaticN[i], nDynamic1[i], nDynamicN[i], nGuided[i]); } printf("------------------------------------------------\n"); return 0; } void replacecharacters(char dnabig[]) // function to replace characters R and W { int c=0; int cc=0; //char newseq[1000000]; for(int i=0;i<1000000;i++) { if((dnabig[i]!='R')&&(dnabig[i]!='W')) { //newseq[l]=dnabig[i]; continue; } else if(dnabig[i]=='R') { if(c%2==0) { dnabig[i]='A'; c=c+1; } else { dnabig[i]='G'; c=c+1; } } else if(dnabig[i]=='W') { if(cc%2==0) { dnabig[i]='A'; cc=cc+1; } else { dnabig[i]='T'; cc=cc+1; } } } } void countA(char dnabig[]) // function to count the number of A's in the sequence of 10^6 { int count=0; for(int i=0;i<1000000;i++) { if(dnabig[i]=='A') { count=count+1; } else { continue; } } }
private.c
/* Copyright (c) 2013, Intel Corporation Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /******************************************************************* NAME: RefCount PURPOSE: This program tests the efficiency of exclusive access to a pair of non-adjacent private reference counters USAGE: The program takes as input the total number of times each thread updates its the reference counters, and the number of threads involved. <progname> <# threads><# iterations> The output consists of diagnostics to make sure the algorithm worked, and of timing statistics. FUNCTIONS CALLED: Other than OpenMP or standard C functions, the following functions are used in this program: wtime() bail_out() HISTORY: Written by Rob Van der Wijngaart, January 2006. *******************************************************************/ #include <par-res-kern_general.h> #include <par-res-kern_omp.h> /* choose a default cache line size (bytes); not that if we do not undefine before redefining the variable, we get a warning */ #if !defined(LINE_LENGTH) || LINE_LENGTH < 1 #undef LINE_LENGTH #define LINE_LENGTH 128 #endif int main(int argc, char ** argv) { int iterations; /* number of reference counter updates per thread */ int iter, thread; int line_fit; /* indicates that elements fit on different lines */ s64Int alloc_unit; /* amount of space reserved per element */ s64Int **pcounter1, **pcounter2; /* pointers to pointers to space for counters */ s64Int *counter_space; /* pointer to space reserved for counters */ omp_lock_t **counter_lock; omp_lock_t *lock_space; /* pointer to space reserved for lock handles */ double refcount_time; /* timing parameter */ int nthread_input, nthread; /* number of threads requested and used */ s64Int global_counter1, global_counter2; int num_error=0; /* flag that signals that requested and obtained numbers of threads are the same */ /********************************************************************* ** process and test input parameters *********************************************************************/ if (argc != 3){ printf("Usage: %s <# threads> <# counter pair updates>\n", *argv); exit(EXIT_FAILURE); } nthread_input = atoi(*++argv); if ((nthread_input < 1) || (nthread_input > MAX_THREADS)) { printf("ERROR: Invalid number of threads: %d\n", nthread_input); exit(EXIT_FAILURE); } omp_set_num_threads(nthread_input); iterations = atoi(*++argv); if (iterations < 1){ printf("ERROR: iterations must be >= 1 : %d \n",iterations); exit(EXIT_FAILURE); } /* allocate the locks on which we will be pounding; we put them on different cache lines, if possible */ counter_lock = (omp_lock_t **) malloc(nthread_input*sizeof(omp_lock_t *)); if (!counter_lock) { printf("Not able to allocate memory for counter lock handles\n"); exit(EXIT_FAILURE); } /* we try to put counter locks on different cache lines */ line_fit = 1; if (sizeof(omp_lock_t) > LINE_LENGTH) alloc_unit = (sizeof(omp_lock_t)/LINE_LENGTH+1)*LINE_LENGTH; else alloc_unit = LINE_LENGTH; lock_space = (omp_lock_t *) malloc(2*nthread_input*alloc_unit); while (!lock_space && alloc_unit >= 2*sizeof(s64Int)) { line_fit = 0; alloc_unit/=2; lock_space = (omp_lock_t *)malloc(2*nthread_input*alloc_unit); } if (!lock_space) { printf("Not able to allocate memory for lock handles\n"); exit(EXIT_FAILURE); } #ifdef VERBOSE if (!line_fit) printf("Lock handles do not fit on separate cache lines\n"); else printf("Lock handles fit on separate cache lines\n"); #endif /* we try to put private counters on different cache lines */ pcounter1 = (s64Int **) malloc(nthread_input*sizeof(s64Int *)); pcounter2 = (s64Int **) malloc(nthread_input*sizeof(s64Int *)); if (!pcounter1 || !pcounter2) { printf("Not able to allocate memory for reference counter pointers\n"); exit(EXIT_FAILURE); } line_fit = 1; if (sizeof(s64Int) > LINE_LENGTH) alloc_unit = (sizeof(s64Int)/LINE_LENGTH+1)*LINE_LENGTH; else alloc_unit = LINE_LENGTH; counter_space = malloc(2*nthread_input*alloc_unit); while (!counter_space && alloc_unit >= 2*sizeof(s64Int)) { line_fit = 0; alloc_unit/=2; counter_space = malloc(2*nthread_input*alloc_unit); } if (!counter_space) { printf("Not able to allocate memory for reference counters\n"); exit(EXIT_FAILURE); } #ifdef VERBOSE printf("Cache line size used: %d bytes\n", LINE_LENGTH); if (!line_fit) printf("Counters do not fit on separate cache lines\n"); else printf("Counters fit on separate cache lines\n"); #endif #pragma omp parallel { int my_ID; /* Thread ID */ int iter; /* dummy */ my_ID = omp_get_thread_num(); /* for maximum performance we rely on first touch and parallel initialization */ /* each thread initializes its own counters */ pcounter1[my_ID] = (s64Int *)((char *)counter_space + my_ID*2*alloc_unit); pcounter2[my_ID] = (s64Int *)((char *)counter_space + (my_ID*2+1)*alloc_unit); *(pcounter1[my_ID]) = 0; *(pcounter2[my_ID]) = 0; /* each thread initializes its own lock */ counter_lock[my_ID] = (omp_lock_t *)((char *)lock_space + my_ID*alloc_unit); omp_init_lock(counter_lock[my_ID]); #pragma omp master { nthread = omp_get_num_threads(); printf("OpenMP exclusive access test RefCount, private counters\n"); if (nthread != nthread_input) { num_error = 1; printf("ERROR: number of requested threads %d does not equal ", nthread_input); printf("number of spawned threads %d\n", nthread); } else { printf("Number of threads = %i;\n",nthread_input); printf("Number of counter pair updates = %i\n", iterations); #ifndef LOCK printf("Not "); #endif printf("using (uncontended) locks\n"); } } bail_out(num_error); #pragma omp master { refcount_time = wtime(); } #pragma omp for for (iter=0; iter<iterations; iter++) { #ifdef LOCK omp_set_lock(counter_lock[my_ID]); #endif (*(pcounter1[my_ID]))++; (*(pcounter2[my_ID]))++; #ifdef LOCK omp_unset_lock(counter_lock[my_ID]); #endif } #pragma omp master { refcount_time = (wtime() - refcount_time); } } /* end of OpenMP parallel region */ global_counter1 = global_counter2 = 0; for (thread=0; thread<nthread; thread++) { global_counter1 += *(pcounter1[thread]); global_counter2 += *(pcounter2[thread]); } if (global_counter1 != iterations || global_counter1 != global_counter2 ) { printf("Incorrect or inconsistent counter sum values: "FSTR64U", "FSTR64U";", global_counter1, global_counter2); printf(" should be %d\n", iterations); exit(EXIT_FAILURE); } else { #ifdef VERBOSE printf("Solution validates; Correct counter value sum of "FSTR64"\n", global_counter1); #else printf("Solution validates\n"); #endif printf("Rate (CPUPs/s): %d, time (s): %lf\n", (int)(iterations/refcount_time), refcount_time); } exit(EXIT_SUCCESS); }
IntegratorHPMCMonoImplicit.h
// Copyright (c) 2009-2016 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. #ifndef __HPMC_MONO_IMPLICIT__H__ #define __HPMC_MONO_IMPLICIT__H__ #include "IntegratorHPMCMono.h" #include "hoomd/Autotuner.h" #include <random> #ifdef _OPENMP #include <omp.h> #endif /*! \file IntegratorHPMCMonoImplicit.h \brief Defines the template class for HPMC with implicit generated depletant solvent \note This header cannot be compiled by nvcc */ #ifdef NVCC #error This header cannot be compiled by nvcc #endif #include <hoomd/extern/pybind/include/pybind11/pybind11.h> namespace hpmc { //! Template class for HPMC update with implicit depletants /*! Depletants are generated randomly on the fly according to the semi-grand canonical ensemble. The penetrable depletants model is simulated. \ingroup hpmc_integrators */ template< class Shape > class IntegratorHPMCMonoImplicit : public IntegratorHPMCMono<Shape> { public: //! Construct the integrator IntegratorHPMCMonoImplicit(std::shared_ptr<SystemDefinition> sysdef, unsigned int seed); //! Destructor virtual ~IntegratorHPMCMonoImplicit(); //! Set the depletant density in the free volume void setDepletantDensity(Scalar n_R) { m_n_R = n_R; m_need_initialize_poisson = true; } //! Set the type of depletant particle void setDepletantType(unsigned int type) { m_type = type; } //! Number of depletant-reinsertions /*! \param n_trial Depletant reinsertions per overlapping depletant */ void setNTrial(unsigned int n_trial) { m_n_trial = n_trial; } //! Return number of depletant re-insertions unsigned int getNTrial() { return m_n_trial; } //! Returns the depletant density Scalar getDepletantDensity() { return m_n_R; } //! Return the depletant type unsigned int getDepletantType() { return m_type; } //! Return the number of re-insertion trials unsigned int getNumTrials() const { return m_n_trial; } //! Reset statistics counters virtual void resetStats() { IntegratorHPMCMono<Shape>::resetStats(); ArrayHandle<hpmc_implicit_counters_t> h_counters(m_implicit_count, access_location::host, access_mode::read); m_implicit_count_run_start = h_counters.data[0]; } //! Print statistics about the hpmc steps taken virtual void printStats() { IntegratorHPMCMono<Shape>::printStats(); hpmc_implicit_counters_t result = getImplicitCounters(1); double cur_time = double(this->m_clock.getTime()) / Scalar(1e9); this->m_exec_conf->msg->notice(2) << "-- Implicit depletants stats:" << "\n"; this->m_exec_conf->msg->notice(2) << "Depletant insertions per second: " << double(result.insert_count)/cur_time << "\n"; this->m_exec_conf->msg->notice(2) << "Configurational bias attempts per second: " << double(result.reinsert_count)/cur_time << "\n"; this->m_exec_conf->msg->notice(2) << "Fraction of depletants in free volume: " << result.getFreeVolumeFraction() << "\n"; this->m_exec_conf->msg->notice(2) << "Fraction of overlapping depletants: " << result.getOverlapFraction()<< "\n"; } //! Get the current counter values hpmc_implicit_counters_t getImplicitCounters(unsigned int mode=0); /* \returns a list of provided quantities */ std::vector< std::string > getProvidedLogQuantities() { // start with the integrator provided quantities std::vector< std::string > result = IntegratorHPMCMono<Shape>::getProvidedLogQuantities(); // then add ours result.push_back("hpmc_fugacity"); result.push_back("hpmc_ntrial"); result.push_back("hpmc_insert_count"); result.push_back("hpmc_reinsert_count"); result.push_back("hpmc_free_volume_fraction"); result.push_back("hpmc_overlap_fraction"); result.push_back("hpmc_configurational_bias_ratio"); return result; } //! Get the value of a logged quantity virtual Scalar getLogValue(const std::string& quantity, unsigned int timestep); //! Method to scale the box virtual bool attemptBoxResize(unsigned int timestep, const BoxDim& new_box); //! Slot to be called when number of types changes void slotNumTypesChange(); protected: Scalar m_n_R; //!< Averge depletant number density in free volume unsigned int m_type; //!< Type of depletant particle to generate GPUArray<hpmc_implicit_counters_t> m_implicit_count; //!< Counter of active cell cluster moves hpmc_implicit_counters_t m_implicit_count_run_start; //!< Counter of active cell cluster moves at run start hpmc_implicit_counters_t m_implicit_count_step_start; //!< Counter of active cell cluster moves at run start std::vector<std::poisson_distribution<unsigned int> > m_poisson; //!< Poisson distribution std::vector<Scalar> m_lambda; //!< Poisson distribution parameters per type Scalar m_d_dep; //!< Depletant circumsphere diameter GPUArray<Scalar> m_d_min; //!< Minimum sphere from which test depletant is excluded GPUArray<Scalar> m_d_max; //!< Maximum sphere for test depletant insertion std::vector<hoomd::detail::Saru> m_rng_depletant; //!< RNGs for depletant insertion bool m_rng_initialized; //!< True if RNGs have been initialized unsigned int m_n_trial; //!< Number of trial re-insertions per depletant bool m_need_initialize_poisson; //!< Flag to tell if we need to initialize the poisson distribution //! Take one timestep forward virtual void update(unsigned int timestep); //! Initalize Poisson distribution parameters virtual void updatePoissonParameters(); //! Initialize the Poisson distributions virtual void initializePoissonDistribution(); //! Set the nominal width appropriate for depletion interaction virtual void updateCellWidth(); //! Generate a random depletant position in a sphere around a particle template<class RNG> inline void generateDepletant(RNG& rng, vec3<Scalar> pos_sphere, Scalar delta, Scalar d_min, vec3<Scalar>& pos, quat<Scalar>& orientation, const typename Shape::param_type& params_depletants); /*! Generate a random depletant position in a region including the sphere around a particle, restricted so that it does not intersect another sphere */ template<class RNG> inline void generateDepletantRestricted(RNG& rng, vec3<Scalar> pos_sphere, Scalar delta, Scalar delta_other, vec3<Scalar>& pos, quat<Scalar>& orientation, const typename Shape::param_type& params_depletants, vec3<Scalar> pos_sphere_other); //! Try inserting a depletant in a configuration such that it overlaps with the particle in the old (new) configuration inline bool insertDepletant(vec3<Scalar>& pos_depletant, const Shape& shape_depletant, unsigned int idx, typename Shape::param_type *h_params, unsigned int *h_overlaps, unsigned int typ_i, Scalar4 *h_postype, Scalar4 *h_orientation, vec3<Scalar> pos_new, quat<Scalar>& orientation_new, const typename Shape::param_type& params_new, unsigned int &overlap_checks, unsigned int &overlap_err_count, bool &overlap_shape, bool new_config); }; /*! \param sysdef System definition \param cl Cell list \param seed Random number generator seed NOTE: only 3d supported at this time */ template< class Shape > IntegratorHPMCMonoImplicit< Shape >::IntegratorHPMCMonoImplicit(std::shared_ptr<SystemDefinition> sysdef, unsigned int seed) : IntegratorHPMCMono<Shape>(sysdef, seed), m_n_R(0), m_type(0), m_d_dep(0.0), m_rng_initialized(false), m_n_trial(0), m_need_initialize_poisson(true) { this->m_exec_conf->msg->notice(5) << "Constructing IntegratorHPMCImplicit" << std::endl; GPUArray<hpmc_implicit_counters_t> implicit_count(1,this->m_exec_conf); m_implicit_count.swap(implicit_count); GPUArray<Scalar> d_min(this->m_pdata->getNTypes(), this->m_exec_conf); m_d_min.swap(d_min); GPUArray<Scalar> d_max(this->m_pdata->getNTypes(), this->m_exec_conf); m_d_max.swap(d_max); m_lambda.resize(this->m_pdata->getNTypes(),FLT_MAX); if (this->m_sysdef->getNDimensions() == 2) { throw std::runtime_error("2D runs not supported for this integrator."); } } //! Destructor template< class Shape > IntegratorHPMCMonoImplicit< Shape >::~IntegratorHPMCMonoImplicit() { } template <class Shape> void IntegratorHPMCMonoImplicit<Shape>::slotNumTypesChange() { // call parent class method IntegratorHPMCMono<Shape>::slotNumTypesChange(); m_lambda.resize(this->m_pdata->getNTypes(),FLT_MAX); GPUArray<Scalar> d_min(this->m_pdata->getNTypes(), this->m_exec_conf); m_d_min.swap(d_min); GPUArray<Scalar> d_max(this->m_pdata->getNTypes(), this->m_exec_conf); m_d_max.swap(d_max); m_need_initialize_poisson = true; } template< class Shape > void IntegratorHPMCMonoImplicit< Shape >::updatePoissonParameters() { ArrayHandle<typename Shape::param_type> h_params(this->m_params, access_location::host, access_mode::read); // Depletant diameter quat<Scalar> o; Shape shape_depletant(o, h_params.data[this->m_type]); m_d_dep = shape_depletant.getCircumsphereDiameter(); // access GPUArrays ArrayHandle<Scalar> h_d_min(m_d_min, access_location::host, access_mode::overwrite); ArrayHandle<Scalar> h_d_max(m_d_max, access_location::host, access_mode::overwrite); for (unsigned int i_type = 0; i_type < this->m_pdata->getNTypes(); ++i_type) { // test sphere diameter and volume Shape shape_i(quat<Scalar>(), h_params.data[i_type]); Scalar delta = shape_i.getCircumsphereDiameter()+m_d_dep; h_d_max.data[i_type] = delta; // volume of insertion sphere Scalar V = Scalar(M_PI/6.0)*delta*delta*delta; // Minimum diameter of colloid sphere in which depletant can be inserted without overlapping with other colloids // Scalar d = std::max(Scalar(2.0)*shape_i.getInsphereRadius()-m_d_dep,0.0); Scalar d = Scalar(0.0); h_d_min.data[i_type] = d; // subtract inner sphere from sampling volume V -= Scalar(M_PI/6.0)*d*d*d; // average number of depletants in volume m_lambda[i_type] = this->m_n_R*V; } } template<class Shape> void IntegratorHPMCMonoImplicit< Shape >::initializePoissonDistribution() { m_poisson.resize(this->m_pdata->getNTypes()); for (unsigned int i_type = 0; i_type < this->m_pdata->getNTypes(); ++i_type) { // parameter for Poisson distribution Scalar lambda = m_lambda[i_type]; if (lambda <= Scalar(0.0)) { // guard against invalid parameters continue; } m_poisson[i_type] = std::poisson_distribution<unsigned int>(lambda); } } template< class Shape > void IntegratorHPMCMonoImplicit< Shape >::updateCellWidth() { this->m_nominal_width = this->getMaxDiameter(); if (m_n_R > Scalar(0.0)) { // add range of depletion interaction ArrayHandle<typename Shape::param_type> h_params(this->m_params, access_location::host, access_mode::read); quat<Scalar> o; Shape tmp(o, h_params.data[m_type]); this->m_nominal_width += tmp.getCircumsphereDiameter(); } this->m_exec_conf->msg->notice(5) << "IntegratorHPMCMonoImplicit: updating nominal width to " << this->m_nominal_width << std::endl; } template< class Shape > void IntegratorHPMCMonoImplicit< Shape >::update(unsigned int timestep) { this->m_exec_conf->msg->notice(10) << "HPMCMonoImplicit update: " << timestep << std::endl; IntegratorHPMC::update(timestep); // update poisson distributions if (m_need_initialize_poisson) { updatePoissonParameters(); initializePoissonDistribution(); m_need_initialize_poisson = false; } if (!m_rng_initialized) { unsigned int n_omp_threads = 1; #ifdef _OPENMP n_omp_threads = omp_get_max_threads(); #endif // initialize a set of random number generators for (unsigned int i = 0; i < n_omp_threads; ++i) { m_rng_depletant.push_back(hoomd::detail::Saru(timestep,this->m_seed+this->m_exec_conf->getRank(), i)); } m_rng_initialized = true; } // get needed vars ArrayHandle<hpmc_counters_t> h_counters(this->m_count_total, access_location::host, access_mode::readwrite); hpmc_counters_t& counters = h_counters.data[0]; ArrayHandle<hpmc_implicit_counters_t> h_implicit_counters(m_implicit_count, access_location::host, access_mode::readwrite); hpmc_implicit_counters_t& implicit_counters = h_implicit_counters.data[0]; m_implicit_count_step_start = implicit_counters; const BoxDim& box = this->m_pdata->getBox(); unsigned int ndim = this->m_sysdef->getNDimensions(); #ifdef ENABLE_MPI // compute the width of the active region Scalar3 npd = box.getNearestPlaneDistance(); Scalar3 ghost_fraction = this->m_nominal_width / npd; #endif // Shuffle the order of particles for this step this->m_update_order.resize(this->m_pdata->getN()); this->m_update_order.shuffle(timestep); // update the AABB Tree this->buildAABBTree(); // limit m_d entries so that particles cannot possibly wander more than one box image in one time step this->limitMoveDistances(); // update the image list this->updateImageList(); // combine the three seeds std::vector<unsigned int> seed_seq(3); seed_seq[0] = this->m_seed; seed_seq[1] = timestep; seed_seq[2] = this->m_exec_conf->getRank(); std::seed_seq seed(seed_seq.begin(), seed_seq.end()); // RNG for poisson distribution std::mt19937 rng_poisson(seed); if (this->m_prof) this->m_prof->push(this->m_exec_conf, "HPMC implicit"); // access depletant insertion sphere dimensions ArrayHandle<Scalar> h_d_min(m_d_min, access_location::host, access_mode::read); ArrayHandle<Scalar> h_d_max(m_d_max, access_location::host, access_mode::read); // loop over local particles nselect times for (unsigned int i_nselect = 0; i_nselect < this->m_nselect; i_nselect++) { // access particle data and system box ArrayHandle<Scalar4> h_postype(this->m_pdata->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<Scalar4> h_orientation(this->m_pdata->getOrientationArray(), access_location::host, access_mode::readwrite); // access parameters and interaction matrix ArrayHandle<typename Shape::param_type> h_params(this->m_params, access_location::host, access_mode::read); ArrayHandle<unsigned int> h_overlaps(this->m_overlaps, access_location::host, access_mode::read); //access move sizes ArrayHandle<Scalar> h_d(this->m_d, access_location::host, access_mode::read); ArrayHandle<Scalar> h_a(this->m_a, access_location::host, access_mode::read); // loop through N particles in a shuffled order for (unsigned int cur_particle = 0; cur_particle < this->m_pdata->getN(); cur_particle++) { unsigned int i = this->m_update_order[cur_particle]; // read in the current position and orientation Scalar4 postype_i = h_postype.data[i]; Scalar4 orientation_i = h_orientation.data[i]; vec3<Scalar> pos_i = vec3<Scalar>(postype_i); #ifdef ENABLE_MPI if (this->m_comm) { // only move particle if active if (!isActive(make_scalar3(postype_i.x, postype_i.y, postype_i.z), box, ghost_fraction)) continue; } #endif // make a trial move for i hoomd::detail::Saru rng_i(i, this->m_seed + this->m_exec_conf->getRank()*this->m_nselect + i_nselect, timestep); int typ_i = __scalar_as_int(postype_i.w); Shape shape_i(quat<Scalar>(orientation_i), h_params.data[typ_i]); unsigned int move_type_select = rng_i.u32() & 0xffff; bool move_type_translate = !shape_i.hasOrientation() || (move_type_select < this->m_move_ratio); if (move_type_translate) { move_translate(pos_i, rng_i, h_d.data[typ_i], ndim); #ifdef ENABLE_MPI if (this->m_comm) { // check if particle has moved into the ghost layer, and skip if it is if (!isActive(vec_to_scalar3(pos_i), box, ghost_fraction)) continue; } #endif } else { move_rotate(shape_i.orientation, rng_i, h_a.data[typ_i], ndim); } // check for overlaps with neighboring particle's positions bool overlap=false; detail::AABB aabb_i_local = shape_i.getAABB(vec3<Scalar>(0,0,0)); // All image boxes (including the primary) const unsigned int n_images = this->m_image_list.size(); for (unsigned int cur_image = 0; cur_image < n_images; cur_image++) { vec3<Scalar> pos_i_image = pos_i + this->m_image_list[cur_image]; detail::AABB aabb = aabb_i_local; aabb.translate(pos_i_image); // stackless search for (unsigned int cur_node_idx = 0; cur_node_idx < this->m_aabb_tree.getNumNodes(); cur_node_idx++) { if (detail::overlap(this->m_aabb_tree.getNodeAABB(cur_node_idx), aabb)) { if (this->m_aabb_tree.isNodeLeaf(cur_node_idx)) { for (unsigned int cur_p = 0; cur_p < this->m_aabb_tree.getNodeNumParticles(cur_node_idx); cur_p++) { // read in its position and orientation unsigned int j = this->m_aabb_tree.getNodeParticle(cur_node_idx, cur_p); Scalar4 postype_j; Scalar4 orientation_j; // handle j==i situations if ( j != i ) { // load the position and orientation of the j particle postype_j = h_postype.data[j]; orientation_j = h_orientation.data[j]; } else { if (cur_image == 0) { // in the first image, skip i == j continue; } else { // If this is particle i and we are in an outside image, use the translated position and orientation postype_j = make_scalar4(pos_i.x, pos_i.y, pos_i.z, postype_i.w); orientation_j = quat_to_scalar4(shape_i.orientation); } } // put particles in coordinate system of particle i vec3<Scalar> r_ij = vec3<Scalar>(postype_j) - pos_i_image; unsigned int typ_j = __scalar_as_int(postype_j.w); Shape shape_j(quat<Scalar>(orientation_j), h_params.data[typ_j]); counters.overlap_checks++; // check circumsphere overlap OverlapReal rsq = dot(r_ij,r_ij); OverlapReal DaDb = shape_i.getCircumsphereDiameter() + shape_j.getCircumsphereDiameter(); bool circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); if (h_overlaps.data[this->m_overlap_idx(typ_i,typ_j)] && circumsphere_overlap && test_overlap(r_ij, shape_i, shape_j, counters.overlap_err_count)) { overlap = true; break; } } } } else { // skip ahead cur_node_idx += this->m_aabb_tree.getNodeSkip(cur_node_idx); } if (overlap) break; } // end loop over AABB nodes if (overlap) break; } // end loop over images // whether the move is accepted bool accept = !overlap; if (!overlap) { // log of acceptance probability Scalar lnb(0.0); unsigned int zero = 0; // The trial move is valid. Now generate random depletant particles in a sphere // of radius (d_max+d_depletant+move size)/2.0 around the original particle position // draw number from Poisson distribution unsigned int n = 0; if (m_lambda[typ_i] > Scalar(0.0)) { n = m_poisson[typ_i](rng_poisson); } unsigned int n_overlap_checks = 0; unsigned int overlap_err_count = 0; unsigned int insert_count = 0; unsigned int reinsert_count = 0; unsigned int free_volume_count = 0; unsigned int overlap_count = 0; volatile bool flag=false; #pragma omp parallel for reduction(+ : lnb, n_overlap_checks, overlap_err_count, insert_count, reinsert_count, free_volume_count, overlap_count) reduction(max: zero) shared(flag) if (n>0) schedule(dynamic) for (unsigned int k = 0; k < n; ++k) { if (flag) { #ifndef _OPENMP break; #else continue; #endif } insert_count++; // generate a random depletant coordinate and orientation in the sphere around the new position vec3<Scalar> pos_test; quat<Scalar> orientation_test; #ifdef _OPENMP unsigned int thread_idx = omp_get_thread_num(); #else unsigned int thread_idx = 0; #endif generateDepletant(m_rng_depletant[thread_idx], pos_i, h_d_max.data[typ_i], h_d_min.data[typ_i], pos_test, orientation_test, h_params.data[m_type]); Shape shape_test(orientation_test, h_params.data[m_type]); detail::AABB aabb_test_local = shape_test.getAABB(vec3<Scalar>(0,0,0)); bool overlap_depletant = false; // Check if the new configuration of particle i generates an overlap for (unsigned int cur_image = 0; cur_image < n_images; cur_image++) { vec3<Scalar> pos_test_image = pos_test + this->m_image_list[cur_image]; detail::AABB aabb = aabb_test_local; aabb.translate(pos_test_image); vec3<Scalar> r_ij = pos_i - pos_test_image; n_overlap_checks++; // check circumsphere overlap OverlapReal rsq = dot(r_ij,r_ij); OverlapReal DaDb = shape_test.getCircumsphereDiameter() + shape_i.getCircumsphereDiameter(); bool circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); if (h_overlaps.data[this->m_overlap_idx(m_type, typ_i)] && circumsphere_overlap && test_overlap(r_ij, shape_test, shape_i, overlap_err_count)) { overlap_depletant = true; overlap_count++; break; } } if (overlap_depletant) { // check against overlap with old position bool overlap_old = false; // All image boxes (including the primary) const unsigned int n_images = this->m_image_list.size(); for (unsigned int cur_image = 0; cur_image < n_images; cur_image++) { vec3<Scalar> pos_test_image = pos_test + this->m_image_list[cur_image]; detail::AABB aabb = aabb_test_local; aabb.translate(pos_test_image); // stackless search for (unsigned int cur_node_idx = 0; cur_node_idx < this->m_aabb_tree.getNumNodes(); cur_node_idx++) { if (detail::overlap(this->m_aabb_tree.getNodeAABB(cur_node_idx), aabb)) { if (this->m_aabb_tree.isNodeLeaf(cur_node_idx)) { for (unsigned int cur_p = 0; cur_p < this->m_aabb_tree.getNodeNumParticles(cur_node_idx); cur_p++) { // read in its position and orientation unsigned int j = this->m_aabb_tree.getNodeParticle(cur_node_idx, cur_p); Scalar4 postype_j; Scalar4 orientation_j; // load the old position and orientation of the j particle postype_j = h_postype.data[j]; orientation_j = h_orientation.data[j]; // put particles in coordinate system of particle i vec3<Scalar> r_ij = vec3<Scalar>(postype_j) - pos_test_image; unsigned int typ_j = __scalar_as_int(postype_j.w); Shape shape_j(quat<Scalar>(orientation_j), h_params.data[typ_j]); n_overlap_checks++; // check circumsphere overlap OverlapReal rsq = dot(r_ij,r_ij); OverlapReal DaDb = shape_test.getCircumsphereDiameter() + shape_j.getCircumsphereDiameter(); bool circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); if (h_overlaps.data[this->m_overlap_idx(m_type,typ_j)] && circumsphere_overlap && test_overlap(r_ij, shape_test, shape_j, overlap_err_count)) { // depletant is ignored for any overlap in the old configuration overlap_old = true; break; } } } } else { // skip ahead cur_node_idx += this->m_aabb_tree.getNodeSkip(cur_node_idx); } if (overlap_old) break; } // end loop over AABB nodes if (overlap_old) break; } // end loop over images if (!overlap_old) { free_volume_count++; } else { // the depletant overlap doesn't count since it was already overlapping // in the old configuration overlap_depletant = false; } } if (overlap_depletant && !m_n_trial) { zero = 1; // break out of loop flag = true; } else if (overlap_depletant && m_n_trial) { const typename Shape::param_type& params_depletant = h_params.data[m_type]; // Number of successful depletant insertions in new configuration unsigned int n_success_new = 0; // Number of allowed insertion trials (those which overlap with colloid at old position) unsigned int n_overlap_shape_new = 0; // diameter (around origin) in which we are guaruanteed to intersect with the shape Scalar delta_insphere = Scalar(2.0)*shape_i.getInsphereRadius(); // same for old reverse move. Because we have already sampled one successful insertion // that overlaps with the colloid at the new position, we increment by one (super-detailed // balance) unsigned int n_success_old = 1; unsigned int n_overlap_shape_old = 1; Scalar4& postype_i_old = h_postype.data[i]; vec3<Scalar> pos_i_old(postype_i_old); quat<Scalar> orientation_i_old(h_orientation.data[i]); for (unsigned int l = 0; l < m_n_trial; ++l) { // generate a random depletant position and orientation // in both the old and the new configuration of the colloid particle vec3<Scalar> pos_depletant_old, pos_depletant_new; quat<Scalar> orientation_depletant_old, orientation_depletant_new; // try moving the overlapping depletant in the excluded volume // such that it overlaps with the particle at the old position generateDepletantRestricted(m_rng_depletant[thread_idx], pos_i_old, h_d_max.data[typ_i], delta_insphere, pos_depletant_new, orientation_depletant_new, params_depletant, pos_i); reinsert_count++; Shape shape_depletant_new(orientation_depletant_new, params_depletant); const typename Shape::param_type& params_i = h_params.data[__scalar_as_int(postype_i_old.w)]; bool overlap_shape = false; if (insertDepletant(pos_depletant_new, shape_depletant_new, i, h_params.data, h_overlaps.data, typ_i, h_postype.data, h_orientation.data, pos_i, shape_i.orientation, params_i, n_overlap_checks, overlap_err_count, overlap_shape, false)) { n_success_new++; } if (overlap_shape) { // depletant overlaps with colloid at old position n_overlap_shape_new++; } if (l >= 1) { // as above, in excluded volume sphere at new position generateDepletantRestricted(m_rng_depletant[thread_idx], pos_i, h_d_max.data[typ_i], delta_insphere, pos_depletant_old, orientation_depletant_old, params_depletant, pos_i_old); Shape shape_depletant_old(orientation_depletant_old, params_depletant); if (insertDepletant(pos_depletant_old, shape_depletant_old, i, h_params.data, h_overlaps.data, typ_i, h_postype.data, h_orientation.data, pos_i, shape_i.orientation, params_i, n_overlap_checks, overlap_err_count, overlap_shape, true)) { n_success_old++; } if (overlap_shape) { // depletant overlaps with colloid at new position n_overlap_shape_old++; } reinsert_count++; } n_overlap_checks += counters.overlap_checks; overlap_err_count += counters.overlap_err_count; } // end loop over re-insertion attempts if (n_success_new != 0) { lnb += log((Scalar)n_success_new/(Scalar)n_overlap_shape_new); lnb -= log((Scalar)n_success_old/(Scalar)n_overlap_shape_old); } else { zero = 1; // break out of loop flag = true; } } // end if depletant overlap } // end loop over depletants // increment counters counters.overlap_checks += n_overlap_checks; counters.overlap_err_count += overlap_err_count; implicit_counters.insert_count += insert_count; implicit_counters.free_volume_count += free_volume_count; implicit_counters.overlap_count += overlap_count; implicit_counters.reinsert_count += reinsert_count; // apply acceptance criterium if (!zero) { accept = rng_i.f() < exp(lnb); } else { accept = false; } } // end depletant placement // if the move is accepted if (accept) { // increment accept counter and assign new position if (!shape_i.ignoreStatistics()) { if (move_type_translate) counters.translate_accept_count++; else counters.rotate_accept_count++; } // update the position of the particle in the tree for future updates detail::AABB aabb = aabb_i_local; aabb.translate(pos_i); this->m_aabb_tree.update(i, aabb); // update position of particle h_postype.data[i] = make_scalar4(pos_i.x,pos_i.y,pos_i.z,postype_i.w); if (shape_i.hasOrientation()) { h_orientation.data[i] = quat_to_scalar4(shape_i.orientation); } } else { if (!shape_i.ignoreStatistics()) { // increment reject counter if (move_type_translate) counters.translate_reject_count++; else counters.rotate_reject_count++; } } } // end loop over all particles } // end loop over nselect { ArrayHandle<Scalar4> h_postype(this->m_pdata->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<int3> h_image(this->m_pdata->getImages(), access_location::host, access_mode::readwrite); // wrap particles back into box for (unsigned int i = 0; i < this->m_pdata->getN(); i++) { box.wrap(h_postype.data[i], h_image.data[i]); } } // perform the grid shift #ifdef ENABLE_MPI if (this->m_comm) { ArrayHandle<Scalar4> h_postype(this->m_pdata->getPositions(), access_location::host, access_mode::readwrite); ArrayHandle<int3> h_image(this->m_pdata->getImages(), access_location::host, access_mode::readwrite); // precalculate the grid shift hoomd::detail::Saru rng(timestep, this->m_seed, 0xf4a3210e); Scalar3 shift = make_scalar3(0,0,0); shift.x = rng.s(-this->m_nominal_width/Scalar(2.0),this->m_nominal_width/Scalar(2.0)); shift.y = rng.s(-this->m_nominal_width/Scalar(2.0),this->m_nominal_width/Scalar(2.0)); if (this->m_sysdef->getNDimensions() == 3) { shift.z = rng.s(-this->m_nominal_width/Scalar(2.0),this->m_nominal_width/Scalar(2.0)); } for (unsigned int i = 0; i < this->m_pdata->getN(); i++) { // read in the current position and orientation Scalar4 postype_i = h_postype.data[i]; vec3<Scalar> r_i = vec3<Scalar>(postype_i); // translation from local to global coordinates r_i += vec3<Scalar>(shift); h_postype.data[i] = vec_to_scalar4(r_i, postype_i.w); box.wrap(h_postype.data[i], h_image.data[i]); } this->m_pdata->translateOrigin(shift); } #endif if (this->m_prof) this->m_prof->pop(this->m_exec_conf); // migrate and exchange particles this->communicate(true); // all particle have been moved, the aabb tree is now invalid this->m_aabb_tree_invalid = true; } /* \param rng The random number generator * \param pos_sphere Center of sphere * \param delta diameter of sphere * \param d_min Diameter of smaller sphere excluding depletant * \param pos Position of depletant (return value) * \param orientation ion of depletant (return value) * \param params_depletant Depletant parameters */ template<class Shape> template<class RNG> inline void IntegratorHPMCMonoImplicit<Shape>::generateDepletant(RNG& rng, vec3<Scalar> pos_sphere, Scalar delta, Scalar d_min, vec3<Scalar>& pos, quat<Scalar>& orientation, const typename Shape::param_type& params_depletant) { // draw a random vector in the excluded volume sphere of the colloid Scalar theta = rng.template s<Scalar>(Scalar(0.0),Scalar(2.0*M_PI)); Scalar z = rng.template s<Scalar>(Scalar(-1.0),Scalar(1.0)); // random normalized vector vec3<Scalar> n(fast::sqrt(Scalar(1.0)-z*z)*fast::cos(theta),fast::sqrt(Scalar(1.0)-z*z)*fast::sin(theta),z); // draw random radial coordinate in test sphere Scalar r3 = rng.template s<Scalar>(fast::pow(d_min/delta,Scalar(3.0)),Scalar(1.0)); Scalar r = Scalar(0.5)*delta*fast::pow(r3,Scalar(1.0/3.0)); // test depletant position vec3<Scalar> pos_depletant = pos_sphere+r*n; Shape shape_depletant(quat<Scalar>(), params_depletant); if (shape_depletant.hasOrientation()) { orientation = generateRandomOrientation(rng); } pos = pos_depletant; } /* \param rng The random number generator * \param pos_sphere Center of sphere * \param delta diameter of sphere * \param delta_other diameter of other sphere * \param pos Position of depletant (return value) * \param orientation ion of depletant (return value) * \param params_depletant Depletant parameters * \params pos_sphere_other Center of other sphere */ template<class Shape> template<class RNG> inline void IntegratorHPMCMonoImplicit<Shape>::generateDepletantRestricted(RNG& rng, vec3<Scalar> pos_sphere, Scalar delta, Scalar delta_other, vec3<Scalar>& pos, quat<Scalar>& orientation, const typename Shape::param_type& params_depletant, vec3<Scalar> pos_sphere_other) { vec3<Scalar> r_ij = pos_sphere - pos_sphere_other; Scalar d = fast::sqrt(dot(r_ij,r_ij)); Scalar rmin(0.0); Scalar rmax = Scalar(0.5)*delta; Scalar ctheta_min(-1.0); bool do_rotate = false; if (d > Scalar(0.0) && delta_other > Scalar(0.0)) { // draw a random direction in the bounded sphereical shell Scalar ctheta = (delta_other*delta_other+Scalar(4.0)*d*d-delta*delta)/(Scalar(4.0)*delta_other*d); if (ctheta >= Scalar(-1.0) && ctheta < Scalar(1.0)) { // true intersection, we can restrict angular sampling ctheta_min = ctheta; } // is there an intersection? if (Scalar(2.0)*d < delta+delta_other) { // sample in shell around smaller sphere rmin = delta_other/Scalar(2.0); rmax = d+delta/Scalar(2.0); do_rotate = true; } } // draw random radial coordinate in a spherical shell Scalar r3 = rng.template s<Scalar>(fast::pow(rmin/rmax,Scalar(3.0)),Scalar(1.0)); Scalar r = rmax*fast::pow(r3,Scalar(1.0/3.0)); // random direction in spherical shell Scalar z = rng.s(ctheta_min,Scalar(1.0)); Scalar phi = Scalar(2.0*M_PI)*rng.template s<Scalar>(); vec3<Scalar> n; if (do_rotate) { vec3<Scalar> u(r_ij/d); // normal vector vec3<Scalar> v(cross(u,vec3<Scalar>(0,0,1))); if (dot(v,v) < EPSILON) { v = cross(u,vec3<Scalar>(0,1,0)); } v *= fast::rsqrt(dot(v,v)); quat<Scalar> q(quat<Scalar>::fromAxisAngle(u,phi)); n = z*u+(fast::sqrt(Scalar(1.0)-z*z))*rotate(q,v); } else { n = vec3<Scalar>(fast::sqrt(Scalar(1.0)-z*z)*fast::cos(phi),fast::sqrt(Scalar(1.0)-z*z)*fast::sin(phi),z); } // test depletant position pos = r*n; if (do_rotate) { // insert such that it potentially intersects the sphere, but not the other one pos += pos_sphere_other; } else { // insert in sphere pos += pos_sphere; } Shape shape_depletant(quat<Scalar>(), params_depletant); if (shape_depletant.hasOrientation()) { orientation = generateRandomOrientation(rng); } } /*! \param pos_depletant Depletant position * \param shape_depletant Depletant shape * \param idx Index of updated particle * \param h_params Parameter array * \param h_overlaps Interaction matrix * \param typ_i type of updated particle * \param h_orientation ion array * \param pos_new New position of updated particle * \param orientation_new New orientation of updated particle * \param params_new New shape parameters of updated particle * \param counters HPMC overlap counters */ template<class Shape> inline bool IntegratorHPMCMonoImplicit<Shape>::insertDepletant(vec3<Scalar>& pos_depletant, const Shape& shape_depletant, unsigned int idx, typename Shape::param_type *h_params, unsigned int *h_overlaps, unsigned int typ_i, Scalar4 *h_postype, Scalar4 *h_orientation, vec3<Scalar> pos_new, quat<Scalar>& orientation_new, const typename Shape::param_type& params_new, unsigned int &n_overlap_checks, unsigned int &overlap_err_count, bool& overlap_shape, bool new_config) { overlap_shape=false; detail::AABB aabb_depletant_local = shape_depletant.getAABB(vec3<Scalar>(0,0,0)); // now check if depletant overlaps with moved particle in the old configuration Shape shape_i(quat<Scalar>(), params_new); if (shape_i.hasOrientation()) { if (! new_config) { // load old orientation Scalar4 orientation_i = h_orientation[idx]; shape_i.orientation = quat<Scalar>(orientation_i); } else { shape_i.orientation = orientation_new; } } vec3<Scalar> pos_i; if (!new_config) { // load old position pos_i = vec3<Scalar>(h_postype[idx]); } else { pos_i = pos_new; } // only need to consider the (0,0,0) image detail::AABB aabb = aabb_depletant_local; aabb.translate(pos_depletant); // put particles in coordinate system of depletant vec3<Scalar> r_ij = pos_i - pos_depletant; n_overlap_checks++; // test circumsphere overlap OverlapReal rsq = dot(r_ij,r_ij); OverlapReal DaDb = shape_depletant.getCircumsphereDiameter() + shape_i.getCircumsphereDiameter(); bool circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); if (h_overlaps[this->m_overlap_idx(typ_i, m_type)] && circumsphere_overlap && test_overlap(r_ij, shape_depletant, shape_i, overlap_err_count)) { overlap_shape = true; } // same, but for reverse move if (shape_i.hasOrientation()) { if (new_config) { // load old orientation Scalar4 orientation_i = h_orientation[idx]; shape_i.orientation = quat<Scalar>(orientation_i); } else { shape_i.orientation = orientation_new; } } if (new_config) { // load old position pos_i = vec3<Scalar>(h_postype[idx]); } else { pos_i = pos_new; } // only need to consider the (0,0,0) image aabb = aabb_depletant_local; aabb.translate(pos_depletant); // put particles in coordinate system of depletant r_ij = pos_i - pos_depletant; n_overlap_checks++; // test circumsphere overlap rsq = dot(r_ij,r_ij); DaDb = shape_depletant.getCircumsphereDiameter() + shape_i.getCircumsphereDiameter(); circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); // check for overlaps with neighboring particle's positions bool overlap=false; if (h_overlaps[this->m_overlap_idx(m_type, typ_i)] && circumsphere_overlap && test_overlap(r_ij, shape_depletant, shape_i, overlap_err_count)) { // if we are already overlapping in the other configuration, this doesn't count as an insertion overlap = true; } if (!overlap && overlap_shape) { // All image boxes (including the primary) const unsigned int n_images = this->m_image_list.size(); for (unsigned int cur_image = 0; cur_image < n_images; cur_image++) { vec3<Scalar> pos_depletant_image = pos_depletant + this->m_image_list[cur_image]; detail::AABB aabb = aabb_depletant_local; aabb.translate(pos_depletant_image); // stackless search for (unsigned int cur_node_idx = 0; cur_node_idx < this->m_aabb_tree.getNumNodes(); cur_node_idx++) { if (detail::overlap(this->m_aabb_tree.getNodeAABB(cur_node_idx), aabb)) { if (this->m_aabb_tree.isNodeLeaf(cur_node_idx)) { for (unsigned int cur_p = 0; cur_p < this->m_aabb_tree.getNodeNumParticles(cur_node_idx); cur_p++) { // read in its position and orientation unsigned int j = this->m_aabb_tree.getNodeParticle(cur_node_idx, cur_p); // load the position and orientation of the j particle Scalar4 postype_j = h_postype[j]; vec3<Scalar> pos_j(postype_j); Scalar4 orientation_j = h_orientation[j]; unsigned int type = __scalar_as_int(postype_j.w); Shape shape_j(quat<Scalar>(orientation_j), h_params[type]); if (j == idx) { // we have already exclued overlap with the moved particle above continue; } // put particles in coordinate system of depletant vec3<Scalar> r_ij = pos_j - pos_depletant_image; n_overlap_checks++; // check circumsphere overlap OverlapReal rsq = dot(r_ij,r_ij); OverlapReal DaDb = shape_depletant.getCircumsphereDiameter() + shape_j.getCircumsphereDiameter(); bool circumsphere_overlap = (rsq*OverlapReal(4.0) <= DaDb * DaDb); if (h_overlaps[this->m_overlap_idx(type, m_type)] && circumsphere_overlap && test_overlap(r_ij, shape_depletant, shape_j, overlap_err_count)) { overlap = true; break; } } } } else { // skip ahead cur_node_idx += this->m_aabb_tree.getNodeSkip(cur_node_idx); } if (overlap) break; } // end loop over AABB nodes if (overlap) break; } // end loop over images } // end if overlap with shape return overlap_shape && !overlap; } /*! \param quantity Name of the log quantity to get \param timestep Current time step of the simulation \return the requested log quantity. */ template<class Shape> Scalar IntegratorHPMCMonoImplicit<Shape>::getLogValue(const std::string& quantity, unsigned int timestep) { if (quantity == "hpmc_fugacity") { return (Scalar) m_n_R; } if (quantity == "hpmc_ntrial") { return (Scalar) m_n_trial; } hpmc_counters_t counters = IntegratorHPMC::getCounters(2); hpmc_implicit_counters_t implicit_counters = getImplicitCounters(2); if (quantity == "hpmc_insert_count") { // return number of depletant insertions per colloid if (counters.getNMoves() > 0) return (Scalar)implicit_counters.insert_count/(Scalar)counters.getNMoves(); else return Scalar(0.0); } if (quantity == "hpmc_reinsert_count") { // return number of overlapping depletants reinserted per colloid if (counters.getNMoves() > 0) return (Scalar)implicit_counters.reinsert_count/(Scalar)counters.getNMoves(); else return Scalar(0.0); } if (quantity == "hpmc_free_volume_fraction") { // return fraction of free volume in depletant insertion sphere return (Scalar) implicit_counters.getFreeVolumeFraction(); } if (quantity == "hpmc_overlap_fraction") { // return fraction of overlapping depletants after trial move return (Scalar) implicit_counters.getOverlapFraction(); } if (quantity == "hpmc_configurational_bias_ratio") { // return fraction of overlapping depletants after trial move return (Scalar) implicit_counters.getConfigurationalBiasRatio(); } //nothing found -> pass on to base class return IntegratorHPMCMono<Shape>::getLogValue(quantity, timestep); } /*! \param mode 0 -> Absolute count, 1 -> relative to the start of the run, 2 -> relative to the last executed step \return The current state of the acceptance counters IntegratorHPMCMonoImplicit maintains a count of the number of accepted and rejected moves since instantiation. getCounters() provides the current value. The parameter *mode* controls whether the returned counts are absolute, relative to the start of the run, or relative to the start of the last executed step. */ template<class Shape> hpmc_implicit_counters_t IntegratorHPMCMonoImplicit<Shape>::getImplicitCounters(unsigned int mode) { ArrayHandle<hpmc_implicit_counters_t> h_counters(m_implicit_count, access_location::host, access_mode::read); hpmc_implicit_counters_t result; if (mode == 0) result = h_counters.data[0]; else if (mode == 1) result = h_counters.data[0] - m_implicit_count_run_start; else result = h_counters.data[0] - m_implicit_count_step_start; #ifdef ENABLE_MPI if (this->m_comm) { // MPI Reduction to total result values on all ranks MPI_Allreduce(MPI_IN_PLACE, &result.insert_count, 1, MPI_LONG_LONG_INT, MPI_SUM, this->m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.free_volume_count, 1, MPI_LONG_LONG_INT, MPI_SUM, this->m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.overlap_count, 1, MPI_LONG_LONG_INT, MPI_SUM, this->m_exec_conf->getMPICommunicator()); MPI_Allreduce(MPI_IN_PLACE, &result.reinsert_count, 1, MPI_LONG_LONG_INT, MPI_SUM, this->m_exec_conf->getMPICommunicator()); } #endif return result; } /*! NPT simulations are not supported with implicit depletants (The Nmu_ptPT ensemble is instable) \returns false if resize results in overlaps */ template<class Shape> bool IntegratorHPMCMonoImplicit<Shape>::attemptBoxResize(unsigned int timestep, const BoxDim& new_box) { this->m_exec_conf->msg->error() << "Nmu_pPT simulations are unsupported." << std::endl; throw std::runtime_error("Error during implicit depletant integration\n"); } //! Export this hpmc integrator to python /*! \param name Name of the class in the exported python module \tparam Shape An instantiation of IntegratorHPMCMono<Shape> will be exported */ template < class Shape > void export_IntegratorHPMCMonoImplicit(pybind11::module& m, const std::string& name) { pybind11::class_<IntegratorHPMCMonoImplicit<Shape>, std::shared_ptr< IntegratorHPMCMonoImplicit<Shape> > >(m, name.c_str(), pybind11::base< IntegratorHPMCMono<Shape> >()) .def(pybind11::init< std::shared_ptr<SystemDefinition>, unsigned int >()) .def("setDepletantDensity", &IntegratorHPMCMonoImplicit<Shape>::setDepletantDensity) .def("setDepletantType", &IntegratorHPMCMonoImplicit<Shape>::setDepletantType) .def("setNTrial", &IntegratorHPMCMonoImplicit<Shape>::setNTrial) .def("getNTrial", &IntegratorHPMCMonoImplicit<Shape>::getNTrial) .def("getImplicitCounters", &IntegratorHPMCMonoImplicit<Shape>::getImplicitCounters) ; } //! Export the counters for depletants inline void export_hpmc_implicit_counters(pybind11::module& m) { pybind11::class_< hpmc_implicit_counters_t >(m, "hpmc_implicit_counters_t") .def_readwrite("insert_count", &hpmc_implicit_counters_t::insert_count) .def_readwrite("reinsert_count", &hpmc_implicit_counters_t::reinsert_count) .def_readwrite("free_volume_count", &hpmc_implicit_counters_t::free_volume_count) .def_readwrite("overlap_count", &hpmc_implicit_counters_t::overlap_count) .def("getFreeVolumeFraction", &hpmc_implicit_counters_t::getFreeVolumeFraction) .def("getOverlapFraction", &hpmc_implicit_counters_t::getOverlapFraction) .def("getConfigurationalBiasRatio", &hpmc_implicit_counters_t::getConfigurationalBiasRatio) ; } } // end namespace hpmc #endif // __HPMC_MONO_IMPLICIT__H__
blas.c
#include "blas.h" #include "utils.h" #include <math.h> #include <assert.h> #include <float.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void reorg_cpu(float *x, int out_w, int out_h, int out_c, int batch, int stride, int forward, float *out) { int b,i,j,k; int in_c = out_c/(stride*stride); //printf("\n out_c = %d, out_w = %d, out_h = %d, stride = %d, forward = %d \n", out_c, out_w, out_h, stride, forward); //printf(" in_c = %d, in_w = %d, in_h = %d \n", in_c, out_w*stride, out_h*stride); for(b = 0; b < batch; ++b){ for(k = 0; k < out_c; ++k){ for(j = 0; j < out_h; ++j){ for(i = 0; i < out_w; ++i){ int in_index = i + out_w*(j + out_h*(k + out_c*b)); int c2 = k % in_c; int offset = k / in_c; int w2 = i*stride + offset % stride; int h2 = j*stride + offset / stride; int out_index = w2 + out_w*stride*(h2 + out_h*stride*(c2 + in_c*b)); if(forward) out[out_index] = x[in_index]; // used by default for forward (i.e. forward = 0) else out[in_index] = x[out_index]; } } } } } void flatten(float *x, int size, int layers, int batch, int forward) { float* swap = (float*)xcalloc(size * layers * batch, sizeof(float)); int i,c,b; for(b = 0; b < batch; ++b){ for(c = 0; c < layers; ++c){ for(i = 0; i < size; ++i){ int i1 = b*layers*size + c*size + i; int i2 = b*layers*size + i*layers + c; if (forward) swap[i2] = x[i1]; else swap[i1] = x[i2]; } } } memcpy(x, swap, size*layers*batch*sizeof(float)); free(swap); } void weighted_sum_cpu(float *a, float *b, float *s, int n, float *c) { int i; for(i = 0; i < n; ++i){ c[i] = s[i]*a[i] + (1-s[i])*(b ? b[i] : 0); } } void weighted_delta_cpu(float *a, float *b, float *s, float *da, float *db, float *ds, int n, float *dc) { int i; for(i = 0; i < n; ++i){ if(da) da[i] += dc[i] * s[i]; if(db) db[i] += dc[i] * (1-s[i]); ds[i] += dc[i] * (a[i] - b[i]); } } static float relu(float src) { if (src > 0) return src; return 0; } void shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_output, float *out, float *in, float *weights, int nweights, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; const int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float sum = 1, max_val = -FLT_MAX; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[id] = in[id] * w; // [0 or c or (c, h ,w)] } else out[id] = in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *add = layers_output[i]; if (weights) { const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; out[out_index] += add[add_index] * w; // [0 or c or (c, h ,w)] } else out[out_index] += add[add_index]; } } } } void backward_shortcut_multilayer_cpu(int size, int src_outputs, int batch, int n, int *outputs_of_layers, float **layers_delta, float *delta_out, float *delta_in, float *weights, float *weight_updates, int nweights, float *in, float **layers_output, WEIGHTS_NORMALIZATION_T weights_normalization) { // nweights - l.n or l.n*l.c or (l.n*l.c*l.h*l.w) const int layer_step = nweights / (n + 1); // 1 or l.c or (l.c * l.h * l.w) int step = 0; if (nweights > 0) step = src_outputs / layer_step; // (l.c * l.h * l.w) or (l.w*l.h) or 1 int id; #pragma omp parallel for for (id = 0; id < size; ++id) { int src_id = id; int src_i = src_id % src_outputs; src_id /= src_outputs; int src_b = src_id; float grad = 1, sum = 1, max_val = -FLT_MAX;; int i; if (weights && weights_normalization) { if (weights_normalization == SOFTMAX_NORMALIZATION) { for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (max_val < w) max_val = w; } } const float eps = 0.0001; sum = eps; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) sum += relu(w); else if (weights_normalization == SOFTMAX_NORMALIZATION) sum += expf(w - max_val); } /* grad = 0; for (i = 0; i < (n + 1); ++i) { const int weights_index = src_i / step + i*layer_step; // [0 or c or (c, h ,w)] const float delta_w = delta_in[id] * in[id]; const float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) grad += delta_w * relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) grad += delta_w * expf(w - max_val) / sum; } */ } if (weights) { float w = weights[src_i / step]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; delta_out[id] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[src_i / step] += delta_in[id] * in[id] * grad; } else delta_out[id] += delta_in[id]; // layers for (i = 0; i < n; ++i) { int add_outputs = outputs_of_layers[i]; if (src_i < add_outputs) { int add_index = add_outputs*src_b + src_i; int out_index = id; float *layer_delta = layers_delta[i]; if (weights) { float *add = layers_output[i]; const int weights_index = src_i / step + (i + 1)*layer_step; // [0 or c or (c, h ,w)] float w = weights[weights_index]; if (weights_normalization == RELU_NORMALIZATION) w = relu(w) / sum; else if (weights_normalization == SOFTMAX_NORMALIZATION) w = expf(w - max_val) / sum; layer_delta[add_index] += delta_in[id] * w; // [0 or c or (c, h ,w)] weight_updates[weights_index] += delta_in[id] * add[add_index] * grad; } else layer_delta[add_index] += delta_in[id]; } } } } void shortcut_cpu(int batch, int w1, int h1, int c1, float *add, int w2, int h2, int c2, float *out) { int stride = w1/w2; int sample = w2/w1; assert(stride == h1/h2); assert(sample == h2/h1); if(stride < 1) stride = 1; if(sample < 1) sample = 1; int minw = (w1 < w2) ? w1 : w2; int minh = (h1 < h2) ? h1 : h2; int minc = (c1 < c2) ? c1 : c2; int i,j,k,b; for(b = 0; b < batch; ++b){ for(k = 0; k < minc; ++k){ for(j = 0; j < minh; ++j){ for(i = 0; i < minw; ++i){ int out_index = i*sample + w2*(j*sample + h2*(k + c2*b)); int add_index = i*stride + w1*(j*stride + h1*(k + c1*b)); out[out_index] += add[add_index]; } } } } } void mean_cpu(float *x, int batch, int filters, int spatial, float *mean) { float scale = 1./(batch * spatial); int i,j,k; for(i = 0; i < filters; ++i){ mean[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; mean[i] += x[index]; } } mean[i] *= scale; } } void variance_cpu(float *x, float *mean, int batch, int filters, int spatial, float *variance) { float scale = 1./(batch * spatial - 1); int i,j,k; for(i = 0; i < filters; ++i){ variance[i] = 0; for(j = 0; j < batch; ++j){ for(k = 0; k < spatial; ++k){ int index = j*filters*spatial + i*spatial + k; variance[i] += pow((x[index] - mean[i]), 2); } } variance[i] *= scale; } } void normalize_cpu(float *x, float *mean, float *variance, int batch, int filters, int spatial) { int b, f, i; for(b = 0; b < batch; ++b){ for(f = 0; f < filters; ++f){ for(i = 0; i < spatial; ++i){ int index = b*filters*spatial + f*spatial + i; x[index] = (x[index] - mean[f])/(sqrt(variance[f] + .00001f)); } } } } void const_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] = ALPHA; } void mul_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] *= X[i*INCX]; } void pow_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = pow(X[i*INCX], ALPHA); } void axpy_cpu(int N, float ALPHA, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] += ALPHA*X[i*INCX]; } void scal_cpu(int N, float ALPHA, float *X, int INCX) { int i; for(i = 0; i < N; ++i) X[i*INCX] *= ALPHA; } void scal_add_cpu(int N, float ALPHA, float BETA, float *X, int INCX) { int i; for (i = 0; i < N; ++i) X[i*INCX] = X[i*INCX] * ALPHA + BETA; } void fill_cpu(int N, float ALPHA, float *X, int INCX) { int i; if (INCX == 1 && ALPHA == 0) { memset(X, 0, N * sizeof(float)); } else { for (i = 0; i < N; ++i) X[i*INCX] = ALPHA; } } void deinter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ if(X) X[j*NX + i] += OUT[index]; ++index; } for(i = 0; i < NY; ++i){ if(Y) Y[j*NY + i] += OUT[index]; ++index; } } } void inter_cpu(int NX, float *X, int NY, float *Y, int B, float *OUT) { int i, j; int index = 0; for(j = 0; j < B; ++j) { for(i = 0; i < NX; ++i){ OUT[index++] = X[j*NX + i]; } for(i = 0; i < NY; ++i){ OUT[index++] = Y[j*NY + i]; } } } void copy_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; for(i = 0; i < N; ++i) Y[i*INCY] = X[i*INCX]; } void mult_add_into_cpu(int N, float *X, float *Y, float *Z) { int i; for(i = 0; i < N; ++i) Z[i] += X[i]*Y[i]; } void smooth_l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; float abs_val = fabs(diff); if(abs_val < 1) { error[i] = diff * diff; delta[i] = diff; } else { error[i] = 2*abs_val - 1; delta[i] = (diff > 0) ? 1 : -1; } } } void l1_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = fabs(diff); delta[i] = diff > 0 ? 1 : -1; } } void softmax_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = (t) ? -log(p) : 0; delta[i] = t-p; } } void logistic_x_ent_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float t = truth[i]; float p = pred[i]; error[i] = -t*log(p) - (1-t)*log(1-p); delta[i] = t-p; } } void l2_cpu(int n, float *pred, float *truth, float *delta, float *error) { int i; for(i = 0; i < n; ++i){ float diff = truth[i] - pred[i]; error[i] = diff * diff; delta[i] = diff; } } float dot_cpu(int N, float *X, int INCX, float *Y, int INCY) { int i; float dot = 0; for(i = 0; i < N; ++i) dot += X[i*INCX] * Y[i*INCY]; return dot; } void softmax(float *input, int n, float temp, float *output, int stride) { int i; float sum = 0; float largest = -FLT_MAX; for(i = 0; i < n; ++i){ if(input[i*stride] > largest) largest = input[i*stride]; } for(i = 0; i < n; ++i){ float e = exp(input[i*stride]/temp - largest/temp); sum += e; output[i*stride] = e; } for(i = 0; i < n; ++i){ output[i*stride] /= sum; } } void softmax_cpu(float *input, int n, int batch, int batch_offset, int groups, int group_offset, int stride, float temp, float *output) { int g, b; for(b = 0; b < batch; ++b){ for(g = 0; g < groups; ++g){ softmax(input + b*batch_offset + g*group_offset, n, temp, output + b*batch_offset + g*group_offset, stride); } } } void upsample_cpu(float *in, int w, int h, int c, int batch, int stride, int forward, float scale, float *out) { int i, j, k, b; for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { for (j = 0; j < h*stride; ++j) { for (i = 0; i < w*stride; ++i) { int in_index = b*w*h*c + k*w*h + (j / stride)*w + i / stride; int out_index = b*w*h*c*stride*stride + k*w*h*stride*stride + j*w*stride + i; if (forward) out[out_index] = scale*in[in_index]; else in[in_index] += scale*out[out_index]; } } } } } void constrain_cpu(int size, float ALPHA, float *X) { int i; for (i = 0; i < size; ++i) { X[i] = fminf(ALPHA, fmaxf(-ALPHA, X[i])); } } void fix_nan_and_inf_cpu(float *input, size_t size) { int i; for (i = 0; i < size; ++i) { float val = input[i]; if (isnan(val) || isinf(val)) input[i] = 1.0f / i; // pseudo random value } } void get_embedding(float *src, int src_w, int src_h, int src_c, int embedding_size, int cur_w, int cur_h, int cur_n, int cur_b, float *dst) { int i; for (i = 0; i < embedding_size; ++i) { const int src_index = cur_b*(src_c*src_h*src_w) + cur_n*(embedding_size*src_h*src_w) + i*src_h*src_w + cur_h*(src_w) + cur_w; const float val = src[src_index]; dst[i] = val; //printf(" val = %f, ", val); } } // Euclidean_norm float math_vector_length(float *A, unsigned int feature_size) { float sum = 0; int i; for (i = 0; i < feature_size; ++i) { sum += A[i] * A[i]; } float vector_length = sqrtf(sum); return vector_length; } float cosine_similarity(float *A, float *B, unsigned int feature_size) { float mul = 0.0, d_a = 0.0, d_b = 0.0; int i; for(i = 0; i < feature_size; ++i) { mul += A[i] * B[i]; d_a += A[i] * A[i]; d_b += B[i] * B[i]; } float similarity; float divider = sqrtf(d_a) * sqrtf(d_b); if (divider > 0) similarity = mul / divider; else similarity = 0; return similarity; } int get_sim_P_index(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { return -1; // not found } return z; // found } int check_sim(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { return 0; // not found } return 1; // found } float find_sim(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { printf(" Error: find_sim(): sim isn't found: i = %d, j = %d, z = %d \n", i, j, z); getchar(); } return contrast_p[z].sim; } float find_P_constrastive(size_t i, size_t j, contrastive_params *contrast_p, int contrast_p_size) { size_t z; for (z = 0; z < contrast_p_size; ++z) { if (contrast_p[z].i == i && contrast_p[z].j == j) break; } if (z == contrast_p_size) { printf(" Error: find_P_constrastive(): P isn't found: i = %d, j = %d, z = %d \n", i, j, z); getchar(); } return contrast_p[z].P; } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive_f_det(size_t il, int *labels, float **z, unsigned int feature_size, float temperature, contrastive_params *contrast_p, int contrast_p_size) { const float sim = contrast_p[il].sim; const size_t i = contrast_p[il].i; const size_t j = contrast_p[il].j; const float numerator = expf(sim / temperature); float denominator = 0; int k; for (k = 0; k < contrast_p_size; ++k) { contrastive_params cp = contrast_p[k]; //if (k != i && labels[k] != labels[i]) { //if (k != i) { if (cp.i != i && cp.j == j) { //const float sim_den = cp.sim; ////const float sim_den = find_sim(k, l, contrast_p, contrast_p_size); // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += cp.exp_sim; } } float result = 0.9999; if (denominator != 0) result = numerator / denominator; if (result > 1) result = 0.9999; return result; } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive_f(size_t i, size_t l, int *labels, float **z, unsigned int feature_size, float temperature, contrastive_params *contrast_p, int contrast_p_size) { if (i == l) { fprintf(stderr, " Error: in P_constrastive must be i != l, while i = %d, l = %d \n", i, l); getchar(); } const float sim = find_sim(i, l, contrast_p, contrast_p_size); // cosine_similarity(z[i], z[l], feature_size); const float numerator = expf(sim / temperature); float denominator = 0; int k; for (k = 0; k < contrast_p_size; ++k) { contrastive_params cp = contrast_p[k]; //if (k != i && labels[k] != labels[i]) { //if (k != i) { if (cp.i != i && cp.j == l) { //const float sim_den = cp.sim; ////const float sim_den = find_sim(k, l, contrast_p, contrast_p_size); // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += cp.exp_sim; } } float result = 0.9999; if (denominator != 0) result = numerator / denominator; if (result > 1) result = 0.9999; return result; } void grad_contrastive_loss_positive_f(size_t i, int *class_ids, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *delta, int wh, contrastive_params *contrast_p, int contrast_p_size) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j] && labels[i] >= 0) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f, labels[i] = %d \n", N, temperature, vec_len, labels[i]); getchar(); return; } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j] && labels[i] >= 0) { //printf(" i = %d, j = %d, num_of_samples = %d, labels[i] = %d, labels[j] = %d \n", // i, j, num_of_samples, labels[i], labels[j]); const int sim_P_i = get_sim_P_index(i, j, contrast_p, contrast_p_size); if (sim_P_i < 0) continue; const float sim = contrast_p[sim_P_i].sim; const float P = contrast_p[sim_P_i].P; //if (!check_sim(i, j, contrast_p, contrast_p_size)) continue; //const float sim = find_sim(i, j, contrast_p, contrast_p_size); //cos_sim[i*num_of_samples + j]; // cosine_similarity(z[i], z[j], feature_size); //const float P = find_P_constrastive(i, j, contrast_p, contrast_p_size); //p_constrastive[i*num_of_samples + j]; // P_constrastive(i, j, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 - sim; int m; //const float d = mult*(sim * z[i][m] - z[j][m]) * (1 - P); // 1 for (m = 0; m < feature_size; ++m) { //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // my //const float d = mult*(sim * z[i][m] + sim * z[j][m] - z[j][m]) *(1 - P); // 1+2 const float d = mult*(sim * z[i][m] - z[j][m]) *(1 - P); // 1 (70%) //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // 2 // printf(" pos: z[j][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[j][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } void grad_contrastive_loss_negative_f(size_t i, int *class_ids, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *delta, int wh, contrastive_params *contrast_p, int contrast_p_size, int neg_max) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j] && labels[i] >= 0) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f, labels[i] = %d \n", N, temperature, vec_len, labels[i]); getchar(); return; } const float mult = 1 / ((N - 1) * temperature * vec_len); int neg_counter = 0; for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (labels[i] >= 0 && labels[i] == labels[j] && i != j) { size_t k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && k != j && labels[k] != labels[i]) { if (k != i && k != j && labels[k] != labels[i] && class_ids[j] == class_ids[k]) { neg_counter++; const int sim_P_i = get_sim_P_index(i, k, contrast_p, contrast_p_size); if (sim_P_i < 0) continue; const float sim = contrast_p[sim_P_i].sim; const float P = contrast_p[sim_P_i].P; //if (!check_sim(i, k, contrast_p, contrast_p_size)) continue; //const float sim = find_sim(i, k, contrast_p, contrast_p_size); //cos_sim[i*num_of_samples + k]; // cosine_similarity(z[i], z[k], feature_size); //const float P = find_P_constrastive(i, k, contrast_p, contrast_p_size); //p_constrastive[i*num_of_samples + k]; // P_constrastive(i, k, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 + sim; int m; //const float d = mult*(z[k][m] + sim * z[i][m]) * P; // my1 for (m = 0; m < feature_size; ++m) { //const float d = mult*(z[k][m] + sim * z[i][m]) * P; // 1 (70%) //const float d = mult*(z[k][m] - sim * z[k][m] - sim * z[i][m]) * P; // 1+2 const float d = mult*(z[k][m] - sim * z[i][m]) * P; // 1 (70%) //const float d = mult*(z[k][m] - sim * z[k][m]) * P; // 2 //printf(" neg: z[k][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[k][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } if (neg_counter >= neg_max) return; } } } } } // num_of_samples = 2 * loaded_images = mini_batch_size float P_constrastive(size_t i, size_t l, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *exp_cos_sim) { if (i == l) { fprintf(stderr, " Error: in P_constrastive must be i != l, while i = %d, l = %d \n", i, l); getchar(); } //const float sim = cos_sim[i*num_of_samples + l]; // cosine_similarity(z[i], z[l], feature_size); //const float numerator = expf(sim / temperature); const float numerator = exp_cos_sim[i*num_of_samples + l]; float denominator = 0; int k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && labels[k] != labels[i]) { if (k != i) { //const float sim_den = cos_sim[k*num_of_samples + l]; // cosine_similarity(z[k], z[l], feature_size); //denominator += expf(sim_den / temperature); denominator += exp_cos_sim[k*num_of_samples + l]; } } float result = numerator / denominator; return result; } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_positive(size_t i, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta, int wh) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { //printf(" i = %d, j = %d, num_of_samples = %d, labels[i] = %d, labels[j] = %d \n", // i, j, num_of_samples, labels[i], labels[j]); const float sim = cos_sim[i*num_of_samples + j]; // cosine_similarity(z[i], z[j], feature_size); const float P = p_constrastive[i*num_of_samples + j]; // P_constrastive(i, j, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 - sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(sim * z[i][m] - z[j][m]) * (1 - P); // good //const float d = mult*(sim * z[j][m] - z[j][m]) * (1 - P); // bad // printf(" pos: z[j][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[j][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } // i - id of the current sample in mini_batch // labels[num_of_samples] - array with class_id for each sample in the current mini_batch // z[feature_size][num_of_samples] - array of arrays with contrastive features (output of conv-layer, f.e. 128 floats for each sample) // delta[feature_size] - array with deltas for backpropagation // temperature - scalar temperature param (temperature > 0), f.e. temperature = 0.07: Supervised Contrastive Learning void grad_contrastive_loss_negative(size_t i, int *labels, size_t num_of_samples, float **z, unsigned int feature_size, float temperature, float *cos_sim, float *p_constrastive, float *delta, int wh) { const float vec_len = math_vector_length(z[i], feature_size); size_t j; float N = 0; for (j = 0; j < num_of_samples; ++j) { if (labels[i] == labels[j]) N++; } if (N == 0 || temperature == 0 || vec_len == 0) { fprintf(stderr, " Error: N == 0 || temperature == 0 || vec_len == 0. N=%f, temperature=%f, vec_len=%f \n", N, temperature, vec_len); getchar(); } const float mult = 1 / ((N - 1) * temperature * vec_len); for (j = 0; j < num_of_samples; ++j) { //if (i != j && (i/2) == (j/2)) { if (i != j && labels[i] == labels[j]) { size_t k; for (k = 0; k < num_of_samples; ++k) { //if (k != i && k != j && labels[k] != labels[i]) { if (k != i && k != j && labels[k] >= 0) { const float sim = cos_sim[i*num_of_samples + k]; // cosine_similarity(z[i], z[k], feature_size); const float P = p_constrastive[i*num_of_samples + k]; // P_constrastive(i, k, labels, num_of_samples, z, feature_size, temperature, cos_sim); //const float custom_pos_mult = 1 + sim; int m; for (m = 0; m < feature_size; ++m) { const float d = mult*(z[k][m] - sim * z[i][m]) * P; // good //const float d = mult*(z[k][m] - sim * z[k][m]) * P; // bad //printf(" neg: z[k][m] = %f, z[i][m] = %f, d = %f, sim = %f \n", z[k][m], z[i][m], d, sim); const int out_i = m * wh; delta[out_i] -= d; } } } } } }
GB_builder.c
//------------------------------------------------------------------------------ // GB_builder: build a matrix from tuples //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // CALLED BY: GB_build, GB_wait, and GB_transpose // CALLS: Generated/GB_red_build__* workers // This function is called by GB_build to build a matrix T for GrB_Matrix_build // or GrB_Vector_build, by GB_wait to build a matrix T from the list of pending // tuples, and by GB_transpose to transpose a matrix or vector. Duplicates can // appear if called by GB_build or GB_wait, but not GB_transpose. // The indices are provided either as (I_input,J_input) or (I_work,J_work), not // both. The values are provided as S_input or S_work, not both. On return, // the *work arrays are either transplanted into T, or freed, since they are // temporary workspaces. // The work is done in major 5 Steps, some of which can be skipped, depending // on how the tuples are provided (*_work or *_input), and whether or not they // are sorted, or have duplicates. If vdim <= 1, some work is skipped (for // GrB_Vectors, and single-vector GrB_Matrices). Let e be the of tuples on // input. Let p be the # of threads used. // STEP 1: copy user input. O(e/p) read/write per thread, or skipped. // STEP 2: sort the tuples. Time: O((e log e)/p), read/write, or skipped if // the tuples are already sorted. // STEP 3: count vectors and duplicates. O(e/p) reads, per thread, if no // duplicates, or skipped if already done. O(e/p) read/writes // per thread if duplicates appear. // STEP 4: construct T->h and T->p. O(e/p) reads per thread, or skipped if // T is a vector. // STEP 5: assemble the tuples. O(e/p) read/writes per thread, or O(1) if the // values can be transplanted into T as-is. // For GrB_Matrix_build: If the input (I_input, J_input, S_input) is already // sorted with no duplicates, and no typecasting needs to be done, then Step 1 // still must be done (each thread does O(e/p) reads of (I_input,J_input) and // writes to I_work), but Step 1 also does the work for Step 3. Step 2 and 3 // are skipped. Step 4 does O(e/p) reads per thread (J_input only). Then // I_work is transplanted into T->i. Step 5 does O(e/p) read/writes per thread // to copy S into T->x. // For GrB_Vector_build: as GrB_Matrix_build, Step 1 does O(e/p) read/writes // per thread. The input is always a vector, so vdim == 1 always holds. Step // 2 is skipped if the indices are already sorted, and Step 3 does no work at // all unless duplicates appear. Step 4 takes no time, for any vector. Step 5 // does O(e/p) reads/writes per thread. // For GrB_reduce_to_vector: like GrB_Vector_build, but many duplicates are // likely, and the indices will not be sorted. The input is always a single // vector (vdim == 1). Step 1 only does a parallel memcpy, from I_input to // I_work. Step 2 takes O((e log e)/p) time to sort the (i,k) tuples. Step 3 // does O(e/p) read/writes. Step 4 takes no time. Step 5 does O(e/p) // read/writes per thread. // For GB_wait: the pending tuples are provided as I_work, J_work, and S_work, // so Step 1 is skipped (no need to check for invalid indices). The input // J_work may be null (vdim can be anything, since GB_wait is used for both // vectors and matrices). The tuples might be in sorted order already, which // is known precisely known from A->Pending->sorted. Step 2 does O((e log e)/p) // work to sort the tuples. Duplicates may appear, and out-of-order tuples are // likely. Step 3 does O(e/p) read/writes. Step 4 does O(e/p) reads per // thread of (I_work,J_work), or just I_work. Step 5 does O(e/p) read/writes // per thread, or O(1) time if S_work can be transplanted into T->x. // For GB_transpose: uses I_work, J_work, and either S_input (if no op applied // to the values) or S_work (if an op was applied to the A->x values). This is // only done for matrices, not vectors, so vdim > 1 will always hold. The // indices are valid so Step 1 is skipped. The tuples are not sorted, so Step // 2 takes O((e log e)/p) time to do the sort. There are no duplicates, so // Step 3 only does O(e/p) reads of J_work to count the vectors in each slice. // Step 4 only does O(e/p) reads of J_work to compute T->h and T->p. Step 5 // does O(e/p) read/writes per thread, but it uses the simpler case in // GB_reduce_build_template since no duplicates can appear. It is unlikely // able to transplant S_work into T->x since the input will almost always be // unsorted. #include "GB_build.h" #include "GB_sort.h" #ifndef GBCOMPACT #include "GB_red__include.h" #endif #define GB_I_WORK(t) (((t) < 0) ? -1 : I_work [t]) #define GB_J_WORK(t) (((t) < 0) ? -1 : ((J_work == NULL) ? 0 : J_work [t])) #define GB_K_WORK(t) (((t) < 0) ? -1 : ((K_work == NULL) ? t : K_work [t])) #define GB_FREE_WORK \ { \ GB_FREE_MEMORY (tstart_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (tnvec_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (tnz_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (kbad, nthreads, sizeof (int64_t)) ; \ GB_FREE_MEMORY (ilast_slice, nthreads, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*I_work_handle, ijslen, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*J_work_handle, ijslen, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*S_work_handle, ijslen, ssize) ; \ GB_FREE_MEMORY (K_work, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W0, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; \ } //------------------------------------------------------------------------------ // GB_builder //------------------------------------------------------------------------------ GrB_Info GB_builder // build a matrix from tuples ( GrB_Matrix *Thandle, // matrix T to build const GrB_Type ttype, // type of output matrix T const int64_t vlen, // length of each vector of T const int64_t vdim, // number of vectors in T const bool is_csc, // true if T is CSC, false if CSR int64_t **I_work_handle, // for (i,k) or (j,i,k) tuples int64_t **J_work_handle, // for (j,i,k) tuples GB_void **S_work_handle, // array of values of tuples, size ijslen bool known_sorted, // true if tuples known to be sorted bool known_no_duplicates, // true if tuples known to not have dupl int64_t ijslen, // size of I_work and J_work arrays const bool is_matrix, // true if T a GrB_Matrix, false if vector const bool ijcheck, // true if I_input,J_input must be checked const int64_t *GB_RESTRICT I_input,// original indices, size nvals const int64_t *GB_RESTRICT J_input,// original indices, size nvals const GB_void *GB_RESTRICT S_input,// array of values of tuples, size nvals const int64_t nvals, // number of tuples, and size of K_work const GrB_BinaryOp dup, // binary function to assemble duplicates, // if NULL use the SECOND operator to // keep the most recent duplicate. const GB_Type_code scode, // GB_Type_code of S_work or S_input array GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (Thandle != NULL) ; ASSERT (nvals >= 0) ; ASSERT (scode <= GB_UDT_code) ; ASSERT_TYPE_OK (ttype, "ttype for builder", GB0) ; ASSERT_BINARYOP_OK_OR_NULL (dup, "dup for builder", GB0) ; ASSERT (I_work_handle != NULL) ; ASSERT (J_work_handle != NULL) ; ASSERT (S_work_handle != NULL) ; //-------------------------------------------------------------------------- // get S //-------------------------------------------------------------------------- GB_void *GB_RESTRICT S_work = (*S_work_handle) ; const GB_void *GB_RESTRICT S = (S_work == NULL) ? S_input : S_work ; size_t tsize = ttype->size ; size_t ssize = GB_code_size (scode, tsize) ; ASSERT (GB_IMPLIES (nvals > 0, S != NULL)) ; //========================================================================== // symbolic phase of the build ============================================= //========================================================================== // The symbolic phase sorts the tuples and finds any duplicates. The // output matrix T is constructed (not including T->i and T->x), and T->h // and T->p are computed. Then I_work is transplanted into T->i, or T->i is // allocated. T->x is then allocated. It is not computed until the // numeric phase. // When this function returns, I_work is either freed or transplanted into // T->i. J_work is freed, and the I_work and J_work pointers (in the // caller) are set to NULL by setting their handles to NULL. Note that // J_work may already be NULL on input, if T has one or zero vectors // (J_work_handle is always non-NULL however). GrB_Info info ; GrB_Matrix T = NULL ; (*Thandle) = NULL ; int64_t *GB_RESTRICT I_work = (*I_work_handle) ; int64_t *GB_RESTRICT J_work = (*J_work_handle) ; int64_t *GB_RESTRICT K_work = NULL ; int64_t *GB_RESTRICT W0 = NULL ; int64_t *GB_RESTRICT W1 = NULL ; int64_t *GB_RESTRICT W2 = NULL ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (nvals, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t *GB_RESTRICT tstart_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT tnvec_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT tnz_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT kbad = NULL ; // size nthreads int64_t *GB_RESTRICT ilast_slice = NULL ; // size [nthreads] GB_CALLOC_MEMORY (tstart_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (tnvec_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (tnz_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (kbad, nthreads, sizeof (int64_t)) ; GB_CALLOC_MEMORY (ilast_slice, nthreads, sizeof (int64_t)) ; if (tstart_slice == NULL || tnvec_slice == NULL || tnz_slice == NULL || kbad == NULL || ilast_slice == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // partition the tuples for the threads //-------------------------------------------------------------------------- // Thread tid handles tuples tstart_slice [tid] to tstart_slice [tid+1]-1. // Each thread handles about the same number of tuples. This partition // depends only on nvals. tstart_slice [0] = 0 ; for (int tid = 1 ; tid < nthreads ; tid++) { tstart_slice [tid] = GB_PART (tid, nvals, nthreads) ; } tstart_slice [nthreads] = nvals ; // tstart_slice [tid]: first tuple in slice tid // tnvec_slice [tid]: # of vectors that start in a slice. If a vector // starts in one slice and ends in another, it is // counted as being in the first slice. // tnz_slice [tid]: # of entries in a slice after removing duplicates // sentinel values for the final cumulative sum tnvec_slice [nthreads] = 0 ; tnz_slice [nthreads] = 0 ; // this becomes true if the first pass computes tnvec_slice and tnz_slice, // and if the (I_input,J_input) tuples were found to be already sorted with // no duplicates present. bool tnvec_and_tnz_slice_computed = false ; //-------------------------------------------------------------------------- // STEP 1: copy user input and check if valid //-------------------------------------------------------------------------- // If the indices are provided by (I_input,J_input), then import them into // (I_work,J_work) and check if they are valid, and sorted. If the input // happens to be already sorted, then duplicates are detected and the # of // vectors in each slice is counted. if (I_work == NULL) { //---------------------------------------------------------------------- // allocate I_work //---------------------------------------------------------------------- // allocate workspace to load and sort the index tuples: // vdim <= 1: I_work and K_work for (i,k) tuples, where i = I_input [k] // vdim > 1: also J_work for (j,i,k) tuples where i = I_input [k] and // j = J_input [k]. If the tuples are found to be already sorted on // input, then J_work is not allocated, and J_input is used instead. // The k value in the tuple gives the position in the original set of // tuples: I_input [k] and S [k] when vdim <= 1, and also J_input [k] // for matrices with vdim > 1. // The workspace I_work and J_work are allocated here but freed (or // transplanted) inside GB_builder. K_work is allocated, used, and // freed in GB_builder. ASSERT (J_work == NULL) ; GB_MALLOC_MEMORY (I_work, nvals, sizeof (int64_t)) ; (*I_work_handle) = I_work ; ijslen = nvals ; if (I_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } //---------------------------------------------------------------------- // create the tuples to sort, and check for any invalid indices //---------------------------------------------------------------------- known_sorted = true ; bool no_duplicates_found = true ; if (nvals == 0) { //------------------------------------------------------------------ // nothing to do //------------------------------------------------------------------ ; } else if (is_matrix) { //------------------------------------------------------------------ // C is a matrix; check both I_input and J_input //------------------------------------------------------------------ ASSERT (J_input != NULL) ; ASSERT (I_work != NULL) ; ASSERT (vdim >= 0) ; ASSERT (I_input != NULL) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(&&:known_sorted) reduction(&&:no_duplicates_found) for (tid = 0 ; tid < nthreads ; tid++) { kbad [tid] = -1 ; int64_t my_tnvec = 0 ; int64_t kstart = tstart_slice [tid] ; int64_t kend = tstart_slice [tid+1] ; int64_t ilast = (kstart == 0) ? -1 : I_input [kstart-1] ; int64_t jlast = (kstart == 0) ? -1 : J_input [kstart-1] ; for (int64_t k = kstart ; k < kend ; k++) { // get k-th index from user input: (i,j) int64_t i = I_input [k] ; int64_t j = J_input [k] ; if (i < 0 || i >= vlen || j < 0 || j >= vdim) { // halt if out of bounds kbad [tid] = k ; break ; } // check if the tuples are already sorted known_sorted = known_sorted && ((jlast < j) || (jlast == j && ilast <= i)) ; // check if this entry is a duplicate of the one before it no_duplicates_found = no_duplicates_found && (!(jlast == j && ilast == i)) ; // copy the tuple into I_work. J_work is done later. I_work [k] = i ; if (j > jlast) { // vector j starts in this slice (but this is // valid only if J_input is sorted on input) my_tnvec++ ; } // log the last index seen ilast = i ; jlast = j ; } // these are valid only if I_input and J_input are sorted on // input, with no duplicates present. tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = kend - kstart ; } // collect the report from each thread for (int tid = 0 ; tid < nthreads ; tid++) { if (kbad [tid] >= 0) { // invalid index int64_t i = I_input [kbad [tid]] ; int64_t j = J_input [kbad [tid]] ; int64_t row = is_csc ? i : j ; int64_t col = is_csc ? j : i ; int64_t nrows = is_csc ? vlen : vdim ; int64_t ncols = is_csc ? vdim : vlen ; GB_FREE_WORK ; return (GB_ERROR (GrB_INDEX_OUT_OF_BOUNDS, (GB_LOG, "index ("GBd","GBd") out of bounds," " must be < ("GBd", "GBd")", row, col, nrows, ncols))) ; } } // if the tuples were found to be already in sorted order, and if // no duplicates were found, then tnvec_slice and tnz_slice are now // valid, Otherwise, they can only be computed after sorting. tnvec_and_tnz_slice_computed = known_sorted && no_duplicates_found ; //------------------------------------------------------------------ // allocate J_work, if needed //------------------------------------------------------------------ if (vdim > 1 && !known_sorted) { // copy J_input into J_work, so the tuples can be sorted GB_MALLOC_MEMORY (J_work, nvals, sizeof (int64_t)) ; (*J_work_handle) = J_work ; if (J_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } GB_memcpy (J_work, J_input, nvals * sizeof (int64_t), nthreads); } else { // J_work is a shallow copy of J_input. The pointer is not // copied into (*J_work_handle), so it will not be freed. // J_input is not modified, even though it is typecast to the // int64_t *J_work, since J_work is not modified in this case. J_work = (int64_t *) J_input ; } } else if (ijcheck) { //------------------------------------------------------------------ // C is a typecasted GrB_Vector; check only I_input //------------------------------------------------------------------ ASSERT (I_input != NULL) ; ASSERT (J_input == NULL) ; ASSERT (vdim == 1) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(&&:known_sorted) reduction(&&:no_duplicates_found) for (tid = 0 ; tid < nthreads ; tid++) { kbad [tid] = -1 ; int64_t kstart = tstart_slice [tid] ; int64_t kend = tstart_slice [tid+1] ; int64_t ilast = (kstart == 0) ? -1 : I_input [kstart-1] ; for (int64_t k = kstart ; k < kend ; k++) { // get k-th index from user input: (i) int64_t i = I_input [k] ; if (i < 0 || i >= vlen) { // halt if out of bounds kbad [tid] = k ; break ; } // check if the tuples are already sorted known_sorted = known_sorted && (ilast <= i) ; // check if this entry is a duplicate of the one before it no_duplicates_found = no_duplicates_found && (!(ilast == i)) ; // copy the tuple into the work arrays to be sorted I_work [k] = i ; // log the last index seen ilast = i ; } } // collect the report from each thread for (int tid = 0 ; tid < nthreads ; tid++) { if (kbad [tid] >= 0) { // invalid index int64_t i = I_input [kbad [tid]] ; GB_FREE_WORK ; return (GB_ERROR (GrB_INDEX_OUT_OF_BOUNDS, (GB_LOG, "index ("GBd") out of bounds, must be < ("GBd")", i, vlen))) ; } } } else { //------------------------------------------------------------------ // GB_reduce_to_vector: do not check I_input, assume not sorted //------------------------------------------------------------------ // Many duplicates are possible, since the tuples are being used to // construct a single vector. For a CSC format, each entry A(i,j) // becomes an (i,aij) tuple, with the vector index j discarded. All // entries in a single row i are reduced to a single entry in the // vector. The input is unlikely to be sorted, so do not bother to // check. GB_memcpy (I_work, I_input, nvals * sizeof (int64_t), nthreads) ; known_sorted = false ; } //---------------------------------------------------------------------- // determine if duplicates are possible //---------------------------------------------------------------------- // The input is now known to be sorted, or not. If it is sorted, and // if no duplicates were found, then it is known to have no duplicates. // Otherwise, duplicates might appear, but a sort is required first to // check for duplicates. known_no_duplicates = known_sorted && no_duplicates_found ; } //-------------------------------------------------------------------------- // STEP 2: sort the tuples in ascending order //-------------------------------------------------------------------------- // If the tuples are known to already be sorted, Step 2 is skipped. In // that case, K_work is NULL (not allocated), which implicitly means that // K_work [k] = k for all k = 0:nvals-1. if (!known_sorted) { // create the k part of each tuple GB_MALLOC_MEMORY (K_work, nvals, sizeof (int64_t)) ; if (K_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } // The k part of each tuple (i,k) or (j,i,k) records the original // position of the tuple in the input list. This allows an unstable // sorting algorith to be used. Since k is unique, it forces the // result of the sort to be stable regardless of whether or not the // sorting algorithm is stable. It also keeps track of where the // numerical value of the tuple can be found; it is in S[k] for the // tuple (i,k) or (j,i,k), regardless of where the tuple appears in the // list after it is sorted. int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nvals ; k++) { K_work [k] = k ; } // determine # of threads to use in the parallel mergesort int nth = GB_MSORT_NTHREADS (nthreads) ; // sort all the tuples if (vdim > 1) { //------------------------------------------------------------------ // sort a set of (j,i,k) tuples //------------------------------------------------------------------ if (nth > 1) { GB_MALLOC_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W1, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W2, nvals, sizeof (int64_t)) ; if (W0 == NULL || W1 == NULL || W2 == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } GB_msort_3 (J_work, I_work, K_work, W0, W1, W2, nvals, nth) ; } else { //------------------------------------------------------------------ // sort a set of (i,k) tuples //------------------------------------------------------------------ if (nth > 1) { GB_MALLOC_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W1, nvals, sizeof (int64_t)) ; if (W0 == NULL || W1 == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } GB_msort_2 (I_work, K_work, W0, W1, nvals, nth) ; } GB_FREE_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; GB_FREE_MEMORY (W2, nvals, sizeof (int64_t)) ; } //-------------------------------------------------------------------------- // STEP 3: count vectors and duplicates in each slice //-------------------------------------------------------------------------- // Duplicates are located, counted and their indices negated. The # of // vectors in each slice is counted. If the indices are known to not have // duplicates, then only the vectors are counted. Counting the # of // vectors is skipped if already done by Step 1. if (known_no_duplicates) { //---------------------------------------------------------------------- // no duplicates: just count # vectors in each slice //---------------------------------------------------------------------- // This is much faster, particularly if the # of vectors in each slice // has already been computed. #ifdef GB_DEBUG { // assert that there are no duplicates int64_t ilast = -1, jlast = -1 ; for (int64_t t = 0 ; t < nvals ; t++) { int64_t i = GB_I_WORK (t), j = GB_J_WORK (t) ; bool is_duplicate = (i == ilast && j == jlast) ; ASSERT (!is_duplicate) ; ilast = i ; jlast = j ; } } #endif if (vdim <= 1) { // all tuples appear in at most one vector, and there are no // duplicates, so there is no need to scan I_work or J_work. for (int tid = 0 ; tid < nthreads ; tid++) { int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; tnvec_slice [tid] = 0 ; tnz_slice [tid] = tend - tstart ; } tnvec_slice [0] = (nvals == 0) ? 0 : 1 ; } else { // count the # of unique vector indices in J_work. No need to scan // I_work since there are no duplicates to be found. Also no need // to compute them if already found in Step 1. if (!tnvec_and_tnz_slice_computed) { int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = 0 ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t j = J_work [t] ; if (j > jlast) { // vector j starts in this slice my_tnvec++ ; jlast = j ; } } tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = tend - tstart ; } } } } else { //---------------------------------------------------------------------- // look for duplicates and count # vectors in each slice //---------------------------------------------------------------------- for (int tid = 0 ; tid < nthreads ; tid++) { int64_t tstart = tstart_slice [tid] ; ilast_slice [tid] = GB_I_WORK (tstart-1) ; } int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = 0 ; int64_t my_ndupl = 0 ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t ilast = ilast_slice [tid] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t i = I_work [t] ; int64_t j = GB_J_WORK (t) ; // tuples are now sorted but there may be duplicates ASSERT ((jlast < j) || (jlast == j && ilast <= i)) ; // check if (j,i,k) is a duplicate if (i == ilast && j == jlast) { // flag the tuple as a duplicate I_work [t] = -1 ; my_ndupl++ ; // the sort places earlier duplicate tuples (with smaller // k) after later ones (with larger k). ASSERT (GB_K_WORK (t-1) < GB_K_WORK (t)) ; } else { // this is a new tuple if (j > jlast) { // vector j starts in this slice my_tnvec++ ; jlast = j ; } ilast = i ; } } tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = (tend - tstart) - my_ndupl ; } } //-------------------------------------------------------------------------- // find total # of vectors and duplicates in all tuples //-------------------------------------------------------------------------- // Replace tnvec_slice with its cumulative sum, after which each slice tid // will be responsible for the # vectors in T that range from tnvec_slice // [tid] to tnvec_slice [tid+1]-1. GB_cumsum (tnvec_slice, nthreads, NULL, 1) ; int64_t tnvec = tnvec_slice [nthreads] ; // Replace tnz_slice with its cumulative sum GB_cumsum (tnz_slice, nthreads, NULL, 1) ; // find the total # of final entries, after assembling duplicates int64_t tnz = tnz_slice [nthreads] ; int64_t ndupl = nvals - tnz ; //-------------------------------------------------------------------------- // allocate T; always hypersparse //-------------------------------------------------------------------------- // [ allocate T; allocate T->p and T->h but do not initialize them. // T is always hypersparse. GB_NEW (&T, ttype, vlen, vdim, GB_Ap_malloc, is_csc, GB_FORCE_HYPER, GB_ALWAYS_HYPER, tnvec, Context) ; if (info != GrB_SUCCESS) { // out of memory GB_FREE_WORK ; return (info) ; } ASSERT (T->is_hyper) ; ASSERT (T->nzmax == 0) ; // T->i and T->x not yet allocated ASSERT (T->x == NULL) ; ASSERT (T->i == NULL) ; (*Thandle) = T ; //-------------------------------------------------------------------------- // STEP 4: construct the vector pointers and hyperlist for T //-------------------------------------------------------------------------- // Step 4 scans the J_work indices and constructs T->h and T->p. int64_t *GB_RESTRICT Th = T->h ; int64_t *GB_RESTRICT Tp = T->p ; if (vdim <= 1) { //---------------------------------------------------------------------- // special case for vectors //---------------------------------------------------------------------- ASSERT (tnvec == 0 || tnvec == 1) ; if (tnvec > 0) { Th [0] = 0 ; Tp [0] = 0 ; } } else if (ndupl == 0) { //---------------------------------------------------------------------- // no duplicates appear //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = tnvec_slice [tid] ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t j = GB_J_WORK (t) ; if (j > jlast) { // vector j starts in this slice Th [my_tnvec] = j ; Tp [my_tnvec] = t ; my_tnvec++ ; jlast = j ; } } } } else { //---------------------------------------------------------------------- // it is known that at least one duplicate appears //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnz = tnz_slice [tid] ; int64_t my_tnvec = tnvec_slice [tid] ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t i = I_work [t] ; int64_t j = GB_J_WORK (t) ; if (i >= 0) { // this is a new tuple if (j > jlast) { // vector j starts in this slice Th [my_tnvec] = j ; Tp [my_tnvec] = my_tnz ; my_tnvec++ ; jlast = j ; } my_tnz++ ; } } } } // log the end of the last vector T->nvec_nonempty = tnvec ; T->nvec = tnvec ; Tp [tnvec] = tnz ; ASSERT (T->nvec == T->plen) ; T->magic = GB_MAGIC ; // T->p and T->h are now valid ] //-------------------------------------------------------------------------- // free J_work if it exists //-------------------------------------------------------------------------- ASSERT (J_work_handle != NULL) ; GB_FREE_MEMORY (*J_work_handle, ijslen, sizeof (int64_t)) ; J_work = NULL ; //-------------------------------------------------------------------------- // allocate T->i //-------------------------------------------------------------------------- T->nzmax = GB_IMAX (tnz, 1) ; if (ndupl == 0) { // shrink I_work from size ijslen to size T->nzmax if (T->nzmax < ijslen) { // this cannot fail since the size is shrinking. bool ok ; GB_REALLOC_MEMORY (I_work, T->nzmax, ijslen, sizeof (int64_t), &ok); ASSERT (ok) ; } // transplant I_work into T->i T->i = I_work ; I_work = NULL ; (*I_work_handle) = NULL ; } else { // duplicates exist, so allocate a new T->i. I_work must be freed later GB_MALLOC_MEMORY (T->i, tnz, sizeof (int64_t)) ; if (T->i == NULL) { // out of memory GB_MATRIX_FREE (Thandle) ; GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } int64_t *GB_RESTRICT Ti = T->i ; //========================================================================== // numerical phase of the build: assemble any duplicates //========================================================================== // The tuples have been sorted. Assemble any duplicates with a switch // factory of built-in workers, or four generic workers. The vector // pointers T->p and hyperlist T->h (if hypersparse) have already been // computed. // If there are no duplicates, T->i holds the row indices of the tuple. // Otherwise, the row indices are still in I_work. K_work holds the // positions of each tuple in the array S. The tuples are sorted so that // duplicates are adjacent to each other and they appear in the order they // appeared in the original tuples. This method assembles the duplicates // and computes T->i and T->x from I_work, K_work, and S. into T, becoming // T->i. If no duplicates appear, T->i is already computed, and S just // needs to be copied and permuted into T->x. // The (i,k,S[k]) tuples are held in two integer arrays: (1) I_work or T->i, // and (2) K_work, and an array S of numerical values. S has not been // sorted, nor even accessed yet. It is identical to the original unsorted // tuples. The (i,k,S[k]) tuple holds the row index i, the position k, and // the value S [k]. This entry becomes T(i,j) = S [k] in the matrix T, and // duplicates (if any) are assembled via the dup operator. //-------------------------------------------------------------------------- // get opcodes and check types //-------------------------------------------------------------------------- // With GB_build, there can be 1 to 2 different types. // T->type is identical to the types of x,y,z for z=dup(x,y). // dup is never NULL and all its three types are the same // The type of S (scode) can different but must be compatible // with T->type // With GB_wait, there can be 1 to 5 different types: // The pending tuples are in S, of type scode which must be // compatible with dup->ytype and T->type // z = dup (x,y): can be NULL or have 1 to 3 different types // T->type: must be compatible with all above types. // dup may be NULL, in which case it is assumed be the implicit SECOND // operator, with all three types equal to T->type GrB_Type xtype, ytype, ztype ; GxB_binary_function fdup ; #ifndef GBCOMPACT GB_Opcode opcode ; #endif GB_Type_code tcode = ttype->code ; bool op_2nd ; ASSERT_TYPE_OK (ttype, "ttype for build_factorize", GB0) ; if (dup == NULL) { //---------------------------------------------------------------------- // dup is the implicit SECOND operator //---------------------------------------------------------------------- // z = SECOND (x,y) where all three types are the same as ttype // T(i,j) = (ttype) S(k) will be done for all tuples. #ifndef GBCOMPACT opcode = GB_SECOND_opcode ; #endif ASSERT (GB_op_is_second (dup, ttype)) ; xtype = ttype ; ytype = ttype ; ztype = ttype ; fdup = NULL ; op_2nd = true ; } else { //---------------------------------------------------------------------- // dup is an explicit operator //---------------------------------------------------------------------- // T(i,j) = (ttype) S[k] will be done for the first tuple. // for subsequent tuples: T(i,j) += S[k], via the dup operator and // typecasting: // // y = (dup->ytype) S[k] // x = (dup->xtype) T(i,j) // z = (dup->ztype) dup (x,y) // T(i,j) = (ttype) z ASSERT_BINARYOP_OK (dup, "dup for build_factory", GB0) ; #ifndef GBCOMPACT opcode = dup->opcode ; #endif xtype = dup->xtype ; ytype = dup->ytype ; ztype = dup->ztype ; fdup = dup->function ; op_2nd = GB_op_is_second (dup, ttype) ; } //-------------------------------------------------------------------------- // get the sizes and codes of each type //-------------------------------------------------------------------------- GB_Type_code zcode = ztype->code ; GB_Type_code xcode = xtype->code ; GB_Type_code ycode = ytype->code ; ASSERT (GB_code_compatible (tcode, scode)) ; // T(i,j) = (ttype) S ASSERT (GB_code_compatible (ycode, scode)) ; // y = (ytype) S ASSERT (GB_Type_compatible (xtype, ttype)) ; // x = (xtype) T(i,j) ASSERT (GB_Type_compatible (ttype, ztype)) ; // T(i,j) = (ttype) z size_t zsize = ztype->size ; size_t xsize = xtype->size ; size_t ysize = ytype->size ; // no typecasting if all 5 types are the same bool nocasting = (tcode == scode) && (ttype == xtype) && (ttype == ytype) && (ttype == ztype) ; //-------------------------------------------------------------------------- // STEP 5: assemble the tuples //-------------------------------------------------------------------------- bool copy_S_into_T = (nocasting && known_sorted && ndupl == 0) ; if (copy_S_into_T && S_work != NULL) { //---------------------------------------------------------------------- // transplant S_work into T->x //---------------------------------------------------------------------- // No typecasting is needed, the tuples were originally in sorted // order, and no duplicates appear. All that is required is to copy S // into Tx. S can be directly transplanted into T->x since S is // provided as S_work. GB_builder must either transplant or free // S_work. The transplant can be used by GB_wait (whenever the tuples // are already sorted, with no duplicates, and no typecasting is // needed, since S_work is always A->Pending->x). This transplant can // rarely be used for GB_transpose (when op is NULL and the transposed // tuples happen to be sorted, which is unlikely). T->x = S_work ; S_work = NULL ; (*S_work_handle) = NULL ; } else { //---------------------------------------------------------------------- // allocate T->x //---------------------------------------------------------------------- GB_MALLOC_MEMORY (T->x, tnz, ttype->size) ; if (T->x == NULL) { // out of memory GB_MATRIX_FREE (Thandle) ; GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } GB_void *GB_RESTRICT Tx = T->x ; ASSERT (GB_IMPLIES (nvals > 0, S != NULL)) ; if (nvals == 0) { // nothing to do } else if (copy_S_into_T) { //------------------------------------------------------------------ // copy S into T->x //------------------------------------------------------------------ // No typecasting is needed, the tuples were originally in sorted // order, and no duplicates appear. All that is required is to // copy S into Tx. S cannot be transplanted into T->x since // S_work is NULL and S_input cannot be modified by GB_builder. ASSERT (S_work == NULL) ; ASSERT (S == S_input) ; GB_memcpy (Tx, S, nvals * tsize, nthreads) ; } else if (nocasting) { //------------------------------------------------------------------ // assemble the values, S, into T, no typecasting needed //------------------------------------------------------------------ // S (either S_work or S_input) must be permuted and copied into // T->x, since the tuples had to be sorted, or duplicates appear. // Any duplicates are now assembled. // There are 44 common cases of this function for built-in types // and 8 associative operators: MIN, MAX, PLUS, TIMES for 10 types // (all but boolean; and OR, AND, XOR, and EQ for boolean. // In addition, the FIRST and SECOND operators are hard-coded, for // another 22 workers, since SECOND is used by GB_wait and since // FIRST is useful for keeping the first tuple seen. It is // controlled by the GB_INCLUDE_SECOND_OPERATOR definition, so they // do not appear in GB_reduce_to_* where the FIRST and SECOND // operators are not needed. // Early exit cannot be exploited, so the terminal is ignored. #define GB_INCLUDE_SECOND_OPERATOR bool done = false ; #define GB_red(opname,aname) GB_red_build_ ## opname ## aname #define GB_RED_WORKER(opname,aname,atype) \ { \ info = GB_red (opname, aname) ((atype *) Tx, Ti, \ (atype *) S, nvals, ndupl, I_work, K_work, tstart_slice,\ tnz_slice, nthreads) ; \ done = (info != GrB_NO_VALUE) ; \ } \ break ; //------------------------------------------------------------------ // launch the switch factory //------------------------------------------------------------------ #ifndef GBCOMPACT // controlled by opcode and typecode GB_Type_code typecode = tcode ; #include "GB_red_factory.c" #endif //------------------------------------------------------------------ // generic worker //------------------------------------------------------------------ if (!done) { GB_BURBLE_N (nvals, "generic ") ; //-------------------------------------------------------------- // no typecasting, but use the fdup function pointer and memcpy //-------------------------------------------------------------- // Either the fdup operator or type of S and T are // user-defined, or fdup is not an associative operator handled // by the GB_red_factory, or some combination of these // conditions. User-defined types cannot be typecasted, so // this handles all user-defined types. // Tx [p] = (ttype) S [k], but with no typecasting #define GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ memcpy (Tx +((p)*tsize), S +((k)*tsize), tsize) ; if (op_2nd) { //---------------------------------------------------------- // dup is the SECOND operator, with no typecasting //---------------------------------------------------------- // Tx [p] += (ttype) S [k], but 2nd op and no typecasting #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) #include "GB_reduce_build_template.c" } else { //---------------------------------------------------------- // dup is another operator, with no typecasting needed //---------------------------------------------------------- // Tx [p] += (ttype) S [k], but with no typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ fdup (Tx +((p)*tsize), Tx +((p)*tsize), S +((k)*tsize)); #include "GB_reduce_build_template.c" } } } else { //------------------------------------------------------------------ // assemble the values S into T, typecasting as needed //------------------------------------------------------------------ GB_BURBLE_N (nvals, "generic ") ; // S (either S_work or S_input) must be permuted and copied into // T->x, since the tuples had to be sorted, or duplicates appear. // Any duplicates are now assembled. Not all of the 5 types are // the same, but all of them are built-in since user-defined types // cannot be typecasted. GB_cast_function cast_S_to_T = GB_cast_factory (tcode, scode) ; GB_cast_function cast_S_to_Y = GB_cast_factory (ycode, scode) ; GB_cast_function cast_T_to_X = GB_cast_factory (xcode, tcode) ; GB_cast_function cast_Z_to_T = GB_cast_factory (tcode, zcode) ; ASSERT (scode <= GB_FP64_code) ; ASSERT (tcode <= GB_FP64_code) ; ASSERT (xcode <= GB_FP64_code) ; ASSERT (ycode <= GB_FP64_code) ; ASSERT (zcode <= GB_FP64_code) ; // Tx [p] = (ttype) S [k], with typecasting #undef GB_CAST_ARRAY_TO_ARRAY #define GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ cast_S_to_T (Tx +((p)*tsize), S +((k)*ssize), ssize) ; if (op_2nd) { //-------------------------------------------------------------- // dup operator is the SECOND operator, with typecasting //-------------------------------------------------------------- // Tx [p] += (ttype) S [k], but 2nd op, with typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) #include "GB_reduce_build_template.c" } else { //-------------------------------------------------------------- // dup is another operator, with typecasting required //-------------------------------------------------------------- // Tx [p] += S [k], with typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ { \ /* ywork = (ytype) S [k] */ \ GB_void ywork [GB_VLA(ysize)] ; \ cast_S_to_Y (ywork, S +((k)*ssize), ssize) ; \ /* xwork = (xtype) Tx [p] */ \ GB_void xwork [GB_VLA(xsize)] ; \ cast_T_to_X (xwork, Tx +((p)*tsize), tsize) ; \ /* zwork = f (xwork, ywork) */ \ GB_void zwork [GB_VLA(zsize)] ; \ fdup (zwork, xwork, ywork) ; \ /* Tx [tnz-1] = (ttype) zwork */ \ cast_Z_to_T (Tx +((p)*tsize), zwork, zsize) ; \ } #include "GB_reduce_build_template.c" } } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK ; ASSERT_MATRIX_OK (T, "T built", GB0) ; return (GrB_SUCCESS) ; }
raja.h
// Liao 9/30/2016 // Minimal RAJA header #include <stdlib.h> // Simplest input and output code for as example namespace RAJA { typedef int Index_type; // new specialized policy struct switcher_exec{}; // input code , template 1 // Using pragma to specify which template to specialize for now #pragma xgen specialize_template template <typename EXEC_POLICY_T, typename LOOP_BODY> void forall(Index_type begin, Index_type end, LOOP_BODY loop_body) { forall( EXEC_POLICY_T(), begin, end, loop_body ); } // some prebuilt policies struct seq_exec {}; // the type for specialization struct omp_parallel_for_exec {}; struct omp_for_nowait_exec {}; struct omp_parallel_for_segit {}; struct omp_parallel_segit {}; struct omp_taskgraph_segit {}; struct omp_taskgraph_interval_segit {}; struct omp_reduce {}; // Some prebuilt specialization for sequential and parallel executions template <typename LOOP_BODY> void forall(seq_exec, Index_type begin, Index_type end, LOOP_BODY loop_body) { ; #pragma novector for ( Index_type ii = begin ; ii < end ; ++ii ) { loop_body( ii ); } ; } template <typename LOOP_BODY> void forall(omp_parallel_for_exec, Index_type begin, Index_type end, LOOP_BODY loop_body) { ; #pragma omp parallel for schedule(static) for ( Index_type ii = begin ; ii < end ; ++ii ) { loop_body( ii ); } ; } // We can assume this sub namespace is provided as input , including a list of execution policies namespace switcher { enum POLICY_TYPE { seq_exec = 0, omp_parallel_for_exec, NUM_POLICIES }; inline __attribute__((always_inline)) POLICY_TYPE getRandomPolicy() { int coin_toss = rand() % 2; if (coin_toss >= 1) { return seq_exec; } else { return omp_parallel_for_exec; } } } // end switcher namespace #if 0 // things we want to put into a library template <typename LOOP_BODY> void forall(switcher_exec, Index_type begin, Index_type end, LOOP_BODY loop_body) { switch(switcher::getRandomPolicy()) { case switcher::seq_exec: RAJA::forall( RAJA::seq_exec(), begin, end, loop_body ); break; case switcher::omp_parallel_for_exec: RAJA::forall( RAJA::omp_parallel_for_exec(), begin, end, loop_body ); break; } } #endif } // end namespace // g++ -c -std=c++11 // identityTranslator -rose:Cxx11_only
relic_cp_phpe.c
/* * RELIC is an Efficient LIbrary for Cryptography * Copyright (c) 2014 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 * * Implementation of Paillier's Homomorphic Probabilistic Encryption. * * @ingroup cp */ #include <string.h> #include "relic_core.h" #include "relic_multi.h" #include "relic_conf.h" #include "relic_rand.h" #include "relic_bn.h" #include "relic_util.h" #include "relic_cp.h" #include "relic_md.h" /*============================================================================*/ /* Public definitions */ /*============================================================================*/ int cp_phpe_gen(bn_t pub, phpe_t prv, int bits) { int result = RLC_OK; /* Generate primes p and q of equivalent length. */ do { bn_gen_prime(prv->p, bits / 2); bn_gen_prime(prv->q, bits / 2); } while (bn_cmp(prv->p, prv->q) == RLC_EQ); /* Compute n = pq and l = \phi(n). */ bn_mul(prv->n, prv->p, prv->q); #ifdef CP_CRT /* Fix g = n + 1. */ bn_add_dig(pub, prv->n, 1); /* Precompute dp = 1/(pow(g, p-1, p^2)//p mod p. */ bn_sqr(prv->dp, prv->p); bn_sub_dig(prv->p, prv->p, 1); bn_mxp(prv->dp, pub, prv->p, prv->dp); bn_sub_dig(prv->dp, prv->dp, 1); bn_div(prv->dp, prv->dp, prv->p); /* Precompute dq = 1/(pow(g, q-1, q^2)//q mod q. */ bn_sqr(prv->dq, prv->q); bn_sub_dig(prv->q, prv->q, 1); bn_mxp(prv->dq, pub, prv->q, prv->dq); bn_sub_dig(prv->dq, prv->dq, 1); bn_div(prv->dq, prv->dq, prv->q); /* Restore p and q. */ bn_add_dig(prv->p, prv->p, 1); bn_add_dig(prv->q, prv->q, 1); bn_mod_inv(prv->dp, prv->dp, prv->p); bn_mod_inv(prv->dq, prv->dq, prv->q); /* qInv = q^(-1) mod p. */ bn_mod_inv(prv->qi, prv->q, prv->p); #endif bn_copy(pub, prv->n); return result; } int cp_phpe_enc(bn_t c, bn_t m, bn_t pub) { bn_t g, r, s; int result = RLC_OK; bn_null(g); bn_null(r); bn_null(s); if (pub == NULL || bn_bits(m) > bn_bits(pub)) { return RLC_ERR; } RLC_TRY { bn_new(g); bn_new(r); bn_new(s); /* Generate r in Z_n^*. */ bn_rand_mod(r, pub); /* Compute c = (g^m)(r^n) mod n^2. */ bn_add_dig(g, pub, 1); bn_sqr(s, pub); bn_mxp(c, g, m, s); bn_mxp(r, r, pub, s); bn_mul(c, c, r); bn_mod(c, c, s); } RLC_CATCH_ANY { result = RLC_ERR; } RLC_FINALLY { bn_free(g); bn_free(r); bn_free(s); } return result; } int cp_phpe_dec(bn_t m, bn_t c, phpe_t prv) { bn_t s, t, u, v; int result = RLC_OK; if (prv == NULL || bn_bits(c) > 2 * bn_bits(prv->n)) { return RLC_ERR; } bn_null(s); bn_null(t); bn_null(u); bn_null(v); RLC_TRY { bn_new(s); bn_new(t); bn_new(u); bn_new(v); #if !defined(CP_CRT) bn_sub_dig(s, prv->p, 1); bn_sub_dig(t, prv->q, 1); bn_mul(s, s, t); /* Compute (c^l mod n^2) * u mod n. */ bn_sqr(t, prv->n); bn_mxp(m, c, s, t); bn_sub_dig(m, m, 1); bn_div(m, m, prv->n); bn_mod_inv(t, s, prv->n); bn_mul(m, m, t); bn_mod(m, m, prv->n); #else #if MULTI == OPENMP omp_set_num_threads(CORES); #pragma omp parallel copyin(core_ctx) firstprivate(c, prv) { #pragma omp sections { #pragma omp section { #endif /* Compute m_p = (c^(p-1) mod p^2) * dp mod p. */ bn_sub_dig(t, prv->p, 1); bn_sqr(s, prv->p); bn_mxp(s, c, t, s); bn_sub_dig(s, s, 1); bn_div(s, s, prv->p); bn_mul(s, s, prv->dp); bn_mod(s, s, prv->p); #if MULTI == OPENMP } #pragma omp section { #endif /* Compute m_q = (c^(q-1) mod q^2) * dq mod q. */ bn_sub_dig(v, prv->q, 1); bn_sqr(u, prv->q); bn_mxp(u, c, v, u); bn_sub_dig(u, u, 1); bn_div(u, u, prv->q); bn_mul(u, u, prv->dq); bn_mod(u, u, prv->q); #if MULTI == OPENMP } } } #endif /* m = (m_p - m_q) mod p. */ bn_sub(m, s, u); while (bn_sign(m) == RLC_NEG) { bn_add(m, m, prv->p); } bn_mod(m, m, prv->p); /* m1 = qInv(m_p - m_q) mod p. */ bn_mul(m, m, prv->qi); bn_mod(m, m, prv->p); /* m = m2 + m1 * q. */ bn_mul(m, m, prv->q); bn_add(m, m, u); bn_mod(m, m, prv->n); #endif } RLC_CATCH_ANY { result = RLC_ERR; } RLC_FINALLY { bn_free(s); bn_free(t); bn_free(u); bn_free(v); } return result; }
GB_binop__times_fc64.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__times_fc64 // A.*B function (eWiseMult): GB_AemultB__times_fc64 // A*D function (colscale): GB_AxD__times_fc64 // D*A function (rowscale): GB_DxB__times_fc64 // C+=B function (dense accum): GB_Cdense_accumB__times_fc64 // C+=b function (dense accum): GB_Cdense_accumb__times_fc64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__times_fc64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__times_fc64 // C=scalar+B GB_bind1st__times_fc64 // C=scalar+B' GB_bind1st_tran__times_fc64 // C=A+scalar GB_bind2nd__times_fc64 // C=A'+scalar GB_bind2nd_tran__times_fc64 // C type: GxB_FC64_t // A type: GxB_FC64_t // B,b type: GxB_FC64_t // BinaryOp: cij = GB_FC64_mul (aij, bij) #define GB_ATYPE \ GxB_FC64_t #define GB_BTYPE \ GxB_FC64_t #define GB_CTYPE \ GxB_FC64_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ GxB_FC64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ GxB_FC64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = GB_FC64_mul (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_TIMES || GxB_NO_FC64 || GxB_NO_TIMES_FC64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB_Cdense_ewise3_noaccum__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__times_fc64 ( 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__times_fc64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type GxB_FC64_t GxB_FC64_t bwork = (*((GxB_FC64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__times_fc64 ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *GB_RESTRICT kfirst_slice, const int64_t *GB_RESTRICT klast_slice, const int64_t *GB_RESTRICT pstart_slice, const int ntasks, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_DxB__times_fc64 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t *GB_RESTRICT Cx = (GxB_FC64_t *) 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__times_fc64 ( 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__times_fc64 ( 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__times_fc64 ( 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 GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t x = (*((GxB_FC64_t *) x_input)) ; GxB_FC64_t *Bx = (GxB_FC64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; GxB_FC64_t bij = Bx [p] ; Cx [p] = GB_FC64_mul (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__times_fc64 ( 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 ; GxB_FC64_t *Cx = (GxB_FC64_t *) Cx_output ; GxB_FC64_t *Ax = (GxB_FC64_t *) Ax_input ; GxB_FC64_t y = (*((GxB_FC64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; GxB_FC64_t aij = Ax [p] ; Cx [p] = GB_FC64_mul (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) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_mul (x, aij) ; \ } GrB_Info GB_bind1st_tran__times_fc64 ( 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 \ GxB_FC64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else GxB_FC64_t x = (*((const GxB_FC64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ GxB_FC64_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) \ { \ GxB_FC64_t aij = Ax [pA] ; \ Cx [pC] = GB_FC64_mul (aij, y) ; \ } GrB_Info GB_bind2nd_tran__times_fc64 ( 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 GxB_FC64_t y = (*((const GxB_FC64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply) // op(A') function: GB (_unop_tran) // C type: GB_ctype // A type: GB_atype // cast: GB_cast(cij,aij) // unaryop: GB_unaryop(cij,aij) #define GB_ATYPE \ GB_atype #define GB_CTYPE \ GB_ctype // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GB_geta(aij,Ax,pA) #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ GB_unaryop(z, x) ; // casting #define GB_CAST(z, aij) \ GB_cast(z, aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_geta(aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_cast(z, aij) ; \ GB_unaryop(Cx [pC], z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ GB_disable //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ if_unop_apply_enabled GrB_Info GB (_unop_apply) ( GB_ctype *Cx, // Cx and Ax may be aliased const GB_atype *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++) { GB_geta(aij, Ax, p) ; GB_cast(z, aij) ; GB_unaryop(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 ; GB_geta(aij, Ax, p) ; GB_cast(z, aij) ; GB_unaryop(Cx [p], z) ; } } return (GrB_SUCCESS) ; #endif } endif_unop_apply_enabled //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran) ( 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
cvsAdvDiff_bnd_omp.c
/* ----------------------------------------------------------------- * Programmer(s): Daniel Reynolds and Ting Yan @ SMU * Based on cvsAdvDiff_bnd.c and parallelized with OpenMP * ----------------------------------------------------------------- * SUNDIALS Copyright Start * Copyright (c) 2002-2021, Lawrence Livermore National Security * and Southern Methodist University. * All rights reserved. * * See the top-level LICENSE and NOTICE files for details. * * SPDX-License-Identifier: BSD-3-Clause * SUNDIALS Copyright End * ----------------------------------------------------------------- * Example problem: * * The following is a simple example problem with a banded Jacobian, * solved using CVODES. * The problem is the semi-discrete form of the advection-diffusion * equation in 2-D: * du/dt = d^2 u / dx^2 + .5 du/dx + d^2 u / dy^2 * on the rectangle 0 <= x <= 2, 0 <= y <= 1, and the time * interval 0 <= t <= 1. Homogeneous Dirichlet boundary conditions * are posed, and the initial condition is * u(x,y,t=0) = x(2-x)y(1-y)exp(5xy). * The PDE is discretized on a uniform MX+2 by MY+2 grid with * central differencing, and with boundary values eliminated, * leaving an ODE system of size NEQ = MX*MY. * This program solves the problem with the BDF method, Newton * iteration with the BAND linear solver, and a user-supplied * Jacobian routine. * It uses scalar relative and absolute tolerances. * Output is printed at t = .1, .2, ..., 1. * Run statistics (optional outputs) are printed at the end. * * Optionally, we can set the number of threads from environment * variable or command line. To check the current value for number * of threads from environment: * % echo $OMP_NUM_THREADS * * Execution: * * To use the default value or the number of threads from the * environment value, run without arguments: * % ./cvsAdvDiff_bnd_omp * The environment variable can be over-ridden with a command line * argument specifying the number of threads to use, e.g: * % ./cvsAdvDiff_bnd_omp 5 * ----------------------------------------------------------------- */ #include <stdio.h> #include <stdlib.h> #include <math.h> /* Header files with a description of contents */ #include <cvodes/cvodes.h> /* prototypes for CVODE fcts., consts. */ #include <nvector/nvector_openmp.h> /* serial N_Vector types, fcts., macros */ #include <sunmatrix/sunmatrix_band.h> /* access to band SUNMatrix */ #include <sunlinsol/sunlinsol_band.h> /* access to band SUNLinearSolver */ #include <sundials/sundials_types.h> /* definition of type realtype */ #ifdef _OPENMP #include <omp.h> #endif /* Problem Constants */ #define XMAX RCONST(2.0) /* domain boundaries */ #define YMAX RCONST(1.0) #define MX 10 /* mesh dimensions */ #define MY 5 #define NEQ MX*MY /* number of equations */ #define ATOL RCONST(1.0e-5) /* scalar absolute tolerance */ #define T0 RCONST(0.0) /* initial time */ #define T1 RCONST(0.1) /* first output time */ #define DTOUT RCONST(0.1) /* output time increment */ #define NOUT 10 /* number of output times */ #define ZERO RCONST(0.0) #define HALF RCONST(0.5) #define ONE RCONST(1.0) #define TWO RCONST(2.0) #define FIVE RCONST(5.0) /* User-defined vector access macro IJth */ /* IJth is defined in order to isolate the translation from the mathematical 2-dimensional structure of the dependent variable vector to the underlying 1-dimensional storage. IJth(vdata,i,j) references the element in the vdata array for u at mesh point (i,j), where 1 <= i <= MX, 1 <= j <= MY. The vdata array is obtained via the macro call vdata = NV_DATA_S(v), where v is an N_Vector. The variables are ordered by the y index j, then by the x index i. */ #define IJth(vdata,i,j) (vdata[(j-1) + (i-1)*MY]) /* Type : UserData (contains grid constants) */ typedef struct { realtype dx, dy, hdcoef, hacoef, vdcoef; int nthreads; } *UserData; /* Private Helper Functions */ static void SetIC(N_Vector u, UserData data); static void PrintHeader(realtype reltol, realtype abstol, realtype umax); static void PrintOutput(realtype t, realtype umax, long int nst); static void PrintFinalStats(void *cvode_mem); /* Private function to check function return values */ static int check_retval(void *returnvalue, char *funcname, int opt); /* Functions Called by the Solver */ static int f(realtype t, N_Vector u, N_Vector udot, void *user_data); static int Jac(realtype t, N_Vector u, N_Vector fu, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3); /* *------------------------------- * Main Program *------------------------------- */ int main(int argc, char *argv[]) { realtype dx, dy, reltol, abstol, t, tout, umax; N_Vector u; UserData data; SUNMatrix A; SUNLinearSolver LS; void *cvode_mem; int iout, retval; long int nst; int num_threads; u = NULL; data = NULL; A = NULL; LS = NULL; cvode_mem = NULL; /* Set the number of threads to use */ num_threads = 1; /* default value */ #ifdef _OPENMP num_threads = omp_get_max_threads(); /* Overwrite with OMP_NUM_THREADS environment variable */ #endif if (argc > 1) /* overwrite with command line value, if supplied */ num_threads = (int) strtol(argv[1], NULL, 0); /* Create an OpenMP vector */ u = N_VNew_OpenMP(NEQ, num_threads); /* Allocate u vector */ if(check_retval((void*)u, "N_VNew_OpenMP", 0)) return(1); reltol = ZERO; /* Set the tolerances */ abstol = ATOL; data = (UserData) malloc(sizeof *data); /* Allocate data memory */ if(check_retval((void *)data, "malloc", 2)) return(1); dx = data->dx = XMAX/(MX+1); /* Set grid coefficients in data */ dy = data->dy = YMAX/(MY+1); data->hdcoef = ONE/(dx*dx); data->hacoef = HALF/(TWO*dx); data->vdcoef = ONE/(dy*dy); data->nthreads = num_threads; SetIC(u, data); /* Initialize u vector */ /* Call CVodeCreate to create the solver memory and specify the * Backward Differentiation Formula */ cvode_mem = CVodeCreate(CV_BDF); if(check_retval((void *)cvode_mem, "CVodeCreate", 0)) return(1); /* Call CVodeInit to initialize the integrator memory and specify the * user's right hand side function in u'=f(t,u), the inital time T0, and * the initial dependent variable vector u. */ retval = CVodeInit(cvode_mem, f, T0, u); if(check_retval(&retval, "CVodeInit", 1)) return(1); /* Call CVodeSStolerances to specify the scalar relative tolerance * and scalar absolute tolerance */ retval = CVodeSStolerances(cvode_mem, reltol, abstol); if (check_retval(&retval, "CVodeSStolerances", 1)) return(1); /* Set the pointer to user-defined data */ retval = CVodeSetUserData(cvode_mem, data); if(check_retval(&retval, "CVodeSetUserData", 1)) return(1); /* Create banded SUNMatrix for use in linear solves -- since this will be factored, set the storage bandwidth to be the sum of upper and lower bandwidths */ A = SUNBandMatrix(NEQ, MY, MY); if(check_retval((void *)A, "SUNBandMatrix", 0)) return(1); /* Create banded SUNLinearSolver object for use by CVode */ LS = SUNLinSol_Band(u, A); if(check_retval((void *)LS, "SUNLinSol_Band", 0)) return(1); /* Call CVodeSetLinearSolver to attach the matrix and linear solver to CVode */ retval = CVodeSetLinearSolver(cvode_mem, LS, A); if(check_retval(&retval, "CVodeSetLinearSolver", 1)) return(1); /* Set the user-supplied Jacobian routine Jac */ retval = CVodeSetJacFn(cvode_mem, Jac); if(check_retval(&retval, "CVodeSetJacFn", 1)) return(1); /* In loop over output points: call CVode, print results, test for errors */ umax = N_VMaxNorm(u); PrintHeader(reltol, abstol, umax); for(iout=1, tout=T1; iout <= NOUT; iout++, tout += DTOUT) { retval = CVode(cvode_mem, tout, u, &t, CV_NORMAL); if(check_retval(&retval, "CVode", 1)) break; umax = N_VMaxNorm(u); retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); PrintOutput(t, umax, nst); } PrintFinalStats(cvode_mem); /* Print some final statistics */ printf("num_threads = %i\n\n", num_threads); N_VDestroy(u); /* Free the u vector */ CVodeFree(&cvode_mem); /* Free the integrator memory */ SUNLinSolFree(LS); /* Free the linear solver memory */ SUNMatDestroy(A); /* Free the matrix memory */ free(data); /* Free the user data */ return(0); } /* *------------------------------- * Functions called by the solver *------------------------------- */ /* f routine. Compute f(t,u). */ static int f(realtype t, N_Vector u,N_Vector udot, void *user_data) { realtype uij, udn, uup, ult, urt, hordc, horac, verdc, hdiff, hadv, vdiff; realtype *udata, *dudata; sunindextype i, j; UserData data; i = j = 0; udata = NV_DATA_OMP(u); dudata = NV_DATA_OMP(udot); /* Extract needed constants from data */ data = (UserData) user_data; hordc = data->hdcoef; horac = data->hacoef; verdc = data->vdcoef; /* Loop over all grid points. */ #pragma omp parallel for default(shared) private(j, i, uij, udn, uup, ult, urt, hdiff, hadv, vdiff) num_threads(data->nthreads) for (j=1; j <= MY; j++) { for (i=1; i <= MX; i++) { /* Extract u at x_i, y_j and four neighboring points */ uij = IJth(udata, i, j); udn = (j == 1) ? ZERO : IJth(udata, i, j-1); uup = (j == MY) ? ZERO : IJth(udata, i, j+1); ult = (i == 1) ? ZERO : IJth(udata, i-1, j); urt = (i == MX) ? ZERO : IJth(udata, i+1, j); /* Set diffusion and advection terms and load into udot */ hdiff = hordc*(ult - TWO*uij + urt); hadv = horac*(urt - ult); vdiff = verdc*(uup - TWO*uij + udn); IJth(dudata, i, j) = hdiff + hadv + vdiff; } } return(0); } /* Jacobian routine. Compute J(t,u). */ static int Jac(realtype t, N_Vector u, N_Vector fu, SUNMatrix J, void *user_data, N_Vector tmp1, N_Vector tmp2, N_Vector tmp3) { sunindextype i, j, k; realtype *kthCol, hordc, horac, verdc; UserData data; /* The components of f = udot that depend on u(i,j) are f(i,j), f(i-1,j), f(i+1,j), f(i,j-1), f(i,j+1), with df(i,j)/du(i,j) = -2 (1/dx^2 + 1/dy^2) df(i-1,j)/du(i,j) = 1/dx^2 + .25/dx (if i > 1) df(i+1,j)/du(i,j) = 1/dx^2 - .25/dx (if i < MX) df(i,j-1)/du(i,j) = 1/dy^2 (if j > 1) df(i,j+1)/du(i,j) = 1/dy^2 (if j < MY) */ i = j = k = 0; data = (UserData) user_data; hordc = data->hdcoef; horac = data->hacoef; verdc = data->vdcoef; #pragma omp parallel for collapse(2) default(shared) private(i, j, k, kthCol) num_threads(data->nthreads) for (j=1; j <= MY; j++) { for (i=1; i <= MX; i++) { k = j-1 + (i-1)*MY; kthCol = SUNBandMatrix_Column(J,k); /* set the kth column of J */ SM_COLUMN_ELEMENT_B(kthCol,k,k) = -TWO*(verdc+hordc); if (i != 1) SM_COLUMN_ELEMENT_B(kthCol,k-MY,k) = hordc + horac; if (i != MX) SM_COLUMN_ELEMENT_B(kthCol,k+MY,k) = hordc - horac; if (j != 1) SM_COLUMN_ELEMENT_B(kthCol,k-1,k) = verdc; if (j != MY) SM_COLUMN_ELEMENT_B(kthCol,k+1,k) = verdc; } } return(0); } /* *------------------------------- * Private helper functions *------------------------------- */ /* Set initial conditions in u vector */ static void SetIC(N_Vector u, UserData data) { sunindextype i, j; realtype x, y, dx, dy; realtype *udata; i = j = 0; /* Extract needed constants from data */ dx = data->dx; dy = data->dy; /* Set pointer to data array in vector u. */ udata = NV_DATA_OMP(u); /* Load initial profile into u vector */ #pragma omp parallel for default(shared) private(j, i, y, x) for (j=1; j <= MY; j++) { y = j*dy; for (i=1; i <= MX; i++) { x = i*dx; IJth(udata,i,j) = x*(XMAX - x)*y*(YMAX - y)*exp(FIVE*x*y); } } } /* Print first lines of output (problem description) */ static void PrintHeader(realtype reltol, realtype abstol, realtype umax) { printf("\n2-D Advection-Diffusion Equation\n"); printf("Mesh dimensions = %d X %d\n", MX, MY); printf("Total system size = %d\n", NEQ); #if defined(SUNDIALS_EXTENDED_PRECISION) printf("Tolerance parameters: reltol = %Lg abstol = %Lg\n\n", reltol, abstol); printf("At t = %Lg max.norm(u) =%14.6Le \n", T0, umax); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("Tolerance parameters: reltol = %g abstol = %g\n\n", reltol, abstol); printf("At t = %g max.norm(u) =%14.6e \n", T0, umax); #else printf("Tolerance parameters: reltol = %g abstol = %g\n\n", reltol, abstol); printf("At t = %g max.norm(u) =%14.6e \n", T0, umax); #endif return; } /* Print current value */ static void PrintOutput(realtype t, realtype umax, long int nst) { #if defined(SUNDIALS_EXTENDED_PRECISION) printf("At t = %4.2Lf max.norm(u) =%14.6Le nst = %4ld\n", t, umax, nst); #elif defined(SUNDIALS_DOUBLE_PRECISION) printf("At t = %4.2f max.norm(u) =%14.6e nst = %4ld\n", t, umax, nst); #else printf("At t = %4.2f max.norm(u) =%14.6e nst = %4ld\n", t, umax, nst); #endif return; } /* Get and print some final statistics */ static void PrintFinalStats(void *cvode_mem) { int retval; long int nst, nfe, nsetups, netf, nni, ncfn, nje, nfeLS; retval = CVodeGetNumSteps(cvode_mem, &nst); check_retval(&retval, "CVodeGetNumSteps", 1); retval = CVodeGetNumRhsEvals(cvode_mem, &nfe); check_retval(&retval, "CVodeGetNumRhsEvals", 1); retval = CVodeGetNumLinSolvSetups(cvode_mem, &nsetups); check_retval(&retval, "CVodeGetNumLinSolvSetups", 1); retval = CVodeGetNumErrTestFails(cvode_mem, &netf); check_retval(&retval, "CVodeGetNumErrTestFails", 1); retval = CVodeGetNumNonlinSolvIters(cvode_mem, &nni); check_retval(&retval, "CVodeGetNumNonlinSolvIters", 1); retval = CVodeGetNumNonlinSolvConvFails(cvode_mem, &ncfn); check_retval(&retval, "CVodeGetNumNonlinSolvConvFails", 1); retval = CVodeGetNumJacEvals(cvode_mem, &nje); check_retval(&retval, "CVodeGetNumJacEvals", 1); retval = CVodeGetNumLinRhsEvals(cvode_mem, &nfeLS); check_retval(&retval, "CVodeGetNumLinRhsEvals", 1); printf("\nFinal Statistics:\n"); printf("nst = %-6ld nfe = %-6ld nsetups = %-6ld nfeLS = %-6ld nje = %ld\n", nst, nfe, nsetups, nfeLS, nje); printf("nni = %-6ld ncfn = %-6ld netf = %ld\n", nni, ncfn, netf); return; } /* Check function return value... opt == 0 means SUNDIALS function allocates memory so check if returned NULL pointer opt == 1 means SUNDIALS function returns an integer value so check if retval < 0 opt == 2 means function allocates memory so check if returned NULL pointer */ static int check_retval(void *returnvalue, char *funcname, int opt) { int *retval; /* Check if SUNDIALS function returned NULL pointer - no memory allocated */ if (opt == 0 && returnvalue == NULL) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } /* Check if retval < 0 */ else if (opt == 1) { retval = (int *) returnvalue; if (*retval < 0) { fprintf(stderr, "\nSUNDIALS_ERROR: %s() failed with retval = %d\n\n", funcname, *retval); return(1); }} /* Check if function returned NULL pointer - no memory allocated */ else if (opt == 2 && returnvalue == NULL) { fprintf(stderr, "\nMEMORY_ERROR: %s() failed - returned NULL pointer\n\n", funcname); return(1); } return(0); }
FGT_fmt_plug.c
/* * Fortigate (FortiOS) Password cracker * * This software is Copyright (c) 2012 Mat G. <mat.jtr 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. * * Passwords are located in "config system admin" part of the configuration file : * * config system admin * edit "<username>" * set password ENC AK1wTiFOMv7mZOTvQNmKQBAY98hZZjSRLxAY8vZp8NlDWU= * * Password is : AK1|base64encode(salt|hashed_password) * where hashed_password is SHA1(salt|password|fortinet_magic) * * salt is 12 bytes long * hashed_password is 20 bytes long (SHA1 salt) * encoded password is 47 bytes long (3 bytes for AK1 and 44 bytes of base64encode(salt|hashed_password)) * */ #if FMT_EXTERNS_H extern struct fmt_main fmt_FGT; #elif FMT_REGISTERS_H john_register_one(&fmt_FGT); #else #include <string.h> #include "common.h" #include "formats.h" #include "misc.h" #include "sha.h" #include "base64.h" #include "simd-intrinsics.h" #ifdef _OPENMP #include <omp.h> #ifdef __MIC__ #ifndef OMP_SCALE #define OMP_SCALE 8192 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 32768 // tuned on AMD K8 dual-HT (XOP) #endif #endif // __MIC__ #endif #include "memdbg.h" #define FORMAT_LABEL "Fortigate" #define FORMAT_NAME "FortiOS" #define ALGORITHM_NAME "SHA1 " SHA1_ALGORITHM_NAME #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 32 #define CIPHERTEXT_LENGTH 44 #define HASH_LENGTH CIPHERTEXT_LENGTH + 3 #define BINARY_SIZE 20 #define BINARY_ALIGN 4 #define SALT_SIZE 12 #define SALT_ALIGN 4 #define FORTINET_MAGIC "\xa3\x88\xba\x2e\x42\x4c\xb0\x4a\x53\x79\x30\xc1\x31\x07\xcc\x3f\xa1\x32\x90\x29\xa9\x81\x5b\x70" #define FORTINET_MAGIC_LENGTH 24 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests fgt_tests[] = { {"AK1wTiFOMv7mZOTvQNmKQBAY98hZZjSRLxAY8vZp8NlDWU=", "fortigate"}, {"AK1Vd1SCGVtAAT931II/U22WTppAISQkITHOlz0ukIg4nA=", "admin"}, {"AK1DZLDpqz335ElPtuiNTpguiozY7xVaHjHYnxw6sNlI6A=", "ftnt"}, {NULL} }; static SHA_CTX ctx_salt; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static int (*saved_key_len); static uint32_t (*crypt_key)[BINARY_SIZE / sizeof(uint32_t)]; static void init(struct fmt_main *self) { #if defined (_OPENMP) int omp_t = 1; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_key)); saved_key_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key_len)); } static void done(void) { MEM_FREE(saved_key_len); MEM_FREE(crypt_key); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { if (strncmp(ciphertext, "AK1", 3)) return 0; if (strlen(ciphertext) != HASH_LENGTH) return 0; return 1; } static void * get_salt(char *ciphertext) { static union { char b[SALT_SIZE]; uint32_t dummy; } out; char buf[SALT_SIZE+BINARY_SIZE+1]; base64_decode(ciphertext+3, CIPHERTEXT_LENGTH, buf); memcpy(out.b, buf, SALT_SIZE); return out.b; } static void set_salt(void *salt) { SHA1_Init(&ctx_salt); SHA1_Update(&ctx_salt, salt, SALT_SIZE); } static void set_key(char *key, int index) { strnzcpy(saved_key[index], key, PLAINTEXT_LENGTH+1); saved_key_len[index] = strlen(key); } static char * get_key(int index) { return saved_key[index]; } static void * get_binary(char *ciphertext) { static union { char b[BINARY_SIZE]; uint32_t dummy; } bin; char buf[SALT_SIZE+BINARY_SIZE+1]; memset(buf, 0, sizeof(buf)); base64_decode(ciphertext+3, CIPHERTEXT_LENGTH, buf); // skip over the 12 bytes of salt and get only the hashed password memcpy(bin.b, buf+SALT_SIZE, BINARY_SIZE); return bin.b; } static int cmp_all(void *binary, int count) { uint32_t b0 = *(uint32_t *)binary; int i; for (i = 0; i < count; i++) { if (b0 != *(uint32_t *)crypt_key[i]) continue; if (!memcmp(binary, crypt_key[i], BINARY_SIZE)) return 1; } return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_key[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static int crypt_all(int *pcount, struct db_salt *salt) { int count = *pcount; int i=0; char *cp=FORTINET_MAGIC; #ifdef _OPENMP #pragma omp parallel for default(none) private(i) shared(ctx_salt, count, saved_key, saved_key_len, crypt_key, cp) #endif #if defined (_OPENMP) || MAX_KEYS_PER_CRYPT>1 for (i = 0; i < count; i++) #endif { SHA_CTX ctx; memcpy(&ctx, &ctx_salt, sizeof(ctx)); SHA1_Update(&ctx, saved_key[i], saved_key_len[i]); SHA1_Update(&ctx, cp, FORTINET_MAGIC_LENGTH); SHA1_Final((unsigned char*)crypt_key[i], &ctx); } return count; } static int get_hash_0(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_0; } static int get_hash_1(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_1; } static int get_hash_2(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_2; } static int get_hash_3(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_3; } static int get_hash_4(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_4; } static int get_hash_5(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_5; } static int get_hash_6(int index) { return ((uint32_t *)(crypt_key[index]))[0] & PH_MASK_6; } static int salt_hash(void *salt) { uint32_t mysalt = *(uint32_t *)salt; return mysalt & (SALT_HASH_SIZE - 1); } struct fmt_main fmt_FGT = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP , { NULL }, { NULL }, fgt_tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { NULL }, fmt_default_source, { fmt_default_binary_hash_0, fmt_default_binary_hash_1, fmt_default_binary_hash_2, fmt_default_binary_hash_3, fmt_default_binary_hash_4, fmt_default_binary_hash_5, fmt_default_binary_hash_6 }, salt_hash, NULL, set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
PReLU.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/PReLU.c" #else void THNN_(PReLU_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THTensor *weight) { THTensor_(resizeAs)(output, input); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { // handle shared parameter case real w = *THTensor_(data)(weight); TH_TENSOR_APPLY2(real, output, real, input, *output_data = (*input_data > 0) ? *input_data : w*(*input_data); ); return; } input = THTensor_(newContiguous)(input); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } real *output_data = THTensor_(data)(output); real *input_data = THTensor_(data)(input); real *weight_data = THTensor_(data)(weight); THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { real* n_input_data = input_data + i*nOutputPlane*ks; real* n_output_data = output_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { for (k = 0; k < ks; ++k) n_output_data[k] = (n_input_data[k] > 0) ? n_input_data[k] : weight_data[j] * n_input_data[k]; n_input_data += ks; n_output_data += ks; } } THTensor_(free)(input); } void THNN_(PReLU_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight) { THNN_CHECK_NELEMENT(input, gradOutput); THTensor_(resizeAs)(gradInput, input); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { real w = THTensor_(data)(weight)[0]; TH_TENSOR_APPLY3(real, gradInput, real, gradOutput, real, input, if ((*input_data) > 0) *gradInput_data = *gradOutput_data; else *gradInput_data = w * (*gradOutput_data); ); return; } input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); const real *weight_data = THTensor_(data)(weight); real *gradInput_data = THTensor_(data)(gradInput); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } THIndex_t i, j, k; #pragma omp parallel for private(j,k) for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; real *n_gradInput_data = gradInput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real w = weight_data[j]; for (k = 0; k < ks; ++k) { if (n_input_data[k] > 0) n_gradInput_data[k] = n_gradOutput_data[k]; else n_gradInput_data[k] = n_gradOutput_data[k] * w; } n_input_data += ks; n_gradInput_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } void THNN_(PReLU_accGradParameters)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *gradWeight, accreal scale_) { real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_); THNN_CHECK_NELEMENT(input, gradOutput); int64_t nOutputPlane = THTensor_(numel)(weight); if (nOutputPlane == 1) { real *gradWeight_data = THTensor_(data)(gradWeight); real sum = 0; TH_TENSOR_APPLY2(real, input, real, gradOutput, if ((*input_data) <= 0) sum += (*input_data) * (*gradOutput_data); ); gradWeight_data[0] += scale * sum; return; } THArgCheck(THTensor_(isContiguous)(gradWeight), 6, "gradWeight needs to be contiguous"); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); weight = THTensor_(newContiguous)(weight); int64_t bs = 1, ks = 1; { int64_t input_ndim = THTensor_(nDimension)(input); if (input->size[input_ndim > 1] != nOutputPlane) THError("Wrong number of input planes. Expected %d but got %d.", nOutputPlane, input->size[input_ndim > 1]); if (input_ndim > 1) { bs = input->size[0]; for (int d = 2; d < input_ndim; d++) { ks *= input->size[d]; } } } const real *input_data = THTensor_(data)(input); const real *gradOutput_data = THTensor_(data)(gradOutput); const real *weight_data = THTensor_(data)(weight); real *gradWeight_data = THTensor_(data)(gradWeight); THIndex_t i, j, k; for (i = 0; i < bs; ++i) { const real *n_input_data = input_data + i*nOutputPlane*ks; const real *n_gradOutput_data = gradOutput_data + i*nOutputPlane*ks; for (j = 0; j < nOutputPlane; ++j) { real sum = 0; for (k = 0; k < ks; ++k) if (n_input_data[k] <= 0) sum += n_gradOutput_data[k] * n_input_data[k]; gradWeight_data[j] += scale * sum; n_input_data += ks; n_gradOutput_data += ks; } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } #endif
SpatialConvolutionLocal.c
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "generic/SpatialConvolutionLocal.c" #else static inline void THNN_(SpatialConvolutionLocal_shapeCheck)( THTensor *input, THTensor *gradOutput, THTensor *weight, THTensor *bias, int kH, int kW, int dH, int dW, int padH, int padW, long inputHeight, long inputWidth, long outputHeight, long outputWidth) { THArgCheck(kW > 0 && kH > 0, 9, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); THArgCheck(dW > 0 && dH > 0, 11, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); int ndim = input->nDimension; int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } THNN_ARGCHECK(ndim == 3 || ndim == 4, 2, input, "3D or 4D input tensor expected but got: %s"); long nInputPlane = weight->size[2] / (kH * kW); long nOutputPlane = weight->size[1]; if (bias != NULL) { THNN_CHECK_DIM_SIZE(bias, 3, 0, nOutputPlane); THNN_CHECK_DIM_SIZE(bias, 3, 1, outputHeight); THNN_CHECK_DIM_SIZE(bias, 3, 2, outputWidth); } THNN_CHECK_DIM_SIZE(input, ndim, dimf, nInputPlane); if (gradOutput != NULL) { THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimf, nOutputPlane); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimh, outputHeight); THNN_CHECK_DIM_SIZE(gradOutput, ndim, dimw, outputWidth); } } static THTensor* THNN_(view_weight_local)(THTensor *_weight) { THTensor *weight = THTensor_(newContiguous)(_weight); THArgCheck(weight->nDimension == 3 || weight->nDimension == 6, 4, "weight tensor should be 3D or 6D - got %dD", weight->nDimension); if (weight->nDimension == 6) { long s1 = weight->size[0] * weight->size[1]; long s2 = weight->size[2]; long s3 = weight->size[3] * weight->size[4] * weight->size[5]; THTensor *old_weight = weight; weight = THTensor_(newWithStorage3d)(weight->storage, weight->storageOffset, s1, -1, s2, -1, s3, -1); THTensor_(free)(old_weight); } return weight; } static void THNN_(SpatialConvolutionLocal_updateOutput_frame) ( THTensor *input, THTensor *output, THTensor *weight, THTensor *bias, THTensor *finput, int kW, int kH, int dW, int dH, int padW, int padH, long nInputPlane, long inputWidth, long inputHeight, long nOutputPlane, long outputWidth, long outputHeight) { long i; THTensor *output3d, *finput3d; THNN_(unfolded_copy)(finput, input, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, outputWidth, outputHeight); THTensor_(copy)(output, bias); output3d = THTensor_(newWithStorage3d) (output->storage, output->storageOffset, outputHeight * outputWidth, 1, nOutputPlane, outputHeight * outputWidth, 1, nOutputPlane * outputHeight * outputWidth); finput3d = THTensor_(newWithStorage3d) (finput->storage, finput->storageOffset, outputHeight * outputWidth, 1, kW * kH * nInputPlane, outputHeight * outputWidth, 1, kW * kH * nInputPlane * outputHeight * outputWidth); // weight: oH*oW x nOutputPlane x nInputPlane*kH*kW // finput3d: oH*oW x nInputPlane*kH*kW x 1 THTensor_(baddbmm)(output3d, 1.0, output3d, 1.0, weight, finput3d); // output3d: oH*oW x nOutputPlane x 1 THTensor_(free)(output3d); THTensor_(free)(finput3d); } void THNN_(SpatialConvolutionLocal_updateOutput)( THNNState *state, THTensor *input, THTensor *output, THTensor *weight, THTensor *bias, THTensor *finput, THTensor *fgradInput, int kW, int kH, int dW, int dH, int padW, int padH, long inputWidth, long inputHeight, long outputWidth, long outputHeight) { weight = THNN_(view_weight_local)(weight); THNN_(SpatialConvolutionLocal_shapeCheck) (input, NULL, weight, bias, kH, kW, dH, dW, padH, padW, inputHeight, inputWidth, outputHeight, outputWidth); input = THTensor_(newContiguous)(input); long nInputPlane = THTensor_(size)(weight, 2)/ (kW * kH); long nOutputPlane = THTensor_(size)(weight, 1); if(input->nDimension == 3) { THTensor_(resize2d)(finput, kW*kH*nInputPlane, outputHeight*outputWidth); THTensor_(resize3d)(output, nOutputPlane, outputHeight, outputWidth); THNN_(SpatialConvolutionLocal_updateOutput_frame) (input, output, weight, bias, finput, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); } else { long T = input->size[0]; long t; THTensor_(resize3d)(finput, T, kW*kH*nInputPlane, outputHeight*outputWidth); THTensor_(resize4d)(output, T, nOutputPlane, outputHeight, outputWidth); #pragma omp parallel for private(t) for(t = 0; t < T; t++) { THTensor *input_t = THTensor_(newSelect)(input, 0, t); THTensor *output_t = THTensor_(newSelect)(output, 0, t); THTensor *finput_t = THTensor_(newSelect)(finput, 0, t); THNN_(SpatialConvolutionLocal_updateOutput_frame) (input_t, output_t, weight, bias, finput_t, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); THTensor_(free)(input_t); THTensor_(free)(output_t); THTensor_(free)(finput_t); } } THTensor_(free)(input); THTensor_(free)(weight); } static void THNN_(SpatialConvolutionLocal_updateGradInput_frame) (THTensor *gradInput, THTensor *gradOutput, THTensor *weight, THTensor *fgradInput, int kW, int kH, int dW, int dH, int padW, int padH, long nInputPlane, long inputWidth, long inputHeight, long nOutputPlane, long outputWidth, long outputHeight) { THTensor *gradOutput3d, *fgradInput3d; gradOutput3d = THTensor_(newWithStorage3d)(gradOutput->storage, gradOutput->storageOffset, outputHeight*outputWidth, 1, nOutputPlane, outputHeight*outputWidth, 1, nOutputPlane*outputHeight*outputWidth); fgradInput3d = THTensor_(newWithStorage3d)(fgradInput->storage, fgradInput->storageOffset, outputHeight*outputWidth, 1, kW*kH*nInputPlane, outputHeight*outputWidth, 1, kW*kH*nInputPlane*outputHeight*outputWidth); // weight: oH*oW x nInputPlane*kH*kW x nOutputPlane // gradOutput3d: oH*oW x nOutputPlane x 1 THTensor_(baddbmm)(fgradInput3d, 0.0, fgradInput3d, 1.0, weight, gradOutput3d); // fgradInput3d: oH*oW x nInputPlane*kH*kW x 1 THTensor_(free)(gradOutput3d); THTensor_(free)(fgradInput3d); THTensor_(zero)(gradInput); THNN_(unfolded_acc)(fgradInput, gradInput, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, outputWidth, outputHeight); } void THNN_(SpatialConvolutionLocal_updateGradInput)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradInput, THTensor *weight, THTensor *finput, THTensor *fgradInput, int kW, int kH, int dW, int dH, int padW, int padH, long inputWidth, long inputHeight, long outputWidth, long outputHeight) { weight = THNN_(view_weight_local)(weight); THNN_(SpatialConvolutionLocal_shapeCheck) (input, gradOutput, weight, NULL, kH, kW, dH, dW, padH, padW, inputHeight, inputWidth, outputHeight, outputWidth); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); long nInputPlane = THTensor_(size)(weight,2)/(kW*kH); long nOutputPlane = THTensor_(size)(weight,1); THTensor_(resizeAs)(gradInput, input); THTensor_(resizeAs)(fgradInput, finput); THTensor *tweight = THTensor_(new)(); THTensor_(transpose)(tweight, weight, 1, 2); if(input->nDimension == 3) { THNN_(SpatialConvolutionLocal_updateGradInput_frame) (gradInput, gradOutput, tweight, fgradInput, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); } else { long T = input->size[0]; long t; #pragma omp parallel for private(t) for(t = 0; t < T; t++) { THTensor *gradInput_t = THTensor_(newSelect)(gradInput, 0, t); THTensor *gradOutput_t = THTensor_(newSelect)(gradOutput, 0, t); THTensor *fgradInput_t = THTensor_(newSelect)(fgradInput, 0, t); THNN_(SpatialConvolutionLocal_updateGradInput_frame) (gradInput_t, gradOutput_t, tweight, fgradInput_t, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); THTensor_(free)(gradInput_t); THTensor_(free)(gradOutput_t); THTensor_(free)(fgradInput_t); } } THTensor_(free)(tweight); THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(weight); } static void THNN_(SpatialConvolutionLocal_accGradParameters_frame) (THTensor *gradOutput, THTensor *gradWeight, THTensor *gradBias, THTensor *finput, real scale, int kW, int kH, int dW, int dH, int padW, int padH, long nInputPlane, long inputWidth, long inputHeight, long nOutputPlane, long outputWidth, long outputHeight) { THTensor *gradOutput3d, *finput3d; gradOutput3d = THTensor_(newWithStorage3d)(gradOutput->storage, gradOutput->storageOffset, outputHeight*outputWidth, 1, nOutputPlane, outputHeight*outputWidth, 1, nOutputPlane*outputHeight*outputWidth); finput3d = THTensor_(newWithStorage3d)(finput->storage, finput->storageOffset, outputHeight*outputWidth, 1, 1, kW*kH*nInputPlane*outputHeight*outputWidth, kW*kH*nInputPlane, outputHeight*outputWidth); // gradOutput3d: oH*oW x nOutputPlane x 1 // finput3d: oH*oW x 1 x kW*kH*nInputPlane THTensor_(baddbmm)(gradWeight, 1.0, gradWeight, scale, gradOutput3d, finput3d); // gradWeight: oH*oW x nOutputPlane x kW*kH*nInputPlane THTensor_(cadd)(gradBias, gradBias, scale, gradOutput); THTensor_(free)(gradOutput3d); THTensor_(free)(finput3d); } void THNN_(SpatialConvolutionLocal_accGradParameters)( THNNState *state, THTensor *input, THTensor *gradOutput, THTensor *gradWeight, THTensor *gradBias, THTensor *finput, THTensor *fgradInput, int kW, int kH, int dW, int dH, int padW, int padH, long inputWidth, long inputHeight, long outputWidth, long outputHeight, accreal scale_) { THArgCheck(THTensor_(isContiguous)(gradWeight), 4, "gradWeight needs to be contiguous"); THArgCheck(THTensor_(isContiguous)(gradBias), 5, "gradBias needs to be contiguous"); real scale = TH_CONVERT_ACCREAL_TO_REAL(scale_); gradWeight = THNN_(view_weight_local)(gradWeight); THNN_(SpatialConvolutionLocal_shapeCheck) (input, gradOutput, gradWeight, gradBias, kH, kW, dH, dW, padH, padW, inputHeight, inputWidth, outputHeight, outputWidth); input = THTensor_(newContiguous)(input); gradOutput = THTensor_(newContiguous)(gradOutput); long nInputPlane = THTensor_(size)(gradWeight,2)/(kW*kH); long nOutputPlane = THTensor_(size)(gradWeight,1); if(input->nDimension == 3) { THNN_(SpatialConvolutionLocal_accGradParameters_frame) (gradOutput, gradWeight, gradBias, finput, scale, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); } else { long T = input->size[0]; long t; for(t = 0; t < T; t++) { THTensor *gradOutput_t = THTensor_(newSelect)(gradOutput, 0, t); THTensor *finput_t = THTensor_(newSelect)(finput, 0, t); THNN_(SpatialConvolutionLocal_accGradParameters_frame) (gradOutput_t, gradWeight, gradBias, finput_t, scale, kW, kH, dW, dH, padW, padH, nInputPlane, inputWidth, inputHeight, nOutputPlane, outputWidth, outputHeight); THTensor_(free)(gradOutput_t); THTensor_(free)(finput_t); } } THTensor_(free)(input); THTensor_(free)(gradOutput); THTensor_(free)(gradWeight); } #endif
teams_notarget_get_team_num.c
#include <stdlib.h> #include <stdio.h> #include <omp.h> #define N 10000 #define TOTAL_TEAMS 16 int main() { int n = N; int team_id; int team_counts[TOTAL_TEAMS]; int *a = (int *)malloc(n*sizeof(int)); for (int i = 0; i < TOTAL_TEAMS; i++) team_counts[i] = 0; #pragma omp teams distribute num_teams(TOTAL_TEAMS) for(int i = 0; i < n; i++) { team_id = omp_get_team_num(); a[i] = i; team_counts[team_id]++; } int err = 0; for(int i = 0; i < n; i++) { if (a[i] != i) { printf("Error at %d: a = %d, should be %d\n", i, a[i], i); err++; if (err > 10) break; } } for (int i = 0; i < TOTAL_TEAMS; i++) { if (team_counts[i] != N/TOTAL_TEAMS) { printf("Team id : %d is not shared with equal work. It is shared with %d iterations\n", i, team_counts[i]); err++; } } return err; }
mgl.h
/*************************************************************************** * mgl.h is part of Math Graphic Library * Copyright (C) 2007-2016 Alexey Balakin <mathgl.abalakin@gmail.ru> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #ifndef _MGL_H_ #define _MGL_H_ #include "mgl2/mgl_cf.h" #ifdef __cplusplus #include "mgl2/data.h" #include "mgl2/datac.h" #include <sys/stat.h> //----------------------------------------------------------------------------- /// Wrapper class for all graphics class MGL_EXPORT mglGraph { mglGraph(const mglGraph &) {} // copying is not allowed const mglGraph &operator=(const mglGraph &t) { return t; } protected: HMGL gr; public: mglGraph(int kind=0, int width=600, int height=400) { if(kind==-1) gr=NULL; #if MGL_HAVE_OPENGL else if(kind==1) gr=mgl_create_graph_gl(); #else else if(kind==1) { gr=mgl_create_graph(width, height); SetGlobalWarn("OpenGL support was disabled. Please, enable it and rebuild MathGL."); } #endif else gr=mgl_create_graph(width, height); } mglGraph(HMGL graph) { gr = graph; mgl_use_graph(gr,1); } virtual ~mglGraph() { if(mgl_use_graph(gr,-1)<1) mgl_delete_graph(gr); } /// Get pointer to internal HMGL object inline HMGL Self() { return gr; } /// Set default parameters for plotting inline void DefaultPlotParam() { mgl_set_def_param(gr); } /// Set name of plot for saving filename inline void SetPlotId(const char *id) { mgl_set_plotid(gr,id); } /// Get name of plot for saving filename inline const char *GetPlotId() { return mgl_get_plotid(gr); } /// Ask to stop drawing inline void Stop(bool stop=true) { mgl_ask_stop(gr, stop); } /// Check if plot termination is asked inline bool NeedStop() { return mgl_need_stop(gr); } /// Set callback function for event processing inline void SetEventFunc(void (*func)(void *), void *par=NULL) { mgl_set_event_func(gr, func, par); } /// Set the transparency on/off. inline void Alpha(bool enable) { mgl_set_alpha(gr, enable); } /// Set the gray-scale mode on/off. inline void Gray(bool enable) { mgl_set_gray(gr, enable); } /// Set default value of alpha-channel inline void SetAlphaDef(double alpha) { mgl_set_alpha_default(gr, alpha); } /// Set the transparency type (0 - usual, 1 - glass, 2 - lamp) inline void SetTranspType(int type) { mgl_set_transp_type(gr, type); } /// Set the size of semi-transparent area around lines, marks, glyphs, ... Default is 1. inline void SetPenDelta(double d) { mgl_pen_delta(gr,d); } /// Set the using of light on/off. inline void Light(bool enable) { mgl_set_light(gr, enable); } /// Switch on/off the specified light source. inline void Light(int n,bool enable) { mgl_set_light_n(gr, n, enable); } /// Use diffusive light (only for local light sources) -- OBSOLETE inline void SetDifLight(bool dif) { mgl_set_light_dif(gr, dif); } /// Set to attach light settings to inplot. inline void AttachLight(bool enable) { mgl_set_attach_light(gr, enable); } /// Add a light source. inline void AddLight(int n, mglPoint p, char col='w', double bright=0.5, double ap=0) { mgl_add_light_ext(gr, n, p.x, p.y, p.z, col, bright, ap); } inline void AddLight(int n, mglPoint r, mglPoint p, char col='w', double bright=0.5, double ap=0) { mgl_add_light_loc(gr, n, r.x, r.y, r.z, p.x, p.y, p.z, col, bright, ap); } /// Set ambient light brightness inline void SetAmbient(double i) { mgl_set_ambbr(gr, i); } /// Set diffusive light brightness inline void SetDiffuse(double i) { mgl_set_difbr(gr, i); } /// Set the fog distance or switch it off (if d=0). inline void Fog(double d, double dz=0.25) { mgl_set_fog(gr, d, dz); } /// Set relative width of rectangles in Bars, Barh, BoxPlot, Candle, OHLC (default is 0.7) inline void SetBarWidth(double width) { mgl_set_bar_width(gr, width); } /// Set default size of marks (locally you can use "size" option) inline void SetMarkSize(double size) { mgl_set_mark_size(gr, size); } /// Set default size of arrows (locally you can use "size" option) inline void SetArrowSize(double size) { mgl_set_arrow_size(gr, size); } /// Set number of mesh lines (use 0 to draw all of them) inline void SetMeshNum(int num) { mgl_set_meshnum(gr, num); } /// Set number of visible faces (use 0 to draw all of them) inline void SetFaceNum(int num) { mgl_set_facenum(gr, num); } /// Set cutting for points outside of bounding box inline void SetCut(bool cut) { mgl_set_cut(gr, cut); } /// Set additional cutting box inline void SetCutBox(mglPoint p1, mglPoint p2) { mgl_set_cut_box(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z); } /// Set the cutting off condition (formula) inline void CutOff(const char *EqC) { mgl_set_cutoff(gr, EqC); } /// Set default font size inline void SetFontSize(double size) { mgl_set_font_size(gr, size);} /// Set default font style and color inline void SetFontDef(const char *fnt) { mgl_set_font_def(gr, fnt); } /// Set FontSize by size in pt and picture DPI (default is 16 pt for dpi=72) virtual void SetFontSizePT(double pt, int dpi=72) { SetFontSize(pt*27.f/dpi); } /// Set FontSize by size in centimeters and picture DPI (default is 0.56 cm = 16 pt) inline void SetFontSizeCM(double cm, int dpi=72) { SetFontSizePT(cm*28.45f,dpi); } /// Set FontSize by size in inch and picture DPI (default is 0.22 in = 16 pt) inline void SetFontSizeIN(double in, int dpi=72) { SetFontSizePT(in*72.27f,dpi); } /// Load font from file inline void LoadFont(const char *name, const char *path=NULL) { mgl_load_font(gr, name, path); } /// Copy font from another mglGraph instance inline void CopyFont(const mglGraph *GR) { mgl_copy_font(gr, GR->gr);} /// Restore font (load default font for new HMGL objects) inline void RestoreFont() { mgl_restore_font(gr); } /// Set to use or not text rotation inline void SetRotatedText(bool rotated) { mgl_set_rotated_text(gr, rotated); } /// Set default font for all new HMGL and mglGraph objects static inline void SetDefFont(const char *name, const char *path=NULL) { mgl_def_font(name,path); } /// Set default palette inline void SetPalette(const char *colors) { mgl_set_palette(gr, colors); } /// Set default color scheme inline void SetDefScheme(const char *sch) { mgl_set_def_sch(gr, sch); } /// Sets RGB values for color with given id static inline void SetColor(char id, double r, double g, double b) { mgl_set_color(id, r, g, b); } /// Set mask for face coloring as array of type 'unsigned char[8]' static inline void SetMask(char id, const char *mask) { mgl_set_mask(id, mask); } /// Set mask for face coloring as uint64_t number static inline void SetMask(char id, uint64_t mask) { mgl_set_mask_val(id, mask); } /// Set default mask rotation angle inline void SetMaskAngle(int angle) { mgl_set_mask_angle(gr, angle); } /// Get last warning code inline int GetWarn() { return mgl_get_warn(gr);} /// Set warning code ant fill message inline void SetWarn(int code, const char *info) { mgl_set_warn(gr,code,info); } /// Get text of warning message(s) inline const char *Message() { return mgl_get_mess(gr); } /// Set global warning message static inline void SetGlobalWarn(const char *text) { mgl_set_global_warn(text); } /// Get text of global warning message(s) static inline const char *GlobalWarn() { return mgl_get_global_warn(); } /// Suppress printing warnings to stderr static inline void SuppressWarn(bool on) { mgl_suppress_warn(on); } /// Check if MathGL version is valid (return false) or not (return true) static inline bool CheckVersion(const char *ver) { return mgl_check_version(ver); } /// Set axis range scaling -- simplified way to shift/zoom axis range -- need to replot whole image! inline void ZoomAxis(mglPoint p1=mglPoint(0,0,0,0), mglPoint p2=mglPoint(1,1,1,1)) { mgl_zoom_axis(gr, p1.x,p1.y,p1.z,p1.c, p2.x,p2.y,p2.z,p2.c); } /// Add [v1, v2] to the current range in direction dir inline void AddRange(char dir, double v1, double v2) { mgl_add_range_val(gr, dir, v1, v2); } /// Set range in direction dir as [v1, v2] inline void SetRange(char dir, double v1, double v2) { mgl_set_range_val(gr, dir, v1, v2); } /// Set range in direction dir as minimal and maximal values of data a inline void SetRange(char dir, const mglDataA &dat, bool add=false) { mgl_set_range_dat(gr, dir, &dat, add); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz, const mglDataA &cc) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&cc,0); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy, const mglDataA &zz) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); mgl_set_range_dat(gr,'z',&zz,0); mgl_set_range_dat(gr,'c',&zz,0); } /// Set values of axis range as minimal and maximal values of corresponding data inline void SetRanges(const mglDataA &xx, const mglDataA &yy) { mgl_set_range_dat(gr,'x',&xx,0); mgl_set_range_dat(gr,'y',&yy,0); } /// Set values of axis ranges inline void SetRanges(double x1, double x2, double y1, double y2, double z1=0, double z2=0) { mgl_set_ranges(gr, x1, x2, y1, y2, z1, z2); } /// Set values of axis ranges inline void SetRanges(mglPoint p1, mglPoint p2) { mgl_set_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z); } /// Set ranges for automatic variables inline void SetAutoRanges(double x1, double x2, double y1=0, double y2=0, double z1=0, double z2=0, double c1=0, double c2=0) { mgl_set_auto_ranges(gr, x1, x2, y1, y2, z1, z2, c1, c2); } /// Set ranges for automatic variables inline void SetAutoRanges(mglPoint p1, mglPoint p2) { mgl_set_auto_ranges(gr, p1.x, p2.x, p1.y, p2.y, p1.z, p2.z, p1.c, p2.c); } /// Set axis origin inline void SetOrigin(mglPoint p) { mgl_set_origin(gr, p.x, p.y, p.z); } inline void SetOrigin(double x0, double y0, double z0=mglNaN) { mgl_set_origin(gr, x0, y0, z0); } /// Set the transformation formulas for coordinate. Use "" or NULL for built-in ones inline void SetFunc(const char *EqX, const char *EqY, const char *EqZ=NULL, const char *EqA=NULL) { mgl_set_func(gr, EqX, EqY, EqZ, EqA); } /// Set one of predefined transformation rule inline void SetCoor(int how) { mgl_set_coor(gr, how); } /// Set to draw Ternary axis (triangle like axis, grid and so on) /** val=1 for Ternary axis (a+b+c=1, z=z), * val=2 for Quaternary axis (a+b+c+d=1), * val|4 for projections. */ inline void Ternary(int val) { mgl_set_ternary(gr, val); } /// Set to use or not tick labels rotation inline void SetTickRotate(bool val) { mgl_set_tick_rotate(gr,val); } /// Set to use or not tick labels skipping inline void SetTickSkip(bool val) { mgl_set_tick_skip(gr,val); } /// Set tick length inline void SetTickLen(double len, double stt=1) { mgl_set_tick_len(gr, len, stt); } /// Set axis and ticks style inline void SetAxisStl(const char *stl="k", const char *tck=0, const char *sub=0) { mgl_set_axis_stl(gr, stl, tck, sub); } /// Set time templates for ticks inline void SetTicksTime(char dir, double d=0, const char *t="") { mgl_set_ticks_time(gr,dir,d,t); } /// Set ticks text (\n separated). Use "" to disable this feature. inline void SetTicksVal(char dir, const char *lbl, bool add=false) { mgl_set_ticks_str(gr,dir,lbl,add); } inline void SetTicksVal(char dir, const wchar_t *lbl, bool add=false) { mgl_set_ticks_wcs(gr,dir,lbl,add); } /// Set ticks position and text (\n separated). Use "" to disable this feature. inline void SetTicksVal(char dir, const mglDataA &v, const char *lbl, bool add=false) { mgl_set_ticks_val(gr,dir,&v,lbl,add); } inline void SetTicksVal(char dir, const mglDataA &v, const wchar_t *lbl, bool add=false) { mgl_set_ticks_valw(gr,dir,&v,lbl,add); } /// Add manual tick at given position. Use "" to disable this feature. inline void AddTick(char dir, double val, const char *lbl) { mgl_add_tick(gr,dir,val,lbl); } inline void AddTick(char dir, double val, const wchar_t *lbl) { mgl_add_tickw(gr,dir,val,lbl); } /// Set the ticks parameters and string for its factor inline void SetTicks(char dir, double d=0, int ns=0, double org=mglNaN, const char *factor="") { mgl_set_ticks_fact(gr, dir, d, ns, org, factor); } inline void SetTicks(char dir, double d, int ns, double org, const wchar_t *factor) { mgl_set_ticks_factw(gr, dir, d, ns, org, factor); } /// Auto adjust ticks inline void Adjust(const char *dir="xyzc") { mgl_adjust_ticks(gr, dir); } /// Set templates for ticks inline void SetTickTempl(char dir, const char *t) { mgl_set_tick_templ(gr,dir,t); } inline void SetTickTempl(char dir, const wchar_t *t) { mgl_set_tick_templw(gr,dir,t); } /// Tune ticks (tune|1 for common multiplier, tune|2 for common component) inline void SetTuneTicks(int tune, double fact_pos=1.15) { mgl_tune_ticks(gr, tune, fact_pos); } /// Set additional shift of tick labels inline void SetTickShift(mglPoint p) { mgl_set_tick_shift(gr,p.x,p.y,p.z,p.c); } /// Set to use UTC time instead of local time inline void SetTimeUTC(bool enable) { mgl_set_flag(gr,enable, MGL_USE_GMTIME); } /// Set to draw tick labels at axis origin inline void SetOriginTick(bool enable=true) { mgl_set_flag(gr,!enable, MGL_NO_ORIGIN); } /// Put further plotting in m-th cell of nx*ny grid of the image. /** String \a style may contain: * '<' for reserving space at left * '>' for reserving space at right * '^' for reserving space at top * '_' for reserving space at bottom * '#' for using whole region. */ inline void SubPlot(int nx,int ny,int m,const char *style="<>_^", double dx=0, double dy=0) { mgl_subplot_d(gr, nx, ny, m, style, dx, dy); } /// Put further plotting in rectangle of dx*dy cells starting from m-th cell of nx*ny grid of the image. /** String \a style may contain: * '<' for reserving space at left * '>' for reserving space at right * '^' for reserving space at top * '_' for reserving space at bottom * '#' for using whole region. */ inline void MultiPlot(int nx,int ny,int m, int dx, int dy, const char *style="<>_^") { mgl_multiplot(gr, nx, ny, m, dx, dy, style); } /// Put further plotting in a region [x1,x2]*[y1,y2] of the image or subplot (x1,x2,y1,y2 in range [0, 1]). inline void InPlot(double x1,double x2,double y1,double y2, bool rel=true) { if(rel) mgl_relplot(gr, x1, x2, y1, y2); else mgl_inplot(gr, x1, x2, y1, y2); } /// Put further plotting in column cell of previous subplot inline void ColumnPlot(int num, int ind, double d=0) { mgl_columnplot(gr,num,ind,d); } /// Put further plotting in matrix cell of previous subplot inline void GridPlot(int nx, int ny, int ind, double d=0) { mgl_gridplot(gr,nx,ny,ind,d); } /// Put further plotting in cell of stick rotated on angles tet, phi inline void StickPlot(int num, int i, double tet, double phi) { mgl_stickplot(gr,num,i,tet,phi); } /// Put further plotting in cell of stick sheared on sx, sy. inline void ShearPlot(int num, int i, mreal sx, mreal sy, mreal xd=1, mreal yd=0) { mgl_shearplot(gr,num,i,sx,sy,xd,yd); } /// Set factor of plot size inline void SetPlotFactor(double val) { mgl_set_plotfactor(gr,val); } /// Push transformation matrix into stack inline void Push() { mgl_mat_push(gr); } /// Pop transformation matrix from stack inline void Pop() { mgl_mat_pop(gr); } /// Add title for current subplot/inplot /** Style '#' draw box around the title. */ inline void Title(const char *title,const char *stl="",double size=-2) { mgl_title(gr,title,stl,size); } /// Add title for current subplot/inplot /** Style '#' draw box around the title. */ inline void Title(const wchar_t *title,const char *stl="",double size=-2) { mgl_titlew(gr,title,stl,size); } /// Set aspect ratio for further plotting. inline void Aspect(double Ax,double Ay,double Az=1) { mgl_aspect(gr, Ax, Ay, Az); } /// Shear a further plotting. inline void Shear(double Sx,double Sy) { mgl_shear(gr, Sx, Sy); } /// Rotate a further plotting. inline void Rotate(double TetX,double TetZ=0,double TetY=0) { mgl_rotate(gr, TetX, TetZ, TetY); } /// Rotate a further plotting around vector {x,y,z}. inline void RotateN(double Tet,double x,double y,double z) { mgl_rotate_vector(gr, Tet, x, y, z); } /// Set perspective (in range [0,1)) for plot. Set to zero for switching off. inline void Perspective(double val) { mgl_perspective(gr, val); } /// Set angle of view independently from Rotate(). inline void View(double TetX,double TetZ=0,double TetY=0) { mgl_view(gr, TetX, TetZ, TetY); } /// Set angle of view independently from Rotate(). inline void ViewAsRotate(double TetZ,double TetX,double TetY=0) { mgl_view(gr, -TetX, -TetZ, -TetY); } /// Zoom in/out a part of picture (use Zoom(0, 0, 1, 1) for restore default) inline void Zoom(double x1, double y1, double x2, double y2) { mgl_zoom(gr, x1, y1, x2, y2); } /// Set size of frame in pixels. Normally this function is called internally. inline void SetSize(int width, int height, bool clf=true) { if(clf) mgl_set_size(gr, width, height); else mgl_scale_size(gr, width, height); } /// Scaling for all further set size calls. static inline void SetSizeScl(double scl) { mgl_set_size_scl(scl); } /// Set plot quality /** qual=0 -- no face drawing (fastest), * qual=1 -- no color interpolation (fast), * qual=2 -- high quality (normal), * qual|4 -- direct bitmap drawing (low memory usage); * qual|8 for dots drawing instead of primitives (extremely fast). */ inline void SetQuality(int qual=MGL_DRAW_NORM) { mgl_set_quality(gr, qual); } /// Get plot quality inline int GetQuality() { return mgl_get_quality(gr); } /// Set drawing region for Quality&4 inline void SetDrawReg(long nx=1, long ny=1, long m=0) { mgl_set_draw_reg(gr,nx,ny,m); } /// Start group of objects inline void StartGroup(const char *name) { mgl_start_group(gr, name); } /// End group of objects inline void EndGroup() { mgl_end_group(gr); } /// Highlight objects with given id inline void Highlight(int id) { mgl_highlight(gr, id); } /// Show current image inline void ShowImage(const char *viewer, bool keep=0) { mgl_show_image(gr, viewer, keep); } /// Write the frame in file (depending extension, write current frame if fname is empty) inline void WriteFrame(const char *fname=0,const char *descr="") { mgl_write_frame(gr, fname, descr); } /// Write the frame in file using JPEG format inline void WriteJPEG(const char *fname,const char *descr="") { mgl_write_jpg(gr, fname, descr); } /// Write the frame in file using PNG format with transparency inline void WritePNG(const char *fname,const char *descr="", bool alpha=true) { if(alpha) mgl_write_png(gr, fname, descr); else mgl_write_png_solid(gr, fname, descr); } /// Write the frame in file using BMP format inline void WriteBMP(const char *fname,const char *descr="") { mgl_write_bmp(gr, fname, descr); } /// Write the frame in file using BMP format inline void WriteTGA(const char *fname,const char *descr="") { mgl_write_tga(gr, fname, descr); } /// Write the frame in file using PostScript format inline void WriteEPS(const char *fname,const char *descr="") { mgl_write_eps(gr, fname, descr); } /// Write the frame in file using LaTeX format inline void WriteTEX(const char *fname,const char *descr="") { mgl_write_tex(gr, fname, descr); } /// Write the frame in file using PostScript format as bitmap inline void WriteBPS(const char *fname,const char *descr="") { mgl_write_bps(gr, fname, descr); } /// Write the frame in file using SVG format inline void WriteSVG(const char *fname,const char *descr="") { mgl_write_svg(gr, fname, descr); } /// Write the frame in file using GIF format (only for current frame!) inline void WriteGIF(const char *fname,const char *descr="") { mgl_write_gif(gr, fname, descr); } /// Write the frame in file using OBJ format inline void WriteOBJ(const char *fname,const char *descr="",bool use_png=true) { mgl_write_obj(gr, fname, descr, use_png); } /// Write the frame in file using OBJ format - Balakin way inline void WriteOBJold(const char *fname,const char *descr="",bool use_png=true) { mgl_write_obj_old(gr, fname, descr, use_png); } /// Write the frame in file using XYZ format inline void WriteXYZ(const char *fname,const char *descr="") { mgl_write_xyz(gr, fname, descr); } /// Write the frame in file using STL format (faces only) inline void WriteSTL(const char *fname,const char *descr="") { mgl_write_stl(gr, fname, descr); } /// Write the frame in file using OFF format inline void WriteOFF(const char *fname,const char *descr="", bool colored=false) { mgl_write_off(gr, fname, descr,colored); } // /// Write the frame in file using X3D format // inline void WriteX3D(const char *fname,const char *descr="") // { mgl_write_x3d(gr, fname, descr); } /// Write the frame in file using PRC format inline void WritePRC(const char *fname,const char *descr="",bool make_pdf=true) { mgl_write_prc(gr, fname, descr, make_pdf); } /// Export in JSON format suitable for later drawing by JavaScript inline void WriteJSON(const char *fname,const char *descr="",bool force_z=false) { if(force_z) mgl_write_json_z(gr, fname, descr); else mgl_write_json(gr, fname, descr); } /// Return string of JSON data suitable for later drawing by JavaScript inline const char *GetJSON() { return mgl_get_json(gr); } /// Force preparing the image. It can be useful for OpenGL mode mostly. inline void Finish() { mgl_finish(gr); } /// Create new frame. inline void NewFrame() { mgl_new_frame(gr); } /// Finish frame drawing inline void EndFrame() { mgl_end_frame(gr); } /// Get the number of created frames inline int GetNumFrame() { return mgl_get_num_frame(gr); } /// Reset frames counter (start it from zero) inline void ResetFrames() { mgl_reset_frames(gr); } /// Delete primitives for i-th frame (work if MGL_VECT_FRAME is set on) inline void DelFrame(int i) { mgl_del_frame(gr, i); } /// Get drawing data for i-th frame (work if MGL_VECT_FRAME is set on) inline void GetFrame(int i) { mgl_get_frame(gr, i); } /// Set drawing data for i-th frame (work if MGL_VECT_FRAME is set on). Work as EndFrame() but don't add frame to GIF image. inline void SetFrame(int i) { mgl_set_frame(gr, i); } /// Append drawing data from i-th frame (work if MGL_VECT_FRAME is set on) inline void ShowFrame(int i){ mgl_show_frame(gr, i); } /// Clear list of primitives for current drawing inline void ClearFrame() { mgl_clear_frame(gr); } /// Start write frames to cinema using GIF format inline void StartGIF(const char *fname, int ms=100) { mgl_start_gif(gr, fname,ms); } /// Stop writing cinema using GIF format inline void CloseGIF() { mgl_close_gif(gr); } /// Export points and primitives in file using MGLD format inline void ExportMGLD(const char *fname, const char *descr=0) { mgl_export_mgld(gr, fname, descr); } /// Import points and primitives from file using MGLD format inline void ImportMGLD(const char *fname, bool add=false) { mgl_import_mgld(gr, fname, add); } /// Copy RGB values into array which is allocated by user /** Position of element {i,j} is [3*i + 3*Width*j]. */ inline bool GetRGB(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=3*w*h) memcpy(imgdata, mgl_get_rgb(gr),3*w*h); return imglen>=3*w*h; } /// Get RGB values of current bitmap /** Position of element {i,j} is [3*i + 3*Width*j]. */ inline const unsigned char *GetRGB() { return mgl_get_rgb(gr); } /// Copy RGBA values into array which is allocated by user /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline bool GetRGBA(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=4*w*h) memcpy(imgdata, mgl_get_rgba(gr),4*w*h); return imglen>=4*w*h; } /// Get RGBA values of current bitmap /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline const unsigned char *GetRGBA() { return mgl_get_rgba(gr); } /// Copy BGRN values into array which is allocated by user inline bool GetBGRN(unsigned char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr), i; const unsigned char *buf=mgl_get_rgb(gr); if(imglen>=4*w*h) for(i=0;i<w*h;i++) { imgdata[4*i] = buf[3*i+2]; imgdata[4*i+1] = buf[3*i+1]; imgdata[4*i+2] = buf[3*i]; imgdata[4*i+3] = 255; } return imglen>=4*w*h; } /// Copy RGBA values of background image into array which is allocated by user /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline bool GetBackground(char *imgdata, int imglen) { long w=mgl_get_width(gr), h=mgl_get_height(gr); if(imglen>=4*w*h) memcpy(imgdata, mgl_get_background(gr),4*w*h); return imglen>=4*w*h; } /// Get RGBA values of background image /** Position of element {i,j} is [4*i + 4*Width*j]. */ inline const unsigned char *GetBackground() { return mgl_get_background(gr); } /// Get width of the image inline int GetWidth() { return mgl_get_width(gr); } /// Get height of the image inline int GetHeight() { return mgl_get_height(gr);} /// Calculate 3D coordinate {x,y,z} for screen point {xs,ys} inline mglPoint CalcXYZ(int xs, int ys) { mreal x,y,z; mgl_calc_xyz(gr,xs,ys,&x,&y,&z); return mglPoint(x,y,z); } /// Calculate screen point {xs,ys} for 3D coordinate {x,y,z} inline mglPoint CalcScr(mglPoint p) { int xs,ys; mgl_calc_scr(gr,p.x,p.y,p.z,&xs,&ys); return mglPoint(xs,ys); } /// Set object/subplot id inline void SetObjId(int id) { mgl_set_obj_id(gr,id); } /// Get object id inline int GetObjId(long x,long y) { return mgl_get_obj_id(gr,x,y); } /// Get subplot id inline int GetSplId(long x,long y) { return mgl_get_spl_id(gr,x,y); } /// Check if {\a xs,\a ys} is close to active point with accuracy d, and return its position or -1 inline long IsActive(int xs, int ys, int d=1) { return mgl_is_active(gr,xs,ys,d); } /// Combine plots from 2 canvases. Result will be saved into this inline void Combine(const mglGraph *g) { mgl_combine_gr(gr,g->gr); } /// Clear up the frame and fill background by specified color inline void Clf(double r, double g, double b) { mgl_clf_rgb(gr, r, g, b); } /// Clear up the frame and fill background by specified color with manual transparency inline void Clf(const char *col) { mgl_clf_str(gr, col); } /// Clear up the frame and fill background by specified color inline void Clf(char col) { mgl_clf_chr(gr, col); } /// Clear up the frame inline void Clf() { mgl_clf(gr); } /// Clear unused points and primitives. Useful only in combination with SetFaceNum(). inline void ClearUnused() { mgl_clear_unused(gr); } /// Load background image inline void LoadBackground(const char *fname, double alpha=1) { mgl_load_background(gr,fname,alpha); } /// Force drawing the image and use it as background one inline void Rasterize() { mgl_rasterize(gr); } /// Draws the point (ball) at position {x,y,z} with color c inline void Ball(mglPoint p, char c='r') { char s[3]={'.',c,0}; mgl_mark(gr, p.x, p.y, p.z, s); } /// Draws the mark at position p inline void Mark(mglPoint p, const char *mark) { mgl_mark(gr, p.x, p.y, p.z, mark); } /// Draws the line between points by specified pen /** Large \a n (for example, n=100) should be used for geodesic line in curved coordinates */ inline void Line(mglPoint p1, mglPoint p2, const char *pen="B",int n=2) { mgl_line(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, pen, n); } /// Draws the spline curve between points by specified pen inline void Curve(mglPoint p1, mglPoint d1, mglPoint p2, mglPoint d2, const char *pen="B", int n=100) { mgl_curve(gr, p1.x, p1.y, p1.z, d1.x, d1.y, d1.z, p2.x, p2.y, p2.z, d2.x, d2.y, d2.z, pen, n); } /// Draws the 3d error box e for point p inline void Error(mglPoint p, mglPoint e, const char *pen="k") { mgl_error_box(gr, p.x, p.y, p.z, e.x, e.y, e.z, pen); } /// Draws Lamerey diagram for mapping x_new = f(x_old) /** String \a stl may contain: ‘v’ for drawing arrows; ‘~’ for disable 1st segment. * Option value set the number of segments (default is 20).*/ inline void Lamerey(double x0, const mglDataA &f, const char *stl="", const char *opt="") { mgl_lamerey_dat(gr,x0,&f,stl,opt); } inline void Lamerey(double x0, const char *func, const char *stl="", const char *opt="") { mgl_lamerey_str(gr,x0,func,stl,opt); } /// Draws Bifurcation diagram for mapping x_new = f(x_old) in x-axis range /** Option value set the number of stationary points (default is 1024).*/ inline void Bifurcation(double dx, const mglDataA &f, const char *stl="", const char *opt="") { mgl_bifurcation_dat(gr,dx,&f,stl,opt); } inline void Bifurcation(double dx, const char *func, const char *stl="", const char *opt="") { mgl_bifurcation_str(gr,dx,func,stl,opt); } /// Draws the face between points with color stl (include interpolation up to 4 colors). inline void Face(mglPoint p1, mglPoint p2, mglPoint p3, mglPoint p4, const char *stl="r") { mgl_face(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, p3.x, p3.y, p3.z, p4.x, p4.y, p4.z, stl); } /// Draws the face in y-z plane at point p with color stl (include interpolation up to 4 colors). inline void FaceX(mglPoint p, double wy, double wz, const char *stl="w", double dx=0, double dy=0) { mgl_facex(gr, p.x, p.y, p.z, wy, wz, stl, dx, dy); } /// Draws the face in x-z plane at point p with color stl (include interpolation up to 4 colors). inline void FaceY(mglPoint p, double wx, double wz, const char *stl="w", double dx=0, double dy=0) { mgl_facey(gr, p.x, p.y, p.z, wx, wz, stl, dx, dy); } /// Draws the face in x-y plane at point p with color stl (include interpolation up to 4 colors). inline void FaceZ(mglPoint p, double wx, double wy, const char *stl="w", double dx=0, double dy=0) { mgl_facez(gr, p.x, p.y, p.z, wx, wy, stl, dx, dy); } /// Draws the drop at point p in direction d with color col and radius r /** Parameter \a shift set the degree of drop oblongness: ‘0’ is sphere, ‘1’ is maximally oblongness drop. Parameter \a ap set relative width of the drop (this is analogue of “ellipticity” for the sphere).*/ inline void Drop(mglPoint p, mglPoint d, double r, const char *col="r", double shift=1, double ap=1) { mgl_drop(gr, p.x, p.y, p.z, d.x, d.y, d.z, r, col, shift, ap); } /// Draws the sphere at point p with color col and radius r inline void Sphere(mglPoint p, double r, const char *col="r") { mgl_sphere(gr, p.x, p.y, p.z, r, col); } /// Draws the cone between points p1,p2 with radius r1,r2 and with style stl /** Parameter \a stl can contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinder instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones.*/ inline void Cone(mglPoint p1, mglPoint p2, double r1, double r2=-1, const char *stl="r@") { mgl_cone(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z,r1,r2,stl); } /// Draws the ellipse between points p1,p2 with color stl and width r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Ellipse(mglPoint p1, mglPoint p2, double r, const char *stl="r") { mgl_ellipse(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); } /// Draws the circle at point p with color stl and radius r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Circle(mglPoint p, double r, const char *stl="r") { mgl_ellipse(gr, p.x, p.y, p.z, p.x, p.y, p.z, r,stl); } /// Draws the rhomb between points p1,p2 with color stl and width r /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Rhomb(mglPoint p1, mglPoint p2, double r, const char *stl="r") { mgl_rhomb(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, r,stl); } /// Draws the polygon based on points p1,p2 with color stl /** Parameter \a stl can contain: * ‘#’ for wired figure (boundary only); * ‘@’ for filled figure and with boundary (second color or black one is used for boundary).*/ inline void Polygon(mglPoint p1, mglPoint p2, int n, const char *stl="r") { mgl_polygon(gr, p1.x, p1.y, p1.z, p2.x, p2.y, p2.z, n,stl); } /// Draws the arc around axis pr with center at p0 and starting from p1, by color stl and angle a (in degrees) inline void Arc(mglPoint p0, mglPoint pr, mglPoint p1, double a, const char *stl="r") { mgl_arc_ext(gr, p0.x,p0.y,p0.z, pr.x,pr.y,pr.z, p1.x,p1.y,p1.z, a,stl); } /// Draws the arc around axis 'z' with center at p0 and starting from p1, by color stl and angle a (in degrees) inline void Arc(mglPoint p0, mglPoint p1, double a, const char *stl="r") { mgl_arc_ext(gr, p0.x,p0.y,p0.z, 0,0,1, p1.x,p1.y,p0.z, a,stl); } /// Draws bitmap (logo) which is stretched along whole axis range inline void Logo(long w, long h, const unsigned char *rgba, bool smooth=false, const char *opt="") { mgl_logo(gr, w, h, rgba, smooth, opt); } inline void Logo(const char *fname, bool smooth=false, const char *opt="") { mgl_logo_file(gr, fname, smooth, opt); } /// Print text in position p with specified font inline void Putsw(mglPoint p,const wchar_t *text,const char *font=":C",double size=-1) { mgl_putsw(gr, p.x, p.y, p.z, text, font, size); } /// Print text in position p with specified font inline void Puts(mglPoint p,const char *text,const char *font=":C",double size=-1) { mgl_puts(gr, p.x, p.y, p.z, text, font, size); } /// Print text in position p with specified font inline void Putsw(double x, double y,const wchar_t *text,const char *font=":AC",double size=-1) { mgl_putsw(gr, x, y, 0, text, font, size); } /// Print text in position p with specified font inline void Puts(double x, double y,const char *text,const char *font=":AC",double size=-1) { mgl_puts(gr, x, y, 0, text, font, size); } /// Print text in position p along direction d with specified font inline void Putsw(mglPoint p, mglPoint d, const wchar_t *text, const char *font=":L", double size=-1) { mgl_putsw_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); } /// Print text in position p along direction d with specified font inline void Puts(mglPoint p, mglPoint d, const char *text, const char *font=":L", double size=-1) { mgl_puts_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, text, font, size); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *font="", const char *opt="") { mgl_text_xyz(gr, &x, &y, &z, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const char *text, const char *font="", const char *opt="") { mgl_text_xy(gr, &x, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &y, const char *text, const char *font="", const char *opt="") { mgl_text_y(gr, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_xyz(gr, &x, &y, &z, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_xy(gr, &x, &y, text, font, opt); } /// Print text along the curve inline void Text(const mglDataA &y, const wchar_t *text, const char *font="", const char *opt="") { mgl_textw_y(gr, &y, text, font, opt); } /// Draws bounding box outside the plotting volume with color c. /** Style ‘@’ produce filled back faces. */ inline void Box(const char *col="", bool ticks=true) { mgl_box_str(gr, col, ticks); } /// Draw axises with ticks in direction(s) dir. /** Parameter \a dir may contain: * ‘xyzt’for drawing axis in corresponding direction; * ‘XYZT’ for drawing axis in corresponding direction but with inverted positions of labels; * ‘~’, ‘_’ for disabling tick labels; * ‘U’ for disabling rotation of tick labels; * ‘^’ for inverting default axis origin; * ‘!’ for disabling ticks tuning; * ‘AKDTVISO’ for drawing arrow at the end of axis; * ‘a’ for forced adjusting of axis ticks; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels. * Option "value" set the manual rotation angle for the ticks. */ inline void Axis(const char *dir="xyzt", const char *stl="", const char *opt="") { mgl_axis(gr, dir,stl,opt); } /// Draw grid lines perpendicular to direction(s) dir. inline void Grid(const char *dir="xyzt",const char *pen="B", const char *opt="") { mgl_axis_grid(gr, dir, pen, opt); } /// Print the label text for axis dir. /** Option "value" set additional shifting of the label. */ inline void Label(char dir, const char *text, double pos=+1, const char *opt="") { mgl_label(gr, dir, text, pos, opt); } /// Print the label text for axis dir. /** Option "value" set additional shifting of the label. */ inline void Label(char dir, const wchar_t *text, double pos=+1, const char *opt="") { mgl_labelw(gr, dir, text, pos, opt); } /// Draw colorbar at edge of axis /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const char *sch="") { mgl_colorbar(gr, sch); } /// Draw colorbar at manual position /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const char *sch,double x,double y,double w=1,double h=1) { mgl_colorbar_ext(gr, sch, x,y,w,h); } /// Draw colorbar with manual colors at edge of axis /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const mglDataA &val, const char *sch="") { mgl_colorbar_val(gr, &val, sch); } /// Draw colorbar with manual colors at manual position /** Parameter \a sch may contain: * ‘<>^_’ for positioning at left, at right, at top or at bottom correspondingly; * ‘I’ for positioning near bounding (by default, at edges of subplot); * ‘A’ for using absolute coordinates; * ‘~’ for disabling tick labels. * ‘!’ for disabling ticks tuning; * ‘f’ for printing ticks labels in fixed format; * ‘E’ for using ‘E’ instead of ‘e’ in ticks labels; * ‘F’ for printing ticks labels in LaTeX format; * ‘+’ for printing ‘+’ for positive ticks; * ‘-’ for printing usual ‘-’ in ticks labels; * ‘0123456789’ for precision at printing ticks labels.*/ inline void Colorbar(const mglDataA &val, const char *sch,double x,double y,double w=1,double h=1) { mgl_colorbar_val_ext(gr, &val, sch, x,y,w,h); } /// Add string to legend inline void AddLegend(const char *text,const char *style) { mgl_add_legend(gr, text, style); } inline void AddLegend(const wchar_t *text,const char *style) { mgl_add_legendw(gr, text, style); } /// Clear saved legend string inline void ClearLegend() { mgl_clear_legend(gr); } /// Draw legend of accumulated strings at position {x,y} /** Parameter fnt may contain: * font style for legend text; * colors for background (first one), border (second one) and text (last one); * ‘A’ for positioning in absolute coordinates; * ‘^’ for positioning outside of specified point; * ‘-’ for arranging entries horizontally; * ‘#’ for drawing box around legend. * Option value set the space between line samples and text (default is 0.1).*/ inline void Legend(double x, double y, const char *font="#", const char *opt="") { mgl_legend_pos(gr, x, y, font, opt); } /// Draw legend of accumulated strings /** Parameter fnt may contain: * font style for legend text; * colors for background (first one), border (second one) and text (last one); * ‘A’ for positioning in absolute coordinates; * ‘^’ for positioning outside of specified point; * ‘-’ for arranging entries horizontally; * ‘#’ for drawing box around legend. * Option value set the space between line samples and text (default is 0.1). * Parameter \a where sets position: 0 at bottom-left, 1 at bottom-right, 2 at top-left, 3 at top-right (default).*/ inline void Legend(int where=3, const char *font="#", const char *opt="") { mgl_legend(gr, where, font, opt); } /// Set number of marks in legend sample inline void SetLegendMarks(int num) { mgl_set_legend_marks(gr, num); } /// Draw usual curve {x,y,z} inline void Plot(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_plot_xyz(gr, &x, &y, &z, pen, opt); } /// Draw usual curve {x,y} inline void Plot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_plot_xy(gr, &x, &y, pen,opt); } /// Draw usual curve {x,y} with x in x-axis range inline void Plot(const mglDataA &y, const char *pen="", const char *opt="") { mgl_plot(gr, &y, pen,opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y,z} /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_tape_xyz(gr, &x, &y, &z, pen, opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y} /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_tape_xy(gr, &x, &y, pen,opt); } /// Draw tapes which rotates as (bi-)normales of curve {x,y} with x in x-axis range /** The width of tape is proportional to barwidth and can be changed by option "value".*/ inline void Tape(const mglDataA &y, const char *pen="", const char *opt="") { mgl_tape(gr, &y, pen,opt); } /// Draw radar chart (plot in curved coordinates) /** Option "value" set the additional shift of data (i.e. the data a+value is used instead of a).*/ inline void Radar(const mglDataA &a, const char *pen="", const char *opt="") { mgl_radar(gr, &a, pen, opt); } /// Draw stairs for points in arrays {x,y,z} inline void Step(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_step_xyz(gr, &x, &y, &z, pen, opt); } /// Draw stairs for points in arrays {x,y} inline void Step(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_step_xy(gr, &x, &y, pen, opt); } /// Draw stairs for points in arrays {x,y} with x in x-axis range inline void Step(const mglDataA &y, const char *pen="", const char *opt="") { mgl_step(gr, &y, pen, opt); } /// Draw curve {x,y,z} which is colored by c (like tension plot) inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens_xyz(gr, &x, &y, &z, &c, pen, opt); } /// Draw curve {x,y} which is colored by c (like tension plot) inline void Tens(const mglDataA &x, const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens_xy(gr, &x, &y, &c, pen, opt); } /// Draw curve {x,y} with x in x-axis range which is colored by c (like tension plot) inline void Tens(const mglDataA &y, const mglDataA &c, const char *pen="", const char *opt="") { mgl_tens(gr, &y, &c, pen, opt); } /// Fill area between curve {x,y,z} and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_area_xyz(gr, &x, &y, &z, pen, opt); } /// Fill area between curve {x,y} and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_area_xy(gr, &x, &y, pen, opt); } /// Fill area between curve {x,y} with x in x-axis range and axis plane /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Area(const mglDataA &y, const char *pen="", const char *opt="") { mgl_area(gr, &y, pen, opt); } /// Fill area between curves {x,y1} and {x,y2} with x in x-axis range /** Style 'i' will fill area only if y1 < y2. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region(gr, &y1, &y2, pen, opt); } /// Fill area between curves {x,y1} and {x,y2} /** Style 'i' will fill area only if y1 < y2. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region_xy(gr, &x, &y1, &y2, pen, opt); } /// Fill area (draw ribbon) between curves {x1,y1,z1} and {x2,y2,z2} /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &z1, const mglDataA &x2, const mglDataA &y2, const mglDataA &z2, const char *pen="", const char *opt="") { mgl_region_3d(gr, &x1, &y1, &z1, &x2, &y2, &z2, pen, opt); } /// Fill area (draw ribbon) between curves {x1,y1} and {x2,y2} /** Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Region(const mglDataA &x1, const mglDataA &y1, const mglDataA &x2, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_region_3d(gr, &x1, &y1, NULL, &x2, &y2, NULL, pen, opt); } /// Draw vertical lines from points {x,y,z} to axis plane inline void Stem(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_stem_xyz(gr, &x, &y, &z, pen, opt); } /// Draw vertical lines from points {x,y} to axis plane inline void Stem(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_stem_xy(gr, &x, &y, pen, opt); } /// Draw vertical lines from points {x,y} with x in x-axis range to axis plane inline void Stem(const mglDataA &y, const char *pen="", const char *opt="") { mgl_stem(gr, &y, pen, opt); } /// Draw vertical bars from points {x,y,z} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="", const char *opt="") { mgl_bars_xyz(gr, &x, &y, &z, pen, opt); } /// Draw vertical bars from points {x,y} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_bars_xy(gr, &x, &y, pen, opt); } /// Draw vertical bars from points {x,y} with x in x-axis range to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Bars(const mglDataA &y, const char *pen="", const char *opt="") { mgl_bars(gr, &y, pen, opt); } /// Draw horizontal bars from points {x,y} to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Barh(const mglDataA &y, const mglDataA &v, const char *pen="", const char *opt="") { mgl_barh_yx(gr, &y, &v, pen, opt); } /// Draw horizontal bars from points {x,y} with y in y-axis range to axis plane /** String \a pen may contain: * ‘a’ for drawing boxes one above another (like summation); * ‘f’ for waterfall chart; * ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Barh(const mglDataA &v, const char *pen="", const char *opt="") { mgl_barh(gr, &v, pen, opt); } /// Draw chart for data a /** Space denote transparent color. Style '#' draw black borders. */ inline void Chart(const mglDataA &a, const char *colors="", const char *opt="") { mgl_chart(gr, &a, colors,opt); } /// Draw Open-High-Low-Close (OHLC) diagram /** Different colors for up and down values are used if number of specified colors is equal to 2*number of curves. */ inline void OHLC(const mglDataA &x, const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="") { mgl_ohlc_x(gr, &x, &open,&high,&low,&close,pen,opt); } /// Draw Open-High-Low-Close (OHLC) diagram with x in x-axis range /** Different colors for up and down values are used if number of specified colors is equal to 2*number of curves. */ inline void OHLC(const mglDataA &open, const mglDataA &high, const mglDataA &low, const mglDataA &close, const char *pen="", const char *opt="") { mgl_ohlc(gr, &open,&high,&low,&close,pen,opt); } /// Draw box-plot (special 5-value plot used in statistic) /** String \a pen may contain ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right.*/ inline void BoxPlot(const mglDataA &x, const mglDataA &y, const char *pen="", const char *opt="") { mgl_boxplot_xy(gr, &x, &y, pen,opt); } /// Draw box-plot (special 5-value plot used in statistic) with x in x-axis range /** String \a pen may contain ‘<’, ‘^’, ‘>’ for aligning boxes: at left, centered, at right.*/ inline void BoxPlot(const mglDataA &y, const char *pen="", const char *opt="") { mgl_boxplot(gr, &y, pen,opt); } /// Draw candle plot /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &x, const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle_xyv(gr, &x, &v1, &v2, &y1, &y2, pen, opt); } /// Draw candle plot with x in x-axis range /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &v1, const mglDataA &v2, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle_yv(gr, &v1, &v2, &y1, &y2, pen, opt); } inline void Candle(const mglDataA &v1, const mglDataA &v2, const char *pen="", const char *opt="") { mgl_candle_yv(gr, &v1, &v2, NULL, NULL, pen, opt); } /// Draw candle plot with v1=v[i], v2=v[i+1] /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &y, const mglDataA &y1, const mglDataA &y2, const char *pen="", const char *opt="") { mgl_candle(gr, &y, &y1, &y2, pen, opt); } /// Draw candle plot with v1=v[i], v2=v[i+1] /** Different colors are used for up and down values if 2 colors are specified. * Style ‘#’ force drawing wire candle even for 2-color scheme. */ inline void Candle(const mglDataA &y, const char *pen="", const char *opt="") { mgl_candle(gr, &y, NULL, NULL, pen, opt); } /// Draw cones from points {x,y,z} to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones_xyz(gr, &x, &y, &z, pen, opt); } /// Draw cones from points {x,z} to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &x, const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones_xz(gr, &x, &z, pen, opt); } /// Draw cones from points {x,z} with x in x-axis range to axis plane /** String \a pen may contain: * ‘@’ for drawing edges; * ‘#’ for wired cones; * ‘t’ for drawing tubes/cylinders instead of cones/prisms; * ‘4’, ‘6’, ‘8’ for drawing square, hex- or octo-prism instead of cones; * ‘<’, ‘^’ or ‘>’ for aligning cones left, right or centering them at its x-coordinates. * Gradient filling is used if number of specified colors is equal to 2*number of curves.*/ inline void Cones(const mglDataA &z, const char *pen="@", const char *opt="") { mgl_cones(gr, &z, pen, opt); } /// Draw error boxes {ey} at points {x,y} with x in x-axis range /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error(gr, &y, &ey, pen, opt); } /// Draw error boxes {ey} at points {x,y} /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error_xy(gr, &x, &y, &ey, pen, opt); } /// Draw error boxes {ex,ey} at points {x,y} /** Style ‘@’ set to draw large semitransparent mark instead of error box.*/ inline void Error(const mglDataA &x, const mglDataA &y, const mglDataA &ex, const mglDataA &ey, const char *pen="", const char *opt="") { mgl_error_exy(gr, &x, &y, &ex, &ey, pen, opt); } /// Draw marks with size r at points {x,y,z} inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_xyz(gr, &x, &y, &z, &r, pen, opt); } /// Draw marks with size r at points {x,y} inline void Mark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_xy(gr, &x, &y, &r, pen, opt); } /// Draw marks with size r at points {x,y} with x in x-axis range inline void Mark(const mglDataA &y, const mglDataA &r, const char *pen, const char *opt="") { mgl_mark_y(gr, &y, &r, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y,z} inline void Pmap(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap_xyz(gr, &x, &y, &z, &s, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y} inline void Pmap(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap_xy(gr, &x, &y, &s, pen, opt); } /// Draw Poincare map at condition s==0 for curve {x,y} with x in x-axis range inline void Pmap(const mglDataA &y, const mglDataA &s, const char *pen, const char *opt="") { mgl_pmap(gr, &y, &s, pen, opt); } /// Draw textual marks with size r at points {x,y,z} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_xyr(gr, &x, &y, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const mglDataA &r, const char *text, const char *fnt="", const char *opt="") { mgl_textmark_yr(gr, &y, &r, text, fnt, opt); } /// Draw textual marks at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_textmark(gr, &y, text, fnt, opt); } /// Draw textual marks with size r at points {x,y,z} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_xyzr(gr, &x, &y, &z, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} inline void TextMark(const mglDataA &x, const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_xyr(gr, &x, &y, &r, text, fnt, opt); } /// Draw textual marks with size r at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const mglDataA &r, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw_yr(gr, &y, &r, text, fnt, opt); } /// Draw textual marks at points {x,y} with x in x-axis range inline void TextMark(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_textmarkw(gr, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y,z} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *text, const char *fnt="", const char *opt="") { mgl_label_xyz(gr, &x, &y, &z, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_label_xy(gr, &x, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} with x in x-axis range /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &y, const char *text, const char *fnt="", const char *opt="") { mgl_label_y(gr, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y,z} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const mglDataA &z, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_xyz(gr, &x, &y, &z, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &x, const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_xy(gr, &x, &y, text, fnt, opt); } /// Draw labels for points coordinate(s) at points {x,y} with x in x-axis range /** String \a fnt may contain: * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers.*/ inline void Label(const mglDataA &y, const wchar_t *text, const char *fnt="", const char *opt="") { mgl_labelw_y(gr, &y, text, fnt, opt); } /// Draw table for values val along given direction with row labels text /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="") { mgl_table(gr, 0, 0, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="") { mgl_tablew(gr, 0, 0, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text at given position /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(double x, double y, const mglDataA &val, const char *text, const char *fnt="#|", const char *opt="") { mgl_table(gr, x, y, &val, text, fnt, opt); } /// Draw table for values val along given direction with row labels text at given position /** String \a fnt may contain: * ‘#’ for drawing cell borders; * ‘|’ for limiting table widh by subplot one (equal to option ‘value 1’); * ‘=’ for equal width of all cells; * ‘f’ for fixed format of printed numbers; * ‘E’ for using ‘E’ instead of ‘e’; * ‘F’ for printing in LaTeX format; * ‘+’ for printing ‘+’ for positive numbers; * ‘-’ for printing usual ‘-’; * ‘0123456789’ for precision at printing numbers. * Option value set the width of the table (default is 1).*/ inline void Table(double x, double y, const mglDataA &val, const wchar_t *text, const char *fnt="#|", const char *opt="") { mgl_tablew(gr, x, y, &val, text, fnt, opt); } /// Draw tube with radius r around curve {x,y,z} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_xyzr(gr, &x, &y, &z, &r, pen, opt); } /// Draw tube with radius r around curve {x,y,z} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &z, double r, const char *pen="", const char *opt="") { mgl_tube_xyz(gr, &x, &y, &z, r, pen, opt); } /// Draw tube with radius r around curve {x,y} inline void Tube(const mglDataA &x, const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_xyr(gr, &x, &y, &r, pen, opt); } /// Draw tube with radius r around curve {x,y} inline void Tube(const mglDataA &x, const mglDataA &y, double r, const char *pen="", const char *opt="") { mgl_tube_xy(gr, &x, &y, r, pen, opt); } /// Draw tube with radius r around curve {x,y} with x in x-axis range inline void Tube(const mglDataA &y, const mglDataA &r, const char *pen="", const char *opt="") { mgl_tube_r(gr, &y, &r, pen, opt); } /// Draw tube with radius r around curve {x,y} with x in x-axis range inline void Tube(const mglDataA &y, double r, const char *pen="", const char *opt="") { mgl_tube(gr, &y, r, pen, opt); } /// Draw surface of curve {r,z} rotation around axis /** Style ‘#’ produce wire plot. Style ‘.’ produce plot by dots.*/ inline void Torus(const mglDataA &r, const mglDataA &z, const char *pen="", const char *opt="") { mgl_torus(gr, &r, &z, pen,opt); } /// Draw mesh lines for 2d data specified parametrically inline void Mesh(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_mesh_xy(gr, &x, &y, &z, stl, opt); } /// Draw mesh lines for 2d data inline void Mesh(const mglDataA &z, const char *stl="", const char *opt="") { mgl_mesh(gr, &z, stl, opt); } /// Draw waterfall plot for 2d data specified parametrically /** Style 'x' draw lines in x-direction. */ inline void Fall(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_fall_xy(gr, &x, &y, &z, stl, opt); } /// Draw waterfall plot for 2d data /** Style 'x' draw lines in x-direction. */ inline void Fall(const mglDataA &z, const char *stl="", const char *opt="") { mgl_fall(gr, &z, stl, opt); } /// Draw belts for 2d data specified parametrically /** Style 'x' draw belts in x-direction. */ inline void Belt(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_belt_xy(gr, &x, &y, &z, stl, opt); } /// Draw belts for 2d data /** Style 'x' draw belts in x-direction. */ inline void Belt(const mglDataA &z, const char *stl="", const char *opt="") { mgl_belt(gr, &z, stl, opt); } /// Draw surface for 2d data specified parametrically with color proportional to z /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Surf(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_surf_xy(gr, &x, &y, &z, stl, opt); } /// Draw surface for 2d data with color proportional to z /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Surf(const mglDataA &z, const char *stl="", const char *opt="") { mgl_surf(gr, &z, stl, opt); } /// Draw grid lines for density plot of 2d data specified parametrically inline void Grid(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_grid_xy(gr, &x, &y, &z, stl, opt); } /// Draw grid lines for density plot of 2d data inline void Grid(const mglDataA &z, const char *stl="", const char *opt="") { mgl_grid(gr, &z, stl, opt); } /// Draw vertical tiles for 2d data specified parametrically inline void Tile(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_tile_xy(gr, &x, &y, &z, stl, opt); } /// Draw vertical tiles for 2d data inline void Tile(const mglDataA &z, const char *stl="", const char *opt="") { mgl_tile(gr, &z, stl, opt); } /// Draw density plot for 2d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Dens(const mglDataA &x, const mglDataA &y, const mglDataA &c, const char *stl="", const char *opt="") { mgl_dens_xy(gr, &x, &y, &c, stl, opt); } /// Draw density plot for 2d data /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void Dens(const mglDataA &c, const char *stl="", const char *opt="") { mgl_dens(gr, &c, stl, opt); } /// Draw vertical boxes for 2d data specified parametrically /** Style ‘#’ draw filled boxes. */ inline void Boxs(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *stl="", const char *opt="") { mgl_boxs_xy(gr, &x, &y, &z, stl, opt); } /// Draw vertical boxes for 2d data /** Style ‘#’ draw filled boxes. */ inline void Boxs(const mglDataA &z, const char *stl="", const char *opt="") { mgl_boxs(gr, &z, stl, opt); } /// Draw contour lines at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Style 't'/'T' draw contour labels below/above contours.*/ inline void Cont(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw contour lines for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Style 't'/'T' draw contour labels below/above contours.*/ inline void Cont(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_val(gr, &v, &z, sch, opt); } /// Draw contour lines at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont_xy(gr, &x, &y, &z, sch, opt); } /// Draw contour lines for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont(const mglDataA &z, const char *sch="", const char *opt="") { mgl_cont(gr, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContF(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContF(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_val(gr, &v, &z, sch, opt); } /// Draw solid contours for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContF(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf_xy(gr, &x, &y, &z, sch, opt); } /// Draw solid contours for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContF(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contf(gr, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data specified parametrically with specified colors /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContD(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw solid contours at manual levels for 2d data with specified colors /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContD(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_val(gr, &v, &z, sch, opt); } /// Draw solid contours for 2d data specified parametrically with specified colors /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContD(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd_xy(gr, &x, &y, &z, sch, opt); } /// Draw solid contours for 2d data with specified colors /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContD(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contd(gr, &z, sch, opt); } /// Draw contour tubes between manual levels for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContV(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_xy_val(gr, &v, &x, &y, &z, sch, opt); } /// Draw contour tubes between manual levels for 2d data /** Style ‘_’ to draw contours at bottom of axis box. */ inline void ContV(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_val(gr, &v, &z, sch, opt); } /// Draw contour tubes for 2d data specified parametrically /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContV(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv_xy(gr, &x, &y, &z, sch, opt); } /// Draw contour tubes for 2d data /** Style ‘_’ to draw contours at bottom of axis box. * Option "value" set the number of contour levels (default is 7). */ inline void ContV(const mglDataA &z, const char *sch="", const char *opt="") { mgl_contv(gr, &z, sch, opt); } /// Draw axial-symmetric isosurfaces at manual levels for 2d data specified parametrically /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). */ inline void Axial(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_xy_val(gr, &v, &x, &y, &z, sch,opt); } /// Draw axial-symmetric isosurfaces at manual levels for 2d data /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). */ inline void Axial(const mglDataA &v, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_val(gr, &v, &z, sch, opt); } /// Draw axial-symmetric isosurfaces for 2d data specified parametrically /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). * Option "value" set the number of isosurfaces (default is 3). */ inline void Axial(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial_xy(gr, &x, &y, &z, sch, opt); } /// Draw axial-symmetric isosurfaces for 2d data /** String \a sch may contain: * ‘#’ for wired plot; * ‘.’ for plot by dots; * ‘x’, ‘z’ for rotation around x-, z-axis correspondingly (default is y-axis). * Option "value" set the number of isosurfaces (default is 3). */ inline void Axial(const mglDataA &z, const char *sch="", const char *opt="") { mgl_axial(gr, &z, sch, opt); } /// Draw grid lines for density plot at slice for 3d data specified parametrically /** Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Grid3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_grid3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); } /// Draw grid lines for density plot at slice for 3d data /** Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Grid3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_grid3(gr, &a, stl, sVal, opt); } /// Draw density plot at slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Dens3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_dens3_xyz(gr, &x, &y, &z, &a, stl, sVal, opt); } /// Draw density plot at slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly.*/ inline void Dens3(const mglDataA &a, const char *stl="", double sVal=-1, const char *opt="") { mgl_dens3(gr, &a, stl, sVal, opt); } /// Draw isosurface for 3d data specified parametrically /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots.*/ inline void Surf3(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_xyz_val(gr, Val, &x, &y, &z, &a, stl, opt); } /// Draw isosurface for 3d data /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots.*/ inline void Surf3(double Val, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_val(gr, Val, &a, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3_xyz(gr, &x, &y, &z, &a, stl, opt); } /// Draw isosurfaces for 3d data /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3(const mglDataA &a, const char *stl="", const char *opt="") { mgl_surf3(gr, &a, stl, opt); } /// Draw a semi-transparent cloud for 3d data specified parametrically /** Style ‘.’ produce plot by dots. Style ‘i’ use inverted values for transparency. */ inline void Cloud(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *stl="", const char *opt="") { mgl_cloud_xyz(gr, &x, &y, &z, &a, stl, opt); } /// Draw a semi-transparent cloud for 3d data /** Style ‘.’ produce plot by dots. Style ‘i’ use inverted values for transparency. */ inline void Cloud(const mglDataA &a, const char *stl="", const char *opt="") { mgl_cloud(gr, &a, stl, opt); } /// Draw contour lines at manual levels along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void Cont3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); } /// Draw contour lines at manual levels along slice for 3d data /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void Cont3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_val(gr, &v, &a, sch, sVal, opt); } /// Draw contour lines along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); } /// Draw contour lines along slice for 3d data /** Style ‘#’ draw grid lines. * Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void Cont3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_cont3(gr, &a, sch, sVal, opt); } /// Draw solid contours at manual levels along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. */ inline void ContF3(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_xyz_val(gr, &v, &x, &y, &z, &a, sch, sVal, opt); } /// Draw solid contours at manual levels along slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. */ inline void ContF3(const mglDataA &v, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_val(gr, &v, &a, sch, sVal, opt); } /// Draw solid contours along slice for 3d data specified parametrically /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Option "value" set the number of contour levels (default is 7).*/ inline void ContF3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3_xyz(gr, &x, &y, &z, &a, sch, sVal, opt); } /// Draw solid contours along slice for 3d data /** Style ‘#’ draw grid lines. Style ‘x’ or ‘z’ produce plot perpendicular to x- or z-direction correspondingly. * Option "value" set the number of contour levels (default is 7).*/ inline void ContF3(const mglDataA &a, const char *sch="", double sVal=-1, const char *opt="") { mgl_contf3(gr, &a, sch, sVal, opt); } /// Draw several isosurfaces for 3d beam in curvilinear coordinates /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots. * Variable \a flag is bitwise: * ‘0x1’ - draw in accompanied (not laboratory) coordinates; * ‘0x2’ - draw projection to \rho-z plane; * ‘0x4’ - draw normalized in each slice field.*/ inline void Beam(const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=0, int flag=0, int num=3) { mgl_beam(gr, &tr,&g1,&g2,&a,r,stl,flag,num); } /// Draw isosurface at value \a val for 3d beam in curvilinear coordinates /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots. * Variable \a flag is bitwise: * ‘0x1’ - draw in accompanied (not laboratory) coordinates; * ‘0x2’ - draw projection to \rho-z plane; * ‘0x4’ - draw normalized in each slice field.*/ inline void Beam(double val, const mglDataA &tr, const mglDataA &g1, const mglDataA &g2, const mglDataA &a, double r, const char *stl=NULL, int flag=0) { mgl_beam_val(gr,val,&tr,&g1,&g2,&a,r,stl,flag); } /// Draw vertical tiles with variable size r for 2d data specified parametrically inline void TileS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="") { mgl_tiles_xy(gr, &x, &y, &z, &r, stl, opt); } /// Draw vertical tiles with variable size r for 2d data inline void TileS(const mglDataA &z, const mglDataA &r, const char *stl="", const char *opt="") { mgl_tiles(gr, &z, &r, stl, opt); } /// Draw surface for 2d data specified parametrically with color proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfC(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfc_xy(gr, &x, &y, &z, &c, sch,opt); } /// Draw surface for 2d data with color proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfC(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfc(gr, &z, &c, sch,opt); } /// Draw surface for 2d data specified parametrically with alpha proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfa_xy(gr, &x, &y, &z, &c, sch,opt); } /// Draw surface for 2d data with alpha proportional to c /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfA(const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_surfa(gr, &z, &c, sch,opt); } /// Draw surface for 2d data specified parametrically with color proportional to c and alpha proportional to a /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfCA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_surfca_xy(gr, &x, &y, &z, &c, &a, sch,opt); } /// Draw surface for 2d data with color proportional to c and alpha proportional to a /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void SurfCA(const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_surfca(gr, &z, &c, &a, sch,opt); } /// Color map of matrix a to matrix b, both matrix can parametrically depend on coordinates /** Style ‘.’ produce plot by dots. */ inline void Map(const mglDataA &x, const mglDataA &y, const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="") { mgl_map_xy(gr, &x, &y, &a, &b, sch, opt); } /// Color map of matrix a to matrix b /** Style ‘.’ produce plot by dots. */ inline void Map(const mglDataA &a, const mglDataA &b, const char *sch="", const char *opt="") { mgl_map(gr, &a, &b, sch, opt); } /// Draw density plot for spectra-gramm specified parametrically /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void STFA(const mglDataA &x, const mglDataA &y, const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="") { mgl_stfa_xy(gr, &x, &y, &re, &im, dn, sch, opt); } /// Draw density plot for spectra-gramm /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void STFA(const mglDataA &re, const mglDataA &im, int dn, const char *sch="", const char *opt="") { mgl_stfa(gr, &re, &im, dn, sch, opt); } /// Draw isosurface for 3d data specified parametrically with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3A(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_xyz_val(gr, Val, &x, &y, &z, &a, &b, stl, opt); } /// Draw isosurface for 3d data with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3A(double Val, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_val(gr, Val, &a, &b, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3A(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a_xyz(gr, &x, &y, &z, &a, &b, stl, opt); } /// Draw isosurfaces for 3d data with alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3A(const mglDataA &a, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3a(gr, &a, &b, stl, opt); } /// Draw isosurface for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3C(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_xyz_val(gr, Val, &x, &y, &z, &a, &c, stl,opt); } /// Draw isosurface for 3d data with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3C(double Val, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_val(gr, Val, &a, &c, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3C(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c_xyz(gr, &x, &y, &z, &a, &c, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3C(const mglDataA &a, const mglDataA &c, const char *stl="", const char *opt="") { mgl_surf3c(gr, &a, &c, stl, opt); } /// Draw isosurface for 3d data specified parametrically with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3CA(double Val, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_xyz_val(gr, Val, &x, &y, &z, &a, &c, &b, stl,opt); } /// Draw isosurface for 3d data with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. */ inline void Surf3CA(double Val, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_val(gr, Val, &a, &c, &b, stl, opt); } /// Draw isosurfaces for 3d data specified parametrically with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3CA(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca_xyz(gr, &x, &y, &z, &a, &c, &b, stl, opt); } /// Draw isosurfaces for 3d data with color proportional to c and alpha proportional to b /** Style ‘#’ draw wired plot. Style ‘.’ produce plot by dots. * Option "value" set the number of isosurfaces (default is 3). */ inline void Surf3CA(const mglDataA &a, const mglDataA &c, const mglDataA &b, const char *stl="", const char *opt="") { mgl_surf3ca(gr, &a, &c, &b, stl, opt); } /// Plot dew drops for vector field {ax,ay} parametrically depended on coordinate {x,y} inline void Dew(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_dew_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot dew drops for vector field {ax,ay} inline void Dew(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_dew_2d(gr, &ax, &ay, sch, opt); } /// Plot vectors at position {x,y} along {ax,ay} with length/color proportional to |a| /** Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). */ inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_traj_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot vectors at position {x,y,z} along {ax,ay,az} with length/color proportional to |a| /** Option value set the vector length factor (if non-zero) or vector length to be proportional the distance between curve points (if value=0). */ inline void Traj(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_traj_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot vector field {ax,ay} parametrically depended on coordinate {x,y} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_vect_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot vector field {ax,ay} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_vect_2d(gr, &ax, &ay, sch, opt); } /// Plot vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_vect_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot vector field {ax,ay,az} with length/color proportional to |a| /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows. */ inline void Vect(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_vect_3d(gr, &ax, &ay, &az, sch, opt); } /// Draw vector plot along slice for 3d data specified parametrically /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows, * ‘ x’, ‘z’ for producing plot perpendicular to x- or z-direction correspondingly. */ inline void Vect3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="") { mgl_vect3_xyz(gr, &x, &y, &z, &ax,&ay,&az, stl, sVal, opt); } /// Draw vector plot along slice for 3d data /** String \a sch may contain: * ‘f’ for drawing arrows with fixed lengths, * ‘ >’, ‘<’ for drawing arrows to or from the ce*ll point (default is centering), * ‘.’ for drawing hachures with dots instead of arrows, * ‘=’ for enabling color gradient along arrows, * ‘ x’, ‘z’ for producing plot perpendicular to x- or z-direction correspondingly. */ inline void Vect3(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *stl="", double sVal=-1, const char *opt="") { mgl_vect3(gr, &ax,&ay,&az, stl, sVal, opt); } /// Plot flows for vector field {ax,ay} parametrically depended on coordinate {x,y} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flow_xy(gr, &x, &y, &ax, &ay, sch, opt); } /// Plot flows for vector field {ax,ay} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flow_2d(gr, &ax, &ay, sch, opt); } /// Plot flows for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flow_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot flows for vector field {ax,ay,az} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Flow(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flow_3d(gr, &ax, &ay, &az, sch, opt); } /// Plot flow from point p for vector field {ax,ay} parametrically depended on coordinate {x,y} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads. */ inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flowp_xy(gr, p.x, p.y, p.z, &x, &y, &ax, &ay, sch, opt); } /// Plot flow from point p for vector field {ax,ay} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads. */ inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const char *sch="", const char *opt="") { mgl_flowp_2d(gr, p.x, p.y, p.z, &ax, &ay, sch, opt); } /// Plot flow from point p for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. */ inline void FlowP(mglPoint p, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flowp_xyz(gr, p.x, p.y, p.z, &x, &y, &z, &ax, &ay, &az, sch, opt); } /// Plot flow from point p for vector field {ax,ay,az} with color proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. */ inline void FlowP(mglPoint p, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", const char *opt="") { mgl_flowp_3d(gr, p.x, p.y, p.z, &ax, &ay, &az, sch, opt); } /// Plot flows for gradient of scalar field phi parametrically depended on coordinate {x,y,z} /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad_xyz(gr,&x,&y,&z,&phi,sch,opt); } /// Plot flows for gradient of scalar field phi parametrically depended on coordinate {x,y} /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &x, const mglDataA &y, const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad_xy(gr,&x,&y,&phi,sch,opt); } /// Plot flows for gradient of scalar field phi /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘v’ for drawing arrows on the threads; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Grad(const mglDataA &phi, const char *sch="", const char *opt="") { mgl_grad(gr,&phi,sch,opt); } /// Plot flow pipes for vector field {ax,ay} parametrically depended on coordinate {x,y} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_xy(gr, &x, &y, &ax, &ay, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &ax, const mglDataA &ay, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_2d(gr, &ax, &ay, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay,az} parametrically depended on coordinate {x,y,z} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, r0, opt); } /// Plot flow pipes for vector field {ax,ay,az} with color and radius proportional to |a| /** String \a sch may contain: * color scheme: up-half (warm) corresponds to normal flow (like attractor), bottom-half (cold) corresponds to inverse flow (like source); * ‘#’ for starting threads from edges only; * ‘i’ for pipe radius to be inverse proportional to amplitude; * ‘x’, ‘z’ for drawing tapes of normals in x-y and y-z planes correspondingly. * Option "value" sets the number of threads (default is 5). */ inline void Pipe(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double r0=0.05, const char *opt="") { mgl_pipe_3d(gr, &ax, &ay, &az, sch, r0, opt); } /// Draw density plot for data at x = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_x(gr, &a, stl, sVal, opt); } /// Draw density plot for data at y = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_y(gr, &a, stl, sVal, opt); } /// Draw density plot for data at z = sVal /** Style ‘#’ draw grid lines. Style ‘.’ produce plot by dots.*/ inline void DensZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_dens_z(gr, &a, stl, sVal, opt); } /// Draw contour lines for data at x = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_x(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at x = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_x_val(gr, &v, &a, stl, sVal, opt); } /// Draw contour lines for data at y = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_y(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at y = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_y_val(gr, &v, &a, stl, sVal, opt); } /// Draw contour lines for data at z = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_z(gr, &a, stl, sVal, opt); } /// Draw contour lines at manual levels for data at z = sVal /** Style ‘t’/‘T’ draw contour labels below/above contours. */ inline void ContZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_cont_z_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at x = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFX(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_x(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at x = sVal inline void ContFX(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_x_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at y = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFY(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_y(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at y = sVal inline void ContFY(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_y_val(gr, &v, &a, stl, sVal, opt); } /// Draw solid contours for data at z = sVal /** Option "value" set the number of contour levels (default is 7). */ inline void ContFZ(const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_z(gr, &a, stl, sVal, opt); } /// Draw solid contours at manual levels for data at z = sVal inline void ContFZ(const mglDataA &v, const mglDataA &a, const char *stl="", double sVal=mglNaN, const char *opt="") { mgl_contf_z_val(gr, &v, &a, stl, sVal, opt); } /// Draw curve for formula with x in x-axis range /** Option "value" set initial number of points. */ inline void FPlot(const char *fy, const char *stl="", const char *opt="") { mgl_fplot(gr, fy, stl, opt); } /// Draw curve for formulas parametrically depended on t in range [0,1] /** Option "value" set initial number of points. */ inline void FPlot(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="") { mgl_fplot_xyz(gr, fx, fy, fz, stl, opt); } /// Draw surface by formula with x,y in axis range /** Option "value" set initial number of points. */ inline void FSurf(const char *fz, const char *stl="", const char *opt="") { mgl_fsurf(gr, fz, stl, opt); } /// Draw surface by formulas parametrically depended on u,v in range [0,1] /** Option "value" set initial number of points. */ inline void FSurf(const char *fx, const char *fy, const char *fz, const char *stl, const char *opt="") { mgl_fsurf_xyz(gr, fx, fy, fz, stl, opt); } /// Draw triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘#’ produce wire plot. If id.ny=c.nx then c set the triangle colors, else vertex colors. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_triplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); } /// Draw triangle mesh for points in arrays {x,y,z} /** Style ‘#’ produce wire plot. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_triplot_xyz(gr, &nums, &x, &y, &z, sch, opt); } /// Draw triangle mesh for points in arrays {x,y} /** Style ‘#’ produce wire plot. */ inline void TriPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="") { mgl_triplot_xy(gr, &nums, &x, &y, sch, opt); } /// Draw quad mesh for points in arrays {x,y,z} with specified color c /** Style ‘#’ produce wire plot. If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *sch="", const char *opt="") { mgl_quadplot_xyzc(gr, &nums, &x, &y, &z, &c, sch, opt); } /// Draw quad mesh for points in arrays {x,y,z} /** Style ‘#’ produce wire plot. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_quadplot_xyz(gr, &nums, &x, &y, &z, sch, opt); } /// Draw quad mesh for points in arrays {x,y} /** Style ‘#’ produce wire plot. */ inline void QuadPlot(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const char *sch="", const char *opt="") { mgl_quadplot_xy(gr, &nums, &x, &y, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricont_xyc(gr, &nums, &x, &y, &z, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. * Option "value" set the number of contour levels (default is 7). */ inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricont_xycv(gr, &v, &nums, &x, &y, &z, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriContV(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour lines for triangle mesh for points in arrays {x,y,z} with specified color c. /** Style ‘_’ to draw contours at bottom of axis box. * Style ‘t’/‘T’ draw contour labels below/above contours. * If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriCont(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricont_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} /** Option "value" set the number of contour levels (default is 7). */ inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_tricontv_xyc(gr, &nums, &x, &y, &z, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} with specified color c /** Option "value" set the number of contour levels (default is 7). */ inline void TriContVt(const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricontv_xyzc(gr, &nums, &x, &y, &z, &a, sch, opt); } /// Draw contour tubes for triangle mesh for points in arrays {x,y,z} with specified color c /** If id.ny=c.nx then c set the quadrangle colors, else vertex colors. */ inline void TriContVt(const mglDataA &v, const mglDataA &nums, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_tricontv_xyzcv(gr, &v, &nums, &x, &y, &z, &a, sch, opt); } /// Draw dots in points {x,y,z}. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_dots(gr, &x, &y, &z, sch, opt); } /// Draw semitransparent dots in points {x,y,z} with specified alpha a. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_dots_a(gr, &x, &y, &z, &a, sch, opt); } /// Draw semitransparent dots in points {x,y,z} with specified color c and alpha a. inline void Dots(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const mglDataA &a, const char *sch="", const char *opt="") { mgl_dots_ca(gr, &x, &y, &z, &c, &a, sch, opt); } /// Draw surface reconstructed for points in arrays {x,y,z}. /** Style ‘#’ produce wired plot. */ inline void Crust(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *sch="", const char *opt="") { mgl_crust(gr, &x, &y, &z, sch, opt); } /// Fit data along x-direction for each data row. Return array with values for found formula. inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_1(gr, &y, eq,vars,0, opt)); } /// Fit data along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_1(gr, &y, eq, vars, &ini, opt)); } /// Fit data along x-, y-directions for each data slice. Return array with values for found formula. inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_2(gr, &z, eq, vars,0, opt)); } /// Fit data along x-, y-direction for each data slice starting from \a ini values. Return array with values for found formula. inline mglData Fit2(const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_2(gr, &z, eq, vars, &ini, opt)); } /// Fit data along along all directions. Return array with values for found formula. inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_3(gr, &a, eq, vars,0, opt)); } /// Fit data along all directions starting from \a ini values. Return array with values for found formula. inline mglData Fit3(const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_3(gr, &a, eq, vars, &ini, opt)); } /// Fit data along x-direction for each data row. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars,0, opt)); } /// Fit data along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xy(gr, &x, &y, eq, vars, &ini, opt)); } /// Fit data along x-, y-directions for each data slice. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars,0, opt)); } /// Fit data along x-, y-directions for each data slice starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyz(gr, &x, &y, &z, eq, vars, &ini, opt)); } /// Fit data along along all directions. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq, vars,0, opt)); } /// Fit data along along all directions starting from \a ini values. Return array with values for found formula. inline mglData Fit(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyza(gr, &x, &y, &z, &a, eq,vars, &ini, opt)); } /// Fit data with dispersion s along x-direction for each data row. Return array with values for found formula. inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_ys(gr, &y, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along x-direction for each data row. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-direction for each data row starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xys(gr, &x, &y, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along x-, y-directions for each data slice. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along x-, y-directions for each data slice starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyzs(gr, &x, &y, &z, &s, eq, vars, &ini, opt)); } /// Fit data with dispersion s along all directions. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, const char *opt="") { return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars,0, opt)); } /// Fit data with dispersion s along all directions starting from \a ini values. Return array with values for found formula. inline mglData FitS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const mglDataA &s, const char *eq, const char *vars, mglData &ini, const char *opt="") { return mglData(true,mgl_fit_xyzas(gr, &x, &y, &z, &a, &s, eq, vars, &ini, opt)); } /// Print fitted last formula (with coefficients) inline void PutsFit(mglPoint p, const char *prefix=0, const char *font="", double size=-1) { mgl_puts_fit(gr, p.x, p.y, p.z, prefix, font, size); } /// Get last fitted formula inline const char *GetFit() const { return mgl_get_fit(gr); } /// Get chi for last fitted formula static inline mreal GetFitChi() { return mgl_get_fit_chi(); } /// Get covariance matrix for last fitted formula static inline mglData GetFitCovar() { return mglData(mgl_get_fit_covar()); } /// Solve PDE with x,y,z in range axis range inline mglData PDE(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglData(true,mgl_pde_solve(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range inline mglDataC PDEc(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglDataC(true,mgl_pde_solve_c(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range using advanced (slow!!!) method (2d only) inline mglData APDE(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglData(true,mgl_pde_adv(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Solve PDE with x,y,z in range axis range using advanced (slow!!!) method (2d only) inline mglDataC APDEc(const char *ham, const mglDataA &ini_re, const mglDataA &ini_im, double dz=0.1, double k0=100, const char *opt="") { return mglDataC(true,mgl_pde_adv_c(gr,ham,&ini_re,&ini_im,dz,k0, opt)); } /// Fill data by formula with x,y,z in range axis range inline void Fill(mglData &u, const char *eq, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, 0, 0, opt); } inline void Fill(mglData &u, const char *eq, const mglDataA &v, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, &v, 0, opt); } inline void Fill(mglData &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="") { mgl_data_fill_eq(gr, &u, eq, &v, &w, opt); } /// Fill data by formula with x,y,z in range axis range inline void Fill(mglDataC &u, const char *eq, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, 0, 0, opt); } inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, &v, 0, opt); } inline void Fill(mglDataC &u, const char *eq, const mglDataA &v, const mglDataA &w, const char *opt="") { mgl_datac_fill_eq(gr, &u, eq, &v, &w, opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,0,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,&ydat,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range inline void Refill(mglData &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &zdat, const mglDataA &vdat, const char *opt="") { mgl_data_refill_gr(gr,&dat,&xdat,&ydat,&zdat,&vdat,-1,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat for x in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,0,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat for x,y in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &vdat, long sl=-1, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,&ydat,0,&vdat,sl,opt); } /// Fill dat by interpolated values of vdat parametrically depended on xdat,ydat,zdat for x,y,z in axis range inline void Refill(mglDataC &dat, const mglDataA &xdat, const mglDataA &ydat, const mglDataA &zdat, const mglDataA &vdat, const char *opt="") { mgl_datac_refill_gr(gr,&dat,&xdat,&ydat,&zdat,&vdat,-1,opt); } /// Set the data by triangulated surface values assuming x,y,z in range axis range inline void DataGrid(mglData &d, const mglDataA &x, const mglDataA &y, const mglDataA &z, const char *opt="") { mgl_data_grid(gr,&d,&x,&y,&z,opt); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_x(gr, &x, &a, opt)); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_xy(gr, &x, &y, &a, opt)); } /// Make histogram (distribution) of data. This function do not plot data. /** Option "value" sets the size of output array (default is mglFitPnts=100). */ inline mglData Hist(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *opt="") { return mglData(true, mgl_hist_xyz(gr, &x, &y, &z, &a, opt)); } inline void Compression(bool){} // NOTE: Add later -- IDTF /// Set the preference for vertex color on/off (for formats that support it, now only PRC does). inline void VertexColor(bool enable) { mgl_set_flag(gr,enable, MGL_PREFERVC); } /// Render only front side of surfaces for dubugging purposes (for formats that support it, now only PRC does). inline void DoubleSided(bool enable) { mgl_set_flag(gr,!enable, MGL_ONESIDED); } // inline void TextureColor(bool){} // NOTE: Add later -- IDTF }; //----------------------------------------------------------------------------- /// Wrapper class for MGL parsing class MGL_EXPORT mglParse { HMPR pr; public: mglParse(HMPR p) { pr = p; mgl_use_parser(pr,1); } mglParse(mglParse &p) { pr = p.pr; mgl_use_parser(pr,1); } mglParse(bool setsize=false) { pr=mgl_create_parser(); mgl_parser_allow_setsize(pr, setsize); } virtual ~mglParse() { #pragma omp critical if(mgl_use_parser(pr,-1)<1) mgl_delete_parser(pr); } /// Get pointer to internal mglParser object inline HMPR Self() { return pr; } /// Parse and draw single line of the MGL script inline int Parse(mglGraph *gr, const char *str, int pos) { return mgl_parse_line(gr->Self(), pr, str, pos); } inline int Parse(mglGraph *gr, const wchar_t *str, int pos) { return mgl_parse_linew(gr->Self(), pr, str, pos); } /// Execute MGL script text with '\n' separated lines inline void Execute(mglGraph *gr, const char *str) { mgl_parse_text(gr->Self(), pr, str); } inline void Execute(mglGraph *gr, const wchar_t *str) { mgl_parse_textw(gr->Self(), pr, str); } /// Execute and draw script from the file inline void Execute(mglGraph *gr, FILE *fp, bool print=false) { mgl_parse_file(gr->Self(), pr, fp, print); } /// Return type of command: 0 - not found, 1 - other data plot, 2 - func plot, /// 3 - setup, 4 - data handle, 5 - data create, 6 - subplot, 7 - program /// 8 - 1d plot, 9 - 2d plot, 10 - 3d plot, 11 - dd plot, 12 - vector plot /// 13 - axis, 14 - primitives, 15 - axis setup, 16 - text/legend, 17 - data transform inline int CmdType(const char *name) { return mgl_parser_cmd_type(pr, name); } /// Return string of command format (command name and its argument[s]) inline const char *CmdFormat(const char *name) { return mgl_parser_cmd_frmt(pr, name); } /// Return description of MGL command inline const char *CmdDesc(const char *name) { return mgl_parser_cmd_desc(pr, name); } /// Get name of command with nmber n inline const char *GetCmdName(long n) { return mgl_parser_cmd_name(pr,n); } /// Get number of defined commands inline long GetCmdNum() { return mgl_parser_cmd_num(pr); } /// Load new commands from external dynamic Library (must have "const mglCommand *mgl_cmd_extra" variable) inline void LoadDLL(const char *fname) { mgl_parser_load(pr, fname); } /// Apply one step for equation d vars[i]/dt = eqs[i] using Runge-Kutta method inline void RK_Step(const char *eqs, const char *vars, mreal dt=1) { mgl_rk_step(pr, eqs, vars, dt); } inline void RK_Step(const wchar_t *eqs, const wchar_t *vars, mreal dt=1) { mgl_rk_step_w(pr, eqs, vars, dt); } /// Set value for parameter $N inline void AddParam(int id, const char *str) { mgl_parser_add_param(pr, id, str); } inline void AddParam(int id, const wchar_t *str) { mgl_parser_add_paramw(pr, id, str); } /// Restore once flag inline void RestoreOnce() { mgl_parser_restore_once(pr); } /// Allow changing size of the picture inline void AllowSetSize(bool allow) { mgl_parser_allow_setsize(pr, allow); } /// Allow reading/saving files inline void AllowFileIO(bool allow) { mgl_parser_allow_file_io(pr, allow); } /// Allow loading commands from external libraries inline void AllowDllCall(bool allow) { mgl_parser_allow_dll_call(pr, allow); } /// Set flag to stop script parsing inline void Stop() { mgl_parser_stop(pr); } /// Set variant of argument(s) separated by '?' to be used in further commands inline void SetVariant(int var=0) { mgl_parser_variant(pr, var); } /// Return result of formula evaluation inline mglData Calc(const char *formula) { return mglData(true,mgl_parser_calc(pr,formula)); } inline mglData Calc(const wchar_t *formula) { return mglData(true,mgl_parser_calcw(pr,formula)); } /// Return result of formula evaluation as complex data inline mglDataC CalcComplex(const char *formula) { return mglDataC(true,mgl_parser_calc_complex(pr,formula)); } inline mglDataC CalcComplex(const wchar_t *formula) { return mglDataC(true,mgl_parser_calc_complexw(pr,formula)); } /// Find variable with given name or add a new one /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *AddVar(const char *name) { return mgl_parser_add_var(pr, name); } inline mglDataA *AddVar(const wchar_t *name) { return mgl_parser_add_varw(pr, name); } /// Find variable with given name or return NULL if no one /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *FindVar(const char *name) { return mgl_parser_find_var(pr, name); } inline mglDataA *FindVar(const wchar_t *name) { return mgl_parser_find_varw(pr, name); } /// Get variable with given id. Can be NULL for temporary ones. /// NOTE !!! You must not delete obtained data arrays !!! inline mglDataA *GetVar(unsigned long id) { return mgl_parser_get_var(pr,id); } /// Get number of variables inline long GetNumVar() { return mgl_parser_num_var(pr); } /// Delete variable with name inline void DeleteVar(const char *name) { mgl_parser_del_var(pr, name); } inline void DeleteVar(const wchar_t *name) { mgl_parser_del_varw(pr, name); } /// Delete all data variables void DeleteAll() { mgl_parser_del_all(pr); } }; //----------------------------------------------------------------------------- #endif #endif
qr_decompose.h
/** * @file * \brief Library functions to compute [QR * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of a given * matrix. * \author [Krishna Vedala](https://github.com/kvedala) */ #ifndef NUMERICAL_METHODS_QR_DECOMPOSE_H_ #define NUMERICAL_METHODS_QR_DECOMPOSE_H_ #include <cmath> #include <cstdlib> #include <iomanip> #include <iostream> #include <limits> #include <numeric> #include <valarray> #ifdef _OPENMP #include <omp.h> #endif /** \namespace qr_algorithm * \brief Functions to compute [QR * decomposition](https://en.wikipedia.org/wiki/QR_decomposition) of any * rectangular matrix */ namespace qr_algorithm { /** * operator to print a matrix */ template <typename T> std::ostream &operator<<(std::ostream &out, std::valarray<std::valarray<T>> const &v) { const int width = 12; const char separator = ' '; out.precision(4); for (size_t row = 0; row < v.size(); row++) { for (size_t col = 0; col < v[row].size(); col++) out << std::right << std::setw(width) << std::setfill(separator) << v[row][col]; out << std::endl; } return out; } /** * operator to print a vector */ template <typename T> std::ostream &operator<<(std::ostream &out, std::valarray<T> const &v) { const int width = 10; const char separator = ' '; out.precision(4); for (size_t row = 0; row < v.size(); row++) { out << std::right << std::setw(width) << std::setfill(separator) << v[row]; } return out; } /** * Compute dot product of two vectors of equal lengths * * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ and * \f$\vec{b}=\left[b_0,b_1,b_1,...,b_L\right]\f$ then * \f$\vec{a}\cdot\vec{b}=\displaystyle\sum_{i=0}^L a_i\times b_i\f$ * * \returns \f$\vec{a}\cdot\vec{b}\f$ */ template <typename T> inline double vector_dot(const std::valarray<T> &a, const std::valarray<T> &b) { return (a * b).sum(); // could also use following // return std::inner_product(std::begin(a), std::end(a), std::begin(b), // 0.f); } /** * Compute magnitude of vector. * * If \f$\vec{a}=\left[a_0,a_1,a_2,...,a_L\right]\f$ then * \f$\left|\vec{a}\right|=\sqrt{\displaystyle\sum_{i=0}^L a_i^2}\f$ * * \returns \f$\left|\vec{a}\right|\f$ */ template <typename T> inline double vector_mag(const std::valarray<T> &a) { double dot = vector_dot(a, a); return std::sqrt(dot); } /** * Compute projection of vector \f$\vec{a}\f$ on \f$\vec{b}\f$ defined as * \f[\text{proj}_\vec{b}\vec{a}=\frac{\vec{a}\cdot\vec{b}}{\left|\vec{b}\right|^2}\vec{b}\f] * * \returns NULL if error, otherwise pointer to output */ template <typename T> std::valarray<T> vector_proj(const std::valarray<T> &a, const std::valarray<T> &b) { double num = vector_dot(a, b); double deno = vector_dot(b, b); /*! check for division by zero using machine epsilon */ if (deno <= std::numeric_limits<double>::epsilon()) { std::cerr << "[" << __func__ << "] Possible division by zero\n"; return a; // return vector a back } double scalar = num / deno; return b * scalar; } /** * Decompose matrix \f$A\f$ using [Gram-Schmidt *process](https://en.wikipedia.org/wiki/QR_decomposition). * * \f{eqnarray*}{ * \text{given that}\quad A &=& *\left[\mathbf{a}_1,\mathbf{a}_2,\ldots,\mathbf{a}_{N-1},\right]\\ * \text{where}\quad\mathbf{a}_i &=& * \left[a_{0i},a_{1i},a_{2i},\ldots,a_{(M-1)i}\right]^T\quad\ldots\mbox{(column * vectors)}\\ * \text{then}\quad\mathbf{u}_i &=& \mathbf{a}_i *-\sum_{j=0}^{i-1}\text{proj}_{\mathbf{u}_j}\mathbf{a}_i\\ * \mathbf{e}_i &=&\frac{\mathbf{u}_i}{\left|\mathbf{u}_i\right|}\\ * Q &=& \begin{bmatrix}\mathbf{e}_0 & \mathbf{e}_1 & \mathbf{e}_2 & \dots & * \mathbf{e}_{N-1}\end{bmatrix}\\ * R &=& \begin{bmatrix}\langle\mathbf{e}_0\,,\mathbf{a}_0\rangle & * \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & * \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots \\ * 0 & \langle\mathbf{e}_1\,,\mathbf{a}_1\rangle & * \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & \dots\\ * 0 & 0 & \langle\mathbf{e}_2\,,\mathbf{a}_2\rangle & * \dots\\ \vdots & \vdots & \vdots & \ddots * \end{bmatrix}\\ * \f} */ template <typename T> void qr_decompose( const std::valarray<std::valarray<T>> &A, /**< input matrix to decompose */ std::valarray<std::valarray<T>> *Q, /**< output decomposed matrix */ std::valarray<std::valarray<T>> *R /**< output decomposed matrix */ ) { std::size_t ROWS = A.size(); // number of rows of A std::size_t COLUMNS = A[0].size(); // number of columns of A std::valarray<T> col_vector(ROWS); std::valarray<T> col_vector2(ROWS); std::valarray<T> tmp_vector(ROWS); for (int i = 0; i < COLUMNS; i++) { /* for each column => R is a square matrix of NxN */ int j; R[0][i] = 0.; /* make R upper triangular */ /* get corresponding Q vector */ #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (j = 0; j < ROWS; j++) { tmp_vector[j] = A[j][i]; /* accumulator for uk */ col_vector[j] = A[j][i]; } for (j = 0; j < i; j++) { for (int k = 0; k < ROWS; k++) { col_vector2[k] = Q[0][k][j]; } col_vector2 = vector_proj(col_vector, col_vector2); tmp_vector -= col_vector2; } double mag = vector_mag(tmp_vector); #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (j = 0; j < ROWS; j++) Q[0][j][i] = tmp_vector[j] / mag; /* compute upper triangular values of R */ #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (int kk = 0; kk < ROWS; kk++) { col_vector[kk] = Q[0][kk][i]; } #ifdef _OPENMP // parallelize on threads #pragma omp for #endif for (int k = i; k < COLUMNS; k++) { for (int kk = 0; kk < ROWS; kk++) { col_vector2[kk] = A[kk][k]; } R[0][i][k] = (col_vector * col_vector2).sum(); } } } } // namespace qr_algorithm #endif // NUMERICAL_METHODS_QR_DECOMPOSE_H_
3d25pt.c
/* * Order-2, 3D 25 point stencil * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) #ifndef min #define min(x,y) ((x) < (y)? (x) : (y)) #endif /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); double ****A = (double ****) malloc(sizeof(double***)*2); double ***roc2 = (double ***) malloc(sizeof(double**)); A[0] = (double ***) malloc(sizeof(double**)*Nz); A[1] = (double ***) malloc(sizeof(double**)*Nz); roc2 = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[0][i] = (double**) malloc(sizeof(double*)*Ny); A[1][i] = (double**) malloc(sizeof(double*)*Ny); roc2[i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[0][i][j] = (double*) malloc(sizeof(double)*Nx); A[1][i][j] = (double*) malloc(sizeof(double)*Nx); roc2[i][j] = (double*) malloc(sizeof(double)*Nx); } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 4; tile_size[1] = 4; tile_size[2] = 32; tile_size[3] = 256; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
progress-new.c
/* * Copyright (c) 2009, 2010, 2011, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <assert.h> #include <stdint.h> #include <omp.h> #define ITERATIONS 1000000 #define STACK_SIZE (64 * 1024) #define MAXTHREADS 16 static inline uint64_t rdtsc(void) { uint64_t eax, edx; __asm volatile ("rdtsc" : "=a" (eax), "=d" (edx)); return (edx << 32) | eax; } int main(int argc, char *argv[]) { int nthreads = 1; static uint64_t starta[MAXTHREADS][ITERATIONS]; if(argc == 2) { nthreads = atoi(argv[1]); backend_span_domain(14, STACK_SIZE); bomp_custom_init(NULL); omp_set_num_threads(nthreads); } else { assert(!"Specify number of threads"); } // Do some work #pragma omp parallel { bomp_synchronize(); for(uint64_t i = 0; i < ITERATIONS; i++) { uint64_t lasta = rdtsc(); #pragma omp barrier starta[omp_get_thread_num()][i] = rdtsc() - lasta; } } static uint64_t hgram[15] = { 0 }; for(int i = 0; i < ITERATIONS; i++) { for(int n = 0; n < nthreads; n++) { uint64_t val = starta[n][i]; for(int j = 0; j < 15; j++) { val /= 10; if(val == 0) { hgram[j]++; break; } } } } uint64_t val = 1; for(int i = 0; i < 15; i++) { val *= 10; if(hgram[i] > 0) { printf("%lu\t%lu\n", val, hgram[i]); } } for(;;); return 0; }
deprecate.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % DDDD EEEEE PPPP RRRR EEEEE CCCC AAA TTTTT EEEEE % % D D E P P R R E C A A T E % % D D EEE PPPPP RRRR EEE C AAAAA T EEE % % D D E P R R E C A A T E % % DDDD EEEEE P R R EEEEE CCCC A A T EEEEE % % % % % % MagickWand Deprecated Methods % % % % Software Design % % Cristy % % October 2002 % % % % % % Copyright 1999-2018 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "wand/studio.h" #include "wand/MagickWand.h" #include "wand/magick-wand-private.h" #include "wand/wand.h" #include "magick/monitor-private.h" #include "magick/thread-private.h" /* Define declarations. */ #define PixelViewId "PixelView" /* Typedef declarations. */ struct _PixelView { size_t id; char name[MaxTextExtent]; ExceptionInfo *exception; MagickWand *wand; CacheView *view; RectangleInfo region; size_t number_threads; PixelWand ***pixel_wands; MagickBooleanType debug; size_t signature; }; #if !defined(MAGICKCORE_EXCLUDE_DEPRECATED) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D r a w A l l o c a t e W a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawAllocateWand() allocates an initial drawing wand which is an opaque % handle required by the remaining drawing methods. % % The format of the DrawAllocateWand method is: % % DrawingWand DrawAllocateWand(const DrawInfo *draw_info,Image *image) % % A description of each parameter follows: % % o draw_info: Initial drawing defaults. Set to NULL to use defaults. % % o image: the image to draw on. % */ WandExport DrawingWand *DrawAllocateWand(const DrawInfo *draw_info,Image *image) { return(AcquireDrawingWand(draw_info,image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k A v e r a g e I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickAverageImages() average a set of images. % % The format of the MagickAverageImages method is: % % MagickWand *MagickAverageImages(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ static MagickWand *CloneMagickWandFromImages(const MagickWand *wand, Image *images) { MagickWand *clone_wand; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); clone_wand=(MagickWand *) AcquireMagickMemory(sizeof(*clone_wand)); if (clone_wand == (MagickWand *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", images->filename); (void) memset(clone_wand,0,sizeof(*clone_wand)); clone_wand->id=AcquireWandId(); (void) FormatLocaleString(clone_wand->name,MaxTextExtent,"%s-%.20g", MagickWandId,(double) clone_wand->id); clone_wand->exception=AcquireExceptionInfo(); InheritException(clone_wand->exception,wand->exception); clone_wand->image_info=CloneImageInfo(wand->image_info); clone_wand->quantize_info=CloneQuantizeInfo(wand->quantize_info); clone_wand->images=images; clone_wand->debug=IsEventLogging(); if (clone_wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_wand->name); clone_wand->signature=WandSignature; return(clone_wand); } WandExport MagickWand *MagickAverageImages(MagickWand *wand) { Image *average_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) return((MagickWand *) NULL); average_image=EvaluateImages(wand->images,MeanEvaluateOperator, wand->exception); if (average_image == (Image *) NULL) return((MagickWand *) NULL); return(CloneMagickWandFromImages(wand,average_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C l o n e P i x e l V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelView() makes a copy of the specified pixel view. % % The format of the ClonePixelView method is: % % PixelView *ClonePixelView(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport PixelView *ClonePixelView(const PixelView *pixel_view) { PixelView *clone_view; register ssize_t i; assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); if (pixel_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",pixel_view->name); clone_view=(PixelView *) AcquireMagickMemory(sizeof(*clone_view)); if (clone_view == (PixelView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", pixel_view->name); (void) memset(clone_view,0,sizeof(*clone_view)); clone_view->id=AcquireWandId(); (void) FormatLocaleString(clone_view->name,MaxTextExtent,"%s-%.20g", PixelViewId,(double) clone_view->id); clone_view->exception=AcquireExceptionInfo(); InheritException(clone_view->exception,pixel_view->exception); clone_view->view=CloneCacheView(pixel_view->view); clone_view->region=pixel_view->region; clone_view->number_threads=pixel_view->number_threads; for (i=0; i < (ssize_t) pixel_view->number_threads; i++) clone_view->pixel_wands[i]=ClonePixelWands((const PixelWand **) pixel_view->pixel_wands[i],pixel_view->region.width); clone_view->debug=pixel_view->debug; if (clone_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",clone_view->name); clone_view->signature=WandSignature; return(clone_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e s t r o y P i x e l V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelView() deallocates memory associated with a pixel view. % % The format of the DestroyPixelView method is: % % PixelView *DestroyPixelView(PixelView *pixel_view, % const size_t number_wands,const size_t number_threads) % % A description of each parameter follows: % % o pixel_view: the pixel view. % % o number_wand: the number of pixel wands. % % o number_threads: number of threads. % */ static PixelWand ***DestroyPixelsThreadSet(PixelWand ***pixel_wands, const size_t number_wands,const size_t number_threads) { register ssize_t i; assert(pixel_wands != (PixelWand ***) NULL); for (i=0; i < (ssize_t) number_threads; i++) if (pixel_wands[i] != (PixelWand **) NULL) pixel_wands[i]=DestroyPixelWands(pixel_wands[i],number_wands); pixel_wands=(PixelWand ***) RelinquishMagickMemory(pixel_wands); return(pixel_wands); } WandExport PixelView *DestroyPixelView(PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); pixel_view->pixel_wands=DestroyPixelsThreadSet(pixel_view->pixel_wands, pixel_view->region.width,pixel_view->number_threads); pixel_view->view=DestroyCacheView(pixel_view->view); pixel_view->exception=DestroyExceptionInfo(pixel_view->exception); pixel_view->signature=(~WandSignature); RelinquishWandId(pixel_view->id); pixel_view=(PixelView *) RelinquishMagickMemory(pixel_view); return(pixel_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D u p l e x T r a n s f e r P i x e l V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DuplexTransferPixelViewIterator() iterates over three pixel views in % parallel and calls your transfer method for each scanline of the view. The % source and duplex pixel region is not confined to the image canvas-- that is % you can include negative offsets or widths or heights that exceed the image % dimension. However, the destination pixel view is confined to the image % canvas-- that is no negative offsets or widths or heights that exceed the % image dimension are permitted. % % Use this pragma: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the DuplexTransferPixelViewIterator method is: % % MagickBooleanType DuplexTransferPixelViewIterator(PixelView *source, % PixelView *duplex,PixelView *destination, % DuplexTransferPixelViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source pixel view. % % o duplex: the duplex pixel view. % % o destination: the destination pixel view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType DuplexTransferPixelViewIterator( PixelView *source,PixelView *duplex,PixelView *destination, DuplexTransferPixelViewMethod transfer,void *context) { #define DuplexTransferPixelViewTag "PixelView/DuplexTransfer" ExceptionInfo *exception; Image *destination_image, *duplex_image, *source_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(source != (PixelView *) NULL); assert(source->signature == WandSignature); if (transfer == (DuplexTransferPixelViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; duplex_image=duplex->wand->images; destination_image=destination->wand->images; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) #endif for (y=source->region.y; y < (ssize_t) source->region.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const IndexPacket *magick_restrict duplex_indexes, *magick_restrict indexes; register const PixelPacket *magick_restrict duplex_pixels, *magick_restrict pixels; register IndexPacket *magick_restrict destination_indexes; register ssize_t x; register PixelPacket *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->region.x,y, source->region.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(source->view); for (x=0; x < (ssize_t) source->region.width; x++) PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x); if (source_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetBlackQuantum(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (source_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetIndex(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); duplex_pixels=GetCacheViewVirtualPixels(duplex->view,duplex->region.x,y, duplex->region.width,1,duplex->exception); if (duplex_pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } duplex_indexes=GetCacheViewVirtualIndexQueue(duplex->view); for (x=0; x < (ssize_t) duplex->region.width; x++) PixelSetQuantumColor(duplex->pixel_wands[id][x],duplex_pixels+x); if (duplex_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) duplex->region.width; x++) PixelSetBlackQuantum(duplex->pixel_wands[id][x], GetPixelIndex(duplex_indexes+x)); if (duplex_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) duplex->region.width; x++) PixelSetIndex(duplex->pixel_wands[id][x], GetPixelIndex(duplex_indexes+x)); destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->region.x,y,destination->region.width,1,exception); if (destination_pixels == (PixelPacket *) NULL) { status=MagickFalse; continue; } destination_indexes=GetCacheViewAuthenticIndexQueue(destination->view); for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetQuantumColor(destination->pixel_wands[id][x], destination_pixels+x); if (destination_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetBlackQuantum(destination->pixel_wands[id][x], GetPixelIndex(destination_indexes+x)); if (destination_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetIndex(destination->pixel_wands[id][x], GetPixelIndex(destination_indexes+x)); if (transfer(source,duplex,destination,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) destination->region.width; x++) PixelGetQuantumColor(destination->pixel_wands[id][x], destination_pixels+x); if (destination_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) destination->region.width; x++) SetPixelIndex(destination_indexes+x,PixelGetBlackQuantum( destination->pixel_wands[id][x])); sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_DuplexTransferPixelViewIterator) #endif proceed=SetImageProgress(source_image,DuplexTransferPixelViewTag, progress++,source->region.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewException() returns the severity, reason, and description of any % error that occurs when utilizing a pixel view. % % The format of the GetPixelViewException method is: % % char *GetPixelViewException(const PixelWand *pixel_view, % ExceptionType *severity) % % A description of each parameter follows: % % o pixel_view: the pixel pixel_view. % % o severity: the severity of the error is returned here. % */ WandExport char *GetPixelViewException(const PixelView *pixel_view, ExceptionType *severity) { char *description; assert(pixel_view != (const PixelView *) NULL); assert(pixel_view->signature == WandSignature); if (pixel_view->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",pixel_view->name); assert(severity != (ExceptionType *) NULL); *severity=pixel_view->exception->severity; description=(char *) AcquireQuantumMemory(2UL*MaxTextExtent, sizeof(*description)); if (description == (char *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", pixel_view->name); *description='\0'; if (pixel_view->exception->reason != (char *) NULL) (void) CopyMagickString(description,GetLocaleExceptionMessage( pixel_view->exception->severity,pixel_view->exception->reason), MaxTextExtent); if (pixel_view->exception->description != (char *) NULL) { (void) ConcatenateMagickString(description," (",MaxTextExtent); (void) ConcatenateMagickString(description,GetLocaleExceptionMessage( pixel_view->exception->severity,pixel_view->exception->description), MaxTextExtent); (void) ConcatenateMagickString(description,")",MaxTextExtent); } return(description); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w H e i g h t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewHeight() returns the pixel view height. % % The format of the GetPixelViewHeight method is: % % size_t GetPixelViewHeight(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport size_t GetPixelViewHeight(const PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->region.height); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewIterator() iterates over the pixel view in parallel and calls % your get method for each scanline of the view. The pixel region is % not confined to the image canvas-- that is you can include negative offsets % or widths or heights that exceed the image dimension. Any updates to % the pixels in your callback are ignored. % % Use this pragma: % % #pragma omp critical % % to define a section of code in your callback get method that must be % executed by a single thread at a time. % % The format of the GetPixelViewIterator method is: % % MagickBooleanType GetPixelViewIterator(PixelView *source, % GetPixelViewMethod get,void *context) % % A description of each parameter follows: % % o source: the source pixel view. % % o get: the get callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType GetPixelViewIterator(PixelView *source, GetPixelViewMethod get,void *context) { #define GetPixelViewTag "PixelView/Get" Image *source_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(source != (PixelView *) NULL); assert(source->signature == WandSignature); if (get == (GetPixelViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) #endif for (y=source->region.y; y < (ssize_t) source->region.height; y++) { const int id = GetOpenMPThreadId(); register const IndexPacket *indexes; register const PixelPacket *pixels; register ssize_t x; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->region.x,y, source->region.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(source->view); for (x=0; x < (ssize_t) source->region.width; x++) PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x); if (source_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetBlackQuantum(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (source_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetIndex(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (get(source,context) == MagickFalse) status=MagickFalse; if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_GetPixelViewIterator) #endif proceed=SetImageProgress(source_image,GetPixelViewTag,progress++, source->region.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewPixels() returns the pixel view pixel_wands. % % The format of the GetPixelViewPixels method is: % % PixelWand *GetPixelViewPixels(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport PixelWand **GetPixelViewPixels(const PixelView *pixel_view) { const int id = GetOpenMPThreadId(); assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->pixel_wands[id]); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w W a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewWand() returns the magick wand associated with the pixel view. % % The format of the GetPixelViewWand method is: % % MagickWand *GetPixelViewWand(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport MagickWand *GetPixelViewWand(const PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->wand); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w W i d t h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewWidth() returns the pixel view width. % % The format of the GetPixelViewWidth method is: % % size_t GetPixelViewWidth(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport size_t GetPixelViewWidth(const PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->region.width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w X % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewX() returns the pixel view x offset. % % The format of the GetPixelViewX method is: % % ssize_t GetPixelViewX(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport ssize_t GetPixelViewX(const PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->region.x); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l V i e w Y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelViewY() returns the pixel view y offset. % % The format of the GetPixelViewY method is: % % ssize_t GetPixelViewY(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport ssize_t GetPixelViewY(const PixelView *pixel_view) { assert(pixel_view != (PixelView *) NULL); assert(pixel_view->signature == WandSignature); return(pixel_view->region.y); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s P i x e l V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsPixelView() returns MagickTrue if the the parameter is verified as a pixel % view container. % % The format of the IsPixelView method is: % % MagickBooleanType IsPixelView(const PixelView *pixel_view) % % A description of each parameter follows: % % o pixel_view: the pixel view. % */ WandExport MagickBooleanType IsPixelView(const PixelView *pixel_view) { size_t length; if (pixel_view == (const PixelView *) NULL) return(MagickFalse); if (pixel_view->signature != WandSignature) return(MagickFalse); length=strlen(PixelViewId); if (LocaleNCompare(pixel_view->name,PixelViewId,length) != 0) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k C l i p P a t h I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickClipPathImage() clips along the named paths from the 8BIM profile, if % present. Later operations take effect inside the path. Id may be a number % if preceded with #, to work on a numbered path, e.g., "#1" to use the first % path. % % The format of the MagickClipPathImage method is: % % MagickBooleanType MagickClipPathImage(MagickWand *wand, % const char *pathname,const MagickBooleanType inside) % % A description of each parameter follows: % % o wand: the magick wand. % % o pathname: name of clipping path resource. If name is preceded by #, use % clipping path numbered by name. % % o inside: if non-zero, later operations take effect inside clipping path. % Otherwise later operations take effect outside clipping path. % */ WandExport MagickBooleanType MagickClipPathImage(MagickWand *wand, const char *pathname,const MagickBooleanType inside) { return(MagickClipImagePath(wand,pathname,inside)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G e t F i l l A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGetFillAlpha() returns the alpha used when drawing using the fill % color or fill texture. Fully opaque is 1.0. % % The format of the DrawGetFillAlpha method is: % % double DrawGetFillAlpha(const DrawingWand *wand) % % A description of each parameter follows: % % o wand: the drawing wand. % */ WandExport double DrawGetFillAlpha(const DrawingWand *wand) { return(DrawGetFillOpacity(wand)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w G e t S t r o k e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawGetStrokeAlpha() returns the alpha of stroked object outlines. % % The format of the DrawGetStrokeAlpha method is: % % double DrawGetStrokeAlpha(const DrawingWand *wand) % % A description of each parameter follows: % % o wand: the drawing wand. */ WandExport double DrawGetStrokeAlpha(const DrawingWand *wand) { return(DrawGetStrokeOpacity(wand)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P e e k G r a p h i c W a n d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPeekGraphicWand() returns the current drawing wand. % % The format of the PeekDrawingWand method is: % % DrawInfo *DrawPeekGraphicWand(const DrawingWand *wand) % % A description of each parameter follows: % % o wand: the drawing wand. % */ WandExport DrawInfo *DrawPeekGraphicWand(const DrawingWand *wand) { return(PeekDrawingWand(wand)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P o p G r a p h i c C o n t e x t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPopGraphicContext() destroys the current drawing wand and returns to the % previously pushed drawing wand. Multiple drawing wands may exist. It is an % error to attempt to pop more drawing wands than have been pushed, and it is % proper form to pop all drawing wands which have been pushed. % % The format of the DrawPopGraphicContext method is: % % MagickBooleanType DrawPopGraphicContext(DrawingWand *wand) % % A description of each parameter follows: % % o wand: the drawing wand. % */ WandExport void DrawPopGraphicContext(DrawingWand *wand) { (void) PopDrawingWand(wand); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w P u s h G r a p h i c C o n t e x t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawPushGraphicContext() clones the current drawing wand to create a new % drawing wand. The original drawing wand(s) may be returned to by % invoking PopDrawingWand(). The drawing wands are stored on a drawing wand % stack. For every Pop there must have already been an equivalent Push. % % The format of the DrawPushGraphicContext method is: % % MagickBooleanType DrawPushGraphicContext(DrawingWand *wand) % % A description of each parameter follows: % % o wand: the drawing wand. % */ WandExport void DrawPushGraphicContext(DrawingWand *wand) { (void) PushDrawingWand(wand); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w S e t F i l l A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawSetFillAlpha() sets the alpha to use when drawing using the fill % color or fill texture. Fully opaque is 1.0. % % The format of the DrawSetFillAlpha method is: % % void DrawSetFillAlpha(DrawingWand *wand,const double fill_alpha) % % A description of each parameter follows: % % o wand: the drawing wand. % % o fill_alpha: fill alpha % */ WandExport void DrawSetFillAlpha(DrawingWand *wand,const double fill_alpha) { DrawSetFillOpacity(wand,fill_alpha); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D r a w S e t S t r o k e A l p h a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DrawSetStrokeAlpha() specifies the alpha of stroked object outlines. % % The format of the DrawSetStrokeAlpha method is: % % void DrawSetStrokeAlpha(DrawingWand *wand,const double stroke_alpha) % % A description of each parameter follows: % % o wand: the drawing wand. % % o stroke_alpha: stroke alpha. The value 1.0 is opaque. % */ WandExport void DrawSetStrokeAlpha(DrawingWand *wand,const double stroke_alpha) { DrawSetStrokeOpacity(wand,stroke_alpha); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k C o l o r F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickColorFloodfillImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % The format of the MagickColorFloodfillImage method is: % % MagickBooleanType MagickColorFloodfillImage(MagickWand *wand, % const PixelWand *fill,const double fuzz,const PixelWand *bordercolor, % const ssize_t x,const ssize_t y) % % A description of each parameter follows: % % o wand: the magick wand. % % o fill: the floodfill color pixel wand. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % % o bordercolor: the border color pixel wand. % % o x,y: the starting location of the operation. % */ WandExport MagickBooleanType MagickColorFloodfillImage(MagickWand *wand, const PixelWand *fill,const double fuzz,const PixelWand *bordercolor, const ssize_t x,const ssize_t y) { DrawInfo *draw_info; MagickBooleanType status; PixelPacket target; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); draw_info=CloneDrawInfo(wand->image_info,(DrawInfo *) NULL); PixelGetQuantumColor(fill,&draw_info->fill); (void) GetOneVirtualPixel(wand->images,x % wand->images->columns, y % wand->images->rows,&target,wand->exception); if (bordercolor != (PixelWand *) NULL) PixelGetQuantumColor(bordercolor,&target); wand->images->fuzz=fuzz; status=ColorFloodfillImage(wand->images,draw_info,target,x,y, bordercolor != (PixelWand *) NULL ? FillToBorderMethod : FloodfillMethod); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k D e s c r i b e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickDescribeImage() identifies an image by printing its attributes to the % file. Attributes include the image width, height, size, and others. % % The format of the MagickDescribeImage method is: % % const char *MagickDescribeImage(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport char *MagickDescribeImage(MagickWand *wand) { return(MagickIdentifyImage(wand)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k F l a t t e n I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickFlattenImages() merges a sequence of images. This useful for % combining Photoshop layers into a single image. % % The format of the MagickFlattenImages method is: % % MagickWand *MagickFlattenImages(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickWand *MagickFlattenImages(MagickWand *wand) { Image *flatten_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) return((MagickWand *) NULL); flatten_image=FlattenImages(wand->images,wand->exception); if (flatten_image == (Image *) NULL) return((MagickWand *) NULL); return(CloneMagickWandFromImages(wand,flatten_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageAttribute() returns a value associated with the specified % property. Use MagickRelinquishMemory() to free the value when you are % finished with it. % % The format of the MagickGetImageAttribute method is: % % char *MagickGetImageAttribute(MagickWand *wand,const char *property) % % A description of each parameter follows: % % o wand: the magick wand. % % o property: the property. % */ WandExport char *MagickGetImageAttribute(MagickWand *wand,const char *property) { return(MagickGetImageProperty(wand,property)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a g i c k G e t I m a g e I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageIndex() returns the index of the current image. % % The format of the MagickGetImageIndex method is: % % ssize_t MagickGetImageIndex(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport ssize_t MagickGetImageIndex(MagickWand *wand) { return(MagickGetIteratorIndex(wand)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a g i c k G e t I m a g e C h a n n e l E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageChannelExtrema() gets the extrema for one or more image % channels. % % The format of the MagickGetImageChannelExtrema method is: % % MagickBooleanType MagickGetImageChannelExtrema(MagickWand *wand, % const ChannelType channel,size_t *minima,size_t *maxima) % % A description of each parameter follows: % % o wand: the magick wand. % % o channel: the image channel(s). % % o minima: The minimum pixel value for the specified channel(s). % % o maxima: The maximum pixel value for the specified channel(s). % */ WandExport MagickBooleanType MagickGetImageChannelExtrema(MagickWand *wand, const ChannelType channel,size_t *minima,size_t *maxima) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=GetImageChannelExtrema(wand->images,channel,minima,maxima, wand->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a g i c k G e t I m a g e E x t r e m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageExtrema() gets the extrema for the image. % % The format of the MagickGetImageExtrema method is: % % MagickBooleanType MagickGetImageExtrema(MagickWand *wand, % size_t *minima,size_t *maxima) % % A description of each parameter follows: % % o wand: the magick wand. % % o minima: The minimum pixel value for the specified channel(s). % % o maxima: The maximum pixel value for the specified channel(s). % */ WandExport MagickBooleanType MagickGetImageExtrema(MagickWand *wand, size_t *minima,size_t *maxima) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=GetImageExtrema(wand->images,minima,maxima,wand->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e M a t t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageMatte() returns MagickTrue if the image has a matte channel % otherwise MagickFalse. % % The format of the MagickGetImageMatte method is: % % size_t MagickGetImageMatte(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickBooleanType MagickGetImageMatte(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); return(wand->images->matte); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImagePixels() extracts pixel data from an image and returns it to % you. The method returns MagickTrue on success otherwise MagickFalse if an % error is encountered. The data is returned as char, short int, int, ssize_t, % float, or double in the order specified by map. % % Suppose you want to extract the first scanline of a 640x480 image as % character data in red-green-blue order: % % MagickGetImagePixels(wand,0,0,640,1,"RGB",CharPixel,pixels); % % The format of the MagickGetImagePixels method is: % % MagickBooleanType MagickGetImagePixels(MagickWand *wand, % const ssize_t x,const ssize_t y,const size_t columns, % const size_t rows,const char *map,const StorageType storage, % void *pixels) % % A description of each parameter follows: % % o wand: the magick wand. % % o x, y, columns, rows: These values define the perimeter % of a region of pixels you want to extract. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, % Y = yellow, M = magenta, K = black, I = intensity (for grayscale), % P = pad. % % o storage: Define the data type of the pixels. Float and double types are % expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose from % these types: CharPixel, DoublePixel, FloatPixel, IntegerPixel, % LongPixel, QuantumPixel, or ShortPixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % */ WandExport MagickBooleanType MagickGetImagePixels(MagickWand *wand, const ssize_t x,const ssize_t y,const size_t columns, const size_t rows,const char *map,const StorageType storage, void *pixels) { return(MagickExportImagePixels(wand,x,y,columns,rows,map,storage,pixels)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k G e t I m a g e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickGetImageSize() returns the image length in bytes. % % The format of the MagickGetImageSize method is: % % MagickBooleanType MagickGetImageSize(MagickWand *wand, % MagickSizeType *length) % % A description of each parameter follows: % % o wand: the magick wand. % % o length: the image length in bytes. % */ WandExport MagickSizeType MagickGetImageSize(MagickWand *wand) { assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); return(GetBlobSize(wand->images)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M a p I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMapImage() replaces the colors of an image with the closest color % from a reference image. % % The format of the MagickMapImage method is: % % MagickBooleanType MagickMapImage(MagickWand *wand, % const MagickWand *map_wand,const MagickBooleanType dither) % % A description of each parameter follows: % % o wand: the magick wand. % % o map: the map wand. % % o dither: Set this integer value to something other than zero to dither % the mapped image. % */ WandExport MagickBooleanType MagickMapImage(MagickWand *wand, const MagickWand *map_wand,const MagickBooleanType dither) { MagickBooleanType status; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if ((wand->images == (Image *) NULL) || (map_wand->images == (Image *) NULL)) ThrowWandException(WandError,"ContainsNoImages",wand->name); status=MapImage(wand->images,map_wand->images,dither); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M a t t e F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMatteFloodfillImage() changes the transparency value of any pixel that % matches target and is an immediate neighbor. If the method % FillToBorderMethod is specified, the transparency value is changed for any % neighbor pixel that does not match the bordercolor member of image. % % The format of the MagickMatteFloodfillImage method is: % % MagickBooleanType MagickMatteFloodfillImage(MagickWand *wand, % const double alpha,const double fuzz,const PixelWand *bordercolor, % const ssize_t x,const ssize_t y) % % A description of each parameter follows: % % o wand: the magick wand. % % o alpha: the level of transparency: 1.0 is fully opaque and 0.0 is fully % transparent. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % % o bordercolor: the border color pixel wand. % % o x,y: the starting location of the operation. % */ WandExport MagickBooleanType MagickMatteFloodfillImage(MagickWand *wand, const double alpha,const double fuzz,const PixelWand *bordercolor, const ssize_t x,const ssize_t y) { DrawInfo *draw_info; MagickBooleanType status; PixelPacket target; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); draw_info=CloneDrawInfo(wand->image_info,(DrawInfo *) NULL); (void) GetOneVirtualPixel(wand->images,x % wand->images->columns, y % wand->images->rows,&target,wand->exception); if (bordercolor != (PixelWand *) NULL) PixelGetQuantumColor(bordercolor,&target); wand->images->fuzz=fuzz; status=MatteFloodfillImage(wand->images,target,ClampToQuantum( (MagickRealType) QuantumRange-QuantumRange*alpha),x,y,bordercolor != (PixelWand *) NULL ? FillToBorderMethod : FloodfillMethod); if (status == MagickFalse) InheritException(wand->exception,&wand->images->exception); draw_info=DestroyDrawInfo(draw_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M e d i a n F i l t e r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMedianFilterImage() applies a digital filter that improves the quality % of a noisy image. Each pixel is replaced by the median in a set of % neighboring pixels as defined by radius. % % The format of the MagickMedianFilterImage method is: % % MagickBooleanType MagickMedianFilterImage(MagickWand *wand, % const double radius) % % A description of each parameter follows: % % o wand: the magick wand. % % o radius: the radius of the pixel neighborhood. % */ WandExport MagickBooleanType MagickMedianFilterImage(MagickWand *wand, const double radius) { Image *median_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); median_image=MedianFilterImage(wand->images,radius,wand->exception); if (median_image == (Image *) NULL) return(MagickFalse); ReplaceImageInList(&wand->images,median_image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M i n i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMinimumImages() returns the minimum intensity of an image sequence. % % The format of the MagickMinimumImages method is: % % MagickWand *MagickMinimumImages(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickWand *MagickMinimumImages(MagickWand *wand) { Image *minimum_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) return((MagickWand *) NULL); minimum_image=EvaluateImages(wand->images,MinEvaluateOperator, wand->exception); if (minimum_image == (Image *) NULL) return((MagickWand *) NULL); return(CloneMagickWandFromImages(wand,minimum_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickModeImage() makes each pixel the 'predominant color' of the % neighborhood of the specified radius. % % The format of the MagickModeImage method is: % % MagickBooleanType MagickModeImage(MagickWand *wand, % const double radius) % % A description of each parameter follows: % % o wand: the magick wand. % % o radius: the radius of the pixel neighborhood. % */ WandExport MagickBooleanType MagickModeImage(MagickWand *wand, const double radius) { Image *mode_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); mode_image=ModeImage(wand->images,radius,wand->exception); if (mode_image == (Image *) NULL) return(MagickFalse); ReplaceImageInList(&wand->images,mode_image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M o s a i c I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMosaicImages() inlays an image sequence to form a single coherent % picture. It returns a wand with each image in the sequence composited at % the location defined by the page offset of the image. % % The format of the MagickMosaicImages method is: % % MagickWand *MagickMosaicImages(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickWand *MagickMosaicImages(MagickWand *wand) { Image *mosaic_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) return((MagickWand *) NULL); mosaic_image=MosaicImages(wand->images,wand->exception); if (mosaic_image == (Image *) NULL) return((MagickWand *) NULL); return(CloneMagickWandFromImages(wand,mosaic_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickOpaqueImage() changes any pixel that matches color with the color % defined by fill. % % The format of the MagickOpaqueImage method is: % % MagickBooleanType MagickOpaqueImage(MagickWand *wand, % const PixelWand *target,const PixelWand *fill,const double fuzz) % % A description of each parameter follows: % % o wand: the magick wand. % % o channel: the channel(s). % % o target: Change this target color to the fill color within the image. % % o fill: the fill pixel wand. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % */ WandExport MagickBooleanType MagickOpaqueImage(MagickWand *wand, const PixelWand *target,const PixelWand *fill,const double fuzz) { return(MagickPaintOpaqueImage(wand,target,fill,fuzz)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k P a i n t F l o o d f i l l I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickPaintFloodfillImage() changes the color value of any pixel that matches % target and is an immediate neighbor. If the method FillToBorderMethod is % specified, the color value is changed for any neighbor pixel that does not % match the bordercolor member of image. % % The format of the MagickPaintFloodfillImage method is: % % MagickBooleanType MagickPaintFloodfillImage(MagickWand *wand, % const ChannelType channel,const PixelWand *fill,const double fuzz, % const PixelWand *bordercolor,const ssize_t x,const ssize_t y) % % A description of each parameter follows: % % o wand: the magick wand. % % o channel: the channel(s). % % o fill: the floodfill color pixel wand. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % % o bordercolor: the border color pixel wand. % % o x,y: the starting location of the operation. % */ WandExport MagickBooleanType MagickPaintFloodfillImage(MagickWand *wand, const ChannelType channel,const PixelWand *fill,const double fuzz, const PixelWand *bordercolor,const ssize_t x,const ssize_t y) { MagickBooleanType status; status=MagickFloodfillPaintImage(wand,channel,fill,fuzz,bordercolor,x,y, MagickFalse); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k P a i n t O p a q u e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickPaintOpaqueImage() changes any pixel that matches color with the color % defined by fill. % % The format of the MagickPaintOpaqueImage method is: % % MagickBooleanType MagickPaintOpaqueImage(MagickWand *wand, % const PixelWand *target,const PixelWand *fill,const double fuzz) % MagickBooleanType MagickPaintOpaqueImageChannel(MagickWand *wand, % const ChannelType channel,const PixelWand *target, % const PixelWand *fill,const double fuzz) % % A description of each parameter follows: % % o wand: the magick wand. % % o channel: the channel(s). % % o target: Change this target color to the fill color within the image. % % o fill: the fill pixel wand. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % */ WandExport MagickBooleanType MagickPaintOpaqueImage(MagickWand *wand, const PixelWand *target,const PixelWand *fill,const double fuzz) { return(MagickPaintOpaqueImageChannel(wand,DefaultChannels,target,fill,fuzz)); } WandExport MagickBooleanType MagickPaintOpaqueImageChannel(MagickWand *wand, const ChannelType channel,const PixelWand *target,const PixelWand *fill, const double fuzz) { MagickBooleanType status; status=MagickOpaquePaintImageChannel(wand,channel,target,fill,fuzz, MagickFalse); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k P a i n t T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickPaintTransparentImage() changes any pixel that matches color with the % color defined by fill. % % The format of the MagickPaintTransparentImage method is: % % MagickBooleanType MagickPaintTransparentImage(MagickWand *wand, % const PixelWand *target,const double alpha,const double fuzz) % % A description of each parameter follows: % % o wand: the magick wand. % % o target: Change this target color to specified opacity value within % the image. % % o alpha: the level of transparency: 1.0 is fully opaque and 0.0 is fully % transparent. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % */ WandExport MagickBooleanType MagickPaintTransparentImage(MagickWand *wand, const PixelWand *target,const double alpha,const double fuzz) { return(MagickTransparentPaintImage(wand,target,alpha,fuzz,MagickFalse)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k R a d i a l B l u r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickRadialBlurImage() radial blurs an image. % % The format of the MagickRadialBlurImage method is: % % MagickBooleanType MagickRadialBlurImage(MagickWand *wand, % const double angle) % MagickBooleanType MagickRadialBlurImageChannel(MagickWand *wand, % const ChannelType channel,const double angle) % % A description of each parameter follows: % % o wand: the magick wand. % % o channel: the image channel(s). % % o angle: the angle of the blur in degrees. % */ WandExport MagickBooleanType MagickRadialBlurImage(MagickWand *wand, const double angle) { return(MagickRotationalBlurImage(wand,angle)); } WandExport MagickBooleanType MagickRadialBlurImageChannel(MagickWand *wand, const ChannelType channel,const double angle) { return(MagickRotationalBlurImageChannel(wand,channel,angle)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k R e c o l o r I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickRecolorImage() apply color transformation to an image. The method % permits saturation changes, hue rotation, luminance to alpha, and various % other effects. Although variable-sized transformation matrices can be used, % typically one uses a 5x5 matrix for an RGBA image and a 6x6 for CMYKA % (or RGBA with offsets). The matrix is similar to those used by Adobe Flash % except offsets are in column 6 rather than 5 (in support of CMYKA images) % and offsets are normalized (divide Flash offset by 255). % % The format of the MagickRecolorImage method is: % % MagickBooleanType MagickRecolorImage(MagickWand *wand, % const size_t order,const double *color_matrix) % % A description of each parameter follows: % % o wand: the magick wand. % % o order: the number of columns and rows in the color matrix. % % o color_matrix: An array of doubles representing the color matrix. % */ WandExport MagickBooleanType MagickRecolorImage(MagickWand *wand, const size_t order,const double *color_matrix) { Image *transform_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (color_matrix == (const double *) NULL) return(MagickFalse); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); transform_image=RecolorImage(wand->images,order,color_matrix, wand->exception); if (transform_image == (Image *) NULL) return(MagickFalse); ReplaceImageInList(&wand->images,transform_image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k R e d u c e N o i s e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickReduceNoiseImage() smooths the contours of an image while still % preserving edge information. The algorithm works by replacing each pixel % with its neighbor closest in value. A neighbor is defined by radius. Use % a radius of 0 and ReduceNoise() selects a suitable radius for you. % % The format of the MagickReduceNoiseImage method is: % % MagickBooleanType MagickReduceNoiseImage(MagickWand *wand, % const double radius) % % A description of each parameter follows: % % o wand: the magick wand. % % o radius: the radius of the pixel neighborhood. % */ WandExport MagickBooleanType MagickReduceNoiseImage(MagickWand *wand, const double radius) { Image *noise_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) ThrowWandException(WandError,"ContainsNoImages",wand->name); noise_image=ReduceNoiseImage(wand->images,radius,wand->exception); if (noise_image == (Image *) NULL) return(MagickFalse); ReplaceImageInList(&wand->images,noise_image); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k M a x i m u m I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickMaximumImages() returns the maximum intensity of an image sequence. % % The format of the MagickMaximumImages method is: % % MagickWand *MagickMaximumImages(MagickWand *wand) % % A description of each parameter follows: % % o wand: the magick wand. % */ WandExport MagickWand *MagickMaximumImages(MagickWand *wand) { Image *maximum_image; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); if (wand->images == (Image *) NULL) return((MagickWand *) NULL); maximum_image=EvaluateImages(wand->images,MaxEvaluateOperator, wand->exception); if (maximum_image == (Image *) NULL) return((MagickWand *) NULL); return(CloneMagickWandFromImages(wand,maximum_image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I m a g e A t t r i b u t e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageAttribute() associates a property with an image. % % The format of the MagickSetImageAttribute method is: % % MagickBooleanType MagickSetImageAttribute(MagickWand *wand, % const char *property,const char *value) % % A description of each parameter follows: % % o wand: the magick wand. % % o property: the property. % % o value: the value. % */ WandExport MagickBooleanType MagickSetImageAttribute(MagickWand *wand, const char *property,const char *value) { return(SetImageProperty(wand->images,property,value)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I m a g e I n d e x % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageIndex() set the current image to the position of the list % specified with the index parameter. % % The format of the MagickSetImageIndex method is: % % MagickBooleanType MagickSetImageIndex(MagickWand *wand, % const ssize_t index) % % A description of each parameter follows: % % o wand: the magick wand. % % o index: the scene number. % */ WandExport MagickBooleanType MagickSetImageIndex(MagickWand *wand, const ssize_t index) { return(MagickSetIteratorIndex(wand,index)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a g i c k S e t I m a g e O p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImageOption() associates one or options with a particular image % format (.e.g MagickSetImageOption(wand,"jpeg","perserve","yes"). % % The format of the MagickSetImageOption method is: % % MagickBooleanType MagickSetImageOption(MagickWand *wand, % const char *format,const char *key,const char *value) % % A description of each parameter follows: % % o wand: the magick wand. % % o format: the image format. % % o key: The key. % % o value: The value. % */ WandExport MagickBooleanType MagickSetImageOption(MagickWand *wand, const char *format,const char *key,const char *value) { char option[MaxTextExtent]; assert(wand != (MagickWand *) NULL); assert(wand->signature == WandSignature); if (wand->debug != MagickFalse) (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name); (void) FormatLocaleString(option,MaxTextExtent,"%s:%s=%s",format,key,value); return(DefineImageOption(wand->image_info,option)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k T r a n s p a r e n t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickTransparentImage() changes any pixel that matches color with the % color defined by fill. % % The format of the MagickTransparentImage method is: % % MagickBooleanType MagickTransparentImage(MagickWand *wand, % const PixelWand *target,const double alpha,const double fuzz) % % A description of each parameter follows: % % o wand: the magick wand. % % o target: Change this target color to specified opacity value within % the image. % % o alpha: the level of transparency: 1.0 is fully opaque and 0.0 is fully % transparent. % % o fuzz: By default target must match a particular pixel color % exactly. However, in many cases two colors may differ by a small amount. % The fuzz member of image defines how much tolerance is acceptable to % consider two colors as the same. For example, set fuzz to 10 and the % color red at intensities of 100 and 102 respectively are now interpreted % as the same color for the purposes of the floodfill. % */ WandExport MagickBooleanType MagickTransparentImage(MagickWand *wand, const PixelWand *target,const double alpha,const double fuzz) { return(MagickPaintTransparentImage(wand,target,alpha,fuzz)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k R e g i o n O f I n t e r e s t I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickRegionOfInterestImage() extracts a region of the image and returns it % as a new wand. % % The format of the MagickRegionOfInterestImage method is: % % MagickWand *MagickRegionOfInterestImage(MagickWand *wand, % const size_t width,const size_t height,const ssize_t x, % const ssize_t y) % % A description of each parameter follows: % % o wand: the magick wand. % % o width: the region width. % % o height: the region height. % % o x: the region x offset. % % o y: the region y offset. % */ WandExport MagickWand *MagickRegionOfInterestImage(MagickWand *wand, const size_t width,const size_t height,const ssize_t x, const ssize_t y) { return(MagickGetImageRegion(wand,width,height,x,y)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k S e t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickSetImagePixels() accepts pixel datand stores it in the image at the % location you specify. The method returns MagickFalse on success otherwise % MagickTrue if an error is encountered. The pixel data can be either char, % short int, int, ssize_t, float, or double in the order specified by map. % % Suppose your want to upload the first scanline of a 640x480 image from % character data in red-green-blue order: % % MagickSetImagePixels(wand,0,0,640,1,"RGB",CharPixel,pixels); % % The format of the MagickSetImagePixels method is: % % MagickBooleanType MagickSetImagePixels(MagickWand *wand, % const ssize_t x,const ssize_t y,const size_t columns, % const size_t rows,const char *map,const StorageType storage, % const void *pixels) % % A description of each parameter follows: % % o wand: the magick wand. % % o x, y, columns, rows: These values define the perimeter of a region % of pixels you want to define. % % o map: This string reflects the expected ordering of the pixel array. % It can be any combination or order of R = red, G = green, B = blue, % A = alpha (0 is transparent), O = opacity (0 is opaque), C = cyan, % Y = yellow, M = magenta, K = black, I = intensity (for grayscale), % P = pad. % % o storage: Define the data type of the pixels. Float and double types are % expected to be normalized [0..1] otherwise [0..QuantumRange]. Choose from % these types: CharPixel, ShortPixel, IntegerPixel, LongPixel, FloatPixel, % or DoublePixel. % % o pixels: This array of values contain the pixel components as defined by % map and type. You must preallocate this array where the expected % length varies depending on the values of width, height, map, and type. % */ WandExport MagickBooleanType MagickSetImagePixels(MagickWand *wand, const ssize_t x,const ssize_t y,const size_t columns, const size_t rows,const char *map,const StorageType storage, const void *pixels) { return(MagickImportImagePixels(wand,x,y,columns,rows,map,storage,pixels)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % M a g i c k W r i t e I m a g e B l o b % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MagickWriteImageBlob() implements direct to memory image formats. It % returns the image as a blob and its length. Use MagickSetFormat() to % set the format of the returned blob (GIF, JPEG, PNG, etc.). % % Use MagickRelinquishMemory() to free the blob when you are done with it. % % The format of the MagickWriteImageBlob method is: % % unsigned char *MagickWriteImageBlob(MagickWand *wand,size_t *length) % % A description of each parameter follows: % % o wand: the magick wand. % % o length: the length of the blob. % */ WandExport unsigned char *MagickWriteImageBlob(MagickWand *wand,size_t *length) { return(MagickGetImageBlob(wand,length)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w P i x e l V i e w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewPixelView() returns a pixel view required for all other methods in the % Pixel View API. % % The format of the NewPixelView method is: % % PixelView *NewPixelView(MagickWand *wand) % % A description of each parameter follows: % % o wand: the wand. % */ static PixelWand ***AcquirePixelsThreadSet(const size_t number_wands, const size_t number_threads) { PixelWand ***pixel_wands; register ssize_t i; pixel_wands=(PixelWand ***) AcquireQuantumMemory(number_threads, sizeof(*pixel_wands)); if (pixel_wands == (PixelWand ***) NULL) return((PixelWand ***) NULL); (void) memset(pixel_wands,0,number_threads*sizeof(*pixel_wands)); for (i=0; i < (ssize_t) number_threads; i++) { pixel_wands[i]=NewPixelWands(number_wands); if (pixel_wands[i] == (PixelWand **) NULL) return(DestroyPixelsThreadSet(pixel_wands,number_wands,number_threads)); } return(pixel_wands); } WandExport PixelView *NewPixelView(MagickWand *wand) { PixelView *pixel_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickCoreSignature); pixel_view=(PixelView *) AcquireMagickMemory(sizeof(*pixel_view)); if (pixel_view == (PixelView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) memset(pixel_view,0,sizeof(*pixel_view)); pixel_view->id=AcquireWandId(); (void) FormatLocaleString(pixel_view->name,MaxTextExtent,"%s-%.20g", PixelViewId,(double) pixel_view->id); pixel_view->exception=AcquireExceptionInfo(); pixel_view->wand=wand; pixel_view->view=AcquireVirtualCacheView(pixel_view->wand->images, pixel_view->exception); pixel_view->region.width=wand->images->columns; pixel_view->region.height=wand->images->rows; pixel_view->number_threads=GetOpenMPMaximumThreads(); pixel_view->pixel_wands=AcquirePixelsThreadSet(pixel_view->region.width, pixel_view->number_threads); if (pixel_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); pixel_view->debug=IsEventLogging(); pixel_view->signature=WandSignature; return(pixel_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % N e w P i x e l V i e w R e g i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % NewPixelViewRegion() returns a pixel view required for all other methods % in the Pixel View API. % % The format of the NewPixelViewRegion method is: % % PixelView *NewPixelViewRegion(MagickWand *wand,const ssize_t x, % const ssize_t y,const size_t width,const size_t height) % % A description of each parameter follows: % % o wand: the magick wand. % % o x,y,columns,rows: These values define the perimeter of a region of % pixel_wands view. % */ WandExport PixelView *NewPixelViewRegion(MagickWand *wand,const ssize_t x, const ssize_t y,const size_t width,const size_t height) { PixelView *pixel_view; assert(wand != (MagickWand *) NULL); assert(wand->signature == MagickCoreSignature); pixel_view=(PixelView *) AcquireMagickMemory(sizeof(*pixel_view)); if (pixel_view == (PixelView *) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); (void) memset(pixel_view,0,sizeof(*pixel_view)); pixel_view->id=AcquireWandId(); (void) FormatLocaleString(pixel_view->name,MaxTextExtent,"%s-%.20g", PixelViewId,(double) pixel_view->id); pixel_view->exception=AcquireExceptionInfo(); pixel_view->view=AcquireVirtualCacheView(pixel_view->wand->images, pixel_view->exception); pixel_view->wand=wand; pixel_view->region.width=width; pixel_view->region.height=height; pixel_view->region.x=x; pixel_view->region.y=y; pixel_view->number_threads=GetOpenMPMaximumThreads(); pixel_view->pixel_wands=AcquirePixelsThreadSet(pixel_view->region.width, pixel_view->number_threads); if (pixel_view->pixel_wands == (PixelWand ***) NULL) ThrowWandFatalException(ResourceLimitFatalError,"MemoryAllocationFailed", GetExceptionMessage(errno)); pixel_view->debug=IsEventLogging(); pixel_view->signature=WandSignature; return(pixel_view); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i x e l G e t N e x t R o w % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PixelGetNextRow() returns the next row as an array of pixel wands from the % pixel iterator. % % The format of the PixelGetNextRow method is: % % PixelWand **PixelGetNextRow(PixelIterator *iterator, % size_t *number_wands) % % A description of each parameter follows: % % o iterator: the pixel iterator. % % o number_wands: the number of pixel wands. % */ WandExport PixelWand **PixelGetNextRow(PixelIterator *iterator) { size_t number_wands; return(PixelGetNextIteratorRow(iterator,&number_wands)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % P i x e l I t e r a t o r G e t E x c e p t i o n % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PixelIteratorGetException() returns the severity, reason, and description of % any error that occurs when using other methods in this API. % % The format of the PixelIteratorGetException method is: % % char *PixelIteratorGetException(const Pixeliterator *iterator, % ExceptionType *severity) % % A description of each parameter follows: % % o iterator: the pixel iterator. % % o severity: the severity of the error is returned here. % */ WandExport char *PixelIteratorGetException(const PixelIterator *iterator, ExceptionType *severity) { return(PixelGetIteratorException(iterator,severity)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelViewIterator() iterates over the pixel view in parallel and calls % your set method for each scanline of the view. The pixel region is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension. The pixels are initiallly % undefined and any settings you make in the callback method are automagically % synced back to your image. % % Use this pragma: % % #pragma omp critical % % to define a section of code in your callback set method that must be % executed by a single thread at a time. % % The format of the SetPixelViewIterator method is: % % MagickBooleanType SetPixelViewIterator(PixelView *destination, % SetPixelViewMethod set,void *context) % % A description of each parameter follows: % % o destination: the pixel view. % % o set: the set callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType SetPixelViewIterator(PixelView *destination, SetPixelViewMethod set,void *context) { #define SetPixelViewTag "PixelView/Set" ExceptionInfo *exception; Image *destination_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(destination != (PixelView *) NULL); assert(destination->signature == WandSignature); if (set == (SetPixelViewMethod) NULL) return(MagickFalse); destination_image=destination->wand->images; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) #endif for (y=destination->region.y; y < (ssize_t) destination->region.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(destination->view,destination->region.x, y,destination->region.width,1,exception); if (pixels == (PixelPacket *) NULL) { InheritException(destination->exception,GetCacheViewException( destination->view)); status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(destination->view); if (set(destination,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) destination->region.width; x++) PixelGetQuantumColor(destination->pixel_wands[id][x],pixels+x); if (destination_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) destination->region.width; x++) SetPixelIndex(indexes+x,PixelGetBlackQuantum( destination->pixel_wands[id][x])); sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( destination->view)); status=MagickFalse; } if (destination_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_SetPixelViewIterator) #endif proceed=SetImageProgress(destination_image,SetPixelViewTag,progress++, destination->region.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % T r a n s f e r P i x e l V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % TransferPixelViewIterator() iterates over two pixel views in parallel and % calls your transfer method for each scanline of the view. The source pixel % region is not confined to the image canvas-- that is you can include % negative offsets or widths or heights that exceed the image dimension. % However, the destination pixel view is confined to the image canvas-- that % is no negative offsets or widths or heights that exceed the image dimension % are permitted. % % Use this pragma: % % #pragma omp critical % % to define a section of code in your callback transfer method that must be % executed by a single thread at a time. % % The format of the TransferPixelViewIterator method is: % % MagickBooleanType TransferPixelViewIterator(PixelView *source, % PixelView *destination,TransferPixelViewMethod transfer,void *context) % % A description of each parameter follows: % % o source: the source pixel view. % % o destination: the destination pixel view. % % o transfer: the transfer callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType TransferPixelViewIterator(PixelView *source, PixelView *destination,TransferPixelViewMethod transfer,void *context) { #define TransferPixelViewTag "PixelView/Transfer" ExceptionInfo *exception; Image *destination_image, *source_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(source != (PixelView *) NULL); assert(source->signature == WandSignature); if (transfer == (TransferPixelViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; destination_image=destination->wand->images; if (SetImageStorageClass(destination_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=destination->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) #endif for (y=source->region.y; y < (ssize_t) source->region.height; y++) { const int id = GetOpenMPThreadId(); MagickBooleanType sync; register const IndexPacket *magick_restrict indexes; register const PixelPacket *magick_restrict pixels; register IndexPacket *magick_restrict destination_indexes; register ssize_t x; register PixelPacket *magick_restrict destination_pixels; if (status == MagickFalse) continue; pixels=GetCacheViewVirtualPixels(source->view,source->region.x,y, source->region.width,1,source->exception); if (pixels == (const PixelPacket *) NULL) { status=MagickFalse; continue; } indexes=GetCacheViewVirtualIndexQueue(source->view); for (x=0; x < (ssize_t) source->region.width; x++) PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x); if (source_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetBlackQuantum(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (source_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetIndex(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); destination_pixels=GetCacheViewAuthenticPixels(destination->view, destination->region.x,y,destination->region.width,1,exception); if (destination_pixels == (PixelPacket *) NULL) { status=MagickFalse; continue; } destination_indexes=GetCacheViewAuthenticIndexQueue(destination->view); for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetQuantumColor(destination->pixel_wands[id][x],pixels+x); if (destination_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetBlackQuantum(destination->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (destination_image->storage_class == PseudoClass) for (x=0; x < (ssize_t) destination->region.width; x++) PixelSetIndex(destination->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (transfer(source,destination,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) destination->region.width; x++) PixelGetQuantumColor(destination->pixel_wands[id][x], destination_pixels+x); if (destination_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) destination->region.width; x++) SetPixelIndex(destination_indexes+x,PixelGetBlackQuantum( destination->pixel_wands[id][x])); sync=SyncCacheViewAuthenticPixels(destination->view,exception); if (sync == MagickFalse) { InheritException(destination->exception,GetCacheViewException( source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_TransferPixelViewIterator) #endif proceed=SetImageProgress(source_image,TransferPixelViewTag,progress++, source->region.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U p d a t e P i x e l V i e w I t e r a t o r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UpdatePixelViewIterator() iterates over the pixel view in parallel and calls % your update method for each scanline of the view. The pixel region is % confined to the image canvas-- that is no negative offsets or widths or % heights that exceed the image dimension are permitted. Updates to pixels % in your callback are automagically synced back to the image. % % Use this pragma: % % #pragma omp critical % % to define a section of code in your callback update method that must be % executed by a single thread at a time. % % The format of the UpdatePixelViewIterator method is: % % MagickBooleanType UpdatePixelViewIterator(PixelView *source, % UpdatePixelViewMethod update,void *context) % % A description of each parameter follows: % % o source: the source pixel view. % % o update: the update callback method. % % o context: the user defined context. % */ WandExport MagickBooleanType UpdatePixelViewIterator(PixelView *source, UpdatePixelViewMethod update,void *context) { #define UpdatePixelViewTag "PixelView/Update" ExceptionInfo *exception; Image *source_image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(source != (PixelView *) NULL); assert(source->signature == WandSignature); if (update == (UpdatePixelViewMethod) NULL) return(MagickFalse); source_image=source->wand->images; if (SetImageStorageClass(source_image,DirectClass) == MagickFalse) return(MagickFalse); status=MagickTrue; progress=0; exception=source->exception; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) #endif for (y=source->region.y; y < (ssize_t) source->region.height; y++) { const int id = GetOpenMPThreadId(); register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict pixels; if (status == MagickFalse) continue; pixels=GetCacheViewAuthenticPixels(source->view,source->region.x,y, source->region.width,1,exception); if (pixels == (PixelPacket *) NULL) { InheritException(source->exception,GetCacheViewException( source->view)); status=MagickFalse; continue; } indexes=GetCacheViewAuthenticIndexQueue(source->view); for (x=0; x < (ssize_t) source->region.width; x++) PixelSetQuantumColor(source->pixel_wands[id][x],pixels+x); if (source_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) source->region.width; x++) PixelSetBlackQuantum(source->pixel_wands[id][x], GetPixelIndex(indexes+x)); if (update(source,context) == MagickFalse) status=MagickFalse; for (x=0; x < (ssize_t) source->region.width; x++) PixelGetQuantumColor(source->pixel_wands[id][x],pixels+x); if (source_image->colorspace == CMYKColorspace) for (x=0; x < (ssize_t) source->region.width; x++) SetPixelIndex(indexes+x,PixelGetBlackQuantum( source->pixel_wands[id][x])); if (SyncCacheViewAuthenticPixels(source->view,exception) == MagickFalse) { InheritException(source->exception,GetCacheViewException(source->view)); status=MagickFalse; } if (source_image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickWand_UpdatePixelViewIterator) #endif proceed=SetImageProgress(source_image,UpdatePixelViewTag,progress++, source->region.height); if (proceed == MagickFalse) status=MagickFalse; } } return(status); } #endif
SumaVectoresC-Ej7.c
/* SumaVectoresC.c Suma de dos vectores: v3 = v1 + v2 Para compilar usar (-lrt: real time library): gcc -O2 SumaVectores.c -o SumaVectores –lrt gcc -O2 –S SumaVectores.c –lrt //para generar el código ensamblador Para ejecutar use: SumaVectoresC longitud */ #include <stdlib.h> // biblioteca con funciones atoi(), malloc() y free() #include <stdio.h> // biblioteca donde se encuentra la función printf() #include <time.h> // biblioteca donde se encuentra la función clock_gettime() #ifdef _OPENMP #include <omp.h> #else #define omp_get_thread_num() 0 #define omp_get_num_threads() 1 #endif //#define PRINTF_ALL // comentar para quitar el printf ... // que imprime todos los componentes //Sólo puede estar definida una de las tres constantes VECTOR_ (sólo uno de los ... //tres defines siguientes puede estar descomentado): //#define VECTOR_LOCAL // descomentar para que los vectores sean variables ... // locales (si se supera el tamaño de la pila se ... // generará el error "Violación de Segmento") #define VECTOR_GLOBAL // descomentar para que los vectores sean variables ... // globales (su longitud no estará limitada por el ... // tamaño de la pila del programa) //#define VECTOR_DYNAMIC // descomentar para que los vectores sean variables ... // dinámicas (memoria reutilizable durante la ejecución) #ifdef VECTOR_GLOBAL #define MAX 33554432 //=2^25 //#define MAX 4294967295//=(2^32) -1 double v1[MAX], v2[MAX], v3[MAX]; #endif int main(int argc, char** argv){ int i; double cgt1,cgt2; //struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución //Leer argumento de entrada (no de componentes del vector) if (argc<2){ printf("Faltan no componentes del vector\n"); exit(-1); } unsigned int N = atoi(argv[1]); // Máximo N =2^32-1=4294967295 (sizeof(unsigned int) = 4 B) #ifdef VECTOR_LOCAL double v1[N], v2[N], v3[N]; // Tamaño variable local en tiempo de ejecución ... // disponible en C a partir de actualización C99 #endif #ifdef VECTOR_GLOBAL if (N>MAX) N=MAX; #endif #ifdef VECTOR_DYNAMIC double *v1, *v2, *v3; v1 = (double*) malloc(N*sizeof(double)); // malloc necesita el tamaño en bytes v2 = (double*) malloc(N*sizeof(double)); //si no hay espacio suficiente malloc devuelve NULL v3 = (double*) malloc(N*sizeof(double)); if ( (v1==NULL) || (v2==NULL) || (v3==NULL) ){ printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } #endif //Inicializar vectores #pragma omp parallel { #pragma omp for for(i=0; i<N; i++){ v1[i] = N*0.1+i*0.1; v2[i] = N*0.1-i*0.1; //los valores dependen de N } #pragma omp single { cgt1 = omp_get_wtime(); } //Calcular suma de vectores #pragma omp for for(i=0; i<N; i++) v3[i] = v1[i] + v2[i]; #pragma omp single { cgt2 = omp_get_wtime(); } } ncgt = cgt2-cgt1; //calculo el tiempo que ha transcurrido /*Inicializar vectores for(i=0; i<N; i++){ v1[i] = N*0.1+i*0.1; v2[i] = N*0.1-i*0.1; //los valores dependen de N } clock_gettime(CLOCK_REALTIME,&cgt1); Calcular suma de vectores for(i=0; i<N; i++) v3[i] = v1[i] + v2[i];*/ /*clock_gettime(CLOCK_REALTIME,&cgt2); ncgt=(double) (cgt2.tv_sec-cgt1.tv_sec)+ (double) ((cgt2.tv_nsec-cgt1.tv_nsec)/(1.e+9)); */ //Imprimir resultado de la suma y el tiempo de ejecución #ifdef PRINTF_ALL printf("Tiempo(seg.):%11.9f\t / Tamaño Vectores:%u\n",ncgt,N); for(i=0; i<N; i++) printf("/ V1[%d]+V2[%d]=V3[%d](%8.6f+%8.6f=%8.6f) /\n", i,i,i,v1[i],v2[i],v3[i]); #else printf("Tiempo(seg.):%11.9f\n/ Tamaño Vectores:%u\n/ V1[0]+V2[0]=V3[0](%8.6f+%8.6f=%8.6f) / \n/ V1[%d]+V2[%d]=V3[%d](%8.6f+%8.6f=%8.6f) /\n", ncgt,N,v1[0],v2[0],v3[0],N-1,N-1,N-1,v1[N-1],v2[N-1],v3[N-1]); #endif #ifdef VECTOR_DYNAMIC free(v1); // libera el espacio reservado para v1 free(v2); // libera el espacio reservado para v2 free(v3); // libera el espacio reservado para v3 #endif return 0; }
ca_obj_bitfield.c
/* --------------------------------------------------------------------------- ca_obj_bitfield.c This file is part of Ruby/CArray extension library. Copyright (C) 2005-2020 Hiroki Motoyoshi ---------------------------------------------------------------------------- */ #include "carray.h" typedef struct { int16_t obj_type; int8_t data_type; int8_t ndim; int32_t flags; ca_size_t bytes; ca_size_t elements; ca_size_t *dim; char *ptr; CArray *mask; CArray *parent; uint32_t attach; uint8_t nosync; /* -------------*/ ca_size_t byte_offset; ca_size_t bit_offset; uint64_t bit_mask; } CABitfield; static int8_t CA_OBJ_BITFIELD; static VALUE rb_cCABitfield; /* yard: class CABitField < CAVirtual # :nodoc: end */ static ca_size_t bitfield_bitlen (uint64_t bit_mask, ca_size_t bytes) { ca_size_t bitsize = bytes * 8; ca_size_t count = 0; ca_size_t i; for (i=0; i<bitsize; i++) { if ( ( bit_mask >> i ) & 1 ) { count++; } } return count; } static void bitfield_fetch(char *dst, ca_size_t dbytes, char *src, ca_size_t sbytes, ca_size_t byte_offset, ca_size_t bit_offset, uint64_t bit_mask, ca_size_t elements) { ca_size_t k; switch ( dbytes ) { case 1: { char *p; uint8_t *q, *r; uint8_t mask = (uint8_t) bit_mask; p = src + byte_offset; q = (uint8_t *) dst; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = (uint8_t *) (p+k*sbytes); *(q+k) = (( *r & mask ) >> bit_offset); } break; } case 2: { char *p; uint16_t *q, *r; uint16_t mask = (uint16_t) bit_mask; p = src + byte_offset; q = (uint16_t *) dst; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = (uint16_t *) (p+k*sbytes); *(q+k) = (( *r & mask ) >> bit_offset); } break; } case 4: { char *p; uint32_t *q, *r; uint32_t mask = (uint32_t) bit_mask; p = src + byte_offset; q = (uint32_t *) dst; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = (uint32_t *) (p+k*sbytes); *(q+k) = (( *r & mask ) >> bit_offset); } break; } case 8: { char *p; uint64_t *q, *r; uint64_t mask = (uint64_t) bit_mask; p = src + byte_offset; q = (uint64_t *) dst; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = (uint64_t *) (p+k*sbytes); *(q+k) = (( *r & mask ) >> bit_offset); } break; } default: rb_raise(rb_eRuntimeError, "[BUG]"); } } static void bitfield_store(char *src, ca_size_t sbytes, char *dst, ca_size_t dbytes, ca_size_t byte_offset, ca_size_t bit_offset, uint64_t bit_mask, ca_size_t elements) { ca_size_t k; switch ( dbytes ) { case 1: { char *q; uint8_t *p, *r; uint8_t mask = (uint8_t) bit_mask; p = (uint8_t *) src; q = dst + byte_offset; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = p + k; *(uint8_t*)(q+k*dbytes) = ( ((*(uint8_t*)(q+k*dbytes)) & ~mask) | ((*r << bit_offset) & mask) ); } break; } case 2: { char *q; uint16_t *p, *r; uint16_t mask = (uint16_t) bit_mask; p = (uint16_t *) src; q = dst + byte_offset; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = p + k; *(uint16_t*)(q+k*dbytes) = ( ((*(uint16_t*)(q+k*dbytes)) & ~mask) | ((*r << bit_offset) & mask) ); } break; } case 4: { char *q; uint32_t *p, *r; uint32_t mask = (uint32_t) bit_mask; p = (uint32_t *) src; q = dst + byte_offset; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = p + k; *(uint32_t*)(q+k*dbytes) = ( ((*(uint32_t*)(q+k*dbytes)) & ~mask) | ((*r << bit_offset) & mask) ); } break; } case 8: { char *q; uint64_t *p, *r; uint64_t mask = (uint64_t) bit_mask; p = (uint64_t *) src; q = dst + byte_offset; #ifdef _OPENMP #pragma omp parallel for private(r) #endif for (k=0; k<elements; k++) { r = p + k; *(uint64_t*)(q+k*dbytes) = ( ((*(uint64_t*)(q+k*dbytes)) & ~mask) | ((*r << bit_offset) & mask) ); } break; } default: rb_raise(rb_eRuntimeError, "[BUG]"); } } /* ------------------------------------------------------------------- */ int ca_bitfield_setup (CABitfield *ca, CArray *parent, ca_size_t offset, ca_size_t bitlen) { int8_t ndim; int8_t data_type; ca_size_t bytes = 0, elements; ca_size_t bitsize; ca_size_t byte_offset; ca_size_t bit_offset; uint64_t bit_mask; ca_size_t i; /* check arguments */ /* if ( ! ca_is_integer_type(parent) && ! ca_is_float_type(ca) ) { rb_raise(rb_eCADataTypeError, "invalid data_type for bitfield"); } */ ndim = parent->ndim; bitsize = parent->bytes * 8; elements = parent->elements; if ( bitlen <= 0 || bitlen > 64 ) { rb_raise(rb_eIndexError, "invalid bit length specified for bit field"); } if ( offset + bitlen -1 >= bitsize ) { rb_raise(rb_eIndexError, "invalid offset for bit field"); } if ( bitlen == 1 ) { data_type = CA_BOOLEAN; } else if ( bitlen <= 8 ) { data_type = CA_UINT8; } else if ( bitlen <= 16 ) { data_type = CA_UINT16; } else if ( bitlen <= 32 ) { data_type = CA_UINT32; } else { data_type = CA_UINT64; } CA_CHECK_BYTES(data_type, bytes); if ( bitlen > bytes * 8 ) { rb_raise(rb_eArgError, "invalid bit length for specified data_type"); } if ( ( data_type == CA_BOOLEAN ) && ( bitlen > 1 ) ) { rb_raise(rb_eArgError, "invalid bit length for specified data_type"); } if ( ca_endian == CA_BIG_ENDIAN ) { byte_offset = parent->bytes - offset/8 - bytes; bit_offset = offset % 8; bit_mask = 0; for (i=0; i<bitlen; i++) { bit_mask += 1 << ( bit_offset + i ); } if ( byte_offset < 0 ) { for (i=0; i<-byte_offset; i++) { bit_mask = bit_mask << 8; bit_offset += 8; } byte_offset = 0; } } else { byte_offset = offset / 8; bit_offset = offset % 8; bit_mask = 0; for (i=0; i<bitlen; i++) { bit_mask += 1 << ( bit_offset + i ); } } ca->obj_type = CA_OBJ_BITFIELD; ca->data_type = data_type; ca->flags = 0; ca->ndim = ndim; ca->bytes = bytes; ca->elements = elements; ca->ptr = NULL; ca->mask = NULL; ca->dim = ALLOC_N(ca_size_t, ndim); ca->parent = parent; ca->attach = 0; ca->nosync = 0; ca->byte_offset = byte_offset; ca->bit_offset = bit_offset; ca->bit_mask = bit_mask; memcpy(ca->dim, parent->dim, ndim * sizeof(ca_size_t)); if ( ca_has_mask(parent) ) { ca_create_mask(ca); } return 0; } CABitfield * ca_bitfield_new (CArray *parent, ca_size_t offset, ca_size_t bitlen) { CABitfield *ca = ALLOC(CABitfield); ca_bitfield_setup(ca, parent, offset, bitlen); return ca; } static void free_ca_bitfield (void *ap) { CABitfield *ca = (CABitfield *) ap; if ( ca != NULL ) { ca_free(ca->mask); xfree(ca->dim); xfree(ca); } } static void ca_bitfield_attach (CABitfield *ca); static void ca_bitfield_sync (CABitfield *ca); static void ca_bitfield_fill (CABitfield *ca, char *ptr); /* ------------------------------------------------------------------- */ static void * ca_bitfield_func_clone (void *ap) { CABitfield *ca = (CABitfield *) ap; return ca_bitfield_new(ca->parent, 8 * ca->byte_offset + ca->bit_offset, bitfield_bitlen(ca->bit_mask, ca->bytes)); } static char * ca_bitfield_func_ptr_at_addr (void *ap, ca_size_t addr) { CABitfield *ca = (CABitfield *) ap; if ( ! ca->ptr ) { rb_raise(rb_eRuntimeError, "[BUG]"); return NULL; } else { return ca->ptr + ca->bytes * addr; } } static char * ca_bitfield_func_ptr_at_index (void *ap, ca_size_t *idx) { CABitfield *ca = (CABitfield *) ap; if ( ! ca->ptr ) { rb_raise(rb_eRuntimeError, "[BUG]"); return NULL; } else { return ca_func[CA_OBJ_ARRAY].ptr_at_index(ca, idx); } } static void ca_bitfield_func_fetch_index (void *ap, ca_size_t *idx, void *ptr) { CABitfield *ca = (CABitfield *) ap; char *v = xmalloc(ca->parent->bytes); ca_fetch_index(ca->parent, idx, v); memset(ptr, 0, ca->bytes); bitfield_fetch(ptr, ca->bytes, v, ca->parent->bytes, ca->byte_offset, ca->bit_offset, ca->bit_mask, 1); xfree(v); } static void ca_bitfield_func_store_index (void *ap, ca_size_t *idx, void *ptr) { CABitfield *ca = (CABitfield *) ap; char *v = xmalloc(ca->parent->bytes); ca_fetch_index(ca->parent, idx, v); bitfield_store(ptr, ca->bytes, v, ca->parent->bytes, ca->byte_offset, ca->bit_offset, ca->bit_mask, 1); ca_store_index(ca->parent, idx, v); xfree(v); } static void ca_bitfield_func_allocate (void *ap) { CABitfield *ca = (CABitfield *) ap; ca_attach(ca->parent); /* ca->ptr = ALLOC_N(char, ca_length(ca)); */ ca->ptr = malloc_with_check(ca_length(ca)); } static void ca_bitfield_func_attach (void *ap) { void ca_bitfield_attach (CABitfield *cb); CABitfield *ca = (CABitfield *) ap; ca_attach(ca->parent); /* ca->ptr = ALLOC_N(char, ca_length(ca)); */ ca->ptr = malloc_with_check(ca_length(ca)); ca_bitfield_attach(ca); } static void ca_bitfield_func_sync (void *ap) { CABitfield *ca = (CABitfield *) ap; ca_bitfield_sync(ca); ca_sync(ca->parent); } static void ca_bitfield_func_detach (void *ap) { CABitfield *ca = (CABitfield *) ap; free(ca->ptr); ca->ptr = NULL; ca_detach(ca->parent); } static void ca_bitfield_func_copy_data (void *ap, void *ptr) { CABitfield *ca = (CABitfield *) ap; char *ptr0 = ca->ptr; ca_attach(ca->parent); ca->ptr = ptr; ca_bitfield_attach(ca); ca->ptr = ptr0; ca_detach(ca->parent); } static void ca_bitfield_func_sync_data (void *ap, void *ptr) { CABitfield *ca = (CABitfield *) ap; char *ptr0 = ca->ptr; ca_attach(ca->parent); ca->ptr = ptr; ca_bitfield_sync(ca); ca->ptr = ptr0; ca_sync(ca->parent); ca_detach(ca->parent); } static void ca_bitfield_func_fill_data (void *ap, void *ptr) { CABitfield *ca = (CABitfield *) ap; ca_attach(ca->parent); ca_bitfield_fill(ca, ptr); ca_sync(ca->parent); ca_detach(ca->parent); } static void ca_bitfield_func_create_mask (void *ap) { CABitfield *ca = (CABitfield *) ap; ca_update_mask(ca->parent); if ( ! ca->parent->mask ) { ca_create_mask(ca->parent); } ca->mask = (CArray *) ca_refer_new(ca->parent->mask, CA_BOOLEAN, ca->ndim, ca->dim, 0, 0); } ca_operation_function_t ca_bitfield_func = { -1, /* CA_OBJ_BITFIELD */ CA_VIRTUAL_ARRAY, free_ca_bitfield, ca_bitfield_func_clone, ca_bitfield_func_ptr_at_addr, ca_bitfield_func_ptr_at_index, NULL, ca_bitfield_func_fetch_index, NULL, ca_bitfield_func_store_index, ca_bitfield_func_allocate, ca_bitfield_func_attach, ca_bitfield_func_sync, ca_bitfield_func_detach, ca_bitfield_func_copy_data, ca_bitfield_func_sync_data, ca_bitfield_func_fill_data, ca_bitfield_func_create_mask, }; /* ------------------------------------------------------------------- */ static void ca_bitfield_attach (CABitfield *ca) { memset(ca->ptr, 0, ca_length(ca)); bitfield_fetch(ca->ptr, ca->bytes, ca->parent->ptr, ca->parent->bytes, ca->byte_offset, ca->bit_offset, ca->bit_mask, ca->elements); } static void ca_bitfield_sync (CABitfield *ca) { bitfield_store(ca->ptr, ca->bytes, ca->parent->ptr, ca->parent->bytes, ca->byte_offset, ca->bit_offset, ca->bit_mask, ca->elements); } static void ca_bitfield_fill (CABitfield *ca, char *ptr) { char *q = ca->parent->ptr; ca_size_t bytesp = ca->bytes; ca_size_t bytesq = ca->parent->bytes; ca_size_t byte_offset = ca->byte_offset; ca_size_t bit_offset = ca->bit_offset; uint64_t bit_mask = ca->bit_mask; ca_size_t i; for (i=0; i<ca->elements; i++) { bitfield_store(ptr, bytesp, q, bytesq, byte_offset, bit_offset, bit_mask, 1); q += bytesq; } } /* ------------------------------------------------------------------- */ VALUE rb_ca_bitfield_new (VALUE cary, ca_size_t offset, ca_size_t bitlen) { volatile VALUE obj; CArray *parent; CABitfield *ca; rb_check_carray_object(cary); Data_Get_Struct(cary, CArray, parent); ca = ca_bitfield_new(parent, offset, bitlen); obj = ca_wrap_struct(ca); rb_ca_set_parent(obj, cary); return obj; } /* @overload bitfield (range, type) [TBD] */ VALUE rb_ca_bitfield (int argc, VALUE *argv, VALUE self) { volatile VALUE rrange, rtype; CArray *ca; ca_size_t offset, bitlen, step; int data_type = CA_NONE; ca_size_t bitsize; rb_scan_args(argc, argv, "11", (VALUE *) &rrange, (VALUE *) &rtype); Data_Get_Struct(self, CArray, ca); if ( TYPE(rrange) == T_FIXNUM ) { offset = NUM2INT(rrange); bitlen = 1; } else { bitsize = ca->bytes * 8; ca_parse_range(rrange, bitsize, &offset, &bitlen, &step); if ( step != 1 ) { rb_raise(rb_eIndexError, "invalid bit range specified for bit field"); } } if ( ! NIL_P(rtype) ) { data_type = rb_ca_guess_type(rtype); } return rb_ca_bitfield_new(self, offset, bitlen); } static VALUE rb_ca_bitfield_s_allocate (VALUE klass) { CABitfield *ca; return Data_Make_Struct(klass, CABitfield, ca_mark, ca_free, ca); } static VALUE rb_ca_bitfield_initialize_copy (VALUE self, VALUE other) { CABitfield *ca, *cs; Data_Get_Struct(self, CABitfield, ca); Data_Get_Struct(other, CABitfield, cs); ca_bitfield_setup(ca, cs->parent, 8 * cs->byte_offset + cs->bit_offset, bitfield_bitlen(cs->bit_mask, cs->bytes)); return self; } void Init_ca_obj_bitfield () { rb_cCABitfield = rb_define_class("CABitfield", rb_cCAVirtual); CA_OBJ_BITFIELD = ca_install_obj_type(rb_cCABitfield, ca_bitfield_func); rb_define_const(rb_cObject, "CA_OBJ_BITFIELD", INT2NUM(CA_OBJ_BITFIELD)); rb_define_method(rb_cCArray, "bitfield", rb_ca_bitfield, -1); rb_define_alloc_func(rb_cCABitfield, rb_ca_bitfield_s_allocate); rb_define_method(rb_cCABitfield, "initialize_copy", rb_ca_bitfield_initialize_copy, 1); }
array_init_2.c
// Test the handling of two loops under omp for // watch the loop index replacement (private by default) // and tje array outlining int main(void) { int i, j; float** u = (float**) malloc( 500 * sizeof( float*) ); for( i=0; i<500; i++) u[i] = (float*) malloc( 500 * sizeof(float) ); #pragma omp parallel for for (i=0; i<500; i++) for (j=0; j<500; j++) { u[i][j] = 0.0; } return 0; }
raytracer.h
#pragma once #include "resource.h" #include <linalg.h> #include <memory> #include <omp.h> #include <random> #include <time.h> using namespace linalg::aliases; namespace cg::renderer { struct ray { ray(float3 position, float3 direction) : position(position) { this->direction = normalize(direction); } float3 position; float3 direction; }; struct payload { float t; float3 bary; cg::color color; }; template<typename VB> struct triangle { triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c); float3 a; float3 b; float3 c; float3 ba; float3 ca; float3 na; float3 nb; float3 nc; float3 ambient; float3 diffuse; float3 emissive; }; template<typename VB> inline triangle<VB>::triangle(const VB& vertex_a, const VB& vertex_b, const VB& vertex_c) { a = float3{ vertex_a.x, vertex_a.y, vertex_a.z }; b = float3{ vertex_b.x, vertex_b.y, vertex_b.z }; c = float3{ vertex_c.x, vertex_c.y, vertex_c.z }; ba = b - a; ca = c - a; na = float3{ vertex_a.nx, vertex_a.ny, vertex_a.nz }; nb = float3{ vertex_b.nx, vertex_b.ny, vertex_b.nz }; nc = float3{ vertex_c.nx, vertex_c.ny, vertex_c.nz }; ambient = { vertex_a.ambient_r, vertex_a.ambient_g, vertex_a.ambient_b, }; diffuse = { vertex_a.diffuse_r, vertex_a.diffuse_g, vertex_a.diffuse_b, }; emissive = { vertex_a.emissive_r, vertex_a.emissive_g, vertex_a.emissive_b, }; } template<typename VB> class aabb { public: void add_triangle(const triangle<VB> triangle); const std::vector<triangle<VB>>& get_triangles() const; bool aabb_test(const ray& ray) const; protected: std::vector<triangle<VB>> triangles; float3 aabb_min; float3 aabb_max; }; struct light { float3 position; float3 color; }; template<typename VB, typename RT> class raytracer { public: raytracer(){}; ~raytracer(){}; void set_render_target(std::shared_ptr<resource<RT>> in_render_target); void clear_render_target(const RT& in_clear_value); void set_viewport(size_t in_width, size_t in_height); void set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer); void build_acceleration_structure(); std::vector<aabb<VB>> acceleration_structures; void ray_generation(float3 position, float3 direction, float3 right, float3 up); payload trace_ray(const ray& ray, size_t depth, float max_t = 1000.f, float min_t = 0.001f) const; payload intersection_shader(const triangle<VB>& triangle, const ray& ray) const; std::function<payload(const ray& ray)> miss_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> closest_hit_shader = nullptr; std::function<payload(const ray& ray, payload& payload, const triangle<VB>& triangle)> any_hit_shader = nullptr; protected: std::shared_ptr<cg::resource<RT>> render_target; std::vector<std::shared_ptr<cg::resource<VB>>> per_shape_vertex_buffer; float get_random(const int thread_num, float range = 0.1f) const; size_t width = 1920; size_t height = 1080; }; template<typename VB, typename RT> inline void raytracer<VB, RT>::set_render_target(std::shared_ptr<resource<RT>> in_render_target) { render_target = in_render_target; } template<typename VB, typename RT> inline void raytracer<VB, RT>::clear_render_target(const RT& in_clear_value) { for (size_t i = 0; i < render_target->get_number_of_elements(); i++) { render_target->item(i) = in_clear_value; } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_per_shape_vertex_buffer( std::vector<std::shared_ptr<cg::resource<VB>>> in_per_shape_vertex_buffer) { per_shape_vertex_buffer = in_per_shape_vertex_buffer; } template<typename VB, typename RT> inline void raytracer<VB, RT>::build_acceleration_structure() { for (auto& vertex_buffer : per_shape_vertex_buffer) { size_t vertex_id = 0; aabb<VB> aabb; while (vertex_id < vertex_buffer->get_number_of_elements()) { triangle<VB> triangle( vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++), vertex_buffer->item(vertex_id++)); aabb.add_triangle(triangle); } acceleration_structures.push_back(aabb); } } template<typename VB, typename RT> inline void raytracer<VB, RT>::set_viewport(size_t in_width, size_t in_height) { width = in_width; height = in_height; } template<typename VB, typename RT> inline void raytracer<VB, RT>::ray_generation( float3 position, float3 direction, float3 right, float3 up) { for (int x = 0; x < width; x++) { #pragma omp parallel for for (int y = 0; y < height; y++) { // from [0; width - 1] to [0; 1] to [0; 2] to [-1, 1] float u = (2.f * x / static_cast<float>(width - 1)) - 1.f; float v = (2.f * y / static_cast<float>(height - 1)) - 1.f; u *= static_cast<float>(width) / static_cast<float>(height); float u_delta = 1 / static_cast<float>(width - 1); u_delta *= static_cast<float>(width) / static_cast<float>(height); float v_delta = 1.f / static_cast<float>(height - 1); float x_jitter = get_random(omp_get_thread_num() + clock()); float y_jitter = get_random(omp_get_thread_num() + clock()); float3 ray_direction = direction + (u) * right - (v) * up; ray ray_0(position, ray_direction); payload payload_0 = trace_ray(ray_0, 1); //super sampling /* ray ray_1(position, ray_direction + u_delta * right); payload payload_1 = trace_ray(ray_1, 1); ray ray_2(position, ray_direction - v_delta * up); payload payload_2 = trace_ray(ray_2, 1); ray ray_3(position, ray_direction + u_delta * right - v_delta * up); payload payload_3 = trace_ray(ray_3, 1); // super sampling AA /*cg::color accumed_color{ (payload_0.color.r + payload_1.color.r + payload_2.color.r + payload_3.color.r) / 4, (payload_0.color.g + payload_1.color.g + payload_2.color.g + payload_3.color.g) / 4, (payload_0.color.b + payload_1.color.b + payload_2.color.b + payload_3.color.b) / 4 };*/ cg::color accumed = cg::color::from_float3(render_target->item(x, y).to_float3()); cg::color result{ (accumed.r + payload_0.color.r) / 2.f, (accumed.g + payload_0.color.g) / 2.f, (accumed.b + payload_0.color.b) / 2.f, }; render_target->item(x, y) = RT::from_color(result); } } } template<typename VB, typename RT> inline payload raytracer<VB, RT>::trace_ray(const ray& ray, size_t depth, float max_t, float min_t) const { if (depth == 0) return miss_shader(ray); depth--; payload closest_hit_payload = {}; closest_hit_payload.t = max_t; const triangle<VB>* closest_triangle = nullptr; for (auto& aabb : acceleration_structures) { if (aabb.aabb_test(ray)) { for (auto& triangle : aabb.get_triangles()) { payload payload = intersection_shader(triangle, ray); if (payload.t > min_t && payload.t < closest_hit_payload.t) { closest_hit_payload = payload; closest_triangle = &triangle; if (any_hit_shader) return any_hit_shader(ray, payload, triangle); } } } } if (closest_hit_payload.t < max_t) { if (closest_hit_shader) { return closest_hit_shader(ray, closest_hit_payload, *closest_triangle); } } return miss_shader(ray); } template<typename VB, typename RT> inline payload raytracer<VB, RT>::intersection_shader(const triangle<VB>& triangle, const ray& ray) const { payload payload{}; payload.t = -1.f; float3 pvec = cross(ray.direction, triangle.ca); float det = dot(triangle.ba, pvec); if (det > -1e-8 && det < 1e-8) return payload; float inv_det = 1.f / det; float3 tvec = ray.position - triangle.a; float u = dot(tvec, pvec) * inv_det; if (u < 0.f || u > 1.f) return payload; float3 qvec = cross(tvec, triangle.ba); float v = dot(ray.direction, qvec) * inv_det; if (v < 0.f || u + v > 1.f) { return payload; } payload.t = dot(triangle.ca, qvec) * inv_det; payload.bary = float3{ 1.f - u - v, u, v }; return payload; } template<typename VB, typename RT> inline float raytracer<VB, RT>::get_random(const int thread_num, const float range) const { static std::default_random_engine generator(thread_num); static std::normal_distribution<float> distribution(0.f, range); return distribution(generator); } template<typename VB> inline void aabb<VB>::add_triangle(const triangle<VB> triangle) { if (triangles.empty()) aabb_max = aabb_min = triangle.a; triangles.push_back(triangle); aabb_max = max(triangle.a, aabb_max); aabb_max = max(triangle.b, aabb_max); aabb_max = max(triangle.c, aabb_max); aabb_min = min(triangle.a, aabb_min); aabb_min = min(triangle.b, aabb_min); aabb_min = min(triangle.c, aabb_min); } template<typename VB> inline const std::vector<triangle<VB>>& aabb<VB>::get_triangles() const { return triangles; } template<typename VB> inline bool aabb<VB>::aabb_test(const ray& ray) const { float3 invRaydir = float3(1.f) / ray.direction; float3 t0 = (aabb_max - ray.position) * invRaydir; float3 t1 = (aabb_min - ray.position) * invRaydir; float3 tmin = min(t0, t1); float3 tmax = max(t0, t1); //return std::max_element(tmin) <= std::min_element(tmax); return maxelem(tmin) <= minelem(tmax); } } // namespace cg::renderer
red_black_gs.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ /****************************************************************************** * * This routine assumes a 3-pt (1D), 5-pt (2D), or 7-pt (3D) stencil. * *****************************************************************************/ #include "_hypre_struct_ls.h" #include "red_black_gs.h" /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ void * hypre_RedBlackGSCreate( MPI_Comm comm ) { hypre_RedBlackGSData *relax_data; relax_data = hypre_CTAlloc(hypre_RedBlackGSData, 1); (relax_data -> comm) = comm; (relax_data -> time_index) = hypre_InitializeTiming("RedBlackGS"); /* set defaults */ (relax_data -> tol) = 1.0e-06; (relax_data -> max_iter) = 1000; (relax_data -> rel_change) = 0; (relax_data -> zero_guess) = 0; (relax_data -> rb_start) = 1; (relax_data -> flops) = 0; (relax_data -> A) = NULL; (relax_data -> b) = NULL; (relax_data -> x) = NULL; (relax_data -> compute_pkg) = NULL; return (void *) relax_data; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSDestroy( void *relax_vdata ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; if (relax_data) { hypre_StructMatrixDestroy(relax_data -> A); hypre_StructVectorDestroy(relax_data -> b); hypre_StructVectorDestroy(relax_data -> x); hypre_ComputePkgDestroy(relax_data -> compute_pkg); hypre_FinalizeTiming(relax_data -> time_index); hypre_TFree(relax_data); } return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetup( void *relax_vdata, hypre_StructMatrix *A, hypre_StructVector *b, hypre_StructVector *x ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; HYPRE_Int diag_rank; hypre_ComputePkg *compute_pkg; hypre_StructGrid *grid; hypre_StructStencil *stencil; hypre_Index diag_index; hypre_ComputeInfo *compute_info; /*---------------------------------------------------------- * Find the matrix diagonal *----------------------------------------------------------*/ grid = hypre_StructMatrixGrid(A); stencil = hypre_StructMatrixStencil(A); hypre_SetIndex3(diag_index, 0, 0, 0); diag_rank = hypre_StructStencilElementRank(stencil, diag_index); /*---------------------------------------------------------- * Set up the compute packages *----------------------------------------------------------*/ hypre_CreateComputeInfo(grid, stencil, &compute_info); hypre_ComputePkgCreate(compute_info, hypre_StructVectorDataSpace(x), 1, grid, &compute_pkg); /*---------------------------------------------------------- * Set up the relax data structure *----------------------------------------------------------*/ (relax_data -> A) = hypre_StructMatrixRef(A); (relax_data -> x) = hypre_StructVectorRef(x); (relax_data -> b) = hypre_StructVectorRef(b); (relax_data -> diag_rank) = diag_rank; (relax_data -> compute_pkg) = compute_pkg; return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGS( void *relax_vdata, hypre_StructMatrix *A, hypre_StructVector *b, hypre_StructVector *x ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; HYPRE_Int max_iter = (relax_data -> max_iter); HYPRE_Int zero_guess = (relax_data -> zero_guess); HYPRE_Int rb_start = (relax_data -> rb_start); HYPRE_Int diag_rank = (relax_data -> diag_rank); hypre_ComputePkg *compute_pkg = (relax_data -> compute_pkg); HYPRE_Int ndim = hypre_StructMatrixNDim(A); hypre_CommHandle *comm_handle; hypre_BoxArrayArray *compute_box_aa; hypre_BoxArray *compute_box_a; hypre_Box *compute_box; hypre_Box *A_dbox; hypre_Box *b_dbox; hypre_Box *x_dbox; HYPRE_Int Ai, Astart, Ani, Anj; HYPRE_Int bi, bstart, bni, bnj; HYPRE_Int xi, xstart, xni, xnj; HYPRE_Int xoff0, xoff1, xoff2, xoff3, xoff4, xoff5; HYPRE_Real *Ap; HYPRE_Real *Ap0, *Ap1, *Ap2, *Ap3, *Ap4, *Ap5; HYPRE_Real *bp; HYPRE_Real *xp; hypre_IndexRef start; hypre_Index loop_size; hypre_StructStencil *stencil; hypre_Index *stencil_shape; HYPRE_Int stencil_size; HYPRE_Int offd[6]; HYPRE_Int iter, rb, redblack, d; HYPRE_Int compute_i, i, j, ii, jj, kk; HYPRE_Int ni, nj, nk; /*---------------------------------------------------------- * Initialize some things and deal with special cases *----------------------------------------------------------*/ hypre_BeginTiming(relax_data -> time_index); hypre_StructMatrixDestroy(relax_data -> A); hypre_StructVectorDestroy(relax_data -> b); hypre_StructVectorDestroy(relax_data -> x); (relax_data -> A) = hypre_StructMatrixRef(A); (relax_data -> x) = hypre_StructVectorRef(x); (relax_data -> b) = hypre_StructVectorRef(b); (relax_data -> num_iterations) = 0; /* if max_iter is zero, return */ if (max_iter == 0) { /* if using a zero initial guess, return zero */ if (zero_guess) { hypre_StructVectorSetConstantValues(x, 0.0); } hypre_EndTiming(relax_data -> time_index); return hypre_error_flag; } else { stencil = hypre_StructMatrixStencil(A); stencil_shape = hypre_StructStencilShape(stencil); stencil_size = hypre_StructStencilSize(stencil); /* get off-diag entry ranks ready */ i = 0; for (j = 0; j < stencil_size; j++) { if (j != diag_rank) { offd[i] = j; i++; } } } /*---------------------------------------------------------- * Do zero_guess iteration *----------------------------------------------------------*/ rb = rb_start; iter = 0; if (zero_guess) { for (compute_i = 0; compute_i < 2; compute_i++) { switch(compute_i) { case 0: { compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg); } break; case 1: { compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg); } break; } hypre_ForBoxArrayI(i, compute_box_aa) { compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); b_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(b), i); x_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(x), i); Ap = hypre_StructMatrixBoxData(A, i, diag_rank); bp = hypre_StructVectorBoxData(b, i); xp = hypre_StructVectorBoxData(x, i); hypre_ForBoxI(j, compute_box_a) { compute_box = hypre_BoxArrayBox(compute_box_a, j); start = hypre_BoxIMin(compute_box); hypre_BoxGetSize(compute_box, loop_size); /* Are we relaxing index start or start+(1,0,0)? */ redblack = rb; for (d = 0; d < ndim; d++) { redblack += hypre_IndexD(start, d); } redblack = hypre_abs(redblack) % 2; Astart = hypre_BoxIndexRank(A_dbox, start); bstart = hypre_BoxIndexRank(b_dbox, start); xstart = hypre_BoxIndexRank(x_dbox, start); ni = hypre_IndexX(loop_size); nj = hypre_IndexY(loop_size); nk = hypre_IndexZ(loop_size); Ani = hypre_BoxSizeX(A_dbox); bni = hypre_BoxSizeX(b_dbox); xni = hypre_BoxSizeX(x_dbox); Anj = hypre_BoxSizeY(A_dbox); bnj = hypre_BoxSizeY(b_dbox); xnj = hypre_BoxSizeY(x_dbox); if (ndim < 3) { nk = 1; if (ndim < 2) { nj = 1; } } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii,jj,Ai,bi,xi,kk) HYPRE_SMP_SCHEDULE #endif for (kk = 0; kk < nk; kk++) { for (jj = 0; jj < nj; jj++) { ii = (kk + jj + redblack) % 2; Ai = Astart + kk*Anj*Ani + jj*Ani + ii; bi = bstart + kk*bnj*bni + jj*bni + ii; xi = xstart + kk*xnj*xni + jj*xni + ii; for (; ii < ni; ii+=2, Ai+=2, bi+=2, xi+=2) { xp[xi] = bp[bi] / Ap[Ai]; } } } } } } rb = (rb + 1) % 2; iter++; } /*---------------------------------------------------------- * Do regular iterations *----------------------------------------------------------*/ while (iter < 2*max_iter) { for (compute_i = 0; compute_i < 2; compute_i++) { switch(compute_i) { case 0: { xp = hypre_StructVectorData(x); hypre_InitializeIndtComputations(compute_pkg, xp, &comm_handle); compute_box_aa = hypre_ComputePkgIndtBoxes(compute_pkg); } break; case 1: { hypre_FinalizeIndtComputations(comm_handle); compute_box_aa = hypre_ComputePkgDeptBoxes(compute_pkg); } break; } hypre_ForBoxArrayI(i, compute_box_aa) { compute_box_a = hypre_BoxArrayArrayBoxArray(compute_box_aa, i); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), i); b_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(b), i); x_dbox = hypre_BoxArrayBox(hypre_StructVectorDataSpace(x), i); Ap = hypre_StructMatrixBoxData(A, i, diag_rank); bp = hypre_StructVectorBoxData(b, i); xp = hypre_StructVectorBoxData(x, i); hypre_ForBoxI(j, compute_box_a) { compute_box = hypre_BoxArrayBox(compute_box_a, j); start = hypre_BoxIMin(compute_box); hypre_BoxGetSize(compute_box, loop_size); /* Are we relaxing index start or start+(1,0,0)? */ redblack = rb; for (d = 0; d < ndim; d++) { redblack += hypre_IndexD(start, d); } redblack = hypre_abs(redblack) % 2; Astart = hypre_BoxIndexRank(A_dbox, start); bstart = hypre_BoxIndexRank(b_dbox, start); xstart = hypre_BoxIndexRank(x_dbox, start); ni = hypre_IndexX(loop_size); nj = hypre_IndexY(loop_size); nk = hypre_IndexZ(loop_size); Ani = hypre_BoxSizeX(A_dbox); bni = hypre_BoxSizeX(b_dbox); xni = hypre_BoxSizeX(x_dbox); Anj = hypre_BoxSizeY(A_dbox); bnj = hypre_BoxSizeY(b_dbox); xnj = hypre_BoxSizeY(x_dbox); if (ndim < 3) { nk = 1; if (ndim < 2) { nj = 1; } } switch(stencil_size) { case 7: Ap5 = hypre_StructMatrixBoxData(A, i, offd[5]); Ap4 = hypre_StructMatrixBoxData(A, i, offd[4]); xoff5 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[5]]); xoff4 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[4]]); case 5: Ap3 = hypre_StructMatrixBoxData(A, i, offd[3]); Ap2 = hypre_StructMatrixBoxData(A, i, offd[2]); xoff3 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[3]]); xoff2 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[2]]); case 3: Ap1 = hypre_StructMatrixBoxData(A, i, offd[1]); Ap0 = hypre_StructMatrixBoxData(A, i, offd[0]); xoff1 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[1]]); xoff0 = hypre_BoxOffsetDistance( x_dbox, stencil_shape[offd[0]]); break; } switch(stencil_size) { case 7: #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii,jj,Ai,bi,xi,kk) HYPRE_SMP_SCHEDULE #endif for (kk = 0; kk < nk; kk++) { for (jj = 0; jj < nj; jj++) { ii = (kk + jj + redblack) % 2; Ai = Astart + kk*Anj*Ani + jj*Ani + ii; bi = bstart + kk*bnj*bni + jj*bni + ii; xi = xstart + kk*xnj*xni + jj*xni + ii; for (; ii < ni; ii+=2, Ai+=2, bi+=2, xi+=2) { xp[xi] = (bp[bi] - Ap0[Ai] * xp[xi + xoff0] - Ap1[Ai] * xp[xi + xoff1] - Ap2[Ai] * xp[xi + xoff2] - Ap3[Ai] * xp[xi + xoff3] - Ap4[Ai] * xp[xi + xoff4] - Ap5[Ai] * xp[xi + xoff5]) / Ap[Ai]; } } } break; case 5: #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii,jj,Ai,bi,xi,kk) HYPRE_SMP_SCHEDULE #endif for (kk = 0; kk < nk; kk++) { for (jj = 0; jj < nj; jj++) { ii = (kk + jj + redblack) % 2; Ai = Astart + kk*Anj*Ani + jj*Ani + ii; bi = bstart + kk*bnj*bni + jj*bni + ii; xi = xstart + kk*xnj*xni + jj*xni + ii; for (; ii < ni; ii+=2, Ai+=2, bi+=2, xi+=2) { xp[xi] = (bp[bi] - Ap0[Ai] * xp[xi + xoff0] - Ap1[Ai] * xp[xi + xoff1] - Ap2[Ai] * xp[xi + xoff2] - Ap3[Ai] * xp[xi + xoff3]) / Ap[Ai]; } } } break; case 3: #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(ii,jj,Ai,bi,xi,kk) HYPRE_SMP_SCHEDULE #endif for (kk = 0; kk < nk; kk++) { for (jj = 0; jj < nj; jj++) { ii = (kk + jj + redblack) % 2; Ai = Astart + kk*Anj*Ani + jj*Ani + ii; bi = bstart + kk*bnj*bni + jj*bni + ii; xi = xstart + kk*xnj*xni + jj*xni + ii; for (; ii < ni; ii+=2, Ai+=2, bi+=2, xi+=2) { xp[xi] = (bp[bi] - Ap0[Ai] * xp[xi + xoff0] - Ap1[Ai] * xp[xi + xoff1]) / Ap[Ai]; } } } break; } } } } rb = (rb + 1) % 2; iter++; } (relax_data -> num_iterations) = iter / 2; /*----------------------------------------------------------------------- * Return *-----------------------------------------------------------------------*/ hypre_IncFLOPCount(relax_data -> flops); hypre_EndTiming(relax_data -> time_index); return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetTol( void *relax_vdata, HYPRE_Real tol ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; (relax_data -> tol) = tol; return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetMaxIter( void *relax_vdata, HYPRE_Int max_iter ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; (relax_data -> max_iter) = max_iter; return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetZeroGuess( void *relax_vdata, HYPRE_Int zero_guess ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; (relax_data -> zero_guess) = zero_guess; return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetStartRed( void *relax_vdata ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; (relax_data -> rb_start) = 1; return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_RedBlackGSSetStartBlack( void *relax_vdata ) { hypre_RedBlackGSData *relax_data = (hypre_RedBlackGSData *)relax_vdata; (relax_data -> rb_start) = 0; return hypre_error_flag; }
dgemm_entry.c
/******************************************************************** * BenchIT - Performance Measurement for Scientific Applications * Contact: developer@benchit.org * * $Id: dgemm_entry.c 1 2009-09-11 12:26:19Z william $ * $URL: svn+ssh://william@rupert.zih.tu-dresden.de/svn-base/benchit-root/BenchITv6/kernel/numerical/matmul/C/OpenMP/MKL/double/dgemm_entry.c $ * For license details see COPYING in the package base directory *******************************************************************/ /* Kernel: Matrix Multiply, BLAS, MKL (C) - OpenMP version *******************************************************************/ #include <mkl_cblas.h> #include <stdio.h> #include <stdlib.h> #include "dgemm.h" #include "interface.h" #include <omp.h> void init_data(fds *myfds, int size) { long x, index, max; #pragma omp parallel for schedule(static,1) private(x,index,max) shared(myfds,size) for(x = 0; x < size; x++) { index = x * size; max = index + size; for(index; index < max; index++) { myfds->feld1[index] = 30.0; myfds->feld2[index] = 0.01; myfds->feld3[index] = 0.0; } } IDL(5, printf("init_data done\n")); } int bi_entry(void *mcb, int problemSize,double *results){ double one=1.0; double time=0, start, stop; double nOperations=0.0; long lCurrentSize; unsigned long size; char N='N'; double *f1, *f2, *f3; int ii, jj; double dummy = 0.0; if(results == NULL) return -1; size = (unsigned long)bi_get_list_element(problemSize); results[0] = size; nOperations = (1.0*size)*(1.0*size)*(2.0*size-1.0); lCurrentSize = size*size*sizeof(double); ((fds*)mcb)->feld1=malloc(lCurrentSize); ((fds*)mcb)->feld2=malloc(lCurrentSize); ((fds*)mcb)->feld3=malloc(lCurrentSize); f1=((fds*)mcb)->feld1; f2=((fds*)mcb)->feld2; f3=((fds*)mcb)->feld3; if((f1==NULL) || (f2==NULL) || (f3==NULL)) { printf("\nmalloc (%ld bytes) failed in bi_entry()\n",(long) (3.0*lCurrentSize)); bi_cleanup(mcb); exit(127); } init_data(mcb, size); /* ************************** */ start=bi_gettime(); cblas_dgemm(CblasRowMajor,CblasNoTrans,CblasNoTrans, size, size, size, 1.0, f1, size, f2, size, one, f3, size); stop=bi_gettime(); /* ************************** */ time=stop-start - dTimerOverhead; if (time < 3*dTimerGranularity) { results[1]=INVALID_MEASUREMENT; } else { results[1]=nOperations/time; } if(mcb!=NULL) { if(f1!=NULL) { free(f1); f1=NULL; } if(f2!=NULL) { free(f2); f2=NULL; } if(f3!=NULL) { free(f3); f3=NULL; } } return 0; }
GB_binop__atan2_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_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__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_03__atan2_fp32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__atan2_fp32) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((node)) // C+=B function (dense accum): GB (_Cdense_accumB__atan2_fp32) // C+=b function (dense accum): GB (_Cdense_accumb__atan2_fp32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__atan2_fp32) // C=scalar+B GB (_bind1st__atan2_fp32) // C=scalar+B' GB (_bind1st_tran__atan2_fp32) // C=A+scalar GB (_bind2nd__atan2_fp32) // C=A'+scalar GB (_bind2nd_tran__atan2_fp32) // C type: float // A type: float // B,b type: float // BinaryOp: cij = atan2f (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 = atan2f (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ATAN2 || GxB_NO_FP32 || GxB_NO_ATAN2_FP32) //------------------------------------------------------------------------------ // 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__atan2_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__atan2_fp32) ( 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__atan2_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 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 float *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 GB ((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 *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 //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__atan2_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 *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__atan2_fp32) ( 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__atan2_fp32) ( 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__atan2_fp32) ( 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__atan2_fp32) ( 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__atan2_fp32) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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] = atan2f (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__atan2_fp32) ( 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 ; 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] = atan2f (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] = atan2f (x, aij) ; \ } GrB_Info GB (_bind1st_tran__atan2_fp32) ( 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 \ 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] = atan2f (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__atan2_fp32) ( 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 float y = (*((const float *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GA.c
#include "GA.h" #include <stdio.h> //bc we want lots of io for reasons #include <stdlib.h> #include <math.h> //for fabs #include <time.h> #include <omp.h> //the part of the total constraint penalty to eguality contraints float eval_EQ_Pfunc(unsigned neq, const gaf_ptr* EQ, unsigned ndv, const float* DV) { float sum = 0; //equality constraints evaluated like sum(EQ^2) for (unsigned q = 0; q < neq; q++) { float val = EQ[q](ndv, DV); float valsqrd = val * val; //better to do it this way than call the funtion (expensive) twice sum += valsqrd; } return sum; } //the <= constraint penalty part of the total constraints float eval_LE_Pfunc(unsigned nle, const gaf_ptr* LE, unsigned ndv, const float* DV) { float sum = 0; //<= constraints evaluated like sum(LE + |LE|) for (unsigned l = 0; l < nle; l++) { float val = LE[l](ndv, DV); float eval = val + fabs(val); if (eval < 0) printf("something went wrong inside of P_LE\n"); sum += eval; } return sum; } //the >= constraint penalty part of the total constraints float eval_GE_Pfunc(unsigned nge, const gaf_ptr* GE, unsigned ndv, const float* DV) { float sum = 0; //>= constraints evaluated like sum(-GE + abs(GE)) for (unsigned g = 0; g < nge; g++) { float val = GE[g](ndv, DV); float eval = fabs(val) - val; if (eval < 0) printf("something went wrong inside of P_GE\n"); sum += eval; } return sum; } //the penalty function float eval_Pfunc(const FitnessFunc* FitFunc, unsigned ndv, const float* DV) { if (FitFunc->ndv != ndv) { printf("The number of supplied design variables (%i) does not match the number that the fitness function was created for (%i)\n", ndv, FitFunc->ndv); getchar(); return 0; } else { float EQ_part = eval_EQ_Pfunc(FitFunc->neq, FitFunc->EQ, ndv, DV); float LE_part = eval_LE_Pfunc(FitFunc->nle, FitFunc->LE, ndv, DV); float GE_part = eval_GE_Pfunc(FitFunc->nge, FitFunc->GE, ndv, DV); float penalty = EQ_part + LE_part + GE_part; return penalty; } } float eval_Fitfunc(const FitnessFunc* FitFunc, unsigned ndv, const float* DV) { float Pfunc = eval_Pfunc(FitFunc, ndv, DV); float Ofunc = FitFunc->ObjF(ndv, DV); if (FitFunc->ObjType == MIN) { float val = Ofunc + (GA_PENALTY * Pfunc); return val; } else { float val = Ofunc - (GA_PENALTY * Pfunc); return val; } } FitnessFunc* create_FitFunc(unsigned ndv, unsigned neq, unsigned nle, unsigned nge, MinMAX ObjType, const gaf_ptr ObjF, GAbool Binary) { FitnessFunc* F = malloc(sizeof(FitnessFunc)); F->ndv = ndv; //eq F->current_neq = 0; F->neq = neq; F->EQ = calloc(F->neq, sizeof(gaf_ptr)); //le F->current_nle = 0; F->nle = nle; F->LE = calloc(F->nle, sizeof(gaf_ptr)); //ge F->current_nge = 0; F->nge = nge; F->GE = calloc(F->nge, sizeof(gaf_ptr)); F->ObjType = ObjType; F->ObjF = ObjF; return F; } void destroy_FitFunc(FitnessFunc* FitFunc) { free(FitFunc->EQ); free(FitFunc->LE); free(FitFunc->GE); free(FitFunc); } void add_eq(FitnessFunc* FitFunc, const gaf_ptr eq_f) { if (FitFunc->current_neq >= FitFunc->neq) { printf("Cannot add another equality constraint to the fitness function\n"); printf("The number of requested equality constraints is %i, and the current number of equality constraints is %i\n", FitFunc->neq, FitFunc->current_neq); getchar(); } else { FitFunc->current_neq++; unsigned position = FitFunc->current_neq - 1; FitFunc->EQ[position] = eq_f; } } void add_le(FitnessFunc* FitFunc, const gaf_ptr le_f) { if (FitFunc->current_nle >= FitFunc->nle) { printf("Cannot add another l.e. constraint to the fitness function\n"); printf("The number of requested l.e. constraints is %i, and the current number of l.e. constraints is %i\n", FitFunc->nle, FitFunc->current_nle); getchar(); } else { FitFunc->current_nle++; unsigned position = FitFunc->current_nle - 1; FitFunc->LE[position] = le_f; } } void add_ge(FitnessFunc* FitFunc, const gaf_ptr ge_f) { if (FitFunc->current_nge >= FitFunc->nge) { printf("Cannot add another g.e. constraint to the fitness function\n"); printf("The number of requested g.e. constraints is %i, and the current number of g.e. constraints is %i\n", FitFunc->nge, FitFunc->current_nge); getchar(); } else { FitFunc->current_nge++; unsigned position = FitFunc->current_nge - 1; FitFunc->GE[position] = ge_f; } } GAbool check_fitfuncOK(const FitnessFunc* FitFunc) { if (FitFunc->neq == FitFunc->current_neq && FitFunc->nle == FitFunc->current_nle && FitFunc->nge == FitFunc->current_nge && FitFunc->ObjF != NULL) { if (FitFunc->ObjType == MIN) printf("The fitness function is complete and set to minimize\n"); else if (FitFunc->ObjType == MAX) printf("The fitness function is complete and set to maximize\n"); else printf("The fitness function is complete and set to nonesense: %i\n", FitFunc->ObjType); //should never get here because create_FitFunc() requires MinMAX as input return GA_TRUE; } else { printf("The fitness function is not finished being built\n"); getchar(); return GA_TRUE; } } float* create_Population(unsigned ndv, const float* UB, const float* LB) { //population major array treated like matrix population[chromosome, v] = population[ndv*chromosome + v] float* Population = malloc(GA_POPULATION * ndv * sizeof(float)); #pragma omp parallel { unsigned tid = omp_get_thread_num(); srand(time(NULL) + tid); //only works with MSVCRT. include time. int p = 0; #pragma omp for for (p = 0; p < GA_POPULATION; p++) { for (unsigned v = 0; v < ndv; v++) { float MAX = pow(2, GA_RESOLUTION) - 1.0f; unsigned MAXi = (unsigned)MAX; int rndint = rand() % (MAXi + 1); //i assume this is a less than check! float rndn = (((float)rndint / (MAX)) * (UB[v] - LB[v])) + LB[v]; Population[ndv*p + v] = rndn; } } } return Population; } void print_Population(unsigned ndv, const float* Population) { for (unsigned p = 0; p < GA_POPULATION; p++) { printf("\nPrinting info on chrom %i: ", p); for (unsigned v = 0; v < ndv; v++) { float val = Population[ndv*p + v]; printf("%f, ", val); } } } void destroy_Population(unsigned ndv, float* Population) { free(Population); } float* calc_PopFitness(unsigned ndv, const FitnessFunc* FitFunc, const float* Population) { float* Fitness = malloc(GA_POPULATION * sizeof(float)); int p = 0; #pragma omp parallel for for (p = 0; p < GA_POPULATION; p++) { float* DV = malloc(ndv * sizeof(float)); for (unsigned v = 0; v < ndv; v++) { DV[v] = Population[ndv*p + v]; } float Fitness_p = eval_Fitfunc(FitFunc, ndv, DV); free(DV); Fitness[p] = Fitness_p; } return Fitness; } void print_Fitness(const float* Fitness) { for (unsigned p = 0; p < GA_POPULATION; p++) { printf("\nPrinting fitness for chromosome %i: %f", p, Fitness[p]); } } void destroy_Fitness(float* Fitness) { free(Fitness); } float* crossPop_Min(unsigned ndv, const float* Fitness, const float* Population) { //float* NewFitness = malloc(GA_POPULATION * sizeof(float)); float* NewPopulation = malloc(GA_POPULATION * ndv * sizeof(float)); //the following is done in parallel because it is somewhat heavy. I think... Whatever. #pragma omp parallel { unsigned tid = omp_get_thread_num(); srand(time(NULL) + tid); //only works with MSVCRT. include time. int p = 0; #pragma omp for for (p = 0; p < GA_POPULATION; p++) { unsigned oneDex = rand() % (GA_POPULATION); //assuming this works via less than NOT less than or equal unsigned twoDex = rand() % (GA_POPULATION); float oneVal = Fitness[oneDex]; float twoVal = Fitness[twoDex]; unsigned Mindex = 0; if (oneVal <= twoVal) Mindex = oneDex; else Mindex = twoDex; for (unsigned v = 0; v < ndv; v++) NewPopulation[p * ndv + v] = Population[Mindex * ndv + v]; } } return NewPopulation; } float* matePop(unsigned ndv, const float* CrossOverPop, const FitnessFunc* FitFunc) { float* NewPopulation = malloc(GA_POPULATION * ndv * sizeof(float)); #pragma omp parallel { unsigned tid = omp_get_thread_num(); srand(time(NULL) + tid); //only works with MSVCRT. include time. int p = 0; #pragma omp for for (p = 0; p < GA_POPULATION; p++) { unsigned oneDex = rand() % (GA_POPULATION); //assuming this works via less than NOT less than or equal unsigned twoDex = rand() % (GA_POPULATION); float* Baby1 = malloc(ndv * sizeof(float)); for (unsigned v = 0; v < ndv; v++) { unsigned flip = rand() % 2; if (flip == 1) Baby1[v] = CrossOverPop[oneDex * ndv + v]; else if (flip == 0) Baby1[v] = CrossOverPop[twoDex * ndv + v]; else { printf("\nSomething went wrong inside of the mutation function\n"); getchar(); } } for (unsigned v = 0; v < ndv; v++) NewPopulation[p * ndv + v] = Baby1[v]; free(Baby1); } } return NewPopulation; } float* mutPop(unsigned ndv, const float* MatePop, const float* UB, const float* LB) { float* NewPop = malloc(GA_POPULATION * ndv * sizeof(float)); #pragma omp parallel { unsigned tid = omp_get_thread_num(); srand(time(NULL) + tid); //only works with MSVCRT. include time. int p = 0; #pragma omp for for (p = 0; p < GA_POPULATION; p++) { //copy for (unsigned v = 0; v < ndv; v++) { NewPop[p * ndv + v] = MatePop[p * ndv + v]; //should we mutate? unsigned mut = rand() & ndv; if (mut == v) { float MAX = pow(2, GA_RESOLUTION) - 1.0f; unsigned MAXi = (unsigned)MAX; int rndint = rand() % (MAXi + 1); //i assume this is a less than check! float rndf = (((float)rndint / (MAX)) * (UB[v] - LB[v])) + LB[v]; NewPop[p * ndv + v] = rndf; //printf("Mutation on chromosome %i, DV %i with value %f from thread %i\n", p, mdex, rndf, tid); } } } } return NewPop; } void print_minVal(unsigned iter, unsigned ndv, const float* Fitness, const float* Population) { float minVal = Fitness[0]; unsigned minDex = 0; for (unsigned p = 0; p < GA_POPULATION; p++) { if (Fitness[p] < minVal) { minVal = Fitness[p]; minDex = p; } } printf("\nMinimum value of iteration %i is %f with: ", iter, minVal); for (unsigned v = 0; v < ndv; v++) { float val = Population[minDex * ndv + v]; printf("%f, ", val); } } void optimPop_Min(unsigned ndv, const FitnessFunc* FitFunc, const float* UB, const float* LB) { float* Population = create_Population(ndv, UB, LB); //loop here for (unsigned i = 0; i < 100; i++) { float* Fitness = calc_PopFitness(ndv, FitFunc, Population); print_minVal(i, ndv, Fitness, Population); float* CrossOverPop = crossPop_Min(ndv, Fitness, Population); float* MatePop = matePop(ndv, CrossOverPop, FitFunc); float* MutPop = mutPop(ndv, MatePop, UB, LB); destroy_Fitness(Fitness); destroy_Population(ndv, CrossOverPop); destroy_Population(ndv, MatePop); destroy_Population(ndv, Population); Population = MutPop; } //print_Population(ndv, Population); destroy_Population(ndv, Population); }
vt_thrd.c
/** * VampirTrace * http://www.tu-dresden.de/zih/vampirtrace * * Copyright (c) 2005-2008, ZIH, TU Dresden, Federal Republic of Germany * * Copyright (c) 1998-2005, Forschungszentrum Juelich, Juelich Supercomputing * Centre, Federal Republic of Germany * * See the file COPYING in the package base directory for details **/ #include "config.h" #include "vt_thrd.h" #include "vt_metric.h" #include "vt_pform.h" #include "vt_error.h" #include "vt_env.h" #include "vt_trc.h" #include <limits.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #if (defined (VT_MPI) || defined (VT_OMPI)) #include "mpi.h" #include "vt_sync.h" #endif #if (defined (VT_OMPI) || defined (VT_OMP)) #include <omp.h> #endif static uint32_t tnum = 0; /* create thread object with initialised base filename and metrics, but without allocating buffers or files */ VTThrd* VTThrd_create(uint32_t tid) { VTThrd *thread; #if (defined (VT_METR)) int num_metrics = vt_metric_num(); #endif if (tnum > (uint32_t)vt_env_max_threads()) vt_error_msg("FATAL: Cannot create more than %d threads", vt_env_max_threads()); thread = (VTThrd*)malloc(sizeof(VTThrd)); if ( thread == NULL ) vt_error(); thread->tmp_name = (char*)calloc(VT_PATH_MAX + 1, sizeof(char)); if ( thread->tmp_name == NULL ) vt_error(); /* basename includes local path but neither thread identifier nor suffix */ snprintf(thread->tmp_name, VT_PATH_MAX, "%s/%s.%lx.%u", vt_env_ldir(), vt_env_fprefix(), vt_pform_node_id(), getpid()); thread->stack_level = 0; thread->omp_collop_stime = 0; #if (defined (VT_MEMHOOK)) thread->mem_app_alloc = 0; #endif #if (defined (VT_METR)) if (num_metrics > 0) { /* create event set */ thread->metv = vt_metric_create(); /* initialize per-thread arrays for counter values */ thread->valv = (uint64_t*)calloc(num_metrics, sizeof(uint64_t)); if ( thread->valv == NULL ) vt_error(); } #endif #if (defined (RFG)) /* initialize region filter and grouping management */ thread->rfg_regions = RFG_Regions_init(); if( thread->rfg_regions == NULL ) vt_error_msg("Could not initialize region filter and grouping management"); #endif /* enable tracing */ thread->is_trace_on = 1; /* increment the thread object counter (for successful creations) */ #if (defined (VT_OMPI) || defined (VT_OMP)) #pragma omp atomic tnum++; #else tnum++; #endif vt_cntl_msg("Thread object #%u created, total number is %u", tid, tnum); return thread; } void VTThrd_open(VTThrd* thrd, uint32_t tid) { uint8_t mode = (uint8_t)vt_env_mode(); size_t bsize = vt_env_bsize(); #if (defined (VT_OMPI) || defined (VT_OMP)) if (tid == 0) { /* master thread gets most buffer space */ bsize = (bsize / 10) * 7; } else { /* worker threads get less buffer space */ bsize = (bsize / 10); } #endif if (thrd && thrd->tmp_name) thrd->gen = VTGen_open(thrd->tmp_name, tid, bsize, mode); } void VTThrd_close(VTThrd* thrd) { if (thrd && thrd->tmp_name) { uint64_t time; while(thrd->stack_level > 0) { time = vt_pform_wtime(); vt_exit(&time); } VTGen_close(thrd->gen); } } void VTThrd_delete(VTThrd* thrd, uint32_t tid) { if (!thrd) return; if (thrd->gen) VTGen_delete(thrd->gen); #if (defined (VT_METR)) if (thrd->metv && vt_metric_num() > 0 ) vt_metric_free(thrd->metv); #endif #if (defined (RFG)) if (thrd->rfg_regions) RFG_Regions_free( thrd->rfg_regions ); #endif if (thrd->tmp_name) free(thrd->tmp_name); free(thrd); /* decrement the thread object counter */ #if (defined (VT_OMPI) || defined (VT_OMP)) #pragma omp atomic tnum--; #else tnum--; #endif vt_cntl_msg("Thread object #%u deleted, leaving %u", tid, tnum); } uint32_t VTThrd_get_num_thrds() { return tnum; }
omp-parallel.c
#include <omp.h> #define THREADS 2 int main(void) { #pragma omp parallel num_threads(THREADS) { // pass } }
utils.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file utils.h * \brief Basic utilility functions. */ #ifndef MXNET_COMMON_UTILS_H_ #define MXNET_COMMON_UTILS_H_ #include <dmlc/logging.h> #include <dmlc/omp.h> #include <nnvm/graph.h> #include <mxnet/engine.h> #include <mxnet/ndarray.h> #include <mxnet/op_attr_types.h> #include <mxnet/graph_attr_types.h> #include <nnvm/graph_attr_types.h> #include <memory> #include <vector> #include <type_traits> #include <utility> #include <random> #include <string> #include <thread> #include <algorithm> #include <functional> #include <limits> #include "../operator/mxnet_op.h" #if MXNET_USE_MKLDNN == 1 #include "../operator/nn/mkldnn/mkldnn_base-inl.h" #endif namespace mxnet { namespace common { /*! * \brief IndPtr should be non-negative, in non-decreasing order, start with 0 * and end with value equal with size of indices. */ struct csr_indptr_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* indptr, const nnvm::dim_t end, const nnvm::dim_t idx_size) { if (indptr[i+1] < 0 || indptr[i+1] < indptr[i] || (i == 0 && indptr[i] != 0) || (i == end - 1 && indptr[end] != idx_size)) *out = kCSRIndPtrErr; } }; /*! * \brief Indices should be non-negative, less than the number of columns * and in ascending order per row. */ struct csr_idx_check { template<typename DType, typename IType, typename RType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const RType* indptr, const nnvm::dim_t ncols) { for (RType j = indptr[i]; j < indptr[i+1]; j++) { if (idx[j] >= ncols || idx[j] < 0 || (j < indptr[i+1] - 1 && idx[j] >= idx[j+1])) { *out = kCSRIdxErr; break; } } } }; /*! * \brief Indices of RSPNDArray should be non-negative, * less than the size of first dimension and in ascending order */ struct rsp_idx_check { template<typename DType, typename IType> MSHADOW_XINLINE static void Map(int i, DType* out, const IType* idx, const nnvm::dim_t end, const nnvm::dim_t nrows) { if ((i < end && idx[i+1] <= idx[i]) || idx[i] < 0 || idx[i] >= nrows) *out = kRSPIdxErr; } }; template<typename xpu> void CheckFormatWrapper(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check); /*! * \brief Check the validity of CSRNDArray. * \param rctx Execution context. * \param input Input NDArray of CSRStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatCSRImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kCSRStorage) << "CheckFormatCSRImpl is for CSRNDArray"; const TShape shape = input.shape(); const TShape idx_shape = input.aux_shape(csr::kIdx); const TShape indptr_shape = input.aux_shape(csr::kIndPtr); const TShape storage_shape = input.storage_shape(); if ((shape.ndim() != 2) || (idx_shape.ndim() != 1 || indptr_shape.ndim() != 1 || storage_shape.ndim() != 1) || (indptr_shape[0] != shape[0] + 1) || (idx_shape[0] != storage_shape[0])) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kCSRShapeErr; }); return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(csr::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<csr_indptr_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), indptr_shape[0] - 1, idx_shape[0]); // no need to check indices if indices are empty if (idx_shape[0] != 0) { Kernel<csr_idx_check, xpu>::Launch(s, indptr_shape[0] - 1, val_xpu.dptr<DType>(), input.aux_data(csr::kIdx).dptr<IType>(), input.aux_data(csr::kIndPtr).dptr<RType>(), shape[1]); } mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); }); } } /*! * \brief Check the validity of RowSparseNDArray. * \param rctx Execution context. * \param input Input NDArray of RowSparseStorage. * \param err_cpu Error number on cpu. * \param full_check If true, rigorous check, O(N) operations, * otherwise basic check, O(1) operations. */ template<typename xpu> void CheckFormatRSPImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { using namespace op::mxnet_op; CHECK_EQ(input.storage_type(), kRowSparseStorage) << "CheckFormatRSPImpl is for RSPNDArray"; const TShape idx_shape = input.aux_shape(rowsparse::kIdx); if (idx_shape[0] != input.storage_shape()[0]) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { DType* err = err_cpu.dptr<DType>(); *err = kRSPShapeErr; }); return; } if (idx_shape[0] == 0) { return; } if (full_check) { MSHADOW_TYPE_SWITCH(err_cpu.type_flag_, DType, { MSHADOW_IDX_TYPE_SWITCH(input.aux_type(rowsparse::kIdx), IType, { mshadow::Stream<xpu> *s = rctx.get_stream<xpu>(); NDArray ret_xpu = NDArray(mshadow::Shape1(1), rctx.get_ctx(), false, err_cpu.type_flag_); TBlob val_xpu = ret_xpu.data(); Kernel<set_to_int<kNormalErr>, xpu>::Launch(s, val_xpu.Size(), val_xpu.dptr<DType>()); Kernel<rsp_idx_check, xpu>::Launch(s, idx_shape[0], val_xpu.dptr<DType>(), input.aux_data(rowsparse::kIdx).dptr<IType>(), idx_shape[0] - 1, input.shape()[0]); mshadow::Copy(err_cpu.get<cpu, 1, DType>(), val_xpu.get<xpu, 1, DType>(s), s); }); }); } } template<typename xpu> void CheckFormatImpl(const RunContext &rctx, const NDArray &input, const TBlob &err_cpu, const bool full_check) { int stype = input.storage_type(); if (stype == kCSRStorage) { CheckFormatCSRImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kRowSparseStorage) { CheckFormatRSPImpl<xpu>(rctx, input, err_cpu, full_check); } else if (stype == kDefaultStorage) { // no-op for default storage } else { LOG(FATAL) << "Unknown storage type " << stype; } } /*! \brief Pick rows specified by user input index array from a row sparse ndarray * and save them in the output sparse ndarray. */ template<typename xpu> void SparseRetainOpForwardRspWrapper(mshadow::Stream<xpu> *s, const NDArray& input_nd, const TBlob& idx_data, const OpReqType req, NDArray* output_nd); /* \brief Casts tensor storage type to the new type. */ template<typename xpu> void CastStorageDispatch(const OpContext& ctx, const NDArray& input, const NDArray& output); /*! \brief returns true if all storage types in `vstorage` are the same as target `stype`. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype) { if (!vstorage.empty()) { for (const auto& i : vstorage) { if (i != stype) return false; } return true; } return false; } /*! \brief returns true if all storage types in `vstorage` are the same as target `stype1` * or `stype2'. Sets boolean if both found. * false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const StorageTypeVector& vstorage, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!vstorage.empty()) { uint8_t has = 0; for (const auto i : vstorage) { if (i == stype1) { has |= 1; } else if (i == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as target `stype`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() != stype) { return false; } } return true; } return false; } /*! \brief returns true if the storage types of arrays in `ndarrays` * are the same as targets `stype1` or `stype2`. false is returned for empty inputs. */ inline bool ContainsOnlyStorage(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype1, const NDArrayStorageType stype2, bool *has_both) { if (has_both) { *has_both = false; } if (!ndarrays.empty()) { uint8_t has = 0; for (const auto& nd : ndarrays) { const NDArrayStorageType stype = nd.storage_type(); if (stype == stype1) { has |= 1; } else if (stype == stype2) { has |= 2; } else { return false; } } if (has_both) { *has_both = has == 3; } return true; } return false; } /*! \brief returns true if storage type of any array in `ndarrays` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<NDArray>& ndarrays, const NDArrayStorageType stype) { if (!ndarrays.empty()) { for (const auto& nd : ndarrays) { if (nd.storage_type() == stype) { return true; } } } return false; } /*! \brief returns true if any storage type `ndstype` in `ndstypes` * is the same as the target `stype`. false is returned for empty inputs. */ inline bool ContainsStorageType(const std::vector<int>& ndstypes, const NDArrayStorageType stype) { if (!ndstypes.empty()) { for (const auto& ndstype : ndstypes) { if (ndstype == stype) { return true; } } } return false; } /*! \brief get string representation of dispatch_mode */ inline std::string dispatch_mode_string(const DispatchMode x) { switch (x) { case DispatchMode::kFCompute: return "fcompute"; case DispatchMode::kFComputeEx: return "fcompute_ex"; case DispatchMode::kFComputeFallback: return "fcompute_fallback"; case DispatchMode::kVariable: return "variable"; case DispatchMode::kUndefined: return "undefined"; } return "unknown"; } /*! \brief get string representation of storage_type */ inline std::string stype_string(const int x) { switch (x) { case kDefaultStorage: return "default"; case kCSRStorage: return "csr"; case kRowSparseStorage: return "row_sparse"; } return "unknown"; } /*! \brief get string representation of device type */ inline std::string dev_type_string(const int dev_type) { switch (dev_type) { case Context::kCPU: return "cpu"; case Context::kGPU: return "gpu"; case Context::kCPUPinned: return "cpu_pinned"; case Context::kCPUShared: return "cpu_shared"; } return "unknown"; } /*! \brief get string representation of the operator stypes */ inline std::string operator_stype_string(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>& in_attrs, const std::vector<int>& out_attrs) { std::ostringstream os; os << "operator = " << attrs.op->name << "\ninput storage types = ["; for (const int attr : in_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "output storage types = ["; for (const int attr : out_attrs) { os << stype_string(attr) << ", "; } os << "]\n" << "params = {"; for (auto kv : attrs.dict) { os << "\"" << kv.first << "\" : " << kv.second << ", "; } os << "}\n" << "context.dev_mask = " << dev_type_string(dev_mask); return os.str(); } /*! \brief get string representation of the operator */ inline std::string operator_string(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<NDArray>& inputs, const std::vector<OpReqType>& req, const std::vector<NDArray>& outputs) { std::string result = ""; std::vector<int> in_stypes; std::vector<int> out_stypes; in_stypes.reserve(inputs.size()); out_stypes.reserve(outputs.size()); auto xform = [](const NDArray arr) -> int { return arr.storage_type(); }; std::transform(inputs.begin(), inputs.end(), std::back_inserter(in_stypes), xform); std::transform(outputs.begin(), outputs.end(), std::back_inserter(out_stypes), xform); result += operator_stype_string(attrs, ctx.run_ctx.ctx.dev_mask(), in_stypes, out_stypes); return result; } /*! \brief log message once. Intended for storage fallback warning messages. */ inline void LogOnce(const std::string& message) { typedef dmlc::ThreadLocalStore<std::unordered_set<std::string>> LogStore; auto log_store = LogStore::Get(); if (log_store->find(message) == log_store->end()) { LOG(INFO) << message; log_store->insert(message); } } /*! \brief log storage fallback event */ inline void LogStorageFallback(const nnvm::NodeAttrs& attrs, const int dev_mask, const std::vector<int>* in_attrs, const std::vector<int>* out_attrs) { static bool log = dmlc::GetEnv("MXNET_STORAGE_FALLBACK_LOG_VERBOSE", true); if (!log) return; const std::string op_str = operator_stype_string(attrs, dev_mask, *in_attrs, *out_attrs); std::ostringstream os; const char* warning = "\nThe operator with default storage type will be dispatched " "for execution. You're seeing this warning message because the operator above is unable " "to process the given ndarrays with specified storage types, context and parameter. " "Temporary dense ndarrays are generated in order to execute the operator. " "This does not affect the correctness of the programme. " "You can set environment variable MXNET_STORAGE_FALLBACK_LOG_VERBOSE to " "0 to suppress this warning."; os << "\nStorage type fallback detected:\n" << op_str << warning; LogOnce(os.str()); #if MXNET_USE_MKLDNN == 1 if (!MKLDNNEnvSet()) common::LogOnce("MXNET_MKLDNN_ENABLED flag is off. " "You can re-enable by setting MXNET_MKLDNN_ENABLED=1"); if (GetMKLDNNCacheSize() != -1) common::LogOnce("MXNET_MKLDNN_CACHE_NUM is set." "Should only be set if " "your model has variable input shapes, " "as cache size may grow unbounded"); #endif } // heuristic to dermine number of threads per GPU inline int GetNumThreadsPerGPU() { // This is resource efficient option. return dmlc::GetEnv("MXNET_GPU_WORKER_NTHREADS", 2); } // heuristic to get number of matching colors. // this decides how much parallelism we can get in each GPU. inline int GetExecNumMatchColor() { // This is resource efficient option. int num_match_color = dmlc::GetEnv("MXNET_EXEC_NUM_TEMP", 1); return std::min(num_match_color, GetNumThreadsPerGPU()); } template<typename T, typename V> V ParallelAccumulate(const T* a, const int n, V start) { V sum = start; #pragma omp parallel for reduction(+:sum) for (int i = 0; i < n; ++i) { sum += a[i]; } return sum; } /*! * \brief * Helper function for ParallelSort. * DO NOT call this function directly. * Use the interface ParallelSort instead. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSortHelper(RandomIt first, size_t len, size_t grainsize, const Compare& comp) { if (len < grainsize) { std::sort(first, first+len, comp); } else { std::thread thr(ParallelSortHelper<RandomIt, Compare>, first, len/2, grainsize, comp); ParallelSortHelper(first+len/2, len - len/2, grainsize, comp); thr.join(); std::inplace_merge(first, first+len/2, first+len, comp); } } /*! * \brief * Sort the elements in the range [first, last) into the ascending order defined by * the comparator comp. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt, typename Compare> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads, Compare comp) { const auto num = std::distance(first, last); size_t grainsize = std::max(num / num_threads + 5, static_cast<size_t>(1024*16)); ParallelSortHelper(first, num, grainsize, comp); } /*! * \brief * Sort the elements in the range [first, last) into ascending order. * The elements are compared using the default < operator. * If the length of the range [first, last) is greater than a certain threshold, * the range will be recursively divided into two and assign two threads * to sort each half range. * Ref: https://github.com/dmlc/difacto/blob/master/src/common/parallel_sort.h */ template<typename RandomIt> void ParallelSort(RandomIt first, RandomIt last, size_t num_threads) { ParallelSort(first, last, num_threads, std::less<typename std::iterator_traits<RandomIt>::value_type>()); } /*! * \brief Random Engine */ typedef std::mt19937 RANDOM_ENGINE; /*! * \brief Helper functions. */ namespace helper { /*! * \brief Helper for non-array type `T`. */ template <class T> struct UniqueIf { /*! * \brief Type of `T`. */ using SingleObject = std::unique_ptr<T>; }; /*! * \brief Helper for an array of unknown bound `T`. */ template <class T> struct UniqueIf<T[]> { /*! * \brief Type of `T`. */ using UnknownBound = std::unique_ptr<T[]>; }; /*! * \brief Helper for an array of known bound `T`. */ template <class T, size_t kSize> struct UniqueIf<T[kSize]> { /*! * \brief Type of `T`. */ using KnownBound = void; }; } // namespace helper /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs a non-array type `T`. The arguments `args` are passed to the * constructor of `T`. The function does not participate in the overload * resolution if `T` is an array type. */ template <class T, class... Args> typename helper::UniqueIf<T>::SingleObject MakeUnique(Args&&... args) { return std::unique_ptr<T>(new T(std::forward<Args>(args)...)); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param n The size of the array to construct. * \return `std``::``unique_ptr` of an instance of type `T`. * * Constructs an array of unknown bound `T`. The function does not participate * in the overload resolution unless `T` is an array of unknown bound. */ template <class T> typename helper::UniqueIf<T>::UnknownBound MakeUnique(size_t n) { using U = typename std::remove_extent<T>::type; return std::unique_ptr<T>(new U[n]{}); } /*! * \brief Constructs an object of type `T` and wraps it in a * `std``::``unique_ptr`. * \param args List of arguments with which an instance of `T` will be * constructed. * * Constructs an arrays of known bound is disallowed. */ template <class T, class... Args> typename helper::UniqueIf<T>::KnownBound MakeUnique(Args&&... args) = delete; template<typename FCompType> FCompType GetFCompute(const nnvm::Op* op, const std::string& name, const Context& ctx) { static auto& fcompute_cpu = nnvm::Op::GetAttr<FCompType>(name + "<cpu>"); static auto& fcompute_gpu = nnvm::Op::GetAttr<FCompType>(name + "<gpu>"); if (ctx.dev_mask() == cpu::kDevMask) { return fcompute_cpu.get(op, nullptr); } else if (ctx.dev_mask() == gpu::kDevMask) { return fcompute_gpu.get(op, nullptr); } else { LOG(FATAL) << "Unknown device mask"; return nullptr; } } /*! * \brief Return the max integer value representable in the type `T` without loss of precision. */ template <typename T> constexpr size_t MaxIntegerValue() { return std::is_integral<T>::value ? std::numeric_limits<T>::max(): size_t(2) << (std::numeric_limits<T>::digits - 1); } template <> constexpr size_t MaxIntegerValue<mshadow::half::half_t>() { return size_t(2) << 10; } MSHADOW_XINLINE int ilog2ul(size_t a) { int k = 1; while (a >>= 1) ++k; return k; } MSHADOW_XINLINE int ilog2ui(unsigned int a) { int k = 1; while (a >>= 1) ++k; return k; } /*! * \brief Return an NDArray of all zeros. */ inline NDArray InitZeros(const NDArrayStorageType stype, const TShape &shape, const Context &ctx, const int dtype) { // NDArray with default storage if (stype == kDefaultStorage) { NDArray ret(shape, ctx, false, dtype); ret = 0; return ret; } // NDArray with non-default storage. Storage allocation is always delayed. return NDArray(stype, shape, ctx, true, dtype); } /*! * \brief Helper to add a NDArray of zeros to a std::vector. */ inline void EmplaceBackZeros(const NDArrayStorageType stype, const TShape &shape, const Context &ctx, const int dtype, std::vector<NDArray> *vec) { // NDArray with default storage if (stype == kDefaultStorage) { vec->emplace_back(shape, ctx, false, dtype); vec->back() = 0; } else { // NDArray with non-default storage. Storage allocation is always delayed. vec->emplace_back(stype, shape, ctx, true, dtype); } } /*! * \brief parallelize copy by OpenMP. */ template<typename DType> inline void ParallelCopy(DType* dst, const DType* src, index_t size) { static index_t copy_block_size = dmlc::GetEnv("MXNET_CPU_PARALLEL_COPY_SIZE", 2000000000); if (size >= copy_block_size) { #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (index_t i = 0; i < size; ++i) { dst[i] = src[i]; } } else { std::memcpy(dst, src, sizeof(DType) * size); } } } // namespace common } // namespace mxnet #endif // MXNET_COMMON_UTILS_H_
Locks.h
// -*- C++ -*- Copyright (c) Microsoft Corporation; see license.txt #ifndef MESH_PROCESSING_LIBHH_LOCKS_H_ #define MESH_PROCESSING_LIBHH_LOCKS_H_ #include "Hh.h" #if 0 { // critical section parallel_for_int(i, 100) { something(); HH_LOCK { something_synchronized(): } } // alternate std::mutex g_mutex; parallel_for_int(i, 100) { something(); { std::lock_guard<std::mutex> lg(g_mutex); something_synchronized(); } } } #endif #if defined(__clang__) && defined(__GNUC__) && __GNUC__*100+__GNUC_MINOR__<408 && !defined(__APPLE_CC__) && !defined(HH_NO_DEFINE_STD_MUTEX) namespace std { // workaround for current mingw32 4.7.2: no locking // If there is a compilation error here, e.g. "reference to 'mutex' is ambiguous", // use "make HH_NO_DEFINE_STD_MUTEX=1". struct mutex { }; template<typename T> struct lock_guard { lock_guard(T&) { } }; } // namespace std #else #include <mutex> // mutex, lock_guard; C++11 #endif namespace hh { //---------------------------------------------------------------------------- // *** No support for locks. #if defined(__clang__) && defined(__GNUC__) && __GNUC__*100+__GNUC_MINOR__<408 && !defined(__APPLE_CC__) && !defined(HH_NO_DEFINE_STD_MUTEX) #define HH_LOCK //---------------------------------------------------------------------------- // *** Use OpenMP for synchronization (its default is a globally defined mutex). #elif 0 #include <omp.h> // OpenMP #define HH_LOCK HH_PRAGMA(omp critical) // A thread waits at the beginning of a critical region until no other thread is executing a critical region // (anywhere in the program) with the same name. All unnamed critical directives map to the same unspecified // name. // Drawbacks of OpenMP critical sections: // (http://www.thinkingparallel.com/2006/08/21/scoped-locking-vs-critical-in-openmp-a-personal-shootout/) // - cannot leave scope using break, continue, goto, or return // - cannot leave scope with exception (e.g. gcc does implicit catch and reports error)! // - cannot use a separate lock guard per-task in a thread-safe function (rare need). //---------------------------------------------------------------------------- // *** All critical sections across the program share the same globally defined mutex -- like OpenMP default. #elif 0 class MyGlobalLock { public: MyGlobalLock() : _lock_guard(s_f_global_mutex()) { } private: std::lock_guard<std::mutex> _lock_guard; static std::mutex& s_f_global_mutex() { static std::mutex m; return m; } // singleton pattern function }; #define HH_LOCK if (hh::false_capture<hh::MyGlobalLock> HH_UNIQUE_ID(lock){}) { HH_UNREACHABLE; } else //---------------------------------------------------------------------------- // *** The critical sections in each compilation unit (*.cpp file) share the same mutex. #elif 1 namespace { std::mutex s_per_file_mutex; class MyPerFileLock { public: MyPerFileLock() : _lock_guard(s_per_file_mutex) { } private: std::lock_guard<std::mutex> _lock_guard; }; } // namespace #define HH_LOCK if (hh::false_capture<hh::MyPerFileLock> HH_UNIQUE_ID(lock){}) { HH_UNREACHABLE; } else //---------------------------------------------------------------------------- // *** Each critical section has its own mutex. #elif 0 // I can't see a way to implement that using an HH_LOCK { } type macro, // because there is no way to declare/allocate a static variable in the middle of a statement. // Maybe use a false_capture of a templated class with template argument based on __COUNTER__ // (and singleton pattern function)? //---------------------------------------------------------------------------- // *** Old paired macros (all critical sections use a separately defined mutex). #else #error These paired macros are no longer supported. #define HH_BEGIN_LOCK { static std::mutex my_mutex1; std::lock_guard<std::mutex> HH_UNIQUE_ID(lock){my_mutex1}; #define HH_END_LOCK } HH_EAT_SEMICOLON #endif } // namespace hh //---------------------------------------------------------------------------- // Good discussion: // // http://stackoverflow.com/questions/23519630/are-there-c11-critical-sections // The C++11 std::mutex does not require cross-processing locking, so a reasonable implementation // should avoid cross-process objects like named semaphores (or win32 Mutex). // // http://stackoverflow.com/questions/800383/what-is-the-difference-between-mutex-and-critical-section/ // // For Windows, critical sections are lighter-weight than mutexes. [here mutex is a win32 Mutex, not std::mutex] // - Mutexes can be shared between processes, but always result in a system call to the kernel which has some overhead. // - Critical sections can only be used within one process, but have the advantage that they only switch to // kernel mode in the case of contention - Uncontended acquires, which should be the common case, are // incredibly fast. In the case of contention, they enter the kernel to wait on some synchronization primitive // (like an event or semaphore). // The following details are specific to critical sections on windows: // - in the absence of contention, acquiring a critical section is as simple as an InterlockedCompareExchange operation // - the critical section structure holds room for a mutex. It is initially unallocated // - if there is contention between threads for a critical section, the mutex will be allocated and used. The // performance of the critical section will degrade to that of the mutex // - if you anticipate high contention, you can allocate the critical section specifying a spin count. // - if there is contention on a critical section with a spin count, the thread attempting to acquire the // critical section will spin (busy-wait) for that many processor cycles. This can result in better // performance than sleeping, as the number of cycles to perform a context switch to another thread can be // much higher than the number of cycles taken by the owning thread to release the mutex // - if the spin count expires, the mutex will be allocated // - when the owning thread releases the critical section, it is required to check if the mutex is allocated, // if it is then it will set the mutex to release a waiting thread // http://stackoverflow.com/questions/7798010/openmp-atomic-vs-critical/ // In OpenMP all unnamed critical sections are considered identical (if you prefer, there's only one lock for // all unnamed critical sections). // #pragma omp critical [(name)] // Note that name must be enclosed in parentheses. // Also use the following, which is faster than a critical section: // HH_PRAGMA(omp atomic) g_nslow++; // It works for x+=, x-=, x*=, x&=, etc., and --x and ++x. // Better yet, use std::atomic<T>. // Possibly could use atomic_operate() defined in AtomicOperate.h #endif // MESH_PROCESSING_LIBHH_LOCKS_H_
convolution_3x3_pack4.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 conv3x3s1_winograd63_transform_kernel_pack4_msa(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch, const Option& opt) { // winograd63 transform kernel Mat kernel_tm; kernel_tm.create(8 * 8, inch, outch); const float ktm[8][3] = { {1.0f, 0.0f, 0.0f}, {-2.0f / 9, -2.0f / 9, -2.0f / 9}, {-2.0f / 9, 2.0f / 9, -2.0f / 9}, {1.0f / 90, 1.0f / 45, 2.0f / 45}, {1.0f / 90, -1.0f / 45, 2.0f / 45}, {1.0f / 45, 1.0f / 90, 1.0f / 180}, {1.0f / 45, -1.0f / 90, 1.0f / 180}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel, transposed const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[8][3]; for (int i = 0; i < 8; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // v for (int j = 0; j < 8; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 8; i++) { kernel_tm0[j * 8 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 64-inch-outch // dst = pb-pa-inch/pa-64-outch/pb kernel_tm_pack4.create(inch / 4, 64, outch / 4, (size_t)4u * 4 * 4, 4 * 4); for (int q = 0; q + (4 - 1) < outch; q += 4) { Mat g0 = kernel_tm_pack4.channel(q / 4); for (int k = 0; k < 64; k++) { float* g00 = g0.row<float>(k); for (int p = 0; p + (4 - 1) < inch; p += 4) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { const float* k00 = kernel_tm.channel(q + j).row(p + i); g00[0] = (float)k00[k]; g00++; } } } } } } static void conv3x3s1_winograd63_pack4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 6n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 5) / 6 * 6; outh = (outh + 5) / 6 * 6; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tiles = outw / 6; int h_tiles = outh / 6; const int tiles = w_tiles * h_tiles; bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); conv3x3s1_winograd63_transform_input_pack4_msa(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 6 * 8; int h_tm = outh / 6 * 8; const int tiles = h_tm / 8 * w_tm / 8; // permute // bottom_blob_tm.create(tiles, 64, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 64, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 64, 4u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 64, 4u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 64; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 11 < tiles; i += 12) { float* tmpptr = tm2.row(i / 12); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4f32 _r4 = (v4f32)__msa_ld_w(r0 + 4 * 4, 0); v4f32 _r5 = (v4f32)__msa_ld_w(r0 + 4 * 5, 0); v4f32 _r6 = (v4f32)__msa_ld_w(r0 + 4 * 6, 0); v4f32 _r7 = (v4f32)__msa_ld_w(r0 + 4 * 7, 0); v4f32 _r8 = (v4f32)__msa_ld_w(r0 + 4 * 8, 0); v4f32 _r9 = (v4f32)__msa_ld_w(r0 + 4 * 9, 0); v4f32 _ra = (v4f32)__msa_ld_w(r0 + 4 * 10, 0); v4f32 _rb = (v4f32)__msa_ld_w(r0 + 4 * 11, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v4i32 _r45r = __msa_ilvr_w((v4i32)_r5, (v4i32)_r4); v4i32 _r45l = __msa_ilvl_w((v4i32)_r5, (v4i32)_r4); v4i32 _r67r = __msa_ilvr_w((v4i32)_r7, (v4i32)_r6); v4i32 _r67l = __msa_ilvl_w((v4i32)_r7, (v4i32)_r6); v4i32 _r89r = __msa_ilvr_w((v4i32)_r9, (v4i32)_r8); v4i32 _r89l = __msa_ilvl_w((v4i32)_r9, (v4i32)_r8); v4i32 _rabr = __msa_ilvr_w((v4i32)_rb, (v4i32)_ra); v4i32 _rabl = __msa_ilvl_w((v4i32)_rb, (v4i32)_ra); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r4567_0 = __msa_ilvr_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_1 = __msa_ilvl_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_2 = __msa_ilvr_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r4567_3 = __msa_ilvl_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r89ab_0 = __msa_ilvr_d((v2i64)_rabr, (v2i64)_r89r); v2i64 _r89ab_1 = __msa_ilvl_d((v2i64)_rabr, (v2i64)_r89r); v2i64 _r89ab_2 = __msa_ilvr_d((v2i64)_rabl, (v2i64)_r89l); v2i64 _r89ab_3 = __msa_ilvl_d((v2i64)_rabl, (v2i64)_r89l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r4567_0, tmpptr + 4, 0); __msa_st_w((v4i32)_r89ab_0, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4 * 3, 0); __msa_st_w((v4i32)_r4567_1, tmpptr + 4 * 4, 0); __msa_st_w((v4i32)_r89ab_1, tmpptr + 4 * 5, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 6, 0); __msa_st_w((v4i32)_r4567_2, tmpptr + 4 * 7, 0); __msa_st_w((v4i32)_r89ab_2, tmpptr + 4 * 8, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 9, 0); __msa_st_w((v4i32)_r4567_3, tmpptr + 4 * 10, 0); __msa_st_w((v4i32)_r89ab_3, tmpptr + 4 * 11, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 48; } } for (; i + 7 < tiles; i += 8) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4f32 _r4 = (v4f32)__msa_ld_w(r0 + 4 * 4, 0); v4f32 _r5 = (v4f32)__msa_ld_w(r0 + 4 * 5, 0); v4f32 _r6 = (v4f32)__msa_ld_w(r0 + 4 * 6, 0); v4f32 _r7 = (v4f32)__msa_ld_w(r0 + 4 * 7, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v4i32 _r45r = __msa_ilvr_w((v4i32)_r5, (v4i32)_r4); v4i32 _r45l = __msa_ilvl_w((v4i32)_r5, (v4i32)_r4); v4i32 _r67r = __msa_ilvr_w((v4i32)_r7, (v4i32)_r6); v4i32 _r67l = __msa_ilvl_w((v4i32)_r7, (v4i32)_r6); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r4567_0 = __msa_ilvr_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_1 = __msa_ilvl_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_2 = __msa_ilvr_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r4567_3 = __msa_ilvl_d((v2i64)_r67l, (v2i64)_r45l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r4567_0, tmpptr + 4, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r4567_1, tmpptr + 4 * 3, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 4, 0); __msa_st_w((v4i32)_r4567_2, tmpptr + 4 * 5, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 6, 0); __msa_st_w((v4i32)_r4567_3, tmpptr + 4 * 7, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 32; } } for (; i + 3 < tiles; i += 4) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x4 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 3, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 16; } } for (; i + 1 < tiles; i += 2) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x2 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4i32 _r01_0 = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01_1 = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); __msa_st_w((v4i32)_r01_0, tmpptr, 0); __msa_st_w((v4i32)_r01_1, tmpptr + 4, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 8; } } for (; i < tiles; i++) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { v4f32 _val = (v4f32)__msa_ld_w(r0, 0); __msa_st_w((v4i32)_val, tmpptr, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 64, outch, 4u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int r = 0; r < 64; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); v4f32 _sum4 = (v4f32)__msa_fill_w(0); v4f32 _sum5 = (v4f32)__msa_fill_w(0); v4f32 _sum6 = (v4f32)__msa_fill_w(0); v4f32 _sum7 = (v4f32)__msa_fill_w(0); v4f32 _sum8 = (v4f32)__msa_fill_w(0); v4f32 _sum9 = (v4f32)__msa_fill_w(0); v4f32 _suma = (v4f32)__msa_fill_w(0); v4f32 _sumb = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 48); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4i32 _val4567 = __msa_ld_w(r0 + 4, 0); v4i32 _val89ab = __msa_ld_w(r0 + 8, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); _sum4 = __msa_fmadd_w(_sum4, (v4f32)__msa_splati_w(_val4567, 0), _w0); _sum5 = __msa_fmadd_w(_sum5, (v4f32)__msa_splati_w(_val4567, 1), _w0); _sum6 = __msa_fmadd_w(_sum6, (v4f32)__msa_splati_w(_val4567, 2), _w0); _sum7 = __msa_fmadd_w(_sum7, (v4f32)__msa_splati_w(_val4567, 3), _w0); _sum8 = __msa_fmadd_w(_sum8, (v4f32)__msa_splati_w(_val89ab, 0), _w0); _sum9 = __msa_fmadd_w(_sum9, (v4f32)__msa_splati_w(_val89ab, 1), _w0); _suma = __msa_fmadd_w(_suma, (v4f32)__msa_splati_w(_val89ab, 2), _w0); _sumb = __msa_fmadd_w(_sumb, (v4f32)__msa_splati_w(_val89ab, 3), _w0); r0 += 12; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); __msa_st_w((v4i32)_sum4, output0_tm + 4 * 4, 0); __msa_st_w((v4i32)_sum5, output0_tm + 4 * 5, 0); __msa_st_w((v4i32)_sum6, output0_tm + 4 * 6, 0); __msa_st_w((v4i32)_sum7, output0_tm + 4 * 7, 0); __msa_st_w((v4i32)_sum8, output0_tm + 4 * 8, 0); __msa_st_w((v4i32)_sum9, output0_tm + 4 * 9, 0); __msa_st_w((v4i32)_suma, output0_tm + 4 * 10, 0); __msa_st_w((v4i32)_sumb, output0_tm + 4 * 11, 0); output0_tm += 4 * 12; } for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); v4f32 _sum4 = (v4f32)__msa_fill_w(0); v4f32 _sum5 = (v4f32)__msa_fill_w(0); v4f32 _sum6 = (v4f32)__msa_fill_w(0); v4f32 _sum7 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 32); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4i32 _val4567 = __msa_ld_w(r0 + 4, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); _sum4 = __msa_fmadd_w(_sum4, (v4f32)__msa_splati_w(_val4567, 0), _w0); _sum5 = __msa_fmadd_w(_sum5, (v4f32)__msa_splati_w(_val4567, 1), _w0); _sum6 = __msa_fmadd_w(_sum6, (v4f32)__msa_splati_w(_val4567, 2), _w0); _sum7 = __msa_fmadd_w(_sum7, (v4f32)__msa_splati_w(_val4567, 3), _w0); r0 += 8; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); __msa_st_w((v4i32)_sum4, output0_tm + 4 * 4, 0); __msa_st_w((v4i32)_sum5, output0_tm + 4 * 5, 0); __msa_st_w((v4i32)_sum6, output0_tm + 4 * 6, 0); __msa_st_w((v4i32)_sum7, output0_tm + 4 * 7, 0); output0_tm += 4 * 8; } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 16); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); r0 += 4; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); output0_tm += 4 * 4; } for (; i + 1 < tiles; i += 2) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 8); __builtin_prefetch(k0 + 16); v4f32 _val0 = __msa_fill_w_f32(*r0++); v4f32 _val1 = __msa_fill_w_f32(*r0++); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, _val0, _w0); _sum1 = __msa_fmadd_w(_sum1, _val1, _w0); k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); output0_tm += 4 * 2; } for (; i < tiles; i++) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 4); __builtin_prefetch(k0 + 16); v4f32 _val0 = __msa_fill_w_f32(*r0++); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum = __msa_fmadd_w(_sum, _val0, _w0); k0 += 4; } __msa_st_w((v4i32)_sum, output0_tm, 0); output0_tm += 4; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator); } { conv3x3s1_winograd63_transform_output_pack4_msa(top_blob_tm, top_blob_bordered, bias, opt); } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); } static void conv3x3s1_winograd43_transform_kernel_pack4_msa(const Mat& kernel, Mat& kernel_tm_pack4, int inch, int outch, const Option& opt) { // winograd43 transform kernel Mat kernel_tm(6 * 6, inch, outch); const float ktm[6][3] = { {1.0f / 4, 0.0f, 0.0f}, {-1.0f / 6, -1.0f / 6, -1.0f / 6}, {-1.0f / 6, 1.0f / 6, -1.0f / 6}, {1.0f / 24, 1.0f / 12, 1.0f / 6}, {1.0f / 24, -1.0f / 12, 1.0f / 6}, {0.0f, 0.0f, 1.0f} }; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { for (int q = 0; q < inch; q++) { const float* kernel0 = (const float*)kernel + p * inch * 9 + q * 9; float* kernel_tm0 = kernel_tm.channel(p).row(q); // transform kernel const float* k0 = kernel0; const float* k1 = kernel0 + 3; const float* k2 = kernel0 + 6; // h float tmp[6][3]; for (int i = 0; i < 6; i++) { tmp[i][0] = k0[0] * ktm[i][0] + k0[1] * ktm[i][1] + k0[2] * ktm[i][2]; tmp[i][1] = k1[0] * ktm[i][0] + k1[1] * ktm[i][1] + k1[2] * ktm[i][2]; tmp[i][2] = k2[0] * ktm[i][0] + k2[1] * ktm[i][1] + k2[2] * ktm[i][2]; } // U for (int j = 0; j < 6; j++) { float* tmpp = &tmp[j][0]; for (int i = 0; i < 6; i++) { kernel_tm0[j * 6 + i] = tmpp[0] * ktm[i][0] + tmpp[1] * ktm[i][1] + tmpp[2] * ktm[i][2]; } } } } // interleave // src = 36-inch-outch // dst = pb-pa-inch/pa-36-outch/pb kernel_tm_pack4.create(inch / 4, 36, outch / 4, (size_t)4u * 4 * 4, 4 * 4); for (int q = 0; q + (4 - 1) < outch; q += 4) { Mat g0 = kernel_tm_pack4.channel(q / 4); for (int k = 0; k < 36; k++) { float* g00 = g0.row<float>(k); for (int p = 0; p + (4 - 1) < inch; p += 4) { for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { const float* k00 = kernel_tm.channel(q + j).row(p + i); g00[0] = (float)k00[k]; g00++; } } } } } } static void conv3x3s1_winograd43_pack4_msa(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel_tm, const Mat& bias, const Option& opt) { int w = bottom_blob.w; int h = bottom_blob.h; int inch = bottom_blob.c; size_t elemsize = bottom_blob.elemsize; int elempack = bottom_blob.elempack; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; // pad to 4n+2 Mat bottom_blob_bordered = bottom_blob; outw = (outw + 3) / 4 * 4; outh = (outh + 3) / 4 * 4; w = outw + 2; h = outh + 2; copy_make_border(bottom_blob, bottom_blob_bordered, 0, h - bottom_blob.h, 0, w - bottom_blob.w, BORDER_CONSTANT, 0.f, opt); // BEGIN transform input Mat bottom_blob_tm; { int w_tiles = outw / 4; int h_tiles = outh / 4; const int tiles = w_tiles * h_tiles; bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); conv3x3s1_winograd43_transform_input_pack4_msa(bottom_blob_bordered, bottom_blob_tm, opt); } bottom_blob_bordered = Mat(); // END transform input // BEGIN dot Mat top_blob_tm; { int w_tm = outw / 4 * 6; int h_tm = outh / 4 * 6; const int tiles = h_tm / 6 * w_tm / 6; // permute // bottom_blob_tm.create(tiles, 36, inch, elemsize, elempack, opt.workspace_allocator); Mat bottom_blob_tm2; if (tiles >= 12) bottom_blob_tm2.create(12 * inch, tiles / 12 + (tiles % 12) / 8 + (tiles % 12 % 8) / 4 + (tiles % 12 % 4) / 2 + tiles % 12 % 2, 36, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 8) bottom_blob_tm2.create(8 * inch, tiles / 8 + (tiles % 8) / 4 + (tiles % 4) / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 4) bottom_blob_tm2.create(4 * inch, tiles / 4 + (tiles % 4) / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator); else if (tiles >= 2) bottom_blob_tm2.create(2 * inch, tiles / 2 + tiles % 2, 36, 4u * elempack, elempack, opt.workspace_allocator); else // if (tiles >= 1) bottom_blob_tm2.create(1 * inch, tiles, 36, 4u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int r = 0; r < 36; r++) { Mat tm2 = bottom_blob_tm2.channel(r); // tile int i = 0; for (; i + 11 < tiles; i += 12) { float* tmpptr = tm2.row(i / 12); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4f32 _r4 = (v4f32)__msa_ld_w(r0 + 4 * 4, 0); v4f32 _r5 = (v4f32)__msa_ld_w(r0 + 4 * 5, 0); v4f32 _r6 = (v4f32)__msa_ld_w(r0 + 4 * 6, 0); v4f32 _r7 = (v4f32)__msa_ld_w(r0 + 4 * 7, 0); v4f32 _r8 = (v4f32)__msa_ld_w(r0 + 4 * 8, 0); v4f32 _r9 = (v4f32)__msa_ld_w(r0 + 4 * 9, 0); v4f32 _ra = (v4f32)__msa_ld_w(r0 + 4 * 10, 0); v4f32 _rb = (v4f32)__msa_ld_w(r0 + 4 * 11, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v4i32 _r45r = __msa_ilvr_w((v4i32)_r5, (v4i32)_r4); v4i32 _r45l = __msa_ilvl_w((v4i32)_r5, (v4i32)_r4); v4i32 _r67r = __msa_ilvr_w((v4i32)_r7, (v4i32)_r6); v4i32 _r67l = __msa_ilvl_w((v4i32)_r7, (v4i32)_r6); v4i32 _r89r = __msa_ilvr_w((v4i32)_r9, (v4i32)_r8); v4i32 _r89l = __msa_ilvl_w((v4i32)_r9, (v4i32)_r8); v4i32 _rabr = __msa_ilvr_w((v4i32)_rb, (v4i32)_ra); v4i32 _rabl = __msa_ilvl_w((v4i32)_rb, (v4i32)_ra); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r4567_0 = __msa_ilvr_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_1 = __msa_ilvl_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_2 = __msa_ilvr_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r4567_3 = __msa_ilvl_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r89ab_0 = __msa_ilvr_d((v2i64)_rabr, (v2i64)_r89r); v2i64 _r89ab_1 = __msa_ilvl_d((v2i64)_rabr, (v2i64)_r89r); v2i64 _r89ab_2 = __msa_ilvr_d((v2i64)_rabl, (v2i64)_r89l); v2i64 _r89ab_3 = __msa_ilvl_d((v2i64)_rabl, (v2i64)_r89l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r4567_0, tmpptr + 4, 0); __msa_st_w((v4i32)_r89ab_0, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4 * 3, 0); __msa_st_w((v4i32)_r4567_1, tmpptr + 4 * 4, 0); __msa_st_w((v4i32)_r89ab_1, tmpptr + 4 * 5, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 6, 0); __msa_st_w((v4i32)_r4567_2, tmpptr + 4 * 7, 0); __msa_st_w((v4i32)_r89ab_2, tmpptr + 4 * 8, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 9, 0); __msa_st_w((v4i32)_r4567_3, tmpptr + 4 * 10, 0); __msa_st_w((v4i32)_r89ab_3, tmpptr + 4 * 11, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 48; } } for (; i + 7 < tiles; i += 8) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x8 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4f32 _r4 = (v4f32)__msa_ld_w(r0 + 4 * 4, 0); v4f32 _r5 = (v4f32)__msa_ld_w(r0 + 4 * 5, 0); v4f32 _r6 = (v4f32)__msa_ld_w(r0 + 4 * 6, 0); v4f32 _r7 = (v4f32)__msa_ld_w(r0 + 4 * 7, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v4i32 _r45r = __msa_ilvr_w((v4i32)_r5, (v4i32)_r4); v4i32 _r45l = __msa_ilvl_w((v4i32)_r5, (v4i32)_r4); v4i32 _r67r = __msa_ilvr_w((v4i32)_r7, (v4i32)_r6); v4i32 _r67l = __msa_ilvl_w((v4i32)_r7, (v4i32)_r6); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r4567_0 = __msa_ilvr_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_1 = __msa_ilvl_d((v2i64)_r67r, (v2i64)_r45r); v2i64 _r4567_2 = __msa_ilvr_d((v2i64)_r67l, (v2i64)_r45l); v2i64 _r4567_3 = __msa_ilvl_d((v2i64)_r67l, (v2i64)_r45l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r4567_0, tmpptr + 4, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r4567_1, tmpptr + 4 * 3, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 4, 0); __msa_st_w((v4i32)_r4567_2, tmpptr + 4 * 5, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 6, 0); __msa_st_w((v4i32)_r4567_3, tmpptr + 4 * 7, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 32; } } for (; i + 3 < tiles; i += 4) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x4 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4f32 _r2 = (v4f32)__msa_ld_w(r0 + 4 * 2, 0); v4f32 _r3 = (v4f32)__msa_ld_w(r0 + 4 * 3, 0); v4i32 _r01r = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01l = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); v4i32 _r23r = __msa_ilvr_w((v4i32)_r3, (v4i32)_r2); v4i32 _r23l = __msa_ilvl_w((v4i32)_r3, (v4i32)_r2); v2i64 _r0123_0 = __msa_ilvr_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_1 = __msa_ilvl_d((v2i64)_r23r, (v2i64)_r01r); v2i64 _r0123_2 = __msa_ilvr_d((v2i64)_r23l, (v2i64)_r01l); v2i64 _r0123_3 = __msa_ilvl_d((v2i64)_r23l, (v2i64)_r01l); __msa_st_w((v4i32)_r0123_0, tmpptr, 0); __msa_st_w((v4i32)_r0123_1, tmpptr + 4, 0); __msa_st_w((v4i32)_r0123_2, tmpptr + 4 * 2, 0); __msa_st_w((v4i32)_r0123_3, tmpptr + 4 * 3, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 16; } } for (; i + 1 < tiles; i += 2) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { // transpose 4x2 v4f32 _r0 = (v4f32)__msa_ld_w(r0, 0); v4f32 _r1 = (v4f32)__msa_ld_w(r0 + 4, 0); v4i32 _r01_0 = __msa_ilvr_w((v4i32)_r1, (v4i32)_r0); v4i32 _r01_1 = __msa_ilvl_w((v4i32)_r1, (v4i32)_r0); __msa_st_w((v4i32)_r01_0, tmpptr, 0); __msa_st_w((v4i32)_r01_1, tmpptr + 4, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 8; } } for (; i < tiles; i++) { float* tmpptr = tm2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* r0 = bottom_blob_tm; r0 += (r * tiles + i) * 4; for (int q = 0; q < inch; q++) { v4f32 _val = (v4f32)__msa_ld_w(r0, 0); __msa_st_w((v4i32)_val, tmpptr, 0); r0 += bottom_blob_tm.cstep * 4; tmpptr += 4; } } } bottom_blob_tm = Mat(); // permute end top_blob_tm.create(tiles, 36, outch, 4u * elempack, elempack, opt.workspace_allocator); #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < outch; p++) { float* output0_tm = top_blob_tm.channel(p); const Mat kernel0_tm = kernel_tm.channel(p); for (int r = 0; r < 36; r++) { const Mat bb2 = bottom_blob_tm2.channel(r); int i = 0; for (; i + 11 < tiles; i += 12) { const float* r0 = bb2.row(i / 12); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); v4f32 _sum4 = (v4f32)__msa_fill_w(0); v4f32 _sum5 = (v4f32)__msa_fill_w(0); v4f32 _sum6 = (v4f32)__msa_fill_w(0); v4f32 _sum7 = (v4f32)__msa_fill_w(0); v4f32 _sum8 = (v4f32)__msa_fill_w(0); v4f32 _sum9 = (v4f32)__msa_fill_w(0); v4f32 _suma = (v4f32)__msa_fill_w(0); v4f32 _sumb = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 48); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4i32 _val4567 = __msa_ld_w(r0 + 4, 0); v4i32 _val89ab = __msa_ld_w(r0 + 8, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); _sum4 = __msa_fmadd_w(_sum4, (v4f32)__msa_splati_w(_val4567, 0), _w0); _sum5 = __msa_fmadd_w(_sum5, (v4f32)__msa_splati_w(_val4567, 1), _w0); _sum6 = __msa_fmadd_w(_sum6, (v4f32)__msa_splati_w(_val4567, 2), _w0); _sum7 = __msa_fmadd_w(_sum7, (v4f32)__msa_splati_w(_val4567, 3), _w0); _sum8 = __msa_fmadd_w(_sum8, (v4f32)__msa_splati_w(_val89ab, 0), _w0); _sum9 = __msa_fmadd_w(_sum9, (v4f32)__msa_splati_w(_val89ab, 1), _w0); _suma = __msa_fmadd_w(_suma, (v4f32)__msa_splati_w(_val89ab, 2), _w0); _sumb = __msa_fmadd_w(_sumb, (v4f32)__msa_splati_w(_val89ab, 3), _w0); r0 += 12; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); __msa_st_w((v4i32)_sum4, output0_tm + 4 * 4, 0); __msa_st_w((v4i32)_sum5, output0_tm + 4 * 5, 0); __msa_st_w((v4i32)_sum6, output0_tm + 4 * 6, 0); __msa_st_w((v4i32)_sum7, output0_tm + 4 * 7, 0); __msa_st_w((v4i32)_sum8, output0_tm + 4 * 8, 0); __msa_st_w((v4i32)_sum9, output0_tm + 4 * 9, 0); __msa_st_w((v4i32)_suma, output0_tm + 4 * 10, 0); __msa_st_w((v4i32)_sumb, output0_tm + 4 * 11, 0); output0_tm += 4 * 12; } for (; i + 7 < tiles; i += 8) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); v4f32 _sum4 = (v4f32)__msa_fill_w(0); v4f32 _sum5 = (v4f32)__msa_fill_w(0); v4f32 _sum6 = (v4f32)__msa_fill_w(0); v4f32 _sum7 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 32); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4i32 _val4567 = __msa_ld_w(r0 + 4, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); _sum4 = __msa_fmadd_w(_sum4, (v4f32)__msa_splati_w(_val4567, 0), _w0); _sum5 = __msa_fmadd_w(_sum5, (v4f32)__msa_splati_w(_val4567, 1), _w0); _sum6 = __msa_fmadd_w(_sum6, (v4f32)__msa_splati_w(_val4567, 2), _w0); _sum7 = __msa_fmadd_w(_sum7, (v4f32)__msa_splati_w(_val4567, 3), _w0); r0 += 8; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); __msa_st_w((v4i32)_sum4, output0_tm + 4 * 4, 0); __msa_st_w((v4i32)_sum5, output0_tm + 4 * 5, 0); __msa_st_w((v4i32)_sum6, output0_tm + 4 * 6, 0); __msa_st_w((v4i32)_sum7, output0_tm + 4 * 7, 0); output0_tm += 4 * 8; } for (; i + 3 < tiles; i += 4) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); v4f32 _sum2 = (v4f32)__msa_fill_w(0); v4f32 _sum3 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 16); __builtin_prefetch(k0 + 16); v4i32 _val0123 = __msa_ld_w(r0, 0); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, (v4f32)__msa_splati_w(_val0123, 0), _w0); _sum1 = __msa_fmadd_w(_sum1, (v4f32)__msa_splati_w(_val0123, 1), _w0); _sum2 = __msa_fmadd_w(_sum2, (v4f32)__msa_splati_w(_val0123, 2), _w0); _sum3 = __msa_fmadd_w(_sum3, (v4f32)__msa_splati_w(_val0123, 3), _w0); r0 += 4; k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); __msa_st_w((v4i32)_sum2, output0_tm + 4 * 2, 0); __msa_st_w((v4i32)_sum3, output0_tm + 4 * 3, 0); output0_tm += 4 * 4; } for (; i + 1 < tiles; i += 2) { const float* r0 = bb2.row(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2); const float* k0 = kernel0_tm.row(r); int nn = inch * 4; // inch always > 0 v4f32 _sum0 = (v4f32)__msa_fill_w(0); v4f32 _sum1 = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 8); __builtin_prefetch(k0 + 16); v4f32 _val0 = __msa_fill_w_f32(*r0++); v4f32 _val1 = __msa_fill_w_f32(*r0++); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum0 = __msa_fmadd_w(_sum0, _val0, _w0); _sum1 = __msa_fmadd_w(_sum1, _val1, _w0); k0 += 4; } __msa_st_w((v4i32)_sum0, output0_tm, 0); __msa_st_w((v4i32)_sum1, output0_tm + 4, 0); output0_tm += 4 * 2; } for (; i < tiles; i++) { const float* r0 = bb2.row<const float>(i / 12 + (i % 12) / 8 + (i % 12 % 8) / 4 + (i % 12 % 4) / 2 + i % 12 % 2); const float* k0 = kernel0_tm.row<const float>(r); int nn = inch * 4; // inch always > 0 v4f32 _sum = (v4f32)__msa_fill_w(0); for (int j = 0; j < nn; j++) { __builtin_prefetch(r0 + 4); __builtin_prefetch(k0 + 16); v4f32 _val0 = __msa_fill_w_f32(*r0++); v4f32 _w0 = (v4f32)__msa_ld_w(k0, 0); _sum = __msa_fmadd_w(_sum, _val0, _w0); k0 += 4; } __msa_st_w((v4i32)_sum, output0_tm, 0); output0_tm += 4; } } } } bottom_blob_tm = Mat(); // END dot // BEGIN transform output Mat top_blob_bordered; if (outw == top_blob.w && outh == top_blob.h) { top_blob_bordered = top_blob; } else { top_blob_bordered.create(outw, outh, outch, elemsize, elempack, opt.workspace_allocator); } { conv3x3s1_winograd43_transform_output_pack4_msa(top_blob_tm, top_blob_bordered, bias, opt); } // END transform output // cut result pad copy_cut_border(top_blob_bordered, top_blob, 0, top_blob_bordered.h - top_blob.h, 0, top_blob_bordered.w - top_blob.w, opt); }
diffusion.h
// // diffusion.h // // // Created by Ibrahim Harrane on 11/05/2016. // // #ifndef diffusion_h #define diffusion_h /* * * L: Desired parameter lenght * N: Number of nodes * K: Number of iterations * * * A: N x N * C: N x N * w_0 L x N * u L x N x K * d K x N * mu N x 1 * H L x N x K * H_grad L x N x K * M 1 x 1 * M_grad 1 x 1 * w* L x 1 */ #include "mex.h" #include "math.h" #include <string.h> //#include <omp.h> #if defined(NAN_EQUALS_ZERO) #define IsNonZero(d) ((d)!=0.0 || mxIsNaN(d)) #else #define IsNonZero(d) ((d)!=0.0) #endif double dotProduct(double *x, double *y, mwSize n) { mwSize i; double z=0; for (i=0; i<n; i++) { z += (*(x+i)) * (*(y+i)); } return z; } void arrayProduct(double x, double *y, double *z, mwSize n) { mwSize i; /* multiply each element y by x */ for (i=0; i<n; i++) { *(z+i) = x * (*(y+i)); } } void arraySum(double *x, double *y, double *z, mwSize n) { mwSize i; /* add each element y to x */ for (i=0; i<n; i++) { *(z+i) = *(x+i) + (*(y+i)); } } void ATC_RMT_theo(mwSize N, mwSize L, int K, double *tw_0, double *A, double *mu, double *B, double *B_noise, mxArray *options, double *MSD, double *err) { mwSize i,j,k,m,l; double *tw_t, *tw, *Met,*Met_add,*Met_mult; /* Memory allocation */ tw_t=mxMalloc(L*N*sizeof(double)); tw=mxMalloc(L*N*sizeof(double)); Met=mxMalloc(L*sizeof(double)); Met_add=mxMalloc(L*sizeof(double)); Met_mult=mxMalloc(L*sizeof(double)); //MSD_temp=mxMalloc(L*sizeof(double)); memcpy(tw,tw_0,L*N*sizeof(double)); memset (Met,0,L*sizeof(double)); memset (MSD,0,K*N*sizeof(double)); for(m=0; m<L ;m++) { Met_add[m]=1; Met_mult[m]=1; } // for(m=0; m<L ;m++) // { // mexPrintf("Met[%d]= %f \n",m,Met_add[m]); // } for(k=0;k<K;k++) { for(m=0; m<L ;m++) { Met[m]=(1-mu[1]*B[m+L*1])*(1-mu[1]*B[m+L*1]); Met_mult[m]*=Met[m]; Met_add[m] += Met_mult[m]; //Met_add[m + j*L + l*(L*N) + i*(L*N*N) ] += pow(Met[m ],k+1); } //mexPrintf("Met OK \n \n"); // for(m=0; m<L ;m++) // { // mexPrintf("Met[%d]= %f \n",m,Met_add[m]); // } memcpy(tw_t,tw,L*N*sizeof(double)); for (i=0;i<N;i++) { err[k+K*i]=0; for (m=0;m<L;m++) { err[k+K*i]+= fabs(tw_t[m+i*L])/L; } //mexPrintf("err[%d]=%f \n \n",k,err[k+K*i]); //memset (tw+i*L,0,L*sizeof(double)); for(m=0; m<L ;m++) { tw[m+i*L] = 0 ; } for (j=0;j<N;j++) { //err_mean(:,j)= err_mean(:,j) + A(k,j)*(err_mean_t(:,k).*(ones(L,1)-mu(k)*lambda_mean')) for(m=0; m<L ;m++) if (IsNonZero(A[j+N*i])) { { tw[m+i*L] += A[j+N*i] *( tw_t[m+L*j]*(1-mu[j]*B[m+L*j]) ) ; } } } //mexPrintf("afer err[%d]=%f \n \n",k,err[k+K*i]); //mexPrintf("tw OK \n \n"); //mexPrintf("err OK \n \n"); for (j=0;j<N ; j++) { for (l=0; l<N; l++) { if (IsNonZero(A[j+N*i]) && IsNonZero(A[l+N*i]) ) { for(m=0; m<L ;m++) { Met[m]=(1-mu[j]*B[m+L*j])*(1-mu[l]*B[m+L*l]); MSD[k+K*i] += A[j+N*i]*A[l+N*i]*tw_t[m+L*j]*tw_t[m+L*l]*Met[m]+(1.0/N)*A[j+N*i]*A[l+N*i]*mu[j]*mu[l]*B_noise[m+L*i]*Met_add[m]; } } } } //mexPrintf("MSD OK \n \n"); mexPrintf("iter: %d \t node %d \n",k,i); } //mexPrintf("iter: %d \n",k); } mxFree(tw_t); mxFree(tw); mxFree(Met); mxFree(Met_add); mxFree(Met_mult); } void ATC_RMT(mwSize N, mwSize L, int K, double *w_0, double *A, double *mu, double *e, double *err, double *w_k, double *w_star, mxArray *options) { mwSize i,j,k,m,iter_batch; mwIndex index; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i,*Lambda,*noise; mxArray *output_get_data[3], *input_get_data[1]; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*N*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //Lambda=mxMalloc(L*sizeof(double)); //noise=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); output_get_data[2]=options; iter_batch=mxGetScalar(mxGetField(options,0,"iter_batch")); //mexPrintf("iter_batch=%d \n",iter_batch); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } err[k+K*i]=0; for (m=0;m<L;m++) { err[k+K*i]+= fabs(w_star[m] - w_k[L*i+m])/L; } //mexPrintf("tw[%d]=%f \n \n",k,err[k+K*i]); } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*N*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); if ((k % iter_batch)==0) { mexCallMATLAB( 3 , output_get_data, 1, &output_get_data[2] , "get_data_c"); Lambda=mxGetPr(output_get_data[0]); noise=mxGetPr(output_get_data[1]); } //mexPrintf("mexcallMATLAB ok \n"); for (i=0;i<N;i++) { //if (IsNonZero(C[j+N*i])) //{ //phi=mu(i)*(uk*uk')*(w_star -W(:,i)) //#pragma omp parallel for for(m=0; m<L ;m++) { phi[m+L*i] = w_k[L*i+m] + mu[i]*Lambda[m+L*(k % iter_batch)]*(w_star[m] - w_k[L*i+m])+(1.0/N)*mu[i]*noise[m+L*(k % iter_batch)]; } //} } //w_k=0 memset (w_k,0,L*N*sizeof(double)); //#pragma omp parallel for for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[m+L*j]; //w_k[L*i+m]=Lambda[m]; //mexPrintf("W_K[%d,%d] = %f \n ",i,j,w_k[L*i+m]); } } } } mexPrintf("iter %d \n",k); } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); //mxFree(Lambda); //mxFree(noise); } /* ATC diffusion */ void ATC2(mwSize N, mwSize L, mwSize K, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *e, double *w_k) { mwSize i,j,k,m; double *phi,*s,*u_j,*phi_j,p,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 for(m=0;m<L;m++) { for(j=0;j<N;j++) { *(w_k+m+j*L)= *(w_0+m+j*L); } } for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 *(e+i*K+k)=0; // e(k,i)=norm(w_star-w_k(:,i),2)^2; for(m=0;m<L;m++) { *(e+k+i*K)+=(*(w_star+m)-(*(w_k+L*i+m)))*(*(w_star+m)-(*(w_k+L*i+m))); } } /* intermediate estmeate Phi calculation */ for (i=0;i<N;i++) { //s=0 //w_i=w(:,i) //phi(:,i)=w_i for(m=0;m<L;m++) { *(s+m)=0; *(w_i+m)=*(w_k+L*i+m); *(phi+L*i+m)=*(w_i+m); } for(j=0;j<N;j++) { //u_j=u(:,j,k) for(m=0; m<L ;m++) { *(u_j+m)=*(u+m+j*L+k*(N*L)); } //p=u_j'*w_i p=dotProduct(u_j,w_i,L); //p=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p=(*(mu+i))*(*(C+j+N*i))*(*(d+k+K*j)-p); //res=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i) arrayProduct(p,u_j, res ,L); //s=s+mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i) for(m=0;m<L;m++) { *(s+m)+= *(res+m); } } //phi(:,i)=w_i+s for(m=0;m<L;m++) { *(phi+m+L*i)+=*(s+m); } } for(i=0;i<N;i++) { //w(:,i)=0 for(m=0;m<L;m++) { *(w_k+m+i*L)=0; } //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { for(m=0;m<L;m++) { *(w_k+L*i+m)+= (*(A+j+N*i))*(*(phi+m+L*j)); } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* ATC diffusion */ void ATC(mwSize N, mwSize L, mwSize K, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *e, double *w_k) { mwSize i,j,k,m; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*N*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*N*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_k[L*i+m]; } //p=En(k,i)*mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=mu[i]*C[j+N*i]*(d[k+K*j]-p); //phi(:,i)+=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i)=s+mu(i)*C(j,i)*u_j*p2 for(m=0;m<L;m++) { phi[m+L*i] += u[m+j*L+k*(N*L)]*p2; } } } } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[m+L*j]; } } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* compressed diffusion2 */ void compressed_diffusion2(mwSize N, mwSize L, mwSize K, mwSize M, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *e, double *w_k) { mwSize i,j,k,m,idx; double *phi,*s,*u_j,*phi_j,p,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 for(m=0;m<L;m++) { for(j=0;j<N;j++) { *(w_k+m+j*L)= *(w_0+m+j*L); } } for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 *(e+i*K+k)=0; // e(k,i)=norm(w_star-w_k(:,i),2)^2; for(m=0;m<L;m++) { *(e+k+i*K)+=(*(w_star+m)-(*(w_k+L*i+m)))*(*(w_star+m)-(*(w_k+L*i+m))); } } /* intermediate estmeate Phi calculation */ for (i=0;i<N;i++) { //s=0 //w_i=w(:,i) //phi(:,i)=w_i for(m=0;m<L;m++) { *(s+m)=0; *(w_i+m)=*(w_k+L*i+m); *(phi+L*i+m)=*(w_i+m); } for(j=0;j<N;j++) { //w_i(idx(M+1:end))=w(M+1:end,j) for(m=M; m<L ;m++) { idx=*(H+m+L*i+k*(N*L))-1; *(w_i+idx)=*(w_k+L*j+idx); } //u_j=u(:,j,k) for(m=0; m<L ;m++) { *(u_j+m)=*(u+m+j*L+k*(N*L)); } //p=u_j'*w_i p=dotProduct(u_j,w_i,L); //p=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p=(*(mu+i))*(*(C+j+N*i))*(*(d+k+K*j)-p); //res=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i) arrayProduct(p,u_j, res ,L); //s=s+mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i) for(m=0;m<L;m++) { *(s+m)+= *(res+m); } } //phi(:,i)=w_i+s for(m=0;m<L;m++) { *(phi+m+L*i)+=*(s+m); } } for(i=0;i<N;i++) { //w(:,i)=0 for(m=0;m<L;m++) { *(w_k+m+i*L)=0; } //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { for(m=0;m<L;m++) { *(w_k+L*i+m)+= (*(A+j+N*i))*(*(phi+m+L*j)); } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* ATC diffusion with energy consideration */ void ATC_En(mwSize N, mwSize L, mwSize K, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u,double *En, double *e, double *w_k) { mwSize i,j,k,m; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*N*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*N*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_k[L*i+m]; } //p=En(k,i)*mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=En[k+K*i]*En[k+K*j]*mu[i]*C[j+N*i]*(d[k+K*j]-p); //phi(:,i)+=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i)=s+mu(i)*C(j,i)*u_j*p2 for(m=0;m<L;m++) { phi[m+L*i] += u[m+j*L+k*(N*L)]*p2; } } } } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[m+L*j]; } } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /*compressed diffusion */ void compressed_diffusion (mwSize N, mwSize L, mwSize K, mwSize M, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *e, double *w_k) { mwSize i,j,k,m,idx; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i, *phi_t, *w_temp; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); phi_t=mxMalloc(L*sizeof(double)); w_temp=mxMalloc(L*N*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //w_i=w(:,i) //memcpy(w_i, w_k+L*i*sizeof(double),L*sizeof(double)); for(m=0;m<L;m++) { w_i[m]=w_k[L*i+m]; } for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //w_k(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m<L ;m++) { idx=H[m+L*i+k*(N*L)]-1; w_i[idx]=w_k[L*j+idx]; } //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_i[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=mu[i]*C[j+N*i]*(d[k+K*j]-p); //phi(:,i)+=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i)=s+mu(i)*C(j,i)*u_j*p2 for(m=0;m<L;m++) { phi[m+L*i] += u[m+j*L+k*(N*L)]*p2; } } } } memcpy(w_temp, w_k,L*N*sizeof(double)); //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { phi_t[m]=w_temp[L*j+m]; } //w_t(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m< L ;m++) { idx=H[m+L*j+k*(N*L)]-1; phi_t[idx]=phi[L*i+idx]; } if (i!=j) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi_t[m]; } } else { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[L*i+m]; } } } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); mxFree(phi_t); mxFree(w_temp); } /*compressed diffusion with energy consideration */ void compressed_diffusion_En (mwSize N, mwSize L, mwSize K, mwSize M, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *En, double *e, double *w_k) { mwSize i,j,k,m,idx; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //w_i=w(:,i) //memcpy(w_i, w_k+L*i*sizeof(double),L*sizeof(double)); for(m=0;m<L;m++) { w_i[m]=w_k[L*i+m]; } for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //w_k(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m<L ;m++) { idx=H[m+L*i+k*(N*L)]-1; w_i[idx]=w_k[L*j+idx]; } //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_i[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=En[k+K*i]*En[k+K*j]*mu[i]*C[j+N*i]*(d[k+K*j]-p); //phi(:,i)+=mu(i)*C(j,i)*u_j*(d(k,j))-u_j'*w_i)=s+mu(i)*C(j,i)*u_j*p2 for(m=0;m<L;m++) { phi[m+L*i] += u[m+j*L+k*(N*L)]*p2; } } } } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[m+L*j]; } } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* doubly compressed Diffusion2 */ void doubly_compressed_diffusion2(mwSize N, mwSize L, mwSize K, mwSize M, mwSize M_grad, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *H_grad, double *e, double *w_k) { mwSize i,j,k,m,idx,idx_grad; double *grad, *grad_i, *s, *u_j, *phi_j, p, *res, *w_i; /* Memory allocation */ grad=mxMalloc(L*N*sizeof(double)); grad_i=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 for(m=0;m<L;m++) { for(j=0;j<N;j++) { *(w_k+m+j*L)= *(w_0+m+j*L); } } for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 *(e+i*K+k)=0; // e(k,i)=norm(w_star-w_k(:,i),2)^2; for(m=0;m<L;m++) { *(e+k+i*K)+=(*(w_star+m)-(*(w_k+L*i+m)))*(*(w_star+m)-(*(w_k+L*i+m))); } } for (i=0;i<N;i++) { //s=0 //w_i=w(:,i) for(m=0;m<L;m++) { *(s+m)=0; *(w_i+m)=*(w_k+L*i+m); } for(j=0;j<N;j++) { //w_i(idx(M+1:end))=w(M+1:end,j) for(m=M; m<L ;m++) { idx=*(H+m+L*i+k*(N*L))-1; *(w_i+idx)=*(w_k+L*j+idx); *(grad+m+j*L)=0; } //u_j=u(:,j,k) for(m=0; m<L ;m++) { *(u_j+m)=*(u+m+j*L+k*(N*L)); } //p=u_j'*w_i p=dotProduct(u_j,w_i,L); //p=C(j,i)*(d(k,j))-u_j'*w_i) p=(*(C+j+N*i))*(*(d+k+K*j)-p); //res=C(j,i)*u_j*(d(k,j))-u_j'*w_i) arrayProduct(p, u_j, res, L); //grad(:,j)=res(:) for(m=0;m<L;m++) { *(grad+m+j*L)= *(res+m); } } //grad_i=grad(:,i) for(m=0;m<L;m++) { *(grad_i+m)=*(grad+m+L*i); } for(j=0;j<N;j++) { //grad_i(idx(M+1:end))=w(M+1:end,j) for(m=M_grad; m<L ;m++) { idx_grad=*(H_grad+m+L*i+k*(N*L))-1; *(grad_i+idx_grad)=*(grad+idx_grad+L*j); } //s=s+mu(i)*C(j,i)*u_j*grad_p for(m=0;m<L;m++) { *(s+m)+= (*(mu+i))*(*(grad_i+m)); } } //w_k(:,i)=w_k+s for(m=0;m<L;m++) { *(w_k+m+L*i)+=*(s+m); } } } mxFree(grad); mxFree(grad_i); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* doubly compressed Diffusion */ void doubly_compressed_diffusion(mwSize N, mwSize L, mwSize K, mwSize M, mwSize M_grad, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *H_grad, double *e, double *w_k) { mwSize i,j,k,m,idx,idx_grad; double *grad, *grad_i, *phi, *phi_i, *phi_t,*s,*u_j,*phi_j,p,p2,*res,*w_i,*w_t,*grad_l,*grad_e, *w_temp; /* Memory allocation */ grad=mxMalloc(L*N*sizeof(double)); grad_e=mxMalloc(L*sizeof(double)); grad_l=mxMalloc(L*sizeof(double)); grad_i=mxMalloc(L*sizeof(double)); phi=mxMalloc(L*N*sizeof(double)); phi_i=mxMalloc(L*sizeof(double)); phi_t=mxMalloc(L*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); w_t=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); w_temp=mxMalloc(N*L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //phi=w_k memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //w_i=w(:,i) //memcpy(w_i, w_k+L*i*sizeof(double),L*sizeof(double)); for(m=0;m<L;m++) { w_i[m]=w_k[L*i+m]; w_t[m]=w_k[L*i+m]; } //s=0 memset(s,0,L*sizeof(double)); //grad=0; memset(grad,0,L*N*sizeof(double)); for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //w_k(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m<L ;m++) { idx=H[m+L*i+k*(N*L)]-1; w_t[idx]=w_k[L*j+idx]; } //p=u_j'*w_t p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_t[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=C[j+N*i]*(d[k+K*j]-p); //grad_e=C(j,i)*(u(k,:,j)'*(d(k,j) - u(k,:,j)*W_p)); for(m=0;m<L;m++) { grad_e[m] = u[m+j*L+k*(N*L)]*p2; } //p=u_i'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*w_i[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=C[j+N*i]*(d[k+K*i]-p); //grad_l=C(j,i)*(u(k,:,i)'*(d(k,j) - u(k,:,i)*W_p)); for(m=0;m<L;m++) { grad_l[m] = u[m+i*L+k*(N*L)]*p2; } for(m=0;m<L;m++) { grad_i[m]=grad_e[m]; } //if (IsNonZero(C[j+N*i])) //grad_i(idx(M+1:end))=grad(M+1:end,j) for(m=M_grad; m<L ;m++) { idx_grad=H_grad[m+L*j+k*(N*L)]-1; grad_i[idx_grad]=grad_l[idx_grad]; } //s=s+mu(i)*C(j,i)*u_j*grad_p for(m=0;m<L;m++) { s[m]+= mu[i]*grad_i[m]; } } } //w_k(:,i)=w_k+s for(m=0;m<L;m++) { phi[m+L*i]+=s[m]; } } memcpy(w_temp, w_k,L*N*sizeof(double)); //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { for(m=0;m<L;m++) { phi_t[m]=w_temp[L*j+m]; } //w_t(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m< L ;m++) { idx=H[m+L*j+k*(N*L)]-1; phi_t[idx]=phi[L*i+idx]; } if (i!=j) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi_t[m]; } } else { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi[L*i+m]; } } } } } } mxFree(grad); mxFree(grad_e); mxFree(grad_l); mxFree(grad_i); mxFree(phi); mxFree(phi_i); mxFree(phi_t); mxFree(s); mxFree(u_j); mxFree(w_i); mxFree(w_t); mxFree(res); mxFree(w_temp); } /* doubly compressed Diffusion with energy consideration */ void doubly_compressed_diffusion_En(mwSize N, mwSize L, mwSize K, mwSize M, mwSize M_grad, double *w_star, double *w_0, double *A, double *C, double *mu, double *d, double *u, double *H, double *H_grad, double *En, double *e, double *w_k) { mwSize i,j,k,m,idx,idx_grad; double *grad, *grad_i, *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i,*w_t,*grad_l,*grad_e; /* Memory allocation */ grad=mxMalloc(L*N*sizeof(double)); grad_e=mxMalloc(L*sizeof(double)); grad_l=mxMalloc(L*sizeof(double)); grad_i=mxMalloc(L*sizeof(double)); phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); w_t=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //phi=w_k memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //w_i=w(:,i) //w_t=w(:,i) //memcpy(w_i, w_k+L*i*sizeof(double),L*sizeof(double)); for(m=0;m<L;m++) { w_i[m]=w_k[L*i+m]; w_t[m]=w_k[L*i+m]; } //s=0 memset(s,0,L*sizeof(double)); //grad=0; memset(grad,0,L*N*sizeof(double)); for(j=0;j<N;j++) { if (IsNonZero(C[j+N*i])) { //w_t(idx(M+1:end),i)=w(idx(M+1:end),j) for(m=M; m<L ;m++) { idx=H[m+L*i+k*(N*L)]-1; w_t[idx]=w_k[L*j+idx]; } //p=u_j'*w_t p=0; for(m=0; m<L ;m++) { p +=u[m+j*L+k*(N*L)]*w_t[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=C[j+N*i]*(d[k+K*j]-p); //grad_e=C(j,i)*(u(k,:,j)'*(d(k,j) - u(k,:,j)*W_p)); for(m=0;m<L;m++) { grad_e[m] = u[m+j*L+k*(N*L)]*p2; } //p=u_i'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*w_i[m]; } //p2=mu(i)*C(j,i)*(d(k,j))-u_j'*w_i) p2=En[k+K*j]*C[j+N*i]*(d[k+K*i]-p); //grad_l=C(j,i)*(u(k,:,j)'*(d(k,j) - u(k,:,j)*W_p)); for(m=0;m<L;m++) { grad_l[m] = u[m+i*L+k*(N*L)]*p2; } for(m=0;m<L;m++) { grad_i[m]=grad_e[m]; } //if (IsNonZero(C[j+N*i])) //{ //grad_i(idx(M+1:end))=grad(M+1:end,j) for(m=M_grad; m<L ;m++) { idx_grad=H_grad[m+L*j+k*(N*L)]-1; grad_i[idx_grad]=grad_l[idx_grad]; } //s=s+mu(i)*C(j,i)*u_j*grad_p for(m=0;m<L;m++) { s[m]+= En[k+K*i]* mu[i]*grad_i[m]; } } } //w_k(:,i)=w_k+s for(m=0;m<L;m++) { w_k[m+L*i]+=s[m]; } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* Partial model diffusion 2014*/ void ATC_partial_model(mwSize N, mwSize L, mwSize K, mwSize M, double *w_star, double *w_0, double *A, double *mu, double *d, double *u ,double *H, double *e, double *w_k) { mwSize i,j,k,m, idx; double *phi,*phi_i,*s,*u_j,p,p2,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); phi_i=mxMalloc(L*sizeof(double)); s=mxMalloc(L*N*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*N*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*w_k[L*i+m]; } //p=mu(i)*(d(k,j))-u_j'*w_i) p2=mu[i]*(d[k+K*i]-p); //phi(:,i)+=mu(i)*u_i*(d(k,i))-u_i'*w_i)=s+mu(i)*u_i*p2 for(m=0;m<L;m++) { phi[m+L*i] += u[m+i*L+k*(N*L)]*p2; } } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+ a(j,i)*(H*phi(:,j)+(I-H))*phi(:,i) for(j=0;j<N;j++) { if (IsNonZero(A[j+N*i])) { //phi_i=phi(:,i) for(m=0;m<L;m++) { phi_i[m]=phi[L*i+m]; } //phi_i(idx)=w(idx,j) for(m=0; m<M ;m++) { idx=H[m+L*i+k*(N*L)]-1; phi_i[idx]=phi[L*j+idx]; } for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*phi_i[m]; } } } } } mxFree(phi); mxFree(phi_i); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* Reduced Communication ATC Diffusion Arablouei 2015 */ /* The matrix H here is a N x N x K, it containes scrambled indeces vector for each node, we use it to select a subset of nodes to communicate with. we choose the M first indices.*/ void ATC_RCD(mwSize N, mwSize L, mwSize K, mwSize M, double *w_star, double *w_0, double *A, double *mu, double *d, double *u ,double *H, double *e, double *w_k) { mwSize i,j,k,m; double *phi,*s,*u_j,*phi_j,p,p2,*res,*w_i; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); s=mxMalloc(L*N*sizeof(double)); u_j=mxMalloc(L*sizeof(double)); w_i=mxMalloc(L*sizeof(double)); res=mxMalloc(L*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //s=0 //phi=w_k memset (s,0,L*N*sizeof(double)); memcpy(phi,w_k,L*N*sizeof(double)); for (i=0;i<N;i++) { //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*w_k[L*i+m]; } //p=mu(i)*(d(k,j))-u_j'*w_i) p2=mu[i]*(d[k+K*i]-p); //phi(:,i)+=mu(i)*u_j*(d(k,j))-u_j'*w_i) for(m=0;m<L;m++) { phi[m+L*i] += u[m+i*L+k*(N*L)]*p2; } } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //w(:,i)=w(:,i)+A(j,i)*phi(:,j) for(j=0;j<N;j++) { for(m=0;m<L;m++) { w_k[L*i+m]+= A[j+N*i]*(H[j+N*i+k*(N*N)]*phi[m+L*j]+(1-H[j+N*i+k*(N*N)])*phi[m+L*i]); } } } } mxFree(phi); mxFree(s); mxFree(w_i); mxFree(u_j); mxFree(res); } /* Compressive diffusion ATC sayin 2014 */ /* The confidence parameter is calculated using the equation 78 in the same paper */ /* The matrix H here contain projection vectors for K iteration */ void compressive_diff_ATC(mwSize N, mwSize L, mwSize K, double *w_star, double *w_0, double *A, double *mu, double *d, double *u,double *H, double *eta, double* delta, double mu_cvx, double *e, double *w_k) { mwSize i,j,k,m,n; double *phi, p, p2, *err, *Gamma, *phi_t, *epsilon ,*alpha; /* Memory allocation */ phi=mxMalloc(L*N*sizeof(double)); phi_t=mxMalloc(L*N*sizeof(double)); Gamma=mxMalloc(L*N*sizeof(double)); err=mxMalloc(N*sizeof(double)); epsilon=mxMalloc(N*sizeof(double)); alpha=mxMalloc(N*sizeof(double)); //w_k=w_0 memcpy(w_k,w_0,L*N*sizeof(double)); //alpa=zeros(N,1); memset (alpha,0,N*sizeof(double)); //phi_t=zeros(L,N); memset (phi_t,0,L*N*sizeof(double)); //Gamma=zeros(L,N); memset (Gamma,0,L*N*sizeof(double)); for(k=0;k<K;k++) { /* Error calculation*/ for(i=0;i<N;i++) { // e(k,i)=0 e[k+i*K]=0; for(m=0;m<L;m++) { //#pragma omp critical e[k+i*K]+=(w_star[m]-w_k[L*i+m])*(w_star[m]-w_k[L*i+m]); } } /* intermediate estmeate Phi calculation */ //phi=w_k memcpy(phi,w_k,L*N*sizeof(double)); //epsilon=zeros(N,1); memset (epsilon,0,N*sizeof(double)); for (i=0;i<N;i++) { //p=u_j'*w_i p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*w_k[L*i+m]; } // err(i)=(d(k,i) - u(k,:,i)*W(:,i)) err[i]=(d[k+K*i]-p); //p2=mu(i)*(d(k,j))-u_j'*w_i) p2=mu[i]*err[i]; //phi(:,i)+=mu(i)*u_j*(d(k,j))-u_j'*w_i) for(m=0;m<L;m++) { phi[m+L*i] += u[m+i*L+k*(N*L)]*p2; } //epsilon(i)=H(:,i,k)'*(Phi(:,i)-Gamma(:,i)); for(m=0;m<L;m++) { epsilon[i] += H[m+L*i+k*(N*L)]*(phi[m+L*i]- Gamma[m+L*i]); } //Gamma(:,i)=Gamma(:,i)+eta(i)*H(:,i,k)*epsilon(i); for(m=0;m<L;m++) { Gamma[m+i*L] += eta[i]*H[m+i*L+k*(L*N)]*epsilon[i]; } // p=u(k,:,i)*(Phi(:,i)-Phi_t(:,i)) p=0; for(m=0; m<L ;m++) { p +=u[m+i*L+k*(N*L)]*(phi[m+L*i]-phi_t[m+L*i]); } // alpha(i)=alpha(i)-mu_cvx*err(i)*u(k,:,i)*(Phi(:,i)-Phi_t(:,i))*delta(i)*(1-delta(i)); alpha[i]-=mu_cvx * err[i]*p*delta[i]*(1-delta[i]); // delta(i)=1/(1+exp(-alpha(i))); delta[i]=1/(1+exp(-alpha[i])); } //w_k=0 memset (w_k,0,L*N*sizeof(double)); for(i=0;i<N;i++) { //Phi_t(:,i)=A(i,i)*Phi(:,i); for(m=0; m<L ;m++) { phi_t[m+i*L] =A[i+N*i]*phi[m+i*L]; } for(j=0;j<N;j++) { if(i != j) { if (IsNonZero(A[j+N*i])) { //Phi_t(:,i)=Phi_t(:,i)+A(j,i)*Gamma(:,j); for(m=0; m<L ;m++) { phi_t[m+i*L] += A[j+N*i]*Gamma[m+j*L]; } } } } //W(:,i)=(1-delta(i))*Phi_t(:,i)+delta(i)*Phi(:,i); for(m=0;m<L;m++) { w_k[L*i+m]= (1-delta[i])*phi_t[m+L*i]+delta[i]*phi[m+L*i]; } } } mxFree(phi); mxFree(phi_t); mxFree(Gamma); mxFree(err); mxFree(epsilon); mxFree(alpha); } #endif /* diffusion_h */
volumeramsubset.h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2019 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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. * *********************************************************************************/ #ifndef IVW_VOLUMERAMSUBSET_H #define IVW_VOLUMERAMSUBSET_H #include <modules/base/basemoduledefine.h> #include <inviwo/core/datastructures/volume/volumeramprecision.h> #include <inviwo/core/datastructures/volume/volumeborder.h> namespace inviwo { class IVW_MODULE_BASE_API VolumeRAMSubSet { public: static std::shared_ptr<VolumeRAM> apply(const VolumeRepresentation* in, size3_t dim, size3_t offset, const VolumeBorders& border = VolumeBorders(), bool clampBorderOutsideVolume = true); }; namespace detail { struct IVW_MODULE_BASE_API VolumeRAMSubSetDispatcher { using type = std::shared_ptr<VolumeRAM>; template <typename Result, typename T> std::shared_ptr<VolumeRAM> operator()(const VolumeRepresentation* in, size3_t dim, size3_t offset, const VolumeBorders& border, bool clampBorderOutsideVolume); }; template <typename Result, typename DataType> std::shared_ptr<VolumeRAM> VolumeRAMSubSetDispatcher::operator()(const VolumeRepresentation* in, size3_t dim, size3_t offset, const VolumeBorders& border, bool clampBorderOutsideVolume) { using T = typename DataType::type; const VolumeRAMPrecision<T>* volume = dynamic_cast<const VolumeRAMPrecision<T>*>(in); if (!volume) return nullptr; // determine parameters const size3_t dataDims{volume->getDimensions()}; const size3_t copyDataDims{static_cast<size3_t>(glm::max( static_cast<ivec3>(dim) - glm::max(static_cast<ivec3>(offset + dim) - static_cast<ivec3>(dataDims), ivec3(0)), ivec3(0)))}; ivec3 newOffset_Dims = static_cast<ivec3>(glm::min(offset, dataDims) - border.llf); VolumeBorders trueBorder = VolumeBorders(); VolumeBorders correctBorder = border; if (clampBorderOutsideVolume) { correctBorder.llf += static_cast<size3_t>(-glm::min(newOffset_Dims, ivec3(0, 0, 0))); correctBorder.urb += static_cast<size3_t>( -glm::min(static_cast<ivec3>(dataDims) - static_cast<ivec3>(offset + copyDataDims + correctBorder.urb), ivec3(0, 0, 0))); newOffset_Dims = static_cast<ivec3>(offset - correctBorder.llf); } else { trueBorder.llf = static_cast<size3_t>(-glm::min(newOffset_Dims, ivec3(0, 0, 0))); trueBorder.urb = static_cast<size3_t>( glm::max(static_cast<ivec3>(offset + copyDataDims + correctBorder.urb) - static_cast<ivec3>(dataDims), ivec3(0, 0, 0))); } size3_t newOffset_DimsU = static_cast<size3_t>(glm::max(newOffset_Dims, ivec3(0, 0, 0))); size_t initialStartPos = (newOffset_DimsU.z * (dataDims.x * dataDims.y)) + (newOffset_DimsU.y * dataDims.x) + newOffset_DimsU.x; size3_t dimsWithBorder = dim + correctBorder.llf + correctBorder.urb; size3_t copyDimsWithoutBorder = static_cast<size3_t>( glm::max(static_cast<ivec3>(copyDataDims + correctBorder.llf + correctBorder.urb) - static_cast<ivec3>(trueBorder.llf) - static_cast<ivec3>(trueBorder.urb), ivec3(1, 1, 1))); // per row size_t dataSize = copyDimsWithoutBorder.x * static_cast<size_t>(volume->getDataFormat()->getSize()); // allocate space auto newVolume = std::make_shared<VolumeRAMPrecision<T>>(dim + correctBorder.llf + correctBorder.urb); const T* src = static_cast<const T*>(volume->getData()); T* dst = static_cast<T*>(newVolume->getData()); // memcpy each row for every slice to form sub volume for (int i = 0; i < static_cast<int>(copyDimsWithoutBorder.z); i++) { #pragma omp parallel for for (int j = 0; j < static_cast<int>(copyDimsWithoutBorder.y); j++) { size_t volumePos = (j * dataDims.x) + (i * dataDims.x * dataDims.y); size_t subVolumePos = ((j + trueBorder.llf.y) * dimsWithBorder.x) + ((i + trueBorder.llf.z) * dimsWithBorder.x * dimsWithBorder.y) + trueBorder.llf.x; std::memcpy(dst + subVolumePos, (src + volumePos + initialStartPos), dataSize); } } return newVolume; } } // namespace detail } // namespace inviwo #endif // IVW_VOLUMERAMSUBSET_H
GB_unop__creal_fp32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__creal_fp32_fc32) // op(A') function: GB (_unop_tran__creal_fp32_fc32) // C type: float // A type: GxB_FC32_t // cast: GxB_FC32_t cij = (aij) // unaryop: cij = crealf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = crealf (x) ; // casting #define GB_CAST(z, aij) \ GxB_FC32_t z = (aij) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC32_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ GxB_FC32_t z = (aij) ; \ Cx [pC] = crealf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_CREAL || GxB_NO_FP32 || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__creal_fp32_fc32) ( float *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; if (Ab == NULL) { #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = (aij) ; Cx [p] = crealf (z) ; } } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = (aij) ; Cx [p] = crealf (z) ; } } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_tran__creal_fp32_fc32) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__rdiv_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef 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__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_uint8) // A*D function (colscale): GB (_AxD__rdiv_uint8) // D*A function (rowscale): GB (_DxB__rdiv_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__rdiv_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__rdiv_uint8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_uint8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_uint8) // C=scalar+B GB (_bind1st__rdiv_uint8) // C=scalar+B' GB (_bind1st_tran__rdiv_uint8) // C=A+scalar GB (_bind2nd__rdiv_uint8) // C=A'+scalar GB (_bind2nd_tran__rdiv_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 8) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ uint8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ uint8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IDIV_UNSIGNED (y, x, 8) ; // 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_RDIV || GxB_NO_UINT8 || GxB_NO_RDIV_UINT8) //------------------------------------------------------------------------------ // 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__rdiv_uint8) ( 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__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rdiv_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rdiv_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; uint8_t alpha_scalar ; uint8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((uint8_t *) alpha_scalar_in)) ; beta_scalar = (*((uint8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__rdiv_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__rdiv_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rdiv_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (bij, x, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rdiv_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IDIV_UNSIGNED (y, aij, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 8) ; \ } GrB_Info GB (_bind1st_tran__rdiv_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 8) ; \ } GrB_Info GB (_bind2nd_tran__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unop__identity_uint64_fc64.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_atomics.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB (_unop_apply__identity_uint64_fc64) // op(A') function: GB (_unop_tran__identity_uint64_fc64) // C type: uint64_t // A type: GxB_FC64_t // cast: uint64_t cij = GB_cast_to_uint64_t (creal (aij)) // unaryop: cij = aij #define GB_ATYPE \ GxB_FC64_t #define GB_CTYPE \ uint64_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC64_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CAST(z, aij) \ uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; // cij = op (aij) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GxB_FC64_t aij = Ax [pA] ; \ /* Cx [pC] = op (cast (aij)) */ \ uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; \ Cx [pC] = z ; \ } // true if operator is the identity op with no typecasting #define GB_OP_IS_IDENTITY_WITH_NO_TYPECAST \ 0 // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_UINT64 || GxB_NO_FC64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB (_unop_apply__identity_uint64_fc64) ( uint64_t *Cx, // Cx and Ax may be aliased const GxB_FC64_t *Ax, const int8_t *restrict Ab, // A->b if A is bitmap int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; // TODO: if OP is ONE and uniform-valued matrices are exploited, then // do this in O(1) time if (Ab == NULL) { #if ( GB_OP_IS_IDENTITY_WITH_NO_TYPECAST ) GB_memcpy (Cx, Ax, anz * sizeof (GxB_FC64_t), nthreads) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC64_t aij = Ax [p] ; uint64_t z = GB_cast_to_uint64_t (creal (aij)) ; Cx [p] = z ; } #endif } else { // bitmap case, no transpose; A->b already memcpy'd into C->b #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!Ab [p]) continue ; GxB_FC64_t aij = Ax [p] ; uint64_t z = GB_cast_to_uint64_t (creal (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_uint64_fc64) ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
perftest.c
/** * Copyright (C) Mellanox Technologies Ltd. 2001-2014. ALL RIGHTS RESERVED. * Copyright (C) The University of Tennessee and The University * of Tennessee Research Foundation. 2015. ALL RIGHTS RESERVED. * Copyright (C) UT-Battelle, LLC. 2015. ALL RIGHTS RESERVED. * * See file LICENSE for terms. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "api/libperf.h" #include "lib/libperf_int.h" #include <ucs/sys/string.h> #include <ucs/sys/sys.h> #include <ucs/sys/sock.h> #include <ucs/debug/log.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <netdb.h> #include <getopt.h> #include <string.h> #include <sys/types.h> #include <sys/poll.h> #include <locale.h> #if HAVE_MPI # include <mpi.h> #elif HAVE_RTE # include<rte.h> #endif #define MAX_BATCH_FILES 32 #define TL_RESOURCE_NAME_NONE "<none>" #define TEST_PARAMS_ARGS "t:n:s:W:O:w:D:i:H:oSCqM:r:T:d:x:A:BUm:" enum { TEST_FLAG_PRINT_RESULTS = UCS_BIT(0), TEST_FLAG_PRINT_TEST = UCS_BIT(1), TEST_FLAG_SET_AFFINITY = UCS_BIT(8), TEST_FLAG_NUMERIC_FMT = UCS_BIT(9), TEST_FLAG_PRINT_FINAL = UCS_BIT(10), TEST_FLAG_PRINT_CSV = UCS_BIT(11) }; typedef struct sock_rte_group { int is_server; int connfd; } sock_rte_group_t; typedef struct test_type { const char *name; ucx_perf_api_t api; ucx_perf_cmd_t command; ucx_perf_test_type_t test_type; const char *desc; } test_type_t; struct perftest_context { ucx_perf_params_t params; const char *server_addr; int port; int mpi; unsigned cpu; unsigned flags; unsigned num_batch_files; char *batch_files[MAX_BATCH_FILES]; char *test_names[MAX_BATCH_FILES]; sock_rte_group_t sock_rte_group; }; test_type_t tests[] = { {"am_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_PINGPONG, "active message latency"}, {"put_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency"}, {"add_lat", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_PINGPONG, "atomic add latency"}, {"get", UCX_PERF_API_UCT, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate"}, {"fadd", UCX_PERF_API_UCT, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / rate"}, {"swap", UCX_PERF_API_UCT, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / rate"}, {"cswap", UCX_PERF_API_UCT, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / rate"}, {"am_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_AM, UCX_PERF_TEST_TYPE_STREAM_UNI, "active message bandwidth / message rate"}, {"put_bw", UCX_PERF_API_UCT, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth / message rate"}, {"add_mr", UCX_PERF_API_UCT, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add message rate"}, {"tag_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_PINGPONG, "tag match latency"}, {"tag_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag match bandwidth"}, {"tag_sync_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_PINGPONG, "tag sync match latency"}, {"tag_sync_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_TAG_SYNC, UCX_PERF_TEST_TYPE_STREAM_UNI, "tag sync match bandwidth"}, {"ucp_put_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_PINGPONG, "put latency"}, {"ucp_put_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_PUT, UCX_PERF_TEST_TYPE_STREAM_UNI, "put bandwidth"}, {"ucp_get", UCX_PERF_API_UCP, UCX_PERF_CMD_GET, UCX_PERF_TEST_TYPE_STREAM_UNI, "get latency / bandwidth / message rate"}, {"ucp_add", UCX_PERF_API_UCP, UCX_PERF_CMD_ADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic add bandwidth / message rate"}, {"ucp_fadd", UCX_PERF_API_UCP, UCX_PERF_CMD_FADD, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic fetch-and-add latency / bandwidth / rate"}, {"ucp_swap", UCX_PERF_API_UCP, UCX_PERF_CMD_SWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic swap latency / bandwidth / rate"}, {"ucp_cswap", UCX_PERF_API_UCP, UCX_PERF_CMD_CSWAP, UCX_PERF_TEST_TYPE_STREAM_UNI, "atomic compare-and-swap latency / bandwidth / rate"}, {"stream_bw", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_STREAM_UNI, "stream bandwidth"}, {"stream_lat", UCX_PERF_API_UCP, UCX_PERF_CMD_STREAM, UCX_PERF_TEST_TYPE_PINGPONG, "stream latency"}, {NULL} }; static int sock_io(int sock, ssize_t (*sock_call)(int, void *, size_t, int), int poll_events, void *data, size_t size, void (*progress)(void *arg), void *arg, const char *name) { size_t total = 0; struct pollfd pfd; int ret; while (total < size) { pfd.fd = sock; pfd.events = poll_events; pfd.revents = 0; ret = poll(&pfd, 1, 1); /* poll for 1ms */ if (ret > 0) { ucs_assert(ret == 1); ucs_assert(pfd.revents & poll_events); ret = sock_call(sock, (char*)data + total, size - total, 0); if (ret < 0) { ucs_error("%s() failed: %m", name); return -1; } total += ret; } else if ((ret < 0) && (errno != EINTR)) { ucs_error("poll(fd=%d) failed: %m", sock); return -1; } /* progress user context */ if (progress != NULL) { progress(arg); } } return 0; } static int safe_send(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { typedef ssize_t (*sock_call)(int, void *, size_t, int); return sock_io(sock, (sock_call)send, POLLOUT, data, size, progress, arg, "send"); } static int safe_recv(int sock, void *data, size_t size, void (*progress)(void *arg), void *arg) { return sock_io(sock, recv, POLLIN, data, size, progress, arg, "recv"); } static void print_progress(char **test_names, unsigned num_names, const ucx_perf_result_t *result, unsigned flags, int final) { static const char *fmt_csv = "%.0f,%.3f,%.3f,%.3f,%.2f,%.2f,%.0f,%.0f\n"; static const char *fmt_numeric = "%'14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %'11.0f %'11.0f\n"; static const char *fmt_plain = "%14.0f %9.3f %9.3f %9.3f %10.2f %10.2f %11.0f %11.0f\n"; unsigned i; if (!(flags & TEST_FLAG_PRINT_RESULTS) || (!final && (flags & TEST_FLAG_PRINT_FINAL))) { return; } if (flags & TEST_FLAG_PRINT_CSV) { for (i = 0; i < num_names; ++i) { printf("%s,", test_names[i]); } } printf((flags & TEST_FLAG_PRINT_CSV) ? fmt_csv : (flags & TEST_FLAG_NUMERIC_FMT) ? fmt_numeric : fmt_plain, (double)result->iters, result->latency.typical * 1000000.0, result->latency.moment_average * 1000000.0, result->latency.total_average * 1000000.0, result->bandwidth.moment_average / (1024.0 * 1024.0), result->bandwidth.total_average / (1024.0 * 1024.0), result->msgrate.moment_average, result->msgrate.total_average); fflush(stdout); } static void print_header(struct perftest_context *ctx) { const char *test_api_str; const char *test_data_str; test_type_t *test; unsigned i; if (ctx->flags & TEST_FLAG_PRINT_TEST) { for (test = tests; test->name; ++test) { if ((test->command == ctx->params.command) && (test->test_type == ctx->params.test_type)) { break; } } if (test->name != NULL) { if (test->api == UCX_PERF_API_UCT) { test_api_str = "transport layer"; switch (ctx->params.uct.data_layout) { case UCT_PERF_DATA_LAYOUT_SHORT: test_data_str = "short"; break; case UCT_PERF_DATA_LAYOUT_BCOPY: test_data_str = "bcopy"; break; case UCT_PERF_DATA_LAYOUT_ZCOPY: test_data_str = "zcopy"; break; default: test_data_str = "(undefined)"; break; } } else if (test->api == UCX_PERF_API_UCP) { test_api_str = "protocol layer"; test_data_str = "(automatic)"; /* TODO contig/stride/stream */ } else { return; } printf("+------------------------------------------------------------------------------------------+\n"); printf("| API: %-60s |\n", test_api_str); printf("| Test: %-60s |\n", test->desc); printf("| Data layout: %-60s |\n", test_data_str); printf("| Message size: %-60zu |\n", ucx_perf_get_message_size(&ctx->params)); } } if (ctx->flags & TEST_FLAG_PRINT_CSV) { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { for (i = 0; i < ctx->num_batch_files; ++i) { printf("%s,", basename(ctx->batch_files[i])); } printf("iterations,typical_lat,avg_lat,overall_lat,avg_bw,overall_bw,avg_mr,overall_mr\n"); } } else { if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("+--------------+-----------------------------+---------------------+-----------------------+\n"); printf("| | latency (usec) | bandwidth (MB/s) | message rate (msg/s) |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); printf("| # iterations | typical | average | overall | average | overall | average | overall |\n"); printf("+--------------+---------+---------+---------+----------+----------+-----------+-----------+\n"); } else if (ctx->flags & TEST_FLAG_PRINT_TEST) { printf("+------------------------------------------------------------------------------------------+\n"); } } } static void print_test_name(struct perftest_context *ctx) { char buf[200]; unsigned i, pos; if (!(ctx->flags & TEST_FLAG_PRINT_CSV) && (ctx->num_batch_files > 0)) { strcpy(buf, "+--------------+---------+---------+---------+----------+----------+-----------+-----------+"); pos = 1; for (i = 0; i < ctx->num_batch_files; ++i) { if (i != 0) { buf[pos++] = '/'; } memcpy(&buf[pos], ctx->test_names[i], ucs_min(strlen(ctx->test_names[i]), sizeof(buf) - pos - 1)); pos += strlen(ctx->test_names[i]); } if (ctx->flags & TEST_FLAG_PRINT_RESULTS) { printf("%s\n", buf); } } } static void usage(const struct perftest_context *ctx, const char *program) { static const char* api_names[] = { [UCX_PERF_API_UCT] = "UCT", [UCX_PERF_API_UCP] = "UCP" }; test_type_t *test; int UCS_V_UNUSED rank; #if HAVE_MPI MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (ctx->mpi && (rank != 0)) { return; } #endif #if HAVE_MPI printf(" Note: test can be also launched as an MPI application\n"); printf("\n"); #elif HAVE_RTE printf(" Note: this test can be also launched as an libRTE application\n"); printf("\n"); #endif printf(" Usage: %s [ server-hostname ] [ options ]\n", program); printf("\n"); printf(" Common options:\n"); printf(" -t <test> test to run:\n"); for (test = tests; test->name; ++test) { printf(" %13s - %s %s\n", test->name, api_names[test->api], test->desc); } printf("\n"); printf(" -s <size> list of scatter-gather sizes for single message (%zu)\n", ctx->params.msg_size_list[0]); printf(" for example: \"-s 16,48,8192,8192,14\"\n"); printf(" -m <mem type> memory type of messages\n"); printf(" host - system memory(default)\n"); if (ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_CUDA] != NULL) { printf(" cuda - NVIDIA GPU memory\n"); } if (ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_CUDA_MANAGED] != NULL) { printf(" cuda-managed - NVIDIA cuda managed/unified memory\n"); } printf(" -n <iters> number of iterations to run (%ld)\n", ctx->params.max_iter); printf(" -w <iters> number of warm-up iterations (%zu)\n", ctx->params.warmup_iter); printf(" -c <cpu> set affinity to this CPU (off)\n"); printf(" -O <count> maximal number of uncompleted outstanding sends (%u)\n", ctx->params.max_outstanding); printf(" -i <offset> distance between consecutive scatter-gather entries (%zu)\n", ctx->params.iov_stride); printf(" -T <threads> number of threads in the test (%d), if >1 implies \"-M multi\"\n", ctx->params.thread_count); printf(" -B register memory with NONBLOCK flag\n"); printf(" -b <file> read and execute tests from a batch file: every line in the\n"); printf(" file is a test to run, first word is test name, the rest of\n"); printf(" the line is command-line arguments for the test.\n"); printf(" -p <port> TCP port to use for data exchange (%d)\n", ctx->port); #if HAVE_MPI printf(" -P <0|1> disable/enable MPI mode (%d)\n", ctx->mpi); #endif printf(" -h show this help message\n"); printf("\n"); printf(" Output format:\n"); printf(" -N use numeric formatting (thousands separator)\n"); printf(" -f print only final numbers\n"); printf(" -v print CSV-formatted output\n"); printf("\n"); printf(" UCT only:\n"); printf(" -d <device> device to use for testing\n"); printf(" -x <tl> transport to use for testing\n"); printf(" -D <layout> data layout for sender side:\n"); printf(" short - short messages (default, cannot be used for get)\n"); printf(" bcopy - copy-out (cannot be used for atomics)\n"); printf(" zcopy - zero-copy (cannot be used for atomics)\n"); printf(" iov - scatter-gather list (iovec)\n"); printf(" -W <count> flow control window size, for active messages (%u)\n", ctx->params.uct.fc_window); printf(" -H <size> active message header size (%zu)\n", ctx->params.am_hdr_size); printf(" -A <mode> asynchronous progress mode (thread_spinlock)\n"); printf(" thread_spinlock - separate progress thread with spin locking\n"); printf(" thread_mutex - separate progress thread with mutex locking\n"); printf(" signal - signal-based timer\n"); printf("\n"); printf(" UCP only:\n"); printf(" -M <thread> thread support level for progress engine (single)\n"); printf(" single - only the master thread can access\n"); printf(" serialized - one thread can access at a time\n"); printf(" multi - multiple threads can access\n"); printf(" -D <layout>[,<layout>]\n"); printf(" data layout for sender and receiver side (contig)\n"); printf(" contig - Continuous datatype\n"); printf(" iov - Scatter-gather list\n"); printf(" -C use wild-card tag for tag tests\n"); printf(" -U force unexpected flow by using tag probe\n"); printf(" -r <mode> receive mode for stream tests (recv)\n"); printf(" recv : Use ucp_stream_recv_nb\n"); printf(" recv_data : Use ucp_stream_recv_data_nb\n"); printf("\n"); printf(" NOTE: When running UCP tests, transport and device should be specified by\n"); printf(" environment variables: UCX_TLS and UCX_[SELF|SHM|NET]_DEVICES.\n"); printf("\n"); } static ucs_status_t parse_ucp_datatype_params(const char *optarg, ucp_perf_datatype_t *datatype) { const char *iov_type = "iov"; const size_t iov_type_size = strlen("iov"); const char *contig_type = "contig"; const size_t contig_type_size = strlen("contig"); if (0 == strncmp(optarg, iov_type, iov_type_size)) { *datatype = UCP_PERF_DATATYPE_IOV; } else if (0 == strncmp(optarg, contig_type, contig_type_size)) { *datatype = UCP_PERF_DATATYPE_CONTIG; } else { return UCS_ERR_INVALID_PARAM; } return UCS_OK; } static ucs_status_t parse_message_sizes_params(const char *optarg, ucx_perf_params_t *params) { const char delim = ','; size_t *msg_size_list, token_num, token_it; char *optarg_ptr, *optarg_ptr2; optarg_ptr = (char *)optarg; token_num = 0; /* count the number of given message sizes */ while ((optarg_ptr = strchr(optarg_ptr, delim)) != NULL) { ++optarg_ptr; ++token_num; } ++token_num; msg_size_list = realloc(params->msg_size_list, sizeof(*params->msg_size_list) * token_num); if (NULL == msg_size_list) { return UCS_ERR_NO_MEMORY; } params->msg_size_list = msg_size_list; optarg_ptr = (char *)optarg; errno = 0; for (token_it = 0; token_it < token_num; ++token_it) { params->msg_size_list[token_it] = strtoul(optarg_ptr, &optarg_ptr2, 10); if (((ERANGE == errno) && (ULONG_MAX == params->msg_size_list[token_it])) || ((errno != 0) && (params->msg_size_list[token_it] == 0)) || (optarg_ptr == optarg_ptr2)) { free(params->msg_size_list); params->msg_size_list = NULL; /* prevent double free */ ucs_error("Invalid option substring argument at position %lu", token_it); return UCS_ERR_INVALID_PARAM; } optarg_ptr = optarg_ptr2 + 1; } params->msg_size_cnt = token_num; return UCS_OK; } static ucs_status_t init_test_params(ucx_perf_params_t *params) { memset(params, 0, sizeof(*params)); params->api = UCX_PERF_API_LAST; params->command = UCX_PERF_CMD_LAST; params->test_type = UCX_PERF_TEST_TYPE_LAST; params->thread_mode = UCS_THREAD_MODE_SINGLE; params->thread_count = 1; params->async_mode = UCS_ASYNC_THREAD_LOCK_TYPE; params->wait_mode = UCX_PERF_WAIT_MODE_LAST; params->max_outstanding = 1; params->warmup_iter = 10000; params->am_hdr_size = 8; params->alignment = ucs_get_page_size(); params->max_iter = 1000000l; params->max_time = 0.0; params->report_interval = 1.0; params->flags = UCX_PERF_TEST_FLAG_VERBOSE; params->uct.fc_window = UCT_PERF_TEST_MAX_FC_WINDOW; params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; params->mem_type = UCS_MEMORY_TYPE_HOST; params->msg_size_cnt = 1; params->iov_stride = 0; params->ucp.send_datatype = UCP_PERF_DATATYPE_CONTIG; params->ucp.recv_datatype = UCP_PERF_DATATYPE_CONTIG; strcpy(params->uct.dev_name, TL_RESOURCE_NAME_NONE); strcpy(params->uct.tl_name, TL_RESOURCE_NAME_NONE); params->msg_size_list = calloc(params->msg_size_cnt, sizeof(*params->msg_size_list)); if (params->msg_size_list == NULL) { return UCS_ERR_NO_MEMORY; } params->msg_size_list[0] = 8; return UCS_OK; } static ucs_status_t parse_test_params(ucx_perf_params_t *params, char opt, const char *optarg) { test_type_t *test; char *optarg2 = NULL; switch (opt) { case 'd': ucs_snprintf_zero(params->uct.dev_name, sizeof(params->uct.dev_name), "%s", optarg); return UCS_OK; case 'x': ucs_snprintf_zero(params->uct.tl_name, sizeof(params->uct.tl_name), "%s", optarg); return UCS_OK; case 't': for (test = tests; test->name; ++test) { if (!strcmp(optarg, test->name)) { params->api = test->api; params->command = test->command; params->test_type = test->test_type; break; } } if (test->name == NULL) { ucs_error("Invalid option argument for -t"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'D': if (!strcmp(optarg, "short")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_SHORT; } else if (!strcmp(optarg, "bcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_BCOPY; } else if (!strcmp(optarg, "zcopy")) { params->uct.data_layout = UCT_PERF_DATA_LAYOUT_ZCOPY; } else if (UCS_OK == parse_ucp_datatype_params(optarg, &params->ucp.send_datatype)) { optarg2 = strchr(optarg, ','); if (optarg2) { if (UCS_OK != parse_ucp_datatype_params(optarg2 + 1, &params->ucp.recv_datatype)) { return UCS_ERR_INVALID_PARAM; } } } else { ucs_error("Invalid option argument for -D"); return UCS_ERR_INVALID_PARAM; } return UCS_OK; case 'i': params->iov_stride = atol(optarg); return UCS_OK; case 'n': params->max_iter = atol(optarg); return UCS_OK; case 's': return parse_message_sizes_params(optarg, params); case 'H': params->am_hdr_size = atol(optarg); return UCS_OK; case 'W': params->uct.fc_window = atoi(optarg); return UCS_OK; case 'O': params->max_outstanding = atoi(optarg); return UCS_OK; case 'w': params->warmup_iter = atol(optarg); return UCS_OK; case 'o': params->flags |= UCX_PERF_TEST_FLAG_ONE_SIDED; return UCS_OK; case 'B': params->flags |= UCX_PERF_TEST_FLAG_MAP_NONBLOCK; return UCS_OK; case 'q': params->flags &= ~UCX_PERF_TEST_FLAG_VERBOSE; return UCS_OK; case 'C': params->flags |= UCX_PERF_TEST_FLAG_TAG_WILDCARD; return UCS_OK; case 'U': params->flags |= UCX_PERF_TEST_FLAG_TAG_UNEXP_PROBE; return UCS_OK; case 'M': if (!strcmp(optarg, "single")) { params->thread_mode = UCS_THREAD_MODE_SINGLE; return UCS_OK; } else if (!strcmp(optarg, "serialized")) { params->thread_mode = UCS_THREAD_MODE_SERIALIZED; return UCS_OK; } else if (!strcmp(optarg, "multi")) { params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; } else { ucs_error("Invalid option argument for -M"); return UCS_ERR_INVALID_PARAM; } case 'T': params->thread_count = atoi(optarg); params->thread_mode = UCS_THREAD_MODE_MULTI; return UCS_OK; case 'A': if (!strcmp(optarg, "thread") || !strcmp(optarg, "thread_spinlock")) { params->async_mode = UCS_ASYNC_MODE_THREAD_SPINLOCK; return UCS_OK; } else if (!strcmp(optarg, "thread_mutex")) { params->async_mode = UCS_ASYNC_MODE_THREAD_MUTEX; return UCS_OK; } else if (!strcmp(optarg, "signal")) { params->async_mode = UCS_ASYNC_MODE_SIGNAL; return UCS_OK; } else { ucs_error("Invalid option argument for -A"); return UCS_ERR_INVALID_PARAM; } case 'r': if (!strcmp(optarg, "recv_data")) { params->flags |= UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } else if (!strcmp(optarg, "recv")) { params->flags &= ~UCX_PERF_TEST_FLAG_STREAM_RECV_DATA; return UCS_OK; } return UCS_ERR_INVALID_PARAM; case 'm': if (!strcmp(optarg, "host")) { params->mem_type = UCS_MEMORY_TYPE_HOST; return UCS_OK; } else if (!strcmp(optarg, "cuda") && (ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_CUDA] != NULL)) { params->mem_type = UCS_MEMORY_TYPE_CUDA; return UCS_OK; } else if (!strcmp(optarg, "cuda-managed") && (ucx_perf_mem_type_allocators[UCS_MEMORY_TYPE_CUDA_MANAGED] != NULL)) { params->mem_type = UCS_MEMORY_TYPE_CUDA_MANAGED; return UCS_OK; } ucs_error("Unsupported memory type: \"%s\"", optarg); return UCS_ERR_INVALID_PARAM; default: return UCS_ERR_INVALID_PARAM; } } static ucs_status_t read_batch_file(FILE *batch_file, const char *file_name, int *line_num, ucx_perf_params_t *params, char** test_name_p) { #define MAX_SIZE 256 #define MAX_ARG_SIZE 2048 ucs_status_t status; char buf[MAX_ARG_SIZE]; int argc; char *argv[MAX_SIZE + 1]; int c; char *p; do { if (fgets(buf, sizeof(buf) - 1, batch_file) == NULL) { return UCS_ERR_NO_ELEM; } ++(*line_num); argc = 0; p = strtok(buf, " \t\n\r"); while (p && (argc < MAX_SIZE)) { argv[argc++] = p; p = strtok(NULL, " \t\n\r"); } argv[argc] = NULL; } while ((argc == 0) || (argv[0][0] == '#')); optind = 1; while ((c = getopt (argc, argv, TEST_PARAMS_ARGS)) != -1) { status = parse_test_params(params, c, optarg); if (status != UCS_OK) { ucs_error("in batch file '%s' line %d: -%c %s: %s", file_name, *line_num, c, optarg, ucs_status_string(status)); return status; } } *test_name_p = strdup(argv[0]); return UCS_OK; } static ucs_status_t parse_opts(struct perftest_context *ctx, int mpi_initialized, int argc, char **argv) { ucs_status_t status; int c; ucs_trace_func(""); ucx_perf_global_init(); /* initialize memory types */ status = init_test_params(&ctx->params); if (status != UCS_OK) { return status; } ctx->server_addr = NULL; ctx->num_batch_files = 0; ctx->port = 13337; ctx->flags = 0; ctx->mpi = mpi_initialized; optind = 1; while ((c = getopt (argc, argv, "p:b:Nfvc:P:h" TEST_PARAMS_ARGS)) != -1) { switch (c) { case 'p': ctx->port = atoi(optarg); break; case 'b': if (ctx->num_batch_files < MAX_BATCH_FILES) { ctx->batch_files[ctx->num_batch_files++] = optarg; } break; case 'N': ctx->flags |= TEST_FLAG_NUMERIC_FMT; break; case 'f': ctx->flags |= TEST_FLAG_PRINT_FINAL; break; case 'v': ctx->flags |= TEST_FLAG_PRINT_CSV; break; case 'c': ctx->flags |= TEST_FLAG_SET_AFFINITY; ctx->cpu = atoi(optarg); break; case 'P': #if HAVE_MPI ctx->mpi = atoi(optarg) && mpi_initialized; break; #endif case 'h': usage(ctx, ucs_basename(argv[0])); return UCS_ERR_CANCELED; default: status = parse_test_params(&ctx->params, c, optarg); if (status != UCS_OK) { usage(ctx, ucs_basename(argv[0])); return status; } break; } } if (optind < argc) { ctx->server_addr = argv[optind]; } return UCS_OK; } static unsigned sock_rte_group_size(void *rte_group) { return 2; } static unsigned sock_rte_group_index(void *rte_group) { sock_rte_group_t *group = rte_group; return group->is_server ? 0 : 1; } static void sock_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { sock_rte_group_t *group = rte_group; const unsigned magic = 0xdeadbeef; unsigned sync; sync = magic; safe_send(group->connfd, &sync, sizeof(unsigned), progress, arg); sync = 0; safe_recv(group->connfd, &sync, sizeof(unsigned), progress, arg); ucs_assert(sync == magic); } #pragma omp barrier } static void sock_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { sock_rte_group_t *group = rte_group; size_t size; int i; size = 0; for (i = 0; i < iovcnt; ++i) { size += iovec[i].iov_len; } safe_send(group->connfd, &size, sizeof(size), NULL, NULL); for (i = 0; i < iovcnt; ++i) { safe_send(group->connfd, iovec[i].iov_base, iovec[i].iov_len, NULL, NULL); } } static void sock_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { sock_rte_group_t *group = rte_group; int group_index; size_t size; group_index = sock_rte_group_index(rte_group); if (src == group_index) { return; } ucs_assert_always(src == (1 - group_index)); safe_recv(group->connfd, &size, sizeof(size), NULL, NULL); ucs_assert_always(size <= max); safe_recv(group->connfd, buffer, size, NULL, NULL); } static void sock_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t sock_rte = { .group_size = sock_rte_group_size, .group_index = sock_rte_group_index, .barrier = sock_rte_barrier, .post_vec = sock_rte_post_vec, .recv = sock_rte_recv, .exchange_vec = (ucx_perf_rte_exchange_vec_func_t)ucs_empty_function, .report = sock_rte_report, }; static ucs_status_t setup_sock_rte(struct perftest_context *ctx) { struct sockaddr_in inaddr; struct hostent *he; ucs_status_t status; int optval = 1; int sockfd, connfd; int ret; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { ucs_error("socket() failed: %m"); status = UCS_ERR_IO_ERROR; goto err; } if (ctx->server_addr == NULL) { optval = 1; status = ucs_socket_setopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); if (status != UCS_OK) { goto err_close_sockfd; } inaddr.sin_family = AF_INET; inaddr.sin_port = htons(ctx->port); inaddr.sin_addr.s_addr = INADDR_ANY; memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = bind(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("bind() failed: %m"); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } ret = listen(sockfd, 10); if (ret < 0) { ucs_error("listen() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } printf("Waiting for connection...\n"); /* Accept next connection */ connfd = accept(sockfd, NULL, NULL); if (connfd < 0) { ucs_error("accept() failed: %m"); status = UCS_ERR_IO_ERROR; goto err_close_sockfd; } close(sockfd); ret = safe_recv(connfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } if (ctx->params.msg_size_cnt) { ctx->params.msg_size_list = calloc(ctx->params.msg_size_cnt, sizeof(*ctx->params.msg_size_list)); if (NULL == ctx->params.msg_size_list) { status = UCS_ERR_NO_MEMORY; goto err_close_connfd; } ret = safe_recv(connfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt, NULL, NULL); if (ret) { status = UCS_ERR_IO_ERROR; goto err_close_connfd; } } ctx->sock_rte_group.connfd = connfd; ctx->sock_rte_group.is_server = 1; } else { he = gethostbyname(ctx->server_addr); if (he == NULL || he->h_addr_list == NULL) { ucs_error("host %s not found: %s", ctx->server_addr, hstrerror(h_errno)); status = UCS_ERR_INVALID_ADDR; goto err_close_sockfd; } inaddr.sin_family = he->h_addrtype; inaddr.sin_port = htons(ctx->port); ucs_assert(he->h_length == sizeof(inaddr.sin_addr)); memcpy(&inaddr.sin_addr, he->h_addr_list[0], he->h_length); memset(inaddr.sin_zero, 0, sizeof(inaddr.sin_zero)); ret = connect(sockfd, (struct sockaddr*)&inaddr, sizeof(inaddr)); if (ret < 0) { ucs_error("connect() failed: %m"); status = UCS_ERR_UNREACHABLE; goto err_close_sockfd; } safe_send(sockfd, &ctx->params, sizeof(ctx->params), NULL, NULL); if (ctx->params.msg_size_cnt) { safe_send(sockfd, ctx->params.msg_size_list, sizeof(*ctx->params.msg_size_list) * ctx->params.msg_size_cnt, NULL, NULL); } ctx->sock_rte_group.connfd = sockfd; ctx->sock_rte_group.is_server = 0; } if (ctx->sock_rte_group.is_server) { ctx->flags |= TEST_FLAG_PRINT_TEST; } else { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = &ctx->sock_rte_group; ctx->params.rte = &sock_rte; ctx->params.report_arg = ctx; return UCS_OK; err_close_connfd: close(connfd); goto err; err_close_sockfd: close(sockfd); err: return status; } static ucs_status_t cleanup_sock_rte(struct perftest_context *ctx) { close(ctx->sock_rte_group.connfd); return UCS_OK; } #if HAVE_MPI static unsigned mpi_rte_group_size(void *rte_group) { int size; MPI_Comm_size(MPI_COMM_WORLD, &size); return size; } static unsigned mpi_rte_group_index(void *rte_group) { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); return rank; } static void mpi_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { int group_size, my_rank, i; MPI_Request *reqs; int nreqs = 0; int dummy; int flag; #pragma omp barrier #pragma omp master /* * Naive non-blocking barrier implementation over send/recv, to call user * progress while waiting for completion. * Not using MPI_Ibarrier to be compatible with MPI-1. */ MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); /* allocate maximal possible number of requests */ reqs = (MPI_Request*)alloca(sizeof(*reqs) * group_size); if (my_rank == 0) { /* root gathers "ping" from all other ranks */ for (i = 1; i < group_size; ++i) { MPI_Irecv(&dummy, 0, MPI_INT, i /* source */, 1 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } } else { /* every non-root rank sends "ping" and waits for "pong" */ MPI_Send(&dummy, 0, MPI_INT, 0 /* dest */, 1 /* tag */, MPI_COMM_WORLD); MPI_Irecv(&dummy, 0, MPI_INT, 0 /* source */, 2 /* tag */, MPI_COMM_WORLD, &reqs[nreqs++]); } /* Waiting for receive requests */ do { MPI_Testall(nreqs, reqs, &flag, MPI_STATUSES_IGNORE); progress(arg); } while (!flag); if (my_rank == 0) { /* root sends "pong" to all ranks */ for (i = 1; i < group_size; ++i) { MPI_Send(&dummy, 0, MPI_INT, i /* dest */, 2 /* tag */, MPI_COMM_WORLD); } } #pragma omp barrier } static void mpi_rte_post_vec(void *rte_group, const struct iovec *iovec, int iovcnt, void **req) { int group_size; int my_rank; int dest, i; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); MPI_Comm_size(MPI_COMM_WORLD, &group_size); for (dest = 0; dest < group_size; ++dest) { if (dest == my_rank) { continue; } for (i = 0; i < iovcnt; ++i) { MPI_Send(iovec[i].iov_base, iovec[i].iov_len, MPI_BYTE, dest, i == (iovcnt - 1), /* Send last iov with tag == 1 */ MPI_COMM_WORLD); } } *req = (void*)(uintptr_t)1; } static void mpi_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { MPI_Status status; size_t offset; int my_rank; int count; MPI_Comm_rank(MPI_COMM_WORLD, &my_rank); if (src == my_rank) { return; } offset = 0; do { ucs_assert_always(offset < max); MPI_Recv(buffer + offset, max - offset, MPI_BYTE, src, MPI_ANY_TAG, MPI_COMM_WORLD, &status); MPI_Get_count(&status, MPI_BYTE, &count); offset += count; } while (status.MPI_TAG != 1); } static void mpi_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t mpi_rte = { .group_size = mpi_rte_group_size, .group_index = mpi_rte_group_index, .barrier = mpi_rte_barrier, .post_vec = mpi_rte_post_vec, .recv = mpi_rte_recv, .exchange_vec = (void*)ucs_empty_function, .report = mpi_rte_report, }; #elif HAVE_RTE static unsigned ext_rte_group_size(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_size(group); } static unsigned ext_rte_group_index(void *rte_group) { rte_group_t group = (rte_group_t)rte_group; return rte_group_rank(group); } static void ext_rte_barrier(void *rte_group, void (*progress)(void *arg), void *arg) { #pragma omp barrier #pragma omp master { rte_group_t group = (rte_group_t)rte_group; int rc; rc = rte_barrier(group); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_barrier"); } } #pragma omp barrier } static void ext_rte_post_vec(void *rte_group, const struct iovec* iovec, int iovcnt, void **req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session; rte_iovec_t *r_vec; int i, rc; rc = rte_srs_session_create(group, 0, &session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_create"); } r_vec = calloc(iovcnt, sizeof(rte_iovec_t)); if (r_vec == NULL) { return; } for (i = 0; i < iovcnt; ++i) { r_vec[i].iov_base = iovec[i].iov_base; r_vec[i].type = rte_datatype_uint8_t; r_vec[i].count = iovec[i].iov_len; } rc = rte_srs_set_data(session, "KEY_PERF", r_vec, iovcnt); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_set_data"); } *req = session; free(r_vec); } static void ext_rte_recv(void *rte_group, unsigned src, void *buffer, size_t max, void *req) { rte_group_t group = (rte_group_t)rte_group; rte_srs_session_t session = (rte_srs_session_t)req; void *rte_buffer = NULL; rte_iovec_t r_vec; uint32_t offset; int size; int rc; rc = rte_srs_get_data(session, rte_group_index_to_ec(group, src), "KEY_PERF", &rte_buffer, &size); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_get_data"); return; } r_vec.iov_base = buffer; r_vec.type = rte_datatype_uint8_t; r_vec.count = max; offset = 0; rte_unpack(&r_vec, rte_buffer, &offset); rc = rte_srs_session_destroy(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_session_destroy"); } free(rte_buffer); } static void ext_rte_exchange_vec(void *rte_group, void * req) { rte_srs_session_t session = (rte_srs_session_t)req; int rc; rc = rte_srs_exchange_data(session); if (RTE_SUCCESS != rc) { ucs_error("Failed to rte_srs_exchange_data"); } } static void ext_rte_report(void *rte_group, const ucx_perf_result_t *result, void *arg, int is_final) { struct perftest_context *ctx = arg; print_progress(ctx->test_names, ctx->num_batch_files, result, ctx->flags, is_final); } static ucx_perf_rte_t ext_rte = { .group_size = ext_rte_group_size, .group_index = ext_rte_group_index, .barrier = ext_rte_barrier, .report = ext_rte_report, .post_vec = ext_rte_post_vec, .recv = ext_rte_recv, .exchange_vec = ext_rte_exchange_vec, }; #endif static ucs_status_t setup_mpi_rte(struct perftest_context *ctx) { ucs_trace_func(""); #if HAVE_MPI int size, rank; MPI_Comm_size(MPI_COMM_WORLD, &size); if (size != 2) { ucs_error("This test should run with exactly 2 processes (actual: %d)", size); return UCS_ERR_INVALID_PARAM; } MPI_Comm_rank(MPI_COMM_WORLD, &rank); if (rank == 1) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = NULL; ctx->params.rte = &mpi_rte; ctx->params.report_arg = ctx; #elif HAVE_RTE rte_group_t group; rte_init(NULL, NULL, &group); if (1 == rte_group_rank(group)) { ctx->flags |= TEST_FLAG_PRINT_RESULTS; } ctx->params.rte_group = group; ctx->params.rte = &ext_rte; ctx->params.report_arg = ctx; #endif return UCS_OK; } static ucs_status_t cleanup_mpi_rte(struct perftest_context *ctx) { #if HAVE_RTE rte_finalize(); #endif return UCS_OK; } static ucs_status_t check_system(struct perftest_context *ctx) { ucs_sys_cpuset_t cpuset; unsigned i, count, nr_cpus; int ret; ucs_trace_func(""); ret = sysconf(_SC_NPROCESSORS_CONF); if (ret < 0) { ucs_error("failed to get local cpu count: %m"); return UCS_ERR_INVALID_PARAM; } nr_cpus = ret; memset(&cpuset, 0, sizeof(cpuset)); if (ctx->flags & TEST_FLAG_SET_AFFINITY) { if (ctx->cpu >= nr_cpus) { ucs_error("cpu (%u) ot of range (0..%u)", ctx->cpu, nr_cpus - 1); return UCS_ERR_INVALID_PARAM; } CPU_SET(ctx->cpu, &cpuset); ret = ucs_sys_setaffinity(&cpuset); if (ret) { ucs_warn("sched_setaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } } else { ret = ucs_sys_getaffinity(&cpuset); if (ret) { ucs_warn("sched_getaffinity() failed: %m"); return UCS_ERR_INVALID_PARAM; } count = 0; for (i = 0; i < CPU_SETSIZE; ++i) { if (CPU_ISSET(i, &cpuset)) { ++count; } } if (count > 2) { ucs_warn("CPU affinity is not set (bound to %u cpus)." " Performance may be impacted.", count); } } return UCS_OK; } static ucs_status_t clone_params(ucx_perf_params_t *dest, const ucx_perf_params_t *src) { size_t msg_size_list_size; *dest = *src; msg_size_list_size = dest->msg_size_cnt * sizeof(*dest->msg_size_list); dest->msg_size_list = malloc(msg_size_list_size); if (dest->msg_size_list == NULL) { return ((msg_size_list_size != 0) ? UCS_ERR_NO_MEMORY : UCS_OK); } memcpy(dest->msg_size_list, src->msg_size_list, msg_size_list_size); return UCS_OK; } static ucs_status_t run_test_recurs(struct perftest_context *ctx, ucx_perf_params_t *parent_params, unsigned depth) { ucx_perf_params_t params; ucx_perf_result_t result; ucs_status_t status; FILE *batch_file; int line_num; ucs_trace_func("depth=%u, num_files=%u", depth, ctx->num_batch_files); if (parent_params->api == UCX_PERF_API_UCP) { if (strcmp(parent_params->uct.dev_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-d '%s' ignored for UCP test; see NOTES section in help message", parent_params->uct.dev_name); } if (strcmp(parent_params->uct.tl_name, TL_RESOURCE_NAME_NONE)) { ucs_warn("-x '%s' ignored for UCP test; see NOTES section in help message", parent_params->uct.tl_name); } } if (depth >= ctx->num_batch_files) { print_test_name(ctx); return ucx_perf_run(parent_params, &result); } batch_file = fopen(ctx->batch_files[depth], "r"); if (batch_file == NULL) { ucs_error("Failed to open batch file '%s': %m", ctx->batch_files[depth]); return UCS_ERR_IO_ERROR; } status = clone_params(&params, parent_params); if (status != UCS_OK) { goto out; } line_num = 0; while ((status = read_batch_file(batch_file, ctx->batch_files[depth], &line_num, &params, &ctx->test_names[depth])) == UCS_OK) { run_test_recurs(ctx, &params, depth + 1); free(params.msg_size_list); free(ctx->test_names[depth]); ctx->test_names[depth] = NULL; status = clone_params(&params, parent_params); if (status != UCS_OK) { goto out; } } if (status == UCS_ERR_NO_ELEM) { status = UCS_OK; } free(params.msg_size_list); out: fclose(batch_file); return status; } static ucs_status_t run_test(struct perftest_context *ctx) { ucs_status_t status; ucs_trace_func(""); setlocale(LC_ALL, "en_US"); print_header(ctx); status = run_test_recurs(ctx, &ctx->params, 0); if (status != UCS_OK) { ucs_error("Failed to run test: %s", ucs_status_string(status)); } return status; } int main(int argc, char **argv) { struct perftest_context ctx; ucs_status_t status; int mpi_initialized; int mpi_rte; int ret; #if HAVE_MPI mpi_initialized = !isatty(0) && (MPI_Init(&argc, &argv) == 0); #else mpi_initialized = 0; #endif /* Parse command line */ status = parse_opts(&ctx, mpi_initialized, argc, argv); if (status != UCS_OK) { ret = (status == UCS_ERR_CANCELED) ? 0 : -127; goto out; } #ifdef __COVERITY__ /* coverity[dont_call] */ mpi_rte = rand(); /* Shut up deadcode error */ #endif if (ctx.mpi) { mpi_rte = 1; } else { #if HAVE_RTE mpi_rte = 1; #else mpi_rte = 0; #endif } status = check_system(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Create RTE */ status = (mpi_rte) ? setup_mpi_rte(&ctx) : setup_sock_rte(&ctx); if (status != UCS_OK) { ret = -1; goto out; } /* Run the test */ status = run_test(&ctx); if (status != UCS_OK) { ret = -1; goto out_cleanup_rte; } ret = 0; out_cleanup_rte: (mpi_rte) ? cleanup_mpi_rte(&ctx) : cleanup_sock_rte(&ctx); out: if (ctx.params.msg_size_list) { free(ctx.params.msg_size_list); } if (mpi_initialized) { #if HAVE_MPI MPI_Finalize(); #endif } return ret; }
zhetrf.c
/** * * @file * * PLASMA is a software package provided by: * University of Tennessee, US, * University of Manchester, UK. * * @precisions normal z -> s d c * **/ #include "plasma.h" #include "plasma_async.h" #include "plasma_context.h" #include "plasma_descriptor.h" #include "plasma_internal.h" #include "plasma_types.h" #include "plasma_workspace.h" #include <string.h> /***************************************************************************//** * * @ingroup plasma_hetrf * * Factorize a Hermitian matrix A using a 'communication avoiding' Aasen's * algorithm, followed by band LU factorization. The factorization has the form * * \f[ A = P \times L \times T \times L^H \times P^H, \f] * or * \f[ A = P \times U^H \times T \times U \times P^H, \f] * * where U is a unit-diagonal upper triangular matrix and L is a unit-diagonal * lower triangular matrix, T is a band matrix, and P is a permutation matrix. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * TODO: only support Lower for now * * @param[in] n * The order of the matrix A. n >= 0. * * @param[in,out] pA * On entry, the Hermitian matrix A. * If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A * contains the upper triangular part of the matrix A, and the strictly * lower triangular part of A is not referenced. * If uplo = PlasmaLower, the leading N-by-N lower triangular part of A * contains the lower triangular part of the matrix A, and the strictly * upper triangular part of A is not referenced. * On exit, if return value = 0, the factor U or L from the Aasen's * factorization A = (P*U^H)*T*(P*U^H)^H or A = (P*L)*T*(P*L)^H. * * @param[in] lda * The leading dimension of the array A. lda >= max(1,n). * * @param[out] pT * On exit, if return value = 0, the LU factors of the band matrix T. * * @param[in] ldt * The leading dimension of the array T. * * @param[out] ipiv * The pivot indices used by the Aasen's algorithm; for 1 <= i <= min(m,n), * row and column i of the matrix was interchanged with row and column ipiv(i). * * @param[out] ipiv2 * The pivot indices used by the band LU; for 1 <= i <= min(m,n), * row and column i of the matrix was interchanged with row and column ipiv(i). * ******************************************************************************* * * @retval PlasmaSuccess successful exit * @retval < 0 if -i, the i-th argument had an illegal value * @retval > 0 if i, the leading minor of order i of A is not * positive definite, so the factorization could not * be completed, and the solution has not been computed. * ******************************************************************************* * * @sa plasma_omp_zhetrf * @sa plasma_chetrf * @sa plasma_dhetrf * @sa plasma_shetrf * ******************************************************************************/ int plasma_zhetrf(plasma_enum_t uplo, int n, plasma_complex64_t *pA, int lda, int *ipiv, plasma_complex64_t *pT, int ldt, int *ipiv2) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); return PlasmaErrorNotInitialized; } // Check input arguments. if (//(uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo (Upper not supported, yet)"); return -1; } if (n < 0) { plasma_error("illegal value of n"); return -2; } if (lda < imax(1, n)) { plasma_error("illegal value of lda"); return -4; } // quick return if (imax(n, 0) == 0) return PlasmaSuccess; // Set tiling parameters. int nb = plasma->nb; // Initialize barrier plasma_barrier_init(&plasma->barrier); // Create tile matrix. plasma_desc_t A; plasma_desc_t T; plasma_desc_t W; int retval; retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, n, n, 0, 0, n, n, &A); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } // band matrix (general band to prepare for band solve) retval = plasma_desc_general_band_create(PlasmaComplexDouble, PlasmaGeneral, nb, nb, ldt, n, 0, 0, n, n, nb, nb, &T); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_band_create() failed"); return retval; } // workspace int ldw = (1+5*A.mt)*nb; /* block column */ retval = plasma_desc_general_create(PlasmaComplexDouble, nb, nb, ldw, nb, 0, 0, ldw, nb, &W); if (retval != PlasmaSuccess) { plasma_error("plasma_desc_general_create() failed"); return retval; } // Create sequence. plasma_sequence_t *sequence = NULL; retval = plasma_sequence_create(&sequence); if (retval != PlasmaSuccess) { plasma_error("plasma_sequence_create() failed"); return retval; } // Initialize request. plasma_request_t request = PlasmaRequestInitializer; // Initialize data. memset(T.matrix, 0, ldt*n*sizeof(plasma_complex64_t)); for (int i = 0; i < nb; i++) ipiv[i] = 1+i; // asynchronous block #pragma omp parallel #pragma omp master { // Translate to tile layout. plasma_omp_zge2desc(pA, lda, A, sequence, &request); } #pragma omp parallel #pragma omp master { // Call the tile async function to compute LTL^H factor of A, // where T is a band matrix plasma_omp_zhetrf(uplo, A, ipiv, T, ipiv2, W, sequence, &request); } #pragma omp parallel #pragma omp master { // Translate back to LAPACK layout. plasma_omp_zdesc2ge(A, pA, lda, sequence, &request); plasma_omp_zdesc2pb(T, pT, ldt, sequence, &request); } // implicit synchronization // Free matrices in tile layout. plasma_desc_destroy(&A); plasma_desc_destroy(&T); plasma_desc_destroy(&W); // Return status. int status = sequence->status; plasma_sequence_destroy(sequence); return status; } /***************************************************************************//** * * @ingroup plasma_hetrf * * Factorize a Hermitian matrix. * Non-blocking tile version of plasma_zhetrf(). * May return before the computation is finished. * Operates on matrices stored by tiles. * All matrices are passed through descriptors. * All dimensions are taken from the descriptors. * Allows for pipelining of operations at runtime. * ******************************************************************************* * * @param[in] uplo * - PlasmaUpper: Upper triangle of A is stored; * - PlasmaLower: Lower triangle of A is stored. * * @param[in] A * On entry, the Hermitian matrix A. * If uplo = PlasmaUpper, the leading N-by-N upper triangular part of A * contains the upper triangular part of the matrix A, and the strictly * lower triangular part of A is not referenced. * If uplo = PlasmaLower, the leading N-by-N lower triangular part of A * contains the lower triangular part of the matrix A, and the strictly * upper triangular part of A is not referenced. * On exit, if return value = 0, the factor U or L from the Cholesky * factorization A = (P*U^H)*T(P*U^H)^H or A = (P*L)*T(P*L)^H. * * @param[out] T * On exit, if return value = 0, the band matrix T of the factorization * factorization A = (P*U^H)*T*(P*U^H)^H or A = (P*L)*T*(P*L)^H. * * @param[out] ipiv * The pivot indices; for 1 <= i <= min(m,n), row and column i of the * matrix was interchanged with row and column ipiv(i). * * @param[in] sequence * Identifies the sequence of function calls that this call belongs to * (for completion checks and exception handling purposes). Check * the sequence->status for errors. * * @param[out] request * Identifies this function call (for exception handling purposes). * * @retval void * Errors are returned by setting sequence->status and * request->status to error values. The sequence->status and * request->status should never be set to PlasmaSuccess (the * initial values) since another async call may be setting a * failure value at the same time. * ******************************************************************************* * * @sa plasma_zhetrf * @sa plasma_omp_zhetrf * @sa plasma_omp_chetrf * @sa plasma_omp_dhetrf * @sa plasma_omp_shetrf * ******************************************************************************/ void plasma_omp_zhetrf(plasma_enum_t uplo, plasma_desc_t A, int *ipiv, plasma_desc_t T, int *ipiv2, plasma_desc_t W, plasma_sequence_t *sequence, plasma_request_t *request) { // Get PLASMA context. plasma_context_t *plasma = plasma_context_self(); if (plasma == NULL) { plasma_fatal_error("PLASMA not initialized"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // Check input arguments. if (//(uplo != PlasmaUpper) && (uplo != PlasmaLower)) { plasma_error("illegal value of uplo (Upper not supported, yet)"); 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 (sequence == NULL) { plasma_fatal_error("NULL sequence"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } if (request == NULL) { plasma_fatal_error("NULL request"); plasma_request_fail(sequence, request, PlasmaErrorIllegalValue); return; } // quick return if (A.m == 0) return; // Call the parallel function. plasma_pzhetrf_aasen(uplo, A, ipiv, T, W, sequence, request); plasma_pzgbtrf(T, ipiv2, sequence, request); }
GB_binop__ge_int64.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__ge_int64 // A.*B function (eWiseMult): GB_AemultB__ge_int64 // A*D function (colscale): GB_AxD__ge_int64 // D*A function (rowscale): GB_DxB__ge_int64 // C+=B function (dense accum): GB_Cdense_accumB__ge_int64 // C+=b function (dense accum): GB_Cdense_accumb__ge_int64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__ge_int64 // C=scalar+B GB_bind1st__ge_int64 // C=scalar+B' GB_bind1st_tran__ge_int64 // C=A+scalar GB_bind2nd__ge_int64 // C=A'+scalar GB_bind2nd_tran__ge_int64 // C type: bool // A type: int64_t // B,b type: int64_t // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int64_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int64_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ 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_GE || GxB_NO_INT64 || GxB_NO_GE_INT64) //------------------------------------------------------------------------------ // 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__ge_int64 ( 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__ge_int64 ( 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 #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__ge_int64 ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__ge_int64 ( 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__ge_int64 ( 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__ge_int64 ( 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__ge_int64 ( 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__ge_int64 ( 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 ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t bij = Bx [p] ; Cx [p] = (x >= bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__ge_int64 ( 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 ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { int64_t aij = Ax [p] ; Cx [p] = (aij >= y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB_bind1st_tran__ge_int64 ( 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 \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typcasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int64_t aij = Ax [pA] ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB_bind2nd_tran__ge_int64 ( 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 int64_t y = (*((const int64_t *) y_input)) ; #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__ge_int64.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__ge_int64) // A.*B function (eWiseMult): GB (_AemultB_08__ge_int64) // A.*B function (eWiseMult): GB (_AemultB_02__ge_int64) // A.*B function (eWiseMult): GB (_AemultB_04__ge_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__ge_int64) // A*D function (colscale): GB (_AxD__ge_int64) // D*A function (rowscale): GB (_DxB__ge_int64) // C+=B function (dense accum): GB (_Cdense_accumB__ge_int64) // C+=b function (dense accum): GB (_Cdense_accumb__ge_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__ge_int64) // C=scalar+B GB (_bind1st__ge_int64) // C=scalar+B' GB (_bind1st_tran__ge_int64) // C=A+scalar GB (_bind2nd__ge_int64) // C=A'+scalar GB (_bind2nd_tran__ge_int64) // C type: bool // A type: int64_t // A pattern? 0 // B type: int64_t // B pattern? 0 // BinaryOp: cij = (aij >= bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ bool // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 0 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 0 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int64_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) \ int64_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_GE || GxB_NO_INT64 || GxB_NO_GE_INT64) //------------------------------------------------------------------------------ // 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__ge_int64) ( 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__ge_int64) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { #include "GB_dense_subassign_23_template.c" } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__ge_int64) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if 0 { // get the scalar b for C += b, of type int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__ge_int64) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__ge_int64) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *restrict Cx = (bool *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__ge_int64) ( 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) ; int64_t alpha_scalar ; int64_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int64_t *) alpha_scalar_in)) ; beta_scalar = (*((int64_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__ge_int64) ( 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__ge_int64) ( 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__ge_int64) ( 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__ge_int64) ( 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__ge_int64) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else bool *Cx = (bool *) Cx_output ; int64_t x = (*((int64_t *) x_input)) ; int64_t *Bx = (int64_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 ; int64_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__ge_int64) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; bool *Cx = (bool *) Cx_output ; int64_t *Ax = (int64_t *) Ax_input ; int64_t y = (*((int64_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int64_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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (x >= aij) ; \ } GrB_Info GB (_bind1st_tran__ge_int64) ( 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 \ int64_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t x = (*((const int64_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int64_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) \ { \ int64_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = (aij >= y) ; \ } GrB_Info GB (_bind2nd_tran__ge_int64) ( 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 int64_t y = (*((const int64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_binop__islt_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__islt_uint32) // A.*B function (eWiseMult): GB (_AemultB_08__islt_uint32) // A.*B function (eWiseMult): GB (_AemultB_02__islt_uint32) // A.*B function (eWiseMult): GB (_AemultB_04__islt_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__islt_uint32) // A*D function (colscale): GB (_AxD__islt_uint32) // D*A function (rowscale): GB (_DxB__islt_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__islt_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__islt_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__islt_uint32) // C=scalar+B GB (_bind1st__islt_uint32) // C=scalar+B' GB (_bind1st_tran__islt_uint32) // C=A+scalar GB (_bind2nd__islt_uint32) // C=A'+scalar GB (_bind2nd_tran__islt_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_ISLT || GxB_NO_UINT32 || GxB_NO_ISLT_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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__islt_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
single_val_ptr.c
#include <stdlib.h> #include <omp.h> int main() { int* ptr = malloc(sizeof(int)); #pragma omp parallel { *ptr = 42; printf("Value: %d\n", *ptr); } free(ptr); }
volume_basis_function.h
/* Copyright (c) 2020, VSB - Technical University of Ostrava and Graz University of Technology 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 names of VSB - Technical University of Ostrava and Graz University of Technology 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 VSB - TECHNICAL UNIVERSITY OF OSTRAVA AND GRAZ UNIVERSITY OF TECHNOLOGY BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** @file volume_basis_function.h * @brief Contains a parent class for all spatial finite element basis functions * defined on tetrahedral volume meshes. * @note updated documentation */ #ifndef INCLUDE_BESTHEA_VOLUME_BASIS_FUNCTION_H_ #define INCLUDE_BESTHEA_VOLUME_BASIS_FUNCTION_H_ #include "besthea/coordinates.h" #include "besthea/settings.h" #include "besthea/tetrahedral_volume_mesh.h" #include <vector> namespace besthea { namespace bem { template< class derived_type > class volume_basis_function; } } /** * Class representing a volume basis function. */ template< class derived_type > class besthea::bem::volume_basis_function { protected: using mesh_type = besthea::mesh::tetrahedral_volume_mesh; //!< Mesh type. public: /** * Default constructor. */ volume_basis_function( ) : _mesh( nullptr ) { } volume_basis_function( const volume_basis_function & that ) = delete; /** * Destructor. */ virtual ~volume_basis_function( ) { } /** * Returns this cast to the descendant's type. */ derived_type * derived( ) { return static_cast< derived_type * >( this ); } /** * Returns this cast to the descendant's type. */ const derived_type * derived( ) const { return static_cast< const derived_type * >( this ); } /** * Returns the number of basis functions supported on a single tetrahedron. */ virtual lo dimension_local( ) const = 0; /** * Returns the number of basis functions on the whole mesh. */ virtual lo dimension_global( ) const = 0; /** * Provides global indices for local contributions. * @param[in] i_elem Element index. * @param[out] indices Global indices for local contributions. * @remark Example: In case of p1 basis functions the global indices of the * nodes of the tetrahedron with index \p i_elem are returned. */ void local_to_global( lo i_elem, std::vector< lo > & indices ) const { derived( )->do_local_to_global( i_elem, indices ); } /** * Evaluates a basis function in a point in a tetrahedron. The point is given * by coordinates in the reference tetrahedron * (\f$ (x_1,x_2,x_3) \in (0,1)\times(0,1-x_1)\times(0,1-x_1-x_2) \f$). * @param[in] i_elem Index of the tetrahedron. * @param[in] i_fun Local basis function index. * @param[in] x1_ref First coordinate of reference quadrature point. * @param[in] x2_ref Second coordinate of reference quadrature point. * @param[in] x3_ref Third coordinate of reference quadrature point. */ #pragma omp declare simd uniform( i_elem, i_fun ) simdlen( DATA_WIDTH ) sc evaluate( lo i_elem, lo i_fun, sc x1_ref, sc x2_ref, sc x3_ref ) const { return derived( )->do_evaluate( i_elem, i_fun, x1_ref, x2_ref, x3_ref ); } protected: const mesh_type * _mesh; //!< Pointer to the underlying mesh. }; #endif /* INCLUDE_BESTHEA_VOLUME_BASIS_FUNCTION_H_ */
tinyexr.h
/* Copyright (c) 2014 - 2018, 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) // @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. } // Saves single-frame OpenEXR image. Assume EXR image contains RGB(A) channels. // components must be 1(Grayscale), 3(RGB) or 4(RGBA). // Input image format is: `float x width x height`, or `float x RGB(A) x width x // hight` // Save image as fp16(HALF) format when `save_as_fp16` is positive non-zero // value. // Save image as fp32(FLOAT) format when `save_as_fp16` is 0. extern int SaveEXR(const float *data, const int width, const int height, const int components, const int save_as_fp16, const char *filename); // Initialize EXRHeader struct extern void InitEXRHeader(EXRHeader *exr_header); // Initialize EXRImage struct extern void InitEXRImage(EXRImage *exr_image); // Free's internal data of EXRHeader struct extern int FreeEXRHeader(EXRHeader *exr_header); // Free's internal data of EXRImage struct extern int FreeEXRImage(EXRImage *exr_image); // 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 succes. // 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 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 <iostream> #include <sstream> #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 #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 } 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]; } 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) { return false; } marker += sizeof(uint32_t); size -= sizeof(uint32_t); if (size < data_len) { return false; } data->resize(static_cast<size_t>(data_len)); memcpy(&data->at(0), marker, static_cast<size_t>(data_len)); *marker_size = name_len + 1 + type_len + 1 + sizeof(uint32_t) + data_len; return true; } static void WriteAttributeToMemory(std::vector<unsigned char> *out, const char *name, const char *type, const unsigned char *data, int len) { out->insert(out->end(), name, name + strlen(name) + 1); out->insert(out->end(), type, type + strlen(type) + 1); int outLen = len; tinyexr::swap4(reinterpret_cast<unsigned int *>(&outLen)); out->insert(out->end(), reinterpret_cast<unsigned char *>(&outLen), reinterpret_cast<unsigned char *>(&outLen) + sizeof(int)); out->insert(out->end(), data, data + len); } typedef struct { std::string name; // less than 255 bytes long int pixel_type; int x_sampling; int y_sampling; unsigned char p_linear; unsigned char pad[3]; } ChannelInfo; typedef struct { 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; } } HeaderInfo; 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; if (0 > (maxLength -= count)) return 0; memcpy(out, in, count); out += count; in += count; } else { int count = *in++; inLength -= 2; if (0 > (maxLength -= count + 1)) return 0; memset(out, *reinterpret_cast<const char *>(in), count + 1); out += count + 1; in++; } } return static_cast<int>(out - outStart); } #ifdef __clang__ #pragma clang diagnostic pop #endif // End of RLE code from OpenEXR ----------------------------------- static void CompressRle(unsigned char *dst, tinyexr::tinyexr_uint64 &compressedSize, const unsigned char *src, unsigned long src_size) { std::vector<unsigned char> tmpBuf(src_size); // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // // Reorder the pixel data. // const char *srcPtr = reinterpret_cast<const char *>(src); { char *t1 = reinterpret_cast<char *>(&tmpBuf.at(0)); char *t2 = reinterpret_cast<char *>(&tmpBuf.at(0)) + (src_size + 1) / 2; const char *stop = srcPtr + src_size; for (;;) { if (srcPtr < stop) *(t1++) = *(srcPtr++); else break; if (srcPtr < stop) *(t2++) = *(srcPtr++); else break; } } // // Predictor. // { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + src_size; int p = t[-1]; while (t < stop) { int d = int(t[0]) - p + (128 + 256); p = t[0]; t[0] = static_cast<unsigned char>(d); ++t; } } // outSize will be (srcSiz * 3) / 2 at max. int outSize = rleCompress(static_cast<int>(src_size), reinterpret_cast<const char *>(&tmpBuf.at(0)), reinterpret_cast<signed char *>(dst)); assert(outSize > 0); compressedSize = static_cast<tinyexr::tinyexr_uint64>(outSize); // Use uncompressed data when compressed data is larger than uncompressed. // (Issue 40) if (compressedSize >= src_size) { compressedSize = src_size; memcpy(dst, src, src_size); } } static void DecompressRle(unsigned char *dst, const unsigned long uncompressed_size, const unsigned char *src, unsigned long src_size) { if (uncompressed_size == src_size) { // Data is not compressed(Issue 40). memcpy(dst, src, src_size); return; } std::vector<unsigned char> tmpBuf(uncompressed_size); int ret = rleUncompress(static_cast<int>(src_size), static_cast<int>(uncompressed_size), reinterpret_cast<const signed char *>(src), reinterpret_cast<char *>(&tmpBuf.at(0))); assert(ret == static_cast<int>(uncompressed_size)); (void)ret; // // Apply EXR-specific? postprocess. Grabbed from OpenEXR's // ImfRleCompressor.cpp // // Predictor. { unsigned char *t = &tmpBuf.at(0) + 1; unsigned char *stop = &tmpBuf.at(0) + uncompressed_size; while (t < stop) { int d = int(t[-1]) + int(t[0]) - 128; t[0] = static_cast<unsigned char>(d); ++t; } } // Reorder the pixel data. { const char *t1 = reinterpret_cast<const char *>(&tmpBuf.at(0)); const char *t2 = reinterpret_cast<const char *>(&tmpBuf.at(0)) + (uncompressed_size + 1) / 2; char *s = reinterpret_cast<char *>(dst); char *stop = s + uncompressed_size; for (;;) { if (s < stop) *(s++) = *(t1++); else break; if (s < stop) *(s++) = *(t2++); else break; } } } #if TINYEXR_USE_PIZ #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wc++11-long-long" #pragma clang diagnostic ignored "-Wold-style-cast" #pragma clang diagnostic ignored "-Wpadded" #pragma clang diagnostic ignored "-Wsign-conversion" #pragma clang diagnostic ignored "-Wc++11-extensions" #pragma clang diagnostic ignored "-Wconversion" #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" #if __has_warning("-Wcast-qual") #pragma clang diagnostic ignored "-Wcast-qual" #endif #endif // // PIZ compress/uncompress, based on OpenEXR's ImfPizCompressor.cpp // // ----------------------------------------------------------------- // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC) // (3 clause BSD license) // struct PIZChannelData { unsigned short *start; unsigned short *end; int nx; int ny; int ys; int size; }; //----------------------------------------------------------------------------- // // 16-bit Haar Wavelet encoding and decoding // // The source code in this file is derived from the encoding // and decoding routines written by Christian Rouet for his // PIZ image file format. // //----------------------------------------------------------------------------- // // Wavelet basis functions without modulo arithmetic; they produce // the best compression ratios when the wavelet-transformed data are // Huffman-encoded, but the wavelet transform works only for 14-bit // data (untransformed data values must be less than (1 << 14)). // inline void wenc14(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { short as = static_cast<short>(a); short bs = static_cast<short>(b); short ms = (as + bs) >> 1; short ds = as - bs; l = static_cast<unsigned short>(ms); h = static_cast<unsigned short>(ds); } inline void wdec14(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { short ls = static_cast<short>(l); short hs = static_cast<short>(h); int hi = hs; int ai = ls + (hi & 1) + (hi >> 1); short as = static_cast<short>(ai); short bs = static_cast<short>(ai - hi); a = static_cast<unsigned short>(as); b = static_cast<unsigned short>(bs); } // // Wavelet basis functions with modulo arithmetic; they work with full // 16-bit data, but Huffman-encoding the wavelet-transformed data doesn't // compress the data quite as well. // const int NBITS = 16; const int A_OFFSET = 1 << (NBITS - 1); const int M_OFFSET = 1 << (NBITS - 1); const int MOD_MASK = (1 << NBITS) - 1; inline void wenc16(unsigned short a, unsigned short b, unsigned short &l, unsigned short &h) { int ao = (a + A_OFFSET) & MOD_MASK; int m = ((ao + b) >> 1); int d = ao - b; if (d < 0) m = (m + M_OFFSET) & MOD_MASK; d &= MOD_MASK; l = static_cast<unsigned short>(m); h = static_cast<unsigned short>(d); } inline void wdec16(unsigned short l, unsigned short h, unsigned short &a, unsigned short &b) { int m = l; int d = h; int bb = (m - (d >> 1)) & MOD_MASK; int aa = (d + bb - A_OFFSET) & MOD_MASK; b = static_cast<unsigned short>(bb); a = static_cast<unsigned short>(aa); } // // 2D Wavelet encoding: // static void wav2Encode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; // == 1 << level int p2 = 2; // == 1 << (level+1) // // Hierachical loop on smaller dimension n // while (p2 <= n) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet encoding // if (w14) { wenc14(*px, *p01, i00, i01); wenc14(*p10, *p11, i10, i11); wenc14(i00, i10, *px, *p10); wenc14(i01, i11, *p01, *p11); } else { wenc16(*px, *p01, i00, i01); wenc16(*p10, *p11, i10, i11); wenc16(i00, i10, *px, *p10); wenc16(i01, i11, *p01, *p11); } } // // Encode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wenc14(*px, *p10, i00, *p10); else wenc16(*px, *p10, i00, *p10); *px = i00; } } // // Encode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wenc14(*px, *p01, i00, *p01); else wenc16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p = p2; p2 <<= 1; } } // // 2D Wavelet decoding: // static void wav2Decode( unsigned short *in, // io: values are transformed in place int nx, // i : x size int ox, // i : x offset int ny, // i : y size int oy, // i : y offset unsigned short mx) // i : maximum in[x][y] value { bool w14 = (mx < (1 << 14)); int n = (nx > ny) ? ny : nx; int p = 1; int p2; // // Search max level // while (p <= n) p <<= 1; p >>= 1; p2 = p; p >>= 1; // // Hierarchical loop on smaller dimension n // while (p >= 1) { unsigned short *py = in; unsigned short *ey = in + oy * (ny - p2); int oy1 = oy * p; int oy2 = oy * p2; int ox1 = ox * p; int ox2 = ox * p2; unsigned short i00, i01, i10, i11; // // Y loop // for (; py <= ey; py += oy2) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); // // X loop // for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; unsigned short *p10 = px + oy1; unsigned short *p11 = p10 + ox1; // // 2D wavelet decoding // if (w14) { wdec14(*px, *p10, i00, i10); wdec14(*p01, *p11, i01, i11); wdec14(i00, i01, *px, *p01); wdec14(i10, i11, *p10, *p11); } else { wdec16(*px, *p10, i00, i10); wdec16(*p01, *p11, i01, i11); wdec16(i00, i01, *px, *p01); wdec16(i10, i11, *p10, *p11); } } // // Decode (1D) odd column (still in Y loop) // if (nx & p) { unsigned short *p10 = px + oy1; if (w14) wdec14(*px, *p10, i00, *p10); else wdec16(*px, *p10, i00, *p10); *px = i00; } } // // Decode (1D) odd line (must loop in X) // if (ny & p) { unsigned short *px = py; unsigned short *ex = py + ox * (nx - p2); for (; px <= ex; px += ox2) { unsigned short *p01 = px + ox1; if (w14) wdec14(*px, *p01, i00, *p01); else wdec16(*px, *p01, i00, *p01); *px = i00; } } // // Next level // p2 = p; p >>= 1; } } //----------------------------------------------------------------------------- // // 16-bit Huffman compression and decompression. // // The source code in this file is derived from the 8-bit // Huffman compression and decompression routines written // by Christian Rouet for his PIZ image file format. // //----------------------------------------------------------------------------- // Adds some modification for tinyexr. const int HUF_ENCBITS = 16; // literal (value) bit length const int HUF_DECBITS = 14; // decoding bit size (>= 8) const int HUF_ENCSIZE = (1 << HUF_ENCBITS) + 1; // encoding table size const int HUF_DECSIZE = 1 << HUF_DECBITS; // decoding table size const int HUF_DECMASK = HUF_DECSIZE - 1; struct HufDec { // short code long code //------------------------------- int len : 8; // code length 0 int lit : 24; // lit p size int *p; // 0 lits }; inline long long hufLength(long long code) { return code & 63; } inline long long hufCode(long long code) { return code >> 6; } inline void outputBits(int nBits, long long bits, long long &c, int &lc, char *&out) { c <<= nBits; lc += nBits; c |= bits; while (lc >= 8) *out++ = static_cast<char>((c >> (lc -= 8))); } inline long long getBits(int nBits, long long &c, int &lc, const char *&in) { while (lc < nBits) { c = (c << 8) | *(reinterpret_cast<const unsigned char *>(in++)); lc += 8; } lc -= nBits; return (c >> lc) & ((1 << nBits) - 1); } // // ENCODING TABLE BUILDING & (UN)PACKING // // // Build a "canonical" Huffman code table: // - for each (uncompressed) symbol, hcode contains the length // of the corresponding code (in the compressed data) // - canonical codes are computed and stored in hcode // - the rules for constructing canonical codes are as follows: // * shorter codes (if filled with zeroes to the right) // have a numerically higher value than longer codes // * for codes with the same length, numerical values // increase with numerical symbol values // - because the canonical code table can be constructed from // symbol lengths alone, the code table can be transmitted // without sending the actual code values // - see http://www.compressconsult.com/huffman/ // static void hufCanonicalCodeTable(long long hcode[HUF_ENCSIZE]) { long long n[59]; // // For each i from 0 through 58, count the // number of different codes of length i, and // store the count in n[i]. // for (int i = 0; i <= 58; ++i) n[i] = 0; for (int i = 0; i < HUF_ENCSIZE; ++i) n[hcode[i]] += 1; // // For each i from 58 through 1, compute the // numerically lowest code with length i, and // store that code in n[i]. // long long c = 0; for (int i = 58; i > 0; --i) { long long nc = ((c + n[i]) >> 1); n[i] = c; c = nc; } // // hcode[i] contains the length, l, of the // code for symbol i. Assign the next available // code of length l to the symbol and store both // l and the code in hcode[i]. // for (int i = 0; i < HUF_ENCSIZE; ++i) { int l = static_cast<int>(hcode[i]); if (l > 0) hcode[i] = l | (n[l]++ << 6); } } // // Compute Huffman codes (based on frq input) and store them in frq: // - code structure is : [63:lsb - 6:msb] | [5-0: bit length]; // - max code length is 58 bits; // - codes outside the range [im-iM] have a null length (unused values); // - original frequencies are destroyed; // - encoding tables are used by hufEncode() and hufBuildDecTable(); // struct FHeapCompare { bool operator()(long long *a, long long *b) { return *a > *b; } }; static void hufBuildEncTable( long long *frq, // io: input frequencies [HUF_ENCSIZE], output table int *im, // o: min frq index int *iM) // o: max frq index { // // This function assumes that when it is called, array frq // indicates the frequency of all possible symbols in the data // that are to be Huffman-encoded. (frq[i] contains the number // of occurrences of symbol i in the data.) // // The loop below does three things: // // 1) Finds the minimum and maximum indices that point // to non-zero entries in frq: // // frq[im] != 0, and frq[i] == 0 for all i < im // frq[iM] != 0, and frq[i] == 0 for all i > iM // // 2) Fills array fHeap with pointers to all non-zero // entries in frq. // // 3) Initializes array hlink such that hlink[i] == i // for all array entries. // 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 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); 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 // // ----------------------------------------------------------------- // static bool DecodePixelData(/* out */ unsigned char **out_images, const int *requested_pixel_types, const unsigned char *data_ptr, size_t data_len, int compression_type, int line_order, int width, int height, int x_stride, int y, int line_no, int num_lines, size_t pixel_data_size, size_t num_attributes, const EXRAttribute *attributes, size_t num_channels, const EXRChannelInfo *channels, const std::vector<size_t> &channel_offset_list) { if (compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { // PIZ #if TINYEXR_USE_PIZ // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>( static_cast<size_t>(width * num_lines) * pixel_data_size)); size_t tmpBufLen = outBuf.size(); bool ret = tinyexr::DecompressPiz( reinterpret_cast<unsigned char *>(&outBuf.at(0)), data_ptr, tmpBufLen, data_len, static_cast<int>(num_channels), channels, width, num_lines); assert(ret); (void)ret; // For PIZ_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { FP16 hf; // hf.u = line_ptr[u]; tinyexr::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]; if (line_order == 0) { image += (static_cast<size_t>(line_no) + v) * static_cast<size_t>(x_stride) + u; } else { image += static_cast<size_t>( (height - 1 - (line_no + static_cast<int>(v)))) * static_cast<size_t>(x_stride) + u; } *image = f32.f; } } } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { assert(requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT); for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned int *line_ptr = reinterpret_cast<unsigned int *>( &outBuf.at(v * pixel_data_size * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { unsigned int val; // 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]; 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_RLE) { // Allocate original data size. std::vector<unsigned char> outBuf(static_cast<size_t>(width) * static_cast<size_t>(num_lines) * pixel_data_size); unsigned long dstLen = static_cast<unsigned long>(outBuf.size()); assert(dstLen > 0); tinyexr::DecompressRle(reinterpret_cast<unsigned char *>(&outBuf.at(0)), dstLen, data_ptr, static_cast<unsigned long>(data_len)); // For RLE_COMPRESSION: // pixel sample data for channel 0 for scanline 0 // pixel sample data for channel 1 for scanline 0 // pixel sample data for channel ... for scanline 0 // pixel sample data for channel n for scanline 0 // pixel sample data for channel 0 for scanline 1 // pixel sample data for channel 1 for scanline 1 // pixel sample data for channel ... for scanline 1 // pixel sample data for channel n for scanline 1 // ... for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { for (size_t v = 0; v < static_cast<size_t>(num_lines); v++) { const unsigned short *line_ptr = reinterpret_cast<unsigned short *>( &outBuf.at(v * static_cast<size_t>(pixel_data_size) * static_cast<size_t>(width) + channel_offset_list[c] * static_cast<size_t>(width))); for (size_t u = 0; u < static_cast<size_t>(width); u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::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++) { if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { const unsigned short *line_ptr = reinterpret_cast<const unsigned short *>( data_ptr + c * static_cast<size_t>(width) * sizeof(unsigned short)); if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { unsigned short *outLine = reinterpret_cast<unsigned short *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { tinyexr::FP16 hf; // hf.u = line_ptr[u]; tinyexr::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 += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } 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 + c * static_cast<size_t>(width) * sizeof(float)); float *outLine = reinterpret_cast<float *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { float val; 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 + c * static_cast<size_t>(width) * sizeof(unsigned int)); unsigned int *outLine = reinterpret_cast<unsigned int *>(out_images[c]); if (line_order == 0) { outLine += y * x_stride; } else { outLine += (height - 1 - y) * x_stride; } for (int u = 0; u < width; u++) { unsigned int val; 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 void ComputeChannelLayout(std::vector<size_t> *channel_offset_list, int *pixel_data_size, size_t *channel_offset, int num_channels, const EXRChannelInfo *channels) { channel_offset_list->resize(static_cast<size_t>(num_channels)); (*pixel_data_size) = 0; (*channel_offset) = 0; for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { (*channel_offset_list)[c] = (*channel_offset); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { (*pixel_data_size) += sizeof(unsigned short); (*channel_offset) += sizeof(unsigned short); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { (*pixel_data_size) += sizeof(float); (*channel_offset) += sizeof(float); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { (*pixel_data_size) += sizeof(unsigned int); (*channel_offset) += sizeof(unsigned int); } else { assert(0); } } } static unsigned char **AllocateImage(int num_channels, const EXRChannelInfo *channels, const int *requested_pixel_types, int data_width, int data_height) { unsigned char **images = reinterpret_cast<unsigned char **>(static_cast<float **>( malloc(sizeof(float *) * static_cast<size_t>(num_channels)))); for (size_t c = 0; c < static_cast<size_t>(num_channels); c++) { size_t data_len = static_cast<size_t>(data_width) * static_cast<size_t>(data_height); if (channels[c].pixel_type == TINYEXR_PIXELTYPE_HALF) { // pixel_data_size += sizeof(unsigned short); // channel_offset += sizeof(unsigned short); // Alloc internal image for half type. if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { images[c] = reinterpret_cast<unsigned char *>(static_cast<unsigned short *>( malloc(sizeof(unsigned short) * data_len))); } else if (requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else { assert(0); } } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_FLOAT) { // pixel_data_size += sizeof(float); // channel_offset += sizeof(float); images[c] = reinterpret_cast<unsigned char *>( static_cast<float *>(malloc(sizeof(float) * data_len))); } else if (channels[c].pixel_type == TINYEXR_PIXELTYPE_UINT) { // pixel_data_size += sizeof(unsigned int); // channel_offset += sizeof(unsigned int); images[c] = reinterpret_cast<unsigned char *>( static_cast<unsigned int *>(malloc(sizeof(unsigned int) * data_len))); } else { assert(0); } } return images; } static int ParseEXRHeader(HeaderInfo *info, bool *empty_header, const EXRVersion *version, std::string *err, const unsigned char *buf, size_t size) { const char *marker = reinterpret_cast<const char *>(&buf[0]); if (empty_header) { (*empty_header) = false; } if (version->multipart) { if (size > 0 && marker[0] == '\0') { // End of header list. if (empty_header) { (*empty_header) = true; } return TINYEXR_SUCCESS; } } // According to the spec, the header of every OpenEXR file must contain at // least the following attributes: // // channels chlist // compression compression // dataWindow box2i // displayWindow box2i // lineOrder lineOrder // pixelAspectRatio float // screenWindowCenter v2f // screenWindowWidth float bool has_channels = false; bool has_compression = false; bool has_data_window = false; bool has_display_window = false; bool has_line_order = false; bool has_pixel_aspect_ratio = false; bool has_screen_window_center = false; bool has_screen_window_width = false; info->data_window[0] = 0; info->data_window[1] = 0; info->data_window[2] = 0; info->data_window[3] = 0; info->line_order = 0; // @fixme info->display_window[0] = 0; info->display_window[1] = 0; info->display_window[2] = 0; info->display_window[3] = 0; info->screen_window_center[0] = 0.0f; info->screen_window_center[1] = 0.0f; info->screen_window_width = -1.0f; info->pixel_aspect_ratio = -1.0f; info->tile_size_x = -1; info->tile_size_y = -1; info->tile_level_mode = -1; info->tile_rounding_mode = -1; info->attributes.clear(); // Read attributes size_t orig_size = size; for (size_t nattr = 0; nattr < TINYEXR_MAX_HEADER_ATTRIBUTES; nattr++) { if (0 == size) { return TINYEXR_ERROR_INVALID_DATA; } else if (marker[0] == '\0') { size--; break; } std::string attr_name; std::string attr_type; std::vector<unsigned char> data; size_t marker_size; if (!tinyexr::ReadAttribute(&attr_name, &attr_type, &data, &marker_size, marker, size)) { return TINYEXR_ERROR_INVALID_DATA; } marker += marker_size; size -= marker_size; if (version->tiled && attr_name.compare("tiles") == 0) { unsigned int x_size, y_size; unsigned char tile_mode; assert(data.size() == 9); memcpy(&x_size, &data.at(0), sizeof(int)); memcpy(&y_size, &data.at(4), sizeof(int)); tile_mode = data[8]; tinyexr::swap4(&x_size); tinyexr::swap4(&y_size); info->tile_size_x = static_cast<int>(x_size); info->tile_size_y = static_cast<int>(y_size); // mode = levelMode + roundingMode * 16 info->tile_level_mode = tile_mode & 0x3; info->tile_rounding_mode = (tile_mode >> 4) & 0x1; } else if (attr_name.compare("compression") == 0) { bool ok = false; if (data[0] < TINYEXR_COMPRESSIONTYPE_PIZ) { ok = true; } if (data[0] == TINYEXR_COMPRESSIONTYPE_PIZ) { #if TINYEXR_USE_PIZ ok = true; #else if (err) { (*err) = "PIZ compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (data[0] == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP ok = true; #else if (err) { (*err) = "ZFP compression is not supported."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; #endif } if (!ok) { if (err) { (*err) = "Unknown compression type."; } return TINYEXR_ERROR_UNSUPPORTED_FORMAT; } info->compression_type = static_cast<int>(data[0]); has_compression = true; } else if (attr_name.compare("channels") == 0) { // name: zero-terminated string, from 1 to 255 bytes long // pixel type: int, possible values are: UINT = 0 HALF = 1 FLOAT = 2 // pLinear: unsigned char, possible values are 0 and 1 // reserved: three chars, should be zero // xSampling: int // ySampling: int if (!ReadChannelInfo(info->channels, data)) { if (err) { (*err) = "Failed to parse channel info."; } return TINYEXR_ERROR_INVALID_DATA; } if (info->channels.size() < 1) { if (err) { (*err) = "# of channels is zero."; } return TINYEXR_ERROR_INVALID_DATA; } has_channels = true; } else if (attr_name.compare("dataWindow") == 0) { if (data.size() >= 16) { memcpy(&info->data_window[0], &data.at(0), sizeof(int)); memcpy(&info->data_window[1], &data.at(4), sizeof(int)); memcpy(&info->data_window[2], &data.at(8), sizeof(int)); memcpy(&info->data_window[3], &data.at(12), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[0])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[1])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[2])); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->data_window[3])); has_data_window = true; } } else if (attr_name.compare("displayWindow") == 0) { if (data.size() >= 16) { memcpy(&info->display_window[0], &data.at(0), sizeof(int)); memcpy(&info->display_window[1], &data.at(4), sizeof(int)); memcpy(&info->display_window[2], &data.at(8), sizeof(int)); memcpy(&info->display_window[3], &data.at(12), sizeof(int)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[1])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[2])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->display_window[3])); has_display_window = true; } } else if (attr_name.compare("lineOrder") == 0) { if (data.size() >= 1) { info->line_order = static_cast<int>(data[0]); has_line_order = true; } } else if (attr_name.compare("pixelAspectRatio") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->pixel_aspect_ratio, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->pixel_aspect_ratio)); has_pixel_aspect_ratio = true; } } else if (attr_name.compare("screenWindowCenter") == 0) { if (data.size() >= 8) { memcpy(&info->screen_window_center[0], &data.at(0), sizeof(float)); memcpy(&info->screen_window_center[1], &data.at(4), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[0])); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_center[1])); has_screen_window_center = true; } } else if (attr_name.compare("screenWindowWidth") == 0) { if (data.size() >= sizeof(float)) { memcpy(&info->screen_window_width, &data.at(0), sizeof(float)); tinyexr::swap4( reinterpret_cast<unsigned int *>(&info->screen_window_width)); has_screen_window_width = true; } } else if (attr_name.compare("chunkCount") == 0) { if (data.size() >= sizeof(int)) { memcpy(&info->chunk_count, &data.at(0), sizeof(int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&info->chunk_count)); } } else { // Custom attribute(up to TINYEXR_MAX_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) { int num_channels = exr_header->num_channels; int num_scanline_blocks = 1; if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZIP) { num_scanline_blocks = 16; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_PIZ) { num_scanline_blocks = 32; } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { num_scanline_blocks = 16; } int data_width = exr_header->data_window[2] - exr_header->data_window[0] + 1; int data_height = exr_header->data_window[3] - exr_header->data_window[1] + 1; size_t num_blocks = offsets.size(); std::vector<size_t> channel_offset_list; int pixel_data_size = 0; size_t channel_offset = 0; tinyexr::ComputeChannelLayout(&channel_offset_list, &pixel_data_size, &channel_offset, num_channels, exr_header->channels); bool invalid_data = false; // TODO(LTE): Use atomic lock for MT safety. if (exr_header->tiled) { size_t num_tiles = offsets.size(); // = # of blocks exr_image->tiles = static_cast<EXRTile *>( calloc(sizeof(EXRTile), static_cast<size_t>(num_tiles))); for (size_t tile_idx = 0; tile_idx < num_tiles; tile_idx++) { // Allocate memory for each tile. exr_image->tiles[tile_idx].images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, 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) { 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) { return TINYEXR_ERROR_INVALID_DATA; } // Move to data addr: 20 = 16 + 4; data_ptr += 20; tinyexr::DecodeTiledPixelData( exr_image->tiles[tile_idx].images, &(exr_image->tiles[tile_idx].width), &(exr_image->tiles[tile_idx].height), exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, tile_coordinates[0], tile_coordinates[1], exr_header->tile_size_x, exr_header->tile_size_y, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list); exr_image->tiles[tile_idx].offset_x = tile_coordinates[0]; exr_image->tiles[tile_idx].offset_y = tile_coordinates[1]; exr_image->tiles[tile_idx].level_x = tile_coordinates[2]; exr_image->tiles[tile_idx].level_y = tile_coordinates[3]; exr_image->num_tiles = static_cast<int>(num_tiles); } } else { // scanline format exr_image->images = tinyexr::AllocateImage( num_channels, exr_header->channels, exr_header->requested_pixel_types, data_width, data_height); #ifdef _OPENMP #pragma omp parallel for #endif for (int y = 0; y < static_cast<int>(num_blocks); y++) { size_t y_idx = static_cast<size_t>(y); if (offsets[y_idx] + sizeof(int) * 2 > size) { invalid_data = true; } else { // 4 byte: scan line // 4 byte: data size // ~ : pixel data(uncompressed or compressed) size_t data_size = size_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 { int end_line_no = (std::min)(line_no + num_scanline_blocks, (exr_header->data_window[3] + 1)); int num_lines = end_line_no - line_no; // assert(num_lines > 0); if (num_lines <= 0) { invalid_data = true; } else { // Move to data addr: 8 = 4 + 4; data_ptr += 8; // Adjust line_no with data_window.bmin.y line_no -= exr_header->data_window[1]; if (line_no < 0) { invalid_data = true; } else { if (!tinyexr::DecodePixelData( exr_image->images, exr_header->requested_pixel_types, data_ptr, static_cast<size_t>(data_len), exr_header->compression_type, exr_header->line_order, data_width, data_height, data_width, y, line_no, num_lines, static_cast<size_t>(pixel_data_size), static_cast<size_t>(exr_header->num_custom_attributes), exr_header->custom_attributes, static_cast<size_t>(exr_header->num_channels), exr_header->channels, channel_offset_list)) { invalid_data = true; } } } } } } // omp parallel } if (invalid_data) { return TINYEXR_ERROR_INVALID_DATA; } // Overwrite `pixel_type` with `requested_pixel_type`. { for (int c = 0; c < exr_header->num_channels; c++) { exr_header->pixel_types[c] = exr_header->requested_pixel_types[c]; } } { exr_image->num_channels = num_channels; exr_image->width = data_width; exr_image->height = data_height; } return TINYEXR_SUCCESS; } static bool ReconstructLineOffsets( std::vector<tinyexr::tinyexr_uint64> *offsets, size_t n, const unsigned char *head, const unsigned char *marker, const size_t size) { assert(head < marker); assert(offsets->size() == n); for (size_t i = 0; i < n; i++) { size_t offset = static_cast<size_t>(marker - head); // Offset should not exceed whole EXR file/data size. if ((offset + sizeof(tinyexr::tinyexr_uint64)) >= size) { return false; } int y; unsigned int data_len; memcpy(&y, marker, sizeof(int)); memcpy(&data_len, marker + 4, sizeof(unsigned int)); if (data_len >= size) { return false; } tinyexr::swap4(reinterpret_cast<unsigned int *>(&y)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&data_len)); (*offsets)[i] = offset; marker += data_len + 8; // 8 = 4 bytes(y) + 4 bytes(data_len) } return true; } static int DecodeEXRImage(EXRImage *exr_image, const EXRHeader *exr_header, const unsigned char *head, const unsigned char *marker, const size_t size, const char **err) { if (exr_image == NULL || exr_header == NULL || head == NULL || marker == NULL || (size <= tinyexr::kEXRVersionSize)) { 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 window 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 window or data height is negative.", 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; 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; } } } return DecodeChunk(exr_image, exr_header, offsets, head, size); } } // namespace tinyexr int LoadEXR(float **out_rgba, int *width, int *height, const char *filename, const char **err) { if (out_rgba == NULL) { 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) { 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) { return ret; } } // RGBA int idxR = -1; int idxG = -1; int idxB = -1; int idxA = -1; for (int c = 0; c < exr_header.num_channels; c++) { if (strcmp(exr_header.channels[c].name, "R") == 0) { idxR = c; } else if (strcmp(exr_header.channels[c].name, "G") == 0) { idxG = c; } else if (strcmp(exr_header.channels[c].name, "B") == 0) { idxB = c; } else if (strcmp(exr_header.channels[c].name, "A") == 0) { idxA = c; } } if ((idxA == 0) && (idxR == -1) && (idxG == -1) && (idxB == -1)) { // Alpha channel only. if (exr_header.tiled) { // todo.implement this } (*out_rgba) = reinterpret_cast<float *>( malloc(4 * sizeof(float) * static_cast<size_t>(exr_image.width) * static_cast<size_t>(exr_image.height))); for (int i = 0; i < exr_image.width * exr_image.height; i++) { const float val = reinterpret_cast<float **>(exr_image.images)[0][i]; (*out_rgba)[4 * i + 0] = val; (*out_rgba)[4 * i + 1] = val; (*out_rgba)[4 * i + 2] = val; (*out_rgba)[4 * i + 3] = val; } } else { // Assume RGB(A) if (idxR == -1) { 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 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) { 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; } } 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))); 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) { 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; // @fixme } #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<unsigned char> data; std::vector<std::vector<unsigned char> > data_list( static_cast<size_t>(num_blocks)); std::vector<size_t> channel_offset_list( static_cast<size_t>(exr_header->num_channels)); int pixel_data_size = 0; size_t channel_offset = 0; for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { channel_offset_list[c] = channel_offset; if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { pixel_data_size += sizeof(unsigned short); channel_offset += sizeof(unsigned short); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { pixel_data_size += sizeof(float); channel_offset += sizeof(float); } else if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_UINT) { pixel_data_size += sizeof(unsigned int); channel_offset += sizeof(unsigned int); } else { assert(0); } } #if TINYEXR_USE_ZFP tinyexr::ZFPCompressionParam zfp_compression_param; // Use ZFP compression parameter from custom attributes(if such a parameter // exists) { bool ret = tinyexr::FindZFPCompressionParam( &zfp_compression_param, exr_header->custom_attributes, exr_header->num_custom_attributes); if (!ret) { // Use predefined compression parameter. zfp_compression_param.type = 0; zfp_compression_param.rate = 2; } } #endif // Use signed int since some OpenMP compiler doesn't allow unsigned type for // `parallel for` #ifdef _OPENMP #pragma omp parallel for #endif for (int i = 0; i < num_blocks; i++) { size_t ii = static_cast<size_t>(i); int start_y = num_scanlines * i; int endY = (std::min)(num_scanlines * (i + 1), exr_image->height); int h = endY - start_y; std::vector<unsigned char> buf( static_cast<size_t>(exr_image->width * h * pixel_data_size)); for (size_t c = 0; c < static_cast<size_t>(exr_header->num_channels); c++) { if (exr_header->pixel_types[c] == TINYEXR_PIXELTYPE_HALF) { if (exr_header->requested_pixel_types[c] == TINYEXR_PIXELTYPE_FLOAT) { for (int y = 0; y < h; y++) { // 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 = 1024 + static_cast<unsigned int>( 1.2 * static_cast<unsigned int>( buf.size())); // @fixme { compute good bound. } std::vector<unsigned char> block(bufLen); unsigned int outSize = static_cast<unsigned int>(block.size()); CompressPiz(&block.at(0), &outSize, reinterpret_cast<const unsigned char *>(&buf.at(0)), buf.size(), channels, exr_image->width, h); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else if (exr_header->compression_type == TINYEXR_COMPRESSIONTYPE_ZFP) { #if TINYEXR_USE_ZFP std::vector<unsigned char> block; unsigned int outSize; tinyexr::CompressZfp( &block, &outSize, reinterpret_cast<const float *>(&buf.at(0)), exr_image->width, h, exr_header->num_channels, zfp_compression_param); // 4 byte: scan line // 4 byte: data size // ~ : pixel data(compressed) std::vector<unsigned char> header(8); unsigned int data_len = outSize; memcpy(&header.at(0), &start_y, sizeof(int)); memcpy(&header.at(4), &data_len, sizeof(unsigned int)); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(0))); tinyexr::swap4(reinterpret_cast<unsigned int *>(&header.at(4))); data_list[ii].insert(data_list[ii].end(), header.begin(), header.end()); data_list[ii].insert(data_list[ii].end(), block.begin(), block.begin() + data_len); #else assert(0); #endif } else { assert(0); } } // omp parallel for (size_t i = 0; i < static_cast<size_t>(num_blocks); i++) { data.insert(data.end(), data_list[i].begin(), data_list[i].end()); offsets[i] = offset; tinyexr::swap8(reinterpret_cast<tinyexr::tinyexr_uint64 *>(&offsets[i])); offset += data_list[i].size(); } { memory.insert( memory.end(), reinterpret_cast<unsigned char *>(&offsets.at(0)), reinterpret_cast<unsigned char *>(&offsets.at(0)) + sizeof(tinyexr::tinyexr_uint64) * static_cast<size_t>(num_blocks)); } { memory.insert(memory.end(), data.begin(), data.end()); } assert(memory.size() > 0); (*memory_out) = static_cast<unsigned char *>(malloc(memory.size())); memcpy((*memory_out), &memory.at(0), memory.size()); return memory.size(); // OK } int SaveEXRImageToFile(const EXRImage *exr_image, const EXRHeader *exr_header, const char *filename, const char **err) { if (exr_image == NULL || filename == NULL || exr_header->compression_type < 0) { 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 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 #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_OPEN_FILE; } unsigned char *mem = NULL; size_t mem_size = SaveEXRImageToMemory(exr_image, exr_header, &mem, err); if ((mem_size > 0) && mem) { fwrite(mem, 1, mem_size, fp); } free(mem); fclose(fp); return TINYEXR_SUCCESS; } int LoadDeepEXR(DeepImage *deep_image, const char *filename, const char **err) { if (deep_image == NULL) { 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)) { 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) { 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; } } int ret = tinyexr::DecodeChunk(&exr_images[i], exr_headers[i], offset_table, memory, size); if (ret != TINYEXR_SUCCESS) { tinyexr::SetErrorMessage("Error in DecodeChunk()", 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) { if ((components == 1) || components == 3 || components == 4) { // OK } else { return TINYEXR_ERROR_INVALID_ARGUMENT; } // Assume at least 16x16 pixels. if (width < 16) return TINYEXR_ERROR_INVALID_ARGUMENT; if (height < 16) return TINYEXR_ERROR_INVALID_ARGUMENT; EXRHeader header; InitEXRHeader(&header); EXRImage image; InitEXRImage(&image); image.num_channels = components; std::vector<float> images[4]; if (components == 1) { images[0].resize(static_cast<size_t>(width * height)); memcpy(images[0].data(), data, sizeof(float) * size_t(width * height)); } else { images[0].resize(static_cast<size_t>(width * height)); images[1].resize(static_cast<size_t>(width * height)); images[2].resize(static_cast<size_t>(width * height)); images[3].resize(static_cast<size_t>(width * height)); // Split RGB(A)RGB(A)RGB(A)... into R, G and B(and A) layers for (size_t i = 0; i < static_cast<size_t>(width * height); i++) { images[0][i] = data[static_cast<size_t>(components) * i + 0]; images[1][i] = data[static_cast<size_t>(components) * i + 1]; images[2][i] = data[static_cast<size_t>(components) * i + 2]; if (components == 4) { images[3][i] = data[static_cast<size_t>(components) * i + 3]; } } } float *image_ptr[4] = {0, 0, 0, 0}; if (components == 4) { image_ptr[0] = &(images[3].at(0)); // A image_ptr[1] = &(images[2].at(0)); // B image_ptr[2] = &(images[1].at(0)); // G image_ptr[3] = &(images[0].at(0)); // R } else if (components == 3) { image_ptr[0] = &(images[2].at(0)); // B image_ptr[1] = &(images[1].at(0)); // G image_ptr[2] = &(images[0].at(0)); // R } else if (components == 1) { image_ptr[0] = &(images[0].at(0)); // A } image.images = reinterpret_cast<unsigned char **>(image_ptr); image.width = width; image.height = height; header.num_channels = components; header.channels = static_cast<EXRChannelInfo *>(malloc( sizeof(EXRChannelInfo) * static_cast<size_t>(header.num_channels))); // Must be (A)BGR order, since most of EXR viewers expect this channel order. if (components == 4) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); strncpy_s(header.channels[1].name, "B", 255); strncpy_s(header.channels[2].name, "G", 255); strncpy_s(header.channels[3].name, "R", 255); #else strncpy(header.channels[0].name, "A", 255); strncpy(header.channels[1].name, "B", 255); strncpy(header.channels[2].name, "G", 255); strncpy(header.channels[3].name, "R", 255); #endif header.channels[0].name[strlen("A")] = '\0'; header.channels[1].name[strlen("B")] = '\0'; header.channels[2].name[strlen("G")] = '\0'; header.channels[3].name[strlen("R")] = '\0'; } else if (components == 3) { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "B", 255); strncpy_s(header.channels[1].name, "G", 255); strncpy_s(header.channels[2].name, "R", 255); #else strncpy(header.channels[0].name, "B", 255); strncpy(header.channels[1].name, "G", 255); strncpy(header.channels[2].name, "R", 255); #endif header.channels[0].name[strlen("B")] = '\0'; header.channels[1].name[strlen("G")] = '\0'; header.channels[2].name[strlen("R")] = '\0'; } else { #ifdef _MSC_VER strncpy_s(header.channels[0].name, "A", 255); #else strncpy(header.channels[0].name, "A", 255); #endif header.channels[0].name[strlen("A")] = '\0'; } header.pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); header.requested_pixel_types = static_cast<int *>( malloc(sizeof(int) * static_cast<size_t>(header.num_channels))); for (int i = 0; i < header.num_channels; i++) { header.pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // pixel type of input image if (save_as_fp16 > 0) { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_HALF; // save with half(fp16) pixel format } else { header.requested_pixel_types[i] = TINYEXR_PIXELTYPE_FLOAT; // save with float(fp32) pixel format(i.e. // no precision reduction) } } const char *err; int ret = SaveEXRImageToFile(&image, &header, outfilename, &err); if (ret != TINYEXR_SUCCESS) { return ret; } free(header.channels); free(header.pixel_types); free(header.requested_pixel_types); return ret; } #ifdef __clang__ // zero-as-null-ppinter-constant #pragma clang diagnostic pop #endif #endif // TINYEXR_IMPLEMENTATION_DEIFNED #endif // TINYEXR_IMPLEMENTATION
sc_demo.c
/* main.c * Created by Mengyao Zhao on 06/23/11. * Version 0.1.5 * Last revision by Mengyao Zhao on 06/27/14. */ #include <stdlib.h> #include <stdint.h> #include <emmintrin.h> #include <zlib.h> #include <stdio.h> #include <time.h> #include <sys/time.h> #include <string.h> #include <math.h> #include <unistd.h> #include "ssw.h" #include "kseq.h" #include <omp.h> #ifdef __GNUC__ #define LIKELY(x) __builtin_expect((x),1) #define UNLIKELY(x) __builtin_expect((x),0) #else #define LIKELY(x) (x) #define UNLIKELY(x) (x) #endif /*! @function @abstract Round an integer to the next closest power-2 integer. @param x integer to be rounded (in place) @discussion x will be modified. */ #define kroundup32(x) (--(x), (x)|=(x)>>1, (x)|=(x)>>2, (x)|=(x)>>4, (x)|=(x)>>8, (x)|=(x)>>16, ++(x)) KSEQ_INIT(gzFile, gzread); // l is length // m is allocated memory void genSeq(kseq_t *read, kseq_t *ref) { const int reflen = 256; const int readlen = 128; int baseidx; read->name.s = strdup("READ"); read->seq.s = (char*) malloc(readlen*sizeof(char)+1); read->seq.m = readlen; ref->name.s = strdup("REF"); ref->seq.s = (char*) malloc(reflen*sizeof(char)+1); ref->seq.m = reflen; char bases[5] = "ACTG"; for(baseidx = 0; baseidx < reflen; ++baseidx) { char b = bases[rand()%4]; ref->seq.s[baseidx] = b; } ref->seq.l = reflen; for(baseidx = 0; baseidx < readlen; ++baseidx) { char b = bases[rand()%4]; read->seq.s[baseidx] = b; } read->seq.l = readlen; ref->seq.s[reflen] = '\0'; read->seq.s[readlen] = '\0'; /*printf("READ: %s\nREF: %s\n",read->seq.s,ref->seq.s);*/ } void freeSeq(kseq_t *seq) { free(seq->name.s); free(seq->seq.s); } static void ssw_write (const s_align* a, const kseq_t* ref_seq, const kseq_t* read, const char* read_seq, // strand == 0: original read; strand == 1: reverse complement read const int8_t* table, int8_t strand) { // 0: forward aligned ; 1: reverse complement aligned //fprintf(stdout, "target_name: %s\nquery_name: %s\noptimal_alignment_score: %d\t", ref_seq->name.s, read->name.s, a->score1); //if (a->score2 > 0) fprintf(stdout, "suboptimal_alignment_score: %d\t", a->score2); //if (strand == 0) fprintf(stdout, "strand: +\t"); //else fprintf(stdout, "strand: -\t"); //if (a->ref_begin1 + 1) fprintf(stdout, "target_begin: %d\t", a->ref_begin1 + 1); //fprintf(stdout, "target_end: %d\t", a->ref_end1 + 1); //if (a->read_begin1 + 1) fprintf(stdout, "query_begin: %d\t", a->read_begin1 + 1); //fprintf(stdout, "query_end: %d\n\n", a->read_end1 + 1); if (a->cigar) { int32_t c = 0, left = 0, e = 0, qb = a->ref_begin1, pb = a->read_begin1; uint32_t i; while (e < a->cigarLen || left > 0) { int32_t count = 0; int32_t q = qb; int32_t p = pb; fprintf(stdout, "Target: %8d ", q + 1); for (c = e; c < a->cigarLen; ++c) { char letter = cigar_int_to_op(a->cigar[c]); uint32_t length = cigar_int_to_len(a->cigar[c]); uint32_t l = (count == 0 && left > 0) ? left: length; for (i = 0; i < l; ++i) { if (letter == 'I') fprintf(stdout, "-"); else { fprintf(stdout, "%c", *(ref_seq->seq.s + q)); ++ q; } ++ count; if (count == 60) goto step2; } } step2: fprintf(stdout, " %d\n ", q); q = qb; count = 0; for (c = e; c < a->cigarLen; ++c) { char letter = cigar_int_to_op(a->cigar[c]); uint32_t length = cigar_int_to_len(a->cigar[c]); uint32_t l = (count == 0 && left > 0) ? left: length; for (i = 0; i < l; ++i){ if (letter == 'M') { if (table[(int)*(ref_seq->seq.s + q)] == table[(int)*(read_seq + p)])fprintf(stdout, "|"); else fprintf(stdout, "*"); ++q; ++p; } else { fprintf(stdout, " "); if (letter == 'I') ++p; else ++q; } ++ count; if (count == 60) { qb = q; goto step3; } } } step3: p = pb; fprintf(stdout, "\nQuery: %8d ", p + 1); count = 0; for (c = e; c < a->cigarLen; ++c) { char letter = cigar_int_to_op(a->cigar[c]); uint32_t length = cigar_int_to_len(a->cigar[c]); uint32_t l = (count == 0 && left > 0) ? left: length; for (i = 0; i < l; ++i) { if (letter == 'D') fprintf(stdout, "-"); else { fprintf(stdout, "%c", *(read_seq + p)); ++p; } ++ count; if (count == 60) { pb = p; left = l - i - 1; e = (left == 0) ? (c + 1) : c; goto end; } } } e = c; left = 0; end: fprintf(stdout, " %d\n\n", p); } } } void genSSWData(int niter, int numsample, kseq_t **read, kseq_t **ref){ //seed randrom to get more chaotic output srand (time(NULL)); kseq_t *testread = (kseq_t *)malloc(sizeof(kseq_t)*niter*numsample); kseq_t *testref = (kseq_t *)malloc(sizeof(kseq_t)*niter*numsample); int ii; for(ii =0; ii < niter*numsample; ++ii){ genSeq(&testread[ii], &testref[ii]); } *read = testread; *ref = testref; } void deleteSSWData(int niter, int numsample, kseq_t **read, kseq_t **ref){ kseq_t *testread = *read; kseq_t *testref = *ref; int ii; for(ii =0; ii < niter*numsample; ++ii){ freeSeq(&testread[ii]); freeSeq(&testref[ii]); } free(*read); free(*ref); } float SSW(int numsample, int tid, kseq_t *read, kseq_t *ref, unsigned int *maxr, unsigned int *maxc, unsigned int *maxv){ kseq_t *read_seq, *ref_seq; int32_t l, m, k, match = 2, mismatch = 2, gap_open = 3, gap_extension = 1, path = 0, n = 5, s1 = 67108864, s2 = 128, filter = 0; int8_t* mata = (int8_t*)calloc(25, sizeof(int8_t)); const int8_t* mat = mata; int8_t* ref_num = (int8_t*)malloc(s1); int8_t* num = (int8_t*)malloc(s2), *num_rc = 0; char* read_rc = 0; int total = numsample; float total_cups = 0; /* This table is used to transform nucleotide letters into numbers. */ int8_t nt_table[128] = { 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, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; int8_t* table = nt_table; fprintf(stdout, "Processing %d samples using Intel Vector Instruction Set in Thread %d\n", numsample, tid); // initialize scoring matrix for genome sequences for (l = k = 0; LIKELY(l < 4); ++l) { for (m = 0; LIKELY(m < 4); ++m) mata[k++] = l == m ? match : -mismatch; /* weight_match : -weight_mismatch */ mata[k++] = 0; // ambiguous base } for (m = 0; LIKELY(m < 5); ++m) mata[k++] = 0; // alignment int ii; for(ii =0; ii < total; ++ii){ // clear screen newline //printf("\033[2J\033[1;1H"); read_seq = &read[ii]; ref_seq = &ref[ii]; { s_profile* p = 0; int32_t readLen = read_seq->seq.l; int32_t maskLen = readLen / 2; while (readLen >= s2) { ++s2; kroundup32(s2); num = (int8_t*)realloc(num, s2); } for (m = 0; m < readLen; ++m) num[m] = table[(int)read_seq->seq.s[m]]; p = ssw_init(num, readLen, mat, n, 2); { s_align* result, *result_rc = 0; int32_t refLen = ref_seq->seq.l; int8_t flag = 0; while (refLen > s1) { ++s1; kroundup32(s1); ref_num = (int8_t*)realloc(ref_num, s1); } for (m = 0; m < refLen; ++m) ref_num[m] = table[(int)ref_seq->seq.s[m]]; if (path == 1) flag = 2; result = ssw_align (p, ref_num, refLen, gap_open, gap_extension, flag, filter, 0, maskLen, &total_cups, &maxr[ii], &maxc[ii], &maxv[ii]); if (result_rc && result_rc->score1 > result->score1 && result_rc->score1 >= filter) { ssw_write (result_rc, ref_seq, read_seq, read_rc, table, 1); }else if (result && result->score1 >= filter){ ssw_write(result, ref_seq, read_seq, read_seq->seq.s, table, 0); } else if (! result) return 1; if (result_rc) align_destroy(result_rc); align_destroy(result); } init_destroy(p); } } if (num_rc) { free(num_rc); free(read_rc); } //kseq_destroy(read_seq); free(num); free(ref_num); free(mata); return total_cups/(numsample); } long xgetusec() { struct timeval tval_result; gettimeofday(&tval_result, NULL); long retval = tval_result.tv_sec*1e6+tval_result.tv_usec; return retval; } int SSW_par(int nblocks, int nSamples, int nThreads, char **rd, char **rf, unsigned int *maxr, unsigned int *maxc, unsigned int *maxv){ int i; omp_set_num_threads(nThreads); kseq_t *read, *ref; clock_t start, end; start = clock(); printf("Generating samples\n"); genSSWData(nblocks, nSamples, &read, &ref); printf("Done generating %d samples\n", nblocks*nSamples); end = clock(); float cpu_time_read = ((float) (end - start)) / CLOCKS_PER_SEC; printf("Time to generate Samples Secs: %f\n", (float)cpu_time_read); printf("Distributing samples on %d threads\n", nThreads); double ostart = omp_get_wtime(); int ID; int nIter = nThreads; int samples = nblocks*nSamples/nIter; #pragma omp parallel for for(i = 0; i < nIter; ++i) { ID = omp_get_thread_num(); SSW(samples, ID, (read + i*samples), (ref + i*samples), (maxr + i*samples), (maxc + i*samples), (maxv + i*samples)); } double oend = omp_get_wtime(); float Gsamples = 256*128; Gsamples = Gsamples*nSamples*nblocks; Gsamples = Gsamples/(1024*1024*1024); float Gcups = Gsamples/(float)(oend-ostart); printf("Total Cell Updates(G)=%f\n", Gsamples); printf("Total Threads=%d\n", nThreads); printf("Time to complete computation Secs: %f\n", (float)(oend - ostart)); printf("Cell updates per second(GCups)=%f\n", Gcups); for(i = 0; i < nblocks*nSamples; ++i){ strcpy(rd[i], read[i].seq.s); strcpy(rf[i], ref[i].seq.s); } deleteSSWData(nblocks, nSamples, &read, &ref); return 0; } /* int main (int argc, char * const argv[]) { clock_t start, end; float cpu_time; kseq_t *read_seq, *ref_seq; int32_t l, m, k, match = 2, mismatch = 2, gap_open = 3, gap_extension = 1, path = 0, n = 5, s1 = 67108864, s2 = 128, filter=0; int8_t* mata = (int8_t*)calloc(25, sizeof(int8_t)); int8_t nt_table[128] = { 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, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; // Parse command line. while ((l = getopt(argc, argv, "m:x:o:e:a:f:pcrsh")) >= 0) { switch (l) { case 'm': match = atoi(optarg); break; case 'x': mismatch = atoi(optarg); break; case 'o': gap_open = atoi(optarg); break; case 'e': gap_extension = atoi(optarg); break; case 'f': filter = atoi(optarg); break; case 'c': path = 1; break; } } if (0 && optind + 2 > argc) { fprintf(stderr, "\n"); fprintf(stderr, "Usage: ssw_test [options] ... <target.fasta> <query.fasta>(or <query.fastq>)\n"); fprintf(stderr, "Options:\n"); fprintf(stderr, "\t-m N\tN is a positive integer for weight match in genome sequence alignment. [default: 2]\n"); fprintf(stderr, "\t-x N\tN is a positive integer. -N will be used as weight mismatch in genome sequence alignment. [default: 2]\n"); fprintf(stderr, "\t-o N\tN is a positive integer. -N will be used as the weight for the gap opening. [default: 3]\n"); fprintf(stderr, "\t-e N\tN is a positive integer. -N will be used as the weight for the gap extension. [default: 1]\n"); fprintf(stderr, "\t-c\tReturn the alignment path.\n"); fprintf(stderr, "\t-f N\tN is a positive integer. Only output the alignments with the Smith-Waterman score >= N.\n"); return 1; } SSW(); } */
assign_scalar_variable_to_conditions_process.h
// // | / | // ' / __| _` | __| _ \ __| // . \ | ( | | ( |\__ ` // _|\_\_| \__,_|\__|\___/ ____/ // Multi-Physics // // License: BSD License // Kratos default license: kratos/license.txt // // Main authors: Josep Maria Carbonell // #if !defined(KRATOS_ASSIGN_SCALAR_VARIABLE_TO_CONDITIONS_PROCESS_H_INCLUDED ) #define KRATOS_ASSIGN_SCALAR_VARIABLE_TO_CONDITIONS_PROCESS_H_INCLUDED // System includes // External includes // Project includes #include "includes/model_part.h" #include "includes/kratos_parameters.h" #include "processes/process.h" namespace Kratos { ///@name Kratos Classes ///@{ /// The base class for assigning a value to scalar variables or array_1d components processes in Kratos. /** This function assigns a value to a variable belonging to all of the nodes in a given mesh */ class AssignScalarVariableToConditionsProcess : public Process { public: ///@name Type Definitions ///@{ typedef VariableComponent<VectorComponentAdaptor<array_1d<double, 3> > > array_1d_component_type; /// Pointer definition of AssignScalarVariableToConditionsProcess KRATOS_CLASS_POINTER_DEFINITION(AssignScalarVariableToConditionsProcess); ///@} ///@name Life Cycle ///@{ AssignScalarVariableToConditionsProcess( ModelPart& rModelPart, Parameters rParameters ) : Process(Flags()) , mrModelPart(rModelPart) { KRATOS_TRY Parameters default_parameters( R"( { "model_part_name":"MODEL_PART_NAME", "mesh_id": 0, "variable_name": "VARIABLE_NAME", "value" : 1.0 } )" ); // Validate against defaults -- this ensures no type mismatch rParameters.ValidateAndAssignDefaults(default_parameters); mmesh_id = rParameters["mesh_id"].GetInt(); mvariable_name = rParameters["variable_name"].GetString(); if( KratosComponents< Variable<double> >::Has( mvariable_name )) //case of double variable { mdouble_value = rParameters["value"].GetDouble(); } else if( KratosComponents<array_1d_component_type>::Has( mvariable_name ) ) //case of component variable { mdouble_value = rParameters["value"].GetDouble(); } else if( KratosComponents< Variable<int> >::Has( mvariable_name ) ) //case of int variable { mint_value = rParameters["value"].GetInt(); } else if( KratosComponents< Variable<bool> >::Has( mvariable_name ) ) //case of bool variable { mbool_value = rParameters["value"].GetBool(); } else { KRATOS_ERROR <<"Trying to set a variable that is not in the model_part - variable name is " << mvariable_name << std::endl; } KRATOS_CATCH(""); } /// Destructor. ~AssignScalarVariableToConditionsProcess() override {} ///@} ///@name Operators ///@{ /// This operator is provided to call the process as a function and simply calls the Execute method. void operator()() { Execute(); } ///@} ///@name Operations ///@{ /// Execute method is used to execute the AssignScalarVariableToConditionsProcess algorithms. void Execute() override { KRATOS_TRY; if( KratosComponents< Variable<double> >::Has( mvariable_name )) //case of double variable { InternalAssignValue<>(KratosComponents< Variable<double> >::Get(mvariable_name), mdouble_value); } else if( KratosComponents<array_1d_component_type>::Has( mvariable_name ) ) //case of component variable { InternalAssignValueSerial<>(KratosComponents<array_1d_component_type>::Get(mvariable_name), mdouble_value); } else if( KratosComponents< Variable<int> >::Has( mvariable_name ) ) //case of int variable { InternalAssignValue<>(KratosComponents< Variable<int> >::Get(mvariable_name) , mint_value); } else if( KratosComponents< Variable<bool> >::Has( mvariable_name ) ) //case of bool variable { InternalAssignValue<>(KratosComponents< Variable<bool> >::Get(mvariable_name), mbool_value); } else { KRATOS_ERROR << "Not able to set the variable. Attempting to set variable: " << mvariable_name << std::endl; } KRATOS_CATCH(""); } void ExecuteInitializeSolutionStep() override { Execute(); } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. std::string Info() const override { return "AssignScalarVariableToConditionsProcess"; } /// Print information about this object. void PrintInfo(std::ostream& rOStream) const override { rOStream << "AssignScalarVariableToConditionsProcess"; } /// Print object's data. void PrintData(std::ostream& rOStream) const override { } ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ /// Copy constructor. AssignScalarVariableToConditionsProcess(AssignScalarVariableToConditionsProcess const& rOther); ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ModelPart& mrModelPart; std::string mvariable_name; // double mdouble_value; double mdouble_value; int mint_value; bool mbool_value; std::size_t mmesh_id; ///@} ///@name Private Operators ///@{ template< class TVarType, class TDataType > void InternalAssignValue(TVarType& rVar, const TDataType value) { const int nconditions = mrModelPart.GetMesh(mmesh_id).Conditions().size(); if(nconditions != 0) { ModelPart::ConditionsContainerType::iterator it_begin = mrModelPart.GetMesh(mmesh_id).ConditionsBegin(); #pragma omp parallel for for(int i = 0; i<nconditions; i++) { ModelPart::ConditionsContainerType::iterator it = it_begin + i; it->SetValue(rVar, value); } } } template< class TVarType, class TDataType > void InternalAssignValueSerial(TVarType& rVar, const TDataType value) { const int nconditions = mrModelPart.GetMesh(mmesh_id).Conditions().size(); if(nconditions != 0) { ModelPart::ConditionsContainerType::iterator it_begin = mrModelPart.GetMesh(mmesh_id).ConditionsBegin(); for(int i = 0; i<nconditions; i++) { ModelPart::ConditionsContainerType::iterator it = it_begin + i; it->SetValue(rVar, value); } } } ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ /// Assignment operator. AssignScalarVariableToConditionsProcess& operator=(AssignScalarVariableToConditionsProcess const& rOther); ///@} ///@name Serialization ///@{ ///@name Private Inquiry ///@{ ///@} ///@name Un accessible methods ///@{ ///@} }; // Class AssignScalarVariableToConditionsProcess ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function inline std::istream& operator >> (std::istream& rIStream, AssignScalarVariableToConditionsProcess& rThis); /// output stream function inline std::ostream& operator << (std::ostream& rOStream, const AssignScalarVariableToConditionsProcess& rThis) { rThis.PrintInfo(rOStream); rOStream << std::endl; rThis.PrintData(rOStream); return rOStream; } ///@} } // namespace Kratos. #endif // KRATOS_ASSIGN_SCALAR_VARIABLE_TO_CONDITIONS_PROCESS_H_INCLUDED defined
conv.c
#include <stdint.h> #include <stdlib.h> void neuralops_omp_caffe_im2col( const float *in_buf, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, float *col_buf) { //const float *data_im = in_buf; //float *data_col = col_buf; const int output_h = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int output_w = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; const int channel_size = height * width; //for (int channel = channels; channel--; data_im += channel_size) { #pragma omp parallel for for (int channel = 0; channel < channels; channel++) { const float *data_im = in_buf + channel * channel_size; float *data_col = col_buf + channel * output_w * output_h * kernel_w * kernel_h; for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) { for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) { int input_row = -pad_h + kernel_row * dilation_h; for (int output_rows = output_h; output_rows; output_rows--) { //if (!is_a_ge_zero_and_a_lt_b(input_row, height)) { if (!(input_row >= 0 && input_row < height)) { for (int output_cols = output_w; output_cols; output_cols--) { *(data_col++) = 0.0f; } } else { int input_col = -pad_w + kernel_col * dilation_w; for (int output_col = output_w; output_col; output_col--) { //if (is_a_ge_zero_and_a_lt_b(input_col, width)) { if (input_col >= 0 && input_col < width) { *(data_col++) = data_im[input_row * width + input_col]; } else { *(data_col++) = 0.0f; } input_col += stride_w; } } input_row += stride_h; } } } } } void neuralops_omp_caffe_col2im( const float *col_buf, const int channels, const int height, const int width, const int kernel_h, const int kernel_w, const int pad_h, const int pad_w, const int stride_h, const int stride_w, const int dilation_h, const int dilation_w, float *out_buf) { //const float *data_col = col_buf; //float *data_im = out_buf; //caffe_set(height * width * channels, float(0), data_im); const int output_h = (height + 2 * pad_h - (dilation_h * (kernel_h - 1) + 1)) / stride_h + 1; const int output_w = (width + 2 * pad_w - (dilation_w * (kernel_w - 1) + 1)) / stride_w + 1; const int channel_size = height * width; //for (int channel = channels; channel--; data_im += channel_size) { #pragma omp parallel for for (int channel = 0; channel < channels; channel++) { const float *data_col = col_buf + channel * output_w * output_h * kernel_w * kernel_h; float *data_im = out_buf + channel * channel_size; for (int kernel_row = 0; kernel_row < kernel_h; kernel_row++) { for (int kernel_col = 0; kernel_col < kernel_w; kernel_col++) { int input_row = -pad_h + kernel_row * dilation_h; for (int output_rows = output_h; output_rows; output_rows--) { //if (!is_a_ge_zero_and_a_lt_b(input_row, height)) { if (!(input_row >= 0 && input_row < height)) { data_col += output_w; } else { int input_col = -pad_w + kernel_col * dilation_w; for (int output_col = output_w; output_col; output_col--) { //if (is_a_ge_zero_and_a_lt_b(input_col, width)) { if (input_col >= 0 && input_col < width) { data_im[input_row * width + input_col] += *data_col; } data_col++; input_col += stride_w; } } input_row += stride_h; } } } } }
Standard.h
// // Created by thahnen on 01.07.19. // #pragma once #ifndef AIOLOS_STANDARD_H #define AIOLOS_STANDARD_H namespace GLCM { namespace Standard { /** * Creates the standard GLCM based on the given parameters * * @tparam T single channel type: char/uchar, short/ushort, int * @param image the given image * @param glcm the matrix, the GLCM is stored to * @param r the radius, the GLCM is based on * @param theta the angle, the GLCM is based on (in radiant!) * * TODO: change x, y to int (and x2, y2 as well) to test for negative values! */ template <typename T> void GLCM(const cv::Mat_<T>& image, cv::Mat1d& glcm, double r, double theta) { double dist_x = r*cos(theta); double dist_y = r*sin(theta); #pragma omp parallel for collapse(2) shared(dist_x, dist_y) for (unsigned int y = 0; y < image.cols; y++) { for (unsigned int x = 0; x < image.rows; x++) { unsigned int x2 = x + dist_x; if (x2 < 0 || x2 >= image.cols) continue; unsigned int y2 = y + dist_y; if (y2 < 0 || y2 >= image.rows) continue; glcm(image(y, x), image(y2, x2))++; } } } } } #endif //AIOLOS_STANDARD_H
GB_binop__rdiv_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_03__rdiv_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__rdiv_uint8) // A*D function (colscale): GB (_AxD__rdiv_uint8) // D*A function (rowscale): GB (_DxB__rdiv_uint8) // C+=B function (dense accum): GB (_Cdense_accumB__rdiv_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__rdiv_uint8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__rdiv_uint8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__rdiv_uint8) // C=scalar+B GB (_bind1st__rdiv_uint8) // C=scalar+B' GB (_bind1st_tran__rdiv_uint8) // C=A+scalar GB (_bind2nd__rdiv_uint8) // C=A'+scalar GB (_bind2nd_tran__rdiv_uint8) // C type: uint8_t // A type: uint8_t // B,b type: uint8_t // BinaryOp: cij = GB_IDIV_UNSIGNED (bij, aij, 8) #define GB_ATYPE \ uint8_t #define GB_BTYPE \ uint8_t #define GB_CTYPE \ uint8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint8_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint8_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ 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 = GB_IDIV_UNSIGNED (y, x, 8) ; // 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_RDIV || GxB_NO_UINT8 || GxB_NO_RDIV_UINT8) //------------------------------------------------------------------------------ // 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__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__rdiv_uint8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type uint8_t uint8_t bwork = (*((uint8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C = A+B or C<M> = A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__rdiv_uint8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__rdiv_uint8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__rdiv_uint8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__rdiv_uint8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t x = (*((uint8_t *) x_input)) ; uint8_t *Bx = (uint8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; uint8_t bij = Bx [p] ; Cx [p] = GB_IDIV_UNSIGNED (bij, x, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__rdiv_uint8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; uint8_t *Cx = (uint8_t *) Cx_output ; uint8_t *Ax = (uint8_t *) Ax_input ; uint8_t y = (*((uint8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; uint8_t aij = Ax [p] ; Cx [p] = GB_IDIV_UNSIGNED (y, aij, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (aij, x, 8) ; \ } GrB_Info GB (_bind1st_tran__rdiv_uint8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ uint8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t x = (*((const uint8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = Ax [pA] ; \ Cx [pC] = GB_IDIV_UNSIGNED (y, aij, 8) ; \ } GrB_Info GB (_bind2nd_tran__rdiv_uint8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t y = (*((const uint8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
interp2.c
/* * Academic License - for use in teaching, academic research, and meeting * course requirements at degree granting institutions only. Not for * government, commercial, or other organizational use. * * interp2.c * * Code generation for function 'interp2' * */ /* Include files */ #include "interp2.h" #include "eml_int_forloop_overflow_check.h" #include "no_raytracing_latlon_data.h" #include "no_raytracing_latlon_emxutil.h" #include "no_raytracing_latlon_types.h" #include "rt_nonfinite.h" #include "mwmathutil.h" /* Variable Definitions */ static emlrtRSInfo gd_emlrtRSI = { 274,/* lineNo */ "interp2_local", /* fcnName */ "C:\\Program Files\\MATLAB\\R2020b\\toolbox\\eml\\lib\\matlab\\polyfun\\interp2.m"/* pathName */ }; static emlrtRTEInfo jg_emlrtRTEI = { 268,/* lineNo */ 21, /* colNo */ "interp2", /* fName */ "C:\\Program Files\\MATLAB\\R2020b\\toolbox\\eml\\lib\\matlab\\polyfun\\interp2.m"/* pName */ }; /* Function Definitions */ void interp2_local(const emlrtStack *sp, const emxArray_real_T *V, const emxArray_real_T *Xq, const emxArray_real_T *Yq, emxArray_real_T *Vq) { jmp_buf * volatile emlrtJBStack; emlrtStack b_st; emlrtStack st; real_T qx1; real_T qx2; real_T rx; real_T ry; real_T zx1y2; int32_T ix; int32_T ixmax; int32_T iy; int32_T iymax; int32_T k; int32_T ub_loop; st.prev = sp; st.tls = sp->tls; b_st.prev = &st; b_st.tls = st.tls; ixmax = Vq->size[0]; Vq->size[0] = Xq->size[0]; emxEnsureCapacity_real_T(sp, Vq, ixmax, &jg_emlrtRTEI); ixmax = V->size[1] - 1; iymax = V->size[0] - 1; st.site = &gd_emlrtRSI; if ((1 <= Xq->size[0]) && (Xq->size[0] > 2147483646)) { b_st.site = &x_emlrtRSI; check_forloop_overflow_error(&b_st); } ub_loop = Xq->size[0] - 1; emlrtEnterParallelRegion(sp, omp_in_parallel()); emlrtPushJmpBuf(sp, &emlrtJBStack); #pragma omp parallel for \ num_threads(emlrtAllocRegionTLSs(sp->tls, omp_in_parallel(), omp_get_max_threads(), omp_get_num_procs())) \ private(ix,iy,ry,qx1,zx1y2,qx2,rx) for (k = 0; k <= ub_loop; k++) { if ((Xq->data[k] >= 1.0) && (Xq->data[k] <= V->size[1]) && (Yq->data[k] >= 1.0) && (Yq->data[k] <= V->size[0])) { if (Xq->data[k] <= 1.0) { ix = 1; } else if (Xq->data[k] <= ixmax) { ix = (int32_T)muDoubleScalarFloor(Xq->data[k]); } else { ix = ixmax; } if (Yq->data[k] <= 1.0) { iy = 1; } else if (Yq->data[k] <= iymax) { iy = (int32_T)muDoubleScalarFloor(Yq->data[k]); } else { iy = iymax; } ry = V->data[(iy + V->size[0] * (ix - 1)) - 1]; qx1 = V->data[(iy + V->size[0] * ix) - 1]; zx1y2 = V->data[iy + V->size[0] * (ix - 1)]; qx2 = V->data[iy + V->size[0] * ix]; if (Xq->data[k] == ix) { qx1 = ry; qx2 = zx1y2; } else { if (!(Xq->data[k] == (real_T)ix + 1.0)) { rx = (Xq->data[k] - (real_T)ix) / (((real_T)ix + 1.0) - (real_T)ix); if (ry == qx1) { qx1 = ry; } else { qx1 = (1.0 - rx) * ry + rx * qx1; } if (zx1y2 == qx2) { qx2 = zx1y2; } else { qx2 = (1.0 - rx) * zx1y2 + rx * qx2; } } } if ((Yq->data[k] == iy) || (qx1 == qx2)) { Vq->data[k] = qx1; } else if (Yq->data[k] == (real_T)iy + 1.0) { Vq->data[k] = qx2; } else { ry = (Yq->data[k] - (real_T)iy) / (((real_T)iy + 1.0) - (real_T)iy); Vq->data[k] = (1.0 - ry) * qx1 + ry * qx2; } } else { Vq->data[k] = rtNaN; } } emlrtPopJmpBuf(sp, &emlrtJBStack); emlrtExitParallelRegion(sp, omp_in_parallel()); } /* End of code generation (interp2.c) */
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. */ /*! * \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 size_t size = static_cast<size_t>((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 size_t size = static_cast<size_t>((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 size_t size = static_cast<size_t>((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_EXT(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_EXT_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_EXT_WITH_BOOL(inputs[0].type_flag_, DType, { MSHADOW_TYPE_SWITCH_EXT_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_
Softmax.h
// -------------------------------------------------------------------------- // Binary Brain -- binary neural net framework // // Copyright (C) 2018-2019 by Ryuji Fuchikami // https://github.com/ryuz // ryuji.fuchikami@nifty.com // -------------------------------------------------------------------------- #pragma once #include "bb/Manager.h" #include "bb/Activation.h" namespace bb { // Sigmoid(活性化層) template <typename T = float> class Softmax: public Activation { using _super = Activation; public: static inline std::string ModelName(void) { return "Softmax"; } static inline std::string ObjectName(void){ return ModelName() + "_" + DataType<T>::Name(); } std::string GetModelName(void) const override { return ModelName(); } std::string GetObjectName(void) const override { return ObjectName(); } protected: indices_t m_shape; bool m_host_only = false; FrameBuffer m_y_buf; protected: Softmax() { } /** * @brief コマンド処理 * @detail コマンド処理 * @param args コマンド */ void CommandProc(std::vector<std::string> args) override { // HostOnlyモード設定 if (args.size() == 2 && args[0] == "host_only") { m_host_only = EvalBool(args[1]); } } public: static std::shared_ptr<Softmax> Create(void) { return std::shared_ptr<Softmax>(new Softmax); } ~Softmax() {} /** * @brief 入力形状設定 * @detail 入力形状を設定する * 内部変数を初期化し、以降、GetOutputShape()で値取得可能となることとする * 同一形状を指定しても内部変数は初期化されるものとする * @param shape 1フレームのノードを構成するshape * @return 出力形状を返す */ indices_t SetInputShape(indices_t shape) override { // 設定済みなら何もしない if ( shape == this->GetInputShape() ) { return this->GetOutputShape(); } m_shape = shape; return m_shape; } /** * @brief 入力形状取得 * @detail 入力形状を取得する * @return 入力形状を返す */ indices_t GetInputShape(void) const override { return m_shape; } /** * @brief 出力形状取得 * @detail 出力形状を取得する * @return 出力形状を返す */ indices_t GetOutputShape(void) const override { return m_shape; } // 1ノードのみForward計算 std::vector<double> ForwardNode(index_t node, std::vector<double> x_vec) const { std::vector<double> y_vec(x_vec.size()); double max_x = 0; for ( auto x : x_vec ) { max_x = std::max(max_x, x); } double sum = 0; for ( size_t i=0; i < x_vec.size(); ++i ) { auto x = x_vec[i] - max_x; y_vec[i] = std::exp(x); sum += y_vec[i]; } sum = std::max(sum, 1.0e-7); for ( auto& y : y_vec ) { y /= sum; } return y_vec; } /** * @brief forward演算 * @detail forward演算を行う * @param x 入力データ * @param train 学習時にtrueを指定 * @return forward演算結果 */ inline FrameBuffer Forward(FrameBuffer x_buf, bool train = true) override { // binaryモード BB_ASSERT(x_buf.GetType() == DataType<T>::type); // 戻り値のサイズ設定 FrameBuffer y_buf(x_buf.GetFrameSize(), x_buf.GetShape(), x_buf.GetType()); // ローカルに保存 if ( train ) { m_y_buf = y_buf; } { // 汎用版 auto frame_size = x_buf.GetFrameSize(); auto node_size = x_buf.GetNodeSize(); auto shape = x_buf.GetShape(); auto ch_size = shape[0]; auto pix_size = node_size / ch_size; auto x_ptr = x_buf.LockConst<T>(); auto y_ptr = y_buf.Lock<T>(true); // #pragma omp parallel for for (index_t frame = 0; frame < frame_size; ++frame) { for (index_t pix = 0; pix < pix_size; ++pix) { // max T c = 0; for (index_t ch = 0; ch < ch_size; ++ch) { auto node = ch * pix_size + pix; c = std::max(c, x_ptr.Get(frame, node)); } // sum(exp(x - c)) T sum = 0; for (index_t ch = 0; ch < ch_size; ++ch) { auto node = ch * pix_size + pix; sum += std::exp(x_ptr.Get(frame, node) - c); } sum = std::max(sum, (T)1.0e-7); for (index_t ch = 0; ch < ch_size; ++ch) { auto node = ch * pix_size + pix; auto y = std::exp(x_ptr.Get(frame, node) - c) / sum; y_ptr.Set(frame, node, y); } } } return y_buf; } } /** * @brief backward演算 * @detail backward演算を行う * * @return backward演算結果 */ inline FrameBuffer Backward(FrameBuffer dy_buf) override { BB_ASSERT(dy_buf.GetType() == DataType<T>::type); // 戻り値のサイズ設定 FrameBuffer dx_buf(dy_buf.GetFrameSize(), dy_buf.GetShape(), dy_buf.GetType()); FrameBuffer y_buf = m_y_buf; m_y_buf = FrameBuffer(); { auto frame_size = dy_buf.GetFrameSize(); auto node_size = dy_buf.GetNodeSize(); auto shape = dy_buf.GetShape(); auto ch_size = shape[0]; auto pix_size = node_size / ch_size; auto y_ptr = y_buf.LockConst<T>(); auto dy_ptr = dy_buf.LockConst<T>(); auto dx_ptr = dx_buf.Lock<T>(true); // #pragma omp parallel for for (index_t frame = 0; frame < frame_size; ++frame) { for (index_t pix = 0; pix < pix_size; ++pix) { // sum(dy*y) T sum = 0; for (index_t ch = 0; ch < ch_size; ++ch) { auto node = ch * pix_size + pix; auto dy = dy_ptr.Get(frame, node); auto y = y_ptr.Get(frame, node); sum += dy * y; } for (index_t ch = 0; ch < ch_size; ++ch) { auto node = ch * pix_size + pix; auto dy = dy_ptr.Get(frame, node); auto y = y_ptr.Get(frame, node); dx_ptr.Set(frame, node, (dy - sum)*y); } } } return dx_buf; } } // シリアライズ protected: void DumpObjectData(std::ostream &os) const override { // バージョン std::int64_t ver = 1; bb::SaveValue(os, ver); // 親クラス _super::DumpObjectData(os); } void LoadObjectData(std::istream &is) override { // バージョン std::int64_t ver; bb::LoadValue(is, ver); BB_ASSERT(ver == 1); // 親クラス _super::LoadObjectData(is); } }; }
opencl_dmg_fmt_plug.c
/* * DMG cracker patch for JtR. Hacked together during August of 2012 * by Dhiru Kholia <dhiru.kholia at gmail.com> * * This software is Copyright (c) 2012 Lukas Odzioba <ukasz@openwall.net> * Copyright (c) 2015, magnum * and it is hereby released to the general public under the following terms: * Redistribution and use in source and binary forms, with or without * modification, are permitted. */ /* * Debug levels: * 1 show what "test" hits * 2 dump printables from the decrypted blocks * 3 dump hex from the decrypted blocks * 4 dump decrypted blocks to files (will overwrite with no mercy): * dmg.debug.main main block * dmg.debug alternate block (if present, this is the start block) */ //#define DMG_DEBUG 2 #ifdef HAVE_OPENCL #if FMT_EXTERNS_H extern struct fmt_main fmt_opencl_dmg; #elif FMT_REGISTERS_H john_register_one(&fmt_opencl_dmg); #else #include <string.h> #include <openssl/des.h> #include "aes.h" #include "hmac_sha.h" #ifdef _OPENMP #include <omp.h> #endif #ifdef DMG_DEBUG #define NEED_OS_FLOCK #include "os.h" #endif #include "arch.h" #include "formats.h" #include "common.h" #include "stdint.h" #include "options.h" #include "jumbo.h" #include "loader.h" #include "common-opencl.h" #define FORMAT_LABEL "dmg-opencl" #define FORMAT_NAME "Apple DMG" #define ALGORITHM_NAME "PBKDF2-SHA1 OpenCL 3DES/AES" #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1001 #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #define BINARY_SIZE 0 #define BINARY_ALIGN 1 #define PLAINTEXT_LENGTH 64 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(uint32_t) #undef HTONL #define HTONL(n) (((((unsigned long)(n) & 0xFF)) << 24) | \ ((((unsigned long)(n) & 0xFF00)) << 8) | \ ((((unsigned long)(n) & 0xFF0000)) >> 8) | \ ((((unsigned long)(n) & 0xFF000000)) >> 24)) #ifdef DMG_DEBUG extern volatile int bench_running; #endif typedef struct { uint32_t length; uint8_t v[PLAINTEXT_LENGTH]; } dmg_password; typedef struct { uint32_t v[32/4]; } dmg_hash; typedef struct { uint32_t iterations; uint32_t outlen; uint32_t skip_bytes; uint8_t length; uint8_t salt[64]; } dmg_salt; static int *cracked; static int any_cracked; static struct custom_salt { unsigned int saltlen; unsigned char salt[20]; unsigned int ivlen; unsigned char iv[32]; int headerver; unsigned char chunk[8192]; uint32_t encrypted_keyblob_size; uint8_t encrypted_keyblob[128]; unsigned int len_wrapped_aes_key; unsigned char wrapped_aes_key[296]; unsigned int len_hmac_sha1_key; unsigned char wrapped_hmac_sha1_key[300]; char scp; /* start chunk present */ unsigned char zchunk[4096]; /* chunk #0 */ int cno; int data_size; unsigned int iterations; } *cur_salt; static cl_int cl_error; static dmg_password *inbuffer; static dmg_hash *outbuffer; static dmg_salt currentsalt; static cl_mem mem_in, mem_out, mem_setting; static struct fmt_main *self; size_t insize, outsize, settingsize, cracked_size; static struct fmt_tests dmg_tests[] = { // testimage.AES-256.64k.header_v2.dmg {"$dmg$2*20*fd70ac1e078f01fce55a2e56145a2494446db32a*32*9110b1778f09b1a7000000000000000000000000000000000000000000000000*64*68a32866b0e67515f35dc67c4d6747a8561a9f4f6a6718a894b0a77a47c452471e04ecef9bf56f0d83d1201a509a374e00000000000000000000000000000000*14*8192*70ebe6f1d387e33e3d1093cca2e94c9a32e2c9ba47d461d737d49a7dc1b1f69407b7dbc16f7671689ea4a4641652b3f976b6f1c73c551a0a407d5a335caa169db4a6a25bbd27fbbc38fc71b29ee9b1eae349b0d8a21d57959ecca6bf74bc26ccaee69cfee4999b55374605491af6d0b9066c26995209cd1b71925bcb45a8ef5727a6c20338f08de4357d4cb42cb65ecdc2344a5d7387633c913258ba40699ea5f88804b5e562bf973096337b17b4fc1236d3c8a80b9b48aed63c5a0eae3ae924a883e948f374771bba46923658f225fd2795ce0e795269f589e0ffc81615585e1224cddde654d689a3260e69683c6198bdfcd87507c23cefe36d72f8878cb27bbe5dce868752a7cce067f5a3110f20ebd31ecd53840103e0b2d44385656398edc487bf6d1a5ec3a56af54f9d4254fd20988df41eb85e366f13da1270a3f42c6672ad5faf00fa21e9ba3691bde78ab2c267a142f275467d5b853a107dbf1d75839f0e87b3b4f1d2cec88cc02a26bc4a63aa6836b0c43c5dbb44a832050385a48d46968361ebb053c2416c02458b76c95e50970922556d40b100967340a32824e6b6e44c0c1e0da7ce989d9d5ad91560156" "ed39666cbfbea71f28797a5a7a40e77665612e977ecb8b7fe71d500eafc29d9a0ec1d0ff1723fea7c405bc181ea93c0df42f5bf886eace3cfeee8b0dba52ba8cd2ae009e75d8845264d12dd632ca3236bc1b643437881b270183d2e2bd20808ae73d32bfe88347e33bef4921fcfac9646b74f116be1f04fc353d2222499d5247fa842d0d0f00fc9642ea7524adb65c18fff87b6efd060ec850d7de6f59869387b3d4cc8e38014d52d94ead07d16b8d94327fe5533941497c9be2dd6c04142ba57e29daaeef96d0f2d109522651d797715f4bc5f4cc3fb69fa92623b5ea3e08ff78dc59913993c877f4e2c8964dffd2c8cde6c6b6738da2883505486df5b633aaa8c66acbc2886107f3dd61b1df29f54a13ef27a7d2785c02153375240885e5c54297d88827403320799e05213761549eedc1c159c922087983410d2abadf9ef8ae460d018c278a9ea724f52b866e3d7ff2374496103b5137297100c970d195fca8c1286a8f9d3859ee12c84bdaa4b56ca91e307580b61dbe435ce4021007e4a2a8085976549cf1d195f439bb6e642567f91a0224e98796614d9ea6bfab8f6d13f91b7a80a54e538a1a785cd07b5d7ed2b7e45a0658b5722b5f8844f5139cff3b33ce244946757c020c54c8b5e43324023ed11001201213ffe4829e37135686a8bec1837b35fb234049570868dc5ba9c84cef6890d9ec400a794b1723eb209a60758ba9ae9abd23a7ea9f94fc6b73d29a560e24973c9160f195fbe82376c81dfeec1a7f912a8c22c067a26786a22f0b7db298" "3631400f120010706c78acc36ddcc29c7055fe82105f770e2dadf131ab49af93539fb5186d32dbe4a4df6cb0fdf6840c0609c8769fe242cc60d87e04e6e3be1a7884a05d9fb96c3bc1bbc769d96bbcc0413492eefc5502e9c1ac7c3f237b9851dc453b5bfa899b7b68e5e3b92711e7c92945feb6f6e452d6216e154a952cc28a3740925554d9fd44acedc8a44b0c25bbb6aa637fe9560437c08b17992c74de38fe1fb8fd5f66c2933c2d573ddc914f68f42d6cb350f126a51f607a2dd23b63e6382ec1e6ae434f47cfcd1e7d96c8293ef2994f850a27ef2d8210a0df0c219eadd2376ce36a22db56827d92a90d5e2fa55a4154c39061bd5490ba29f8309cf3e2056f761762dff56803bbe0607faef510d023b249663368977fede0577944f2ff05ead4b432bbb07a7d90148ebd1e30bf1204cd9069725d9fdbb850d3d6fde5044da1b9ffa222d99061c8ae217bc5b249960db545e6fece3ea2faeefa7702f065764b326ae0e62f3b8745cb73f35bea1bb9f6ed4fcda591f4d84da0415a0552306f6691a64a1d0efc8ac93559a79e57e357b63df48506c12dde74f6ea8fc5eeb1846c394fb8fd0fd40df26a42e53692db51bb36403305c1aff797e20adb6f8f1721e316705dcf8fe6e6989a5c3da253fdc6cb5de426f1c018161d72e34e6791d73023c5df69c0f83d3ea1d097f3a7ff37720a66868f40d3b87755bdaf508086c7e478ac1efc0dc421987af6db9b2f096a7270de91f5b3b84ee6d1d268d581718d3c534eeffbe2889388e9930cb051b5752c1a" "b1faf1e367866af7d4b37ba25c15a030d9a5f32bb8912ce853fe7988dc62aa61264e3c5a29d18c5121a605558b15004c817cb0ab1646138cbf6375f1a179852bc22d80b83891edfd38e25efcc0dbb78062f479a9dc792e5822e09ba3e0b8ef71c62ad7747dba8cc97707f31383baa93108d5c7253dce2395fa24d77c42cbf3559b5dc0235c0ce49ef9e3cc816598698c8f8c5b32abfaeb44f3c35a01a4f47421a166d5aa893aaba80e57eb576b838c95ed6f9d5b3d389a8f86b97fe629408ec7c7ba7fd95d7625e950c7324fdd35989570b24f2e1e24d52b65ed6116e728dc3a1004d3d8fbfeeaea1c7dc5d3dc7a029f97f8dc7f740e2386eb27e9793680d959821031fda08c7146f46e8ee47ec28c7d25574eb690de09849725e490c39e524b74aecfc68ff0d760d115b4d0a126609cef83b6c80731dd17f4a307331464953c6b41875b6e5fea328fd59f275e2fabd25717781cf9d5cc52286246ebc92527eeac7acc6e2652c6fcff405e7b4a78b8f9475f46bb82a68a6e44037d61de0df58a8b7a81f407aaa260f3a49c4a2641776404fc15bfb77573dc8728573a1872e7e093663842d9368e74cbe3ae547355fa101daeaa0f97dc0a63927e54ae59fe13aac4f488e938fa67a12876d103b4a56b6eb88ff0104330e5cdc7c6886b46545d523bfbfc88f40f9654fcd0f8c4f443a225b50b44af9674166d3de36b6ac63a150fbcda2e2511ae2a42fbe51c08f7238366aada5c6be8eeb41963c6a5374a94b332012e860d6cfbc1b8a4d5a9825b88a90c9a5f" "5615ca503698ad00df2cd93467b66d9b15876bc49895a081959132bad2e63757aa4e5ff77c6f25dd2581a3e9bb8e213c9313ceca0fcf5f8416882849fbee576d8ffb9dc057eb96bf6b81db60a82b0e6f315a13dd31706c0e36f4f21b9ce977ff6700cd77db603120d59ad8088e121cc3c502e37774b098eee7c8244f9bbe0d4a9d0deba3ec22e5abfea69ab72cdb75a001bb53672fe12b4fdbdf7e82c0bb2608de5d8e1961fb4524dd1acc890361923fb691bc5ea436246428a70b5021f9eee2c637eeab574babde4c0d55f57925e511ff623af5c4224d3ccb9c8572179e2610b4b79817ca18ddcb5302151f9facffca96269ff5fbb11e48209e20145bdd70d72bae54f6fbb89a3396bdaaa3d45413e3c5bc672ab98dfbeb3274156096f641494c1c946baab7c388a16c71ce5009b32f45dbbe37998906570045027950bd758b7ab2f72c243eccf9551d539946a99779848b16cddf9f163fcefe1e1ebee3ba7d5240b92698ad56a036274ca798eae19b0dbcf39a1c0ea1a58b29dc0e3de89def08e6c5800c94db47b7eaef5514c002d687b4d99b00fbd44137f56557830d63156f43bf73db8b330bca0ebb4ea5d50941b758929722aaa5452cd4a4e00640165dfc35fd35daaf929997adeb4c4f7611d66befb80809dc7bc6c763879c3bcd8dd0fe6b621898717fd095fb7eb403b07591b931a8e16ab488b01acd636bf4f1e71d5460532b8a3b00d7353e84c071de5cfa25de685cb85b569e08d2f177727cda11f196b040d25c97ccb83e355db98c2bc14844" "1ca95b5f612020bc53a81184ccd0c5f14bf6d9fd6318ec28bafe8d668cb3c98c56ad416007bef4a3ed9e12eafe8f9e7d87fbb02d1f557b497db1a2c0fe40ec3f23ea88332513c68f724cc8a8af6636c9f332a8e55c2d41fd81a23e92e9ffacd3ef14cda669e7dbe31ca08a5238c7fbfe7020933087bf2ce0a7489fd5a3becce5de09628234f60c833002aa8e9c9ec51f57c8e4ba095c1d054750d46d64041bb1f567a82d63bb5e88fb70bdddad0ed7572229e56b90e74dd88ca829f1ce8424bd24a0bbfe3dc3f77d244ee59f364b36a4b05fb511b5b0d7f876c65ab4233803543b0a68b9d2d6d45d292f91eb4700c2dbf431e40c77a4fcc3ac3fdf3a2bae3df35b6417b8f1eedfe84cc65a07c426780871d16ec5ed3201ea4eaa778b71f04cc1999587bb4645bbc43e365395e9188c85bd024f758304aee979f8e67d07636fea251423e920e2b7258580d1918fce772bf02ee66926fc5f9a3dd6a8c89e6ce7e4fc03d4784296df1a9152a1fc66050983a287e3520bf3e04d900d25316c8bd5ab489bf97a2f31f4061f895111caff9968ecb22d75cb9e5400ca1d0fb044acb4fb9cccaa4766cf6c63ae5a7a3f9af90d1b225067f671d85cdb4e2e21d2850f351d995d54520fdcbb8cb30bfa82190ab2071eb8bf350f984408b206597371736110114d12d79da4027f9a58c8fede63cf16fa552d2a956ae2a49c83b0afca3056f87f1e27bdeb9d14a7e5cf30550017a3233c4f386769021a853b971746aa28aa69ca980bb02979779c5bd29259c84911e2b252" "61b92be669e8a731dd74edce66b6f3ab5944695efd57c0004ff637eabfbc02ae346528fedbf2ae80d420580adc4d571a37fa1397fc2b85ec458d5262c15620c88f2dca0eb1bae4ec39d67fef56ecbdf89703919e5a6767d0f77bf6f0f60ba21003d033c9dc3057df18d855a5801110fa9a29a42ce10a44a39ed883df249ccddef8aaf832387e70048d9ad6014cc17f9a2bf7146696ee4eed388d06a45f7bd7696e57500ecfada9e9eb17926b16bbd90146e406e281141f0a918c320cacc9d1f045ac1bba87ce8d1d45cb6303988d5228da6ad33df6d2a5bd7f265b8f610078e9db5fa3db0e08286e500063f0fd6860a11d9985226ad382a95bc3c3941d43378ea1bf28fc85749f616092d77e7c292e311337168b52eba08ffc0f76582710a1a7d33c55162b3c7fbf227a324e1f4579e035ae0fa17fafb1ea964aa977490b5a3fc16c75e1fc50a6d17e193345b71369df804c61a71bf60be4281c3d1f945c690368c23caab006f9dfc913dbe6119d6fe8349cdd424db7074726e8bdd0ae99e2bfb9b800ddb965c06e0587cd10108c9b431cad4fd10d3654a22ceac73553a6b2b2218ed6526c362df46cfa776e2caea0de61b9d5c0c74e03e299ceb2221ed0f30ffc5876354d5607c3eafc77f78e4fce5e0c7f6ba7d417ac5f0511e2635b41b28dfb4f2fbb73d351a69fff920b76f5687386114b3d5ab9cad056c88840a023b7e2df73f007852763570d38a966c8258365b014a12a3497f506dbe55c073244333547223785438372884ecd8b66aa0a794ab5fb" "94b0a519bb3cbf01b43463c0c7fc6ebc67754ca25686002e13edad54c817b0aef64698637d18a4a8bba382add892f4918b720aa99b09ed2a6e02b7140f89e3e00680f37343d3e47412d04ef78005b8b9a23b92d145a8da9c5efafce374955727367a7f1a179b990868550cf960c6df6baf2cddda5fe3e689de8dfcf1474db419ecf88cbce9de7a58e9d8a15991fdf5361846273d195a2892fbc95ad079ca8153910984c4694edb4c790f430043c4019fbd96fe49d8afa5e7d1f6674e4a125bfbdc916b0d3819566898599443ebf2a87b1fdaf41378227d396d2d320dc5b860705bc87f45eba2b6473234fe054267698dba0913ab1234b46697c54e2b19526d1ad4b7e3eab40a413f86170fe9f2a71eae2fb959a021b0b43516f1c8a3e674f37ee235ade79ca296364b0cad5ebe8449e09b63a34e8711587f7f2fe6e181a787b1d3a8f30012ce9549abb834fb80c673c575a25d3c33bb6d846ac231f411dd6422c59215e0a267424c0c57e6c9bd5486e8b6327e9dd16b7065eb74ef91ec9204360b03d08654a4e418346ec2d4d21edd5608a76903494791546d430eac38178d158d61951de3c61fbe5d56c22cbda4a3d40297f7abd83913e8b483d9a80cf000810d90a921f453bcf9e35732d2579c1aaef4a6980c666e3b273a9f91d9918f850bd6e4475d8aa5cb616cec58d6ab6d70dbe2b0f7ad85618b6e60dd4ff5d0faf19dfdf27a9ee48cd7b2d6613e76f04ab6ef5f0af12966a90875816c27c4297a2bf622ddf66fbe7c211670d0c46c7295b93bd2f1" "22568df3dc46e9294c7258a0b7e81b2d45979680edbb7ab323e4857d84306ccc16ca79c711144eab7b37e3437245d7b78ced1cfebfc45892791b9ac6cc1211f83e328ce3f57af3d89b5be89dd2efeac9d738330bd0d8d4a059bfac06d1ad73bf6d427541e559c3d16eb5adc4380c1b25c1b8a9097ce7eeeed1c5d6884dd1a32ee2bfaab8371593a0eef65f80e705b9b56adfc0db4c272024a71947755032a5ebc1bb346ee8a99b01b408cc0b1658a319ffa5ab2eb87e9aa8b3dd9d9d92ce3bc04e4ebcc011a280143927676360f249ccdaf7949bb23770a06ff5861661d36d761508f7e9ba149310d1347c3165e07997853d415abdacfae9579d1dc0b5990a05ae9e6dce8931ac2db9414546dc64f8161a64cf30b9ce8c50ef2a99775f03dfc2c611e780a5cbcc27cab920a87d940acd8b3fd42897ab6f51b29214275bd564c50eb7aab3ad19a2c903c84d2ed5a23c49c81d87cf3244505424332c917d7b671d4a90765b8953c26bb7ed5dfe3e93632610ab44296afee2b5c631fe643a0a78eb9af94d700250f5a82bc57d24825423f1ecfd8cc2bb0daa229670d0d9a4fb342ee8c9b7b16d86d29abc2a57633303b918ac78ea8d2672dfdd4a06ea0bbd756fbadfb0c09e2426a65e90ca829ea00ad66ca8c9e79b9aa5ddd02d435cb23014b1033da00381ddf2dcf408660d1eebd1f6c7bf5ae9fc3fe47e75ff7ca482716534a9f3365f5cdb48f3d59fb19d11bb8782ef96e394296594812e8a7da23a953f6117ce577e55f3d6cb1d3a4007dc7d252c7123a8" "37be12884e54ad10757af405beffb5cff189133bb7df5fc009544b2d62ec44fdc0c1c8240d4413af5b36e031510b1f1537a690ba7049cce9df4bf4dd63f6987c513992fca78a1cb7e8d670fb43a52ea2ca2f49724e35397041e5c75a365b510f40fa9bd076377274d6a95af801981d71972da0a08b536b024f439c43d13902878798153ed825ddd7dee8937181823076f036caecec170edf1b5fbdd84e530bc50a7acc257bb9679d72de3f115602d18d2d12e6ecf4d3242ccbe9a71a1483e7fe40d2447ba028a76aa92c13516ebde90dc4d204095a554cbfad79d6efe4ec540c7b51593413465b929742b729ca688f67ee9d9fe76431fa81217fb135d0dd6ebc91904efcb0cb6dee22867e5ddd7453f530d04935f41575de9ca457da55b67791d2e8b83890b5be543366b92ba6579a6f19f8e82a0bd87e379967766e5b0a58305b984778c562ea03a8b8392e3160ea4532b6ce5de74bc8fa0e8ebe88fbd62a73d7106a309f5a5f5d7617664b015e166fcd87906caa80ab4eb3e62f73e527b5d951a0ed0340fe17bb7b2692e4a31d14798879788fed12413bac50e490ab93ed66311599a6c1362fc60da5319ad907c7ef7852985ce86246276a138379d2004772d4d9a989b83b3e780bdda9825ad06a4b3dcc9a9d4d8025cbdee7cb2e02ea1f77bc90bf4ae56903859025b7283ba6410aa91933466623b996e9ad07e3095e376b11a27ca451c246d5561501e69c6747013ecda44f8d1fa50a75572453c9ddecc07b1aaeebc04cc7e976915f5e68d1236ae2ff" "dea4b9fc4f8e91b03982801e2ba604b46ad80f966838ae09d2734c6482dd16d7738cadc1276593a336e2ce8cf7ce48d1535c7865f7b90445ff3ab9e56f58e254115bc07710de50d7953238d7ca419013d104d90fe79794995c28f219c963d716bf8942e0cc5cb432aafce4afb42f74596b847fde5d87fba9adce5c17fe590fe58e60379393e521ee194fe063211d72c29d58f7dde89addb6b0e20515ca7aa270df2ef2d77f92219781502c49292c6c4a985242b9447521cdef5a52b53b5eefcc43e8036ebe90b51a3565cbb180ea1b3e3d20f63b8f420c2a7f01c475428d5f63c66f122654af4edcbafebe34970c152767cf623eb4f1ee33931a79622cafc70cdd2bc7ccd55ecc1e0aafde3f66f5414315048d3c5c51638c35fa920cfcf7a18ada48a589c12e4da2c801cb8bf3b182463707a17891cf296ae8aae6a8a88ee3d602cc1bb7647861f65ec1a278433ae08d8c8e63727633425fda0b86d78378ac80b1bc1a48abf270dc2b5ea71691eeeb979950cbe0ddfdc451dcf8e3dc657060f4c3f96512b21bcb228a966381efa94bbf5ff4bbf38a803b6aafc719a545e4d0582a62e81e6468aa04eaf131f8d2f545c060651e115032f5b3579fdfb95a2328f5c9a0308874630e840ae1dcec1b9543c36267a9651c94c91cea42a93a91ba3a054ded4a8343864b449e46abec49474e218c8c541b00eb0f8997e710025631ac28be3f08126446dee0cf61bc69b85e4fc021f203c796cbd2ca16ebc8fa15f55510a08ed334155233c6459d2d428df31a3f376c" "d81a530700b3ef08631dc5b50f787d4efe2bf219bd17f0431803d9d946255716e8543bf77fc44a48abc70a97feae8398c2059938d39fb4ac5f7214d92bb89fb9c45b6d117fd51f6207935beb1a89963fb9d1aa020669bf809c21154c20e720aa1178ed2bc13fd548e0d7d01eb1d028aa48318a02dc7aa412e2ae01ff59a86dae40771ad3f48f0fa54b6e679854be00deb9938e37ab3a4c9a96f3b7849ac75b82619cbc806c42f4bc4feb1141f6a8391bf9335f643ce5cd2791590b28b19d03cca7b5cf702f10ffa0317327e828deb4791f71500f243be77a451e5759c6c711b38f8f62757c54d7fc6dc586a90df7777d8cf1c72f9c0947af005d770f4a74b6c9413738c3b5ab32306ff5b41a6446c2de3f59a27b79d877d3f05fe22d11afd69e49e59f35b3725a0ad126642f388602b7816abe397a9c9233cf7d1e12a00362306d2d9b81fddb279544f35e23a8c198930f75986f26e6f292ae8debe5da0a7a5b8add2be71efc78179eff7fa2a2dad35863b69e85e8172073f434f48fb03f7bd1bc78fc2badbda261a68f7bfa171c898897b3b0d4852920674b8d9ffdb37ce66c1b6aaf9b375253a0d74eba4d359737f7fddb42471969d81605e41f615399c5fd6cce1808e9b511ac54f75f774e84b00970474f5136447af04b4866ab6c54aabf7a247c6caf3ee891fecb14073f3cfdc7368ac00f6b1c9b23e301e49257840f949a57c28a95c5c490bca91bf979d40403f7b9458bd255df757e6eea0bf41d5175548aa46243d98f2f0f6c754d6e7e58fbea97" "7d7e0af8b7d0a6bce07d0c483293868a914a50aaedfb9b239b4c3c472381535b287a4146fd52e7bf882c9c3eff7bb2fae15d5b96bb1222d81d26dba563ac550e716b6c08b062cad6702a33a9db4274fa2e81af815e8325101d5a9ce9b345e29619da9e45dcbcd7b0935d7dde07644edc6b049eee9371511bb2cac50ec1170c7aad835c54fa52c8e0a0e8446356488e09c2f07b17413a7ddb872d05016aba129cc36de609831863747310f0fa443480a47524dfc5e1f34eef3ba2fefa29e596e7fff86a924462781930fab55e71fc2f06271e62878e51e0db08ee5dea31f1d2afe9a4f548ad6a4f4763c9d0eecbcdc32323aba1c9c12554a5cfedb5310b4a03caf426a80d725fabd557493c46f2a174aac851d3d39529d5ad919fdb7fb0dc1e5b0ffdf706a9f5af36fcd2bdde28d68c5af4a1da4e67cd44f97b555b62b39cee1274b7c3dd3971ace3da6101c87f9b8f28c5e13d4066a3e63543825dd8bddc3e90b6dc75bac78931da98929a337817f68deec6065f6f7883d5bb10cab909c9945f71a672eb2cda9fadf4a8d9da906e2a5d1f589193b4e791772663f1bbe751498bda065f90244391169d80490208083de39bec984af73dc99b10d85958f372004a03962c45c531b347851dc5e26bf7bcdd68c9b129524d6734282bdd431f991170d6a5c67138a5405d8005b355ec7ce95496a8e98782f6d978c42c30a17db9c12671d82f2d3e257f66980f20bb6380303f1e89b10035ae7bdb3e55d31f2d1574784aed5c95aa09aaa9614989d957a65d893dbd" "abbfaaf30cae0cad575e39f5311aa00a6979fa52ec12dfb2f731a3ce5f8b6097a612c2ce98f5898eb2d1780d0cf9ad30ce5395ae871ba7ca6a0884a13c09732cefc5aed9d7a28c09041cdd62e75d7396432545f0c16496b7f5f516fb2cc603c0ec10a51ee952b7cd0593ec00dddf67e27dfe3f0cdc5bf737170243a8ed3c1f59733fb47bde4b6578d7ef11f95790d4c678d95ab2cbdb1673d2d516c189af00f996371077276e672f1223926fdcd6627ff86816906edad3aa97e3a9e7346562add05ec1a94c2dbb7f3b28ef537715a1d69761bfb8c2092e608311af2f79a4f8188665a48539944374437bcff6e59bdff4e4b9e4dce11307d892915071157698460b9e9fd68ee0d1acd21434810fc8ae702fb8dc794ad5364c79fdd74c8a70f390556930fc2a23064f36411c626179d1d745d4875f5c2b37292cb8ba37bb78d419f05e9a5d2245a38da20b6b14eba2d5ca3d58d23bb5ade1322cf337eb75a97ce98c167b6305907c3fe18038bee1e2450c3095480f99c9f12d2b543b33866e5546a39d539c6e2d639356bdbcbdb3b4e0935ac76e0fdaf54cfdf241d2c5ce135324885f8cd69e6562f48979352bbab357c6861c66b4ff7d9dd5d32a8ab8b6e759a2f5ddcee847fa439a5f9e3989039aa60751019eca6c7dfcc2464ca4a1ae12f079d200961797cb0e52cb046d1f0cb1d97c4699e07f019b48edd6f4a71b99ba26c2e5e72745cd9bb9a7e89d8eaba646461bb76818fcc447de2820196e32cdcf4a57c527c52f64d316b513f6a611c929890be5b0" "3b3d3352cef23bf86d0e058b1cd9c4a10a9a01060aa9c9cc4bf42c7c6cbb677724db3f0c3736461c1828e67c9916e953057024371bb4ad8995672f760c47574bde9df9e73af90773cd46c9df8cb655f8c37eed8cbda40da06304471e32bc828a7dd9457fbe4d63a15633009c1a9f003f3db7f5b2b5e3b22c60f747d5627bce3eb4398a543cf24b18cf0a56728adcc253d7f5343245c1426b5bcd9daff94394499cb6d7ac2b4e63ec424c66f5dbceaf877fc13f47e744aca7d8b5d89c8d5621f4e13488b141062ee04c2312528a0a987a5d32ebc6ffae45657f4b2d1420890970e363a124b75374594dea0560320b36133e31d6a978f90ef079b81484503c7fc3edbceadfc9fcea06f271a60ea6c5d434b694ace1b506eaf013aca2c6103acfe6c565a5a24cdf638f8ee282ac812e32cc2662a8e2d4a31239952836c4896870d973bb65b280f0370f4c3a54c7f4723b2bef522ca4c233d7646da3fdb9743e273afa1e3bfcb947eea9f323ca908bb4961b214aa906cca1d2d56eff25d60952cc5897ee6390f9af4efd5d48b2aee8734cf6b8042f2de75b107f8d135d9a63148e88e43df815fe7871a354741f8863af4e114ed0369515bca104f8d3b24a2d740b8617de3e96a23*0", "vilefault"}, {"$dmg$1*20*f615ec6c463799eccc6a2dfbedf12c6bdc422a2a*56*a595f4a81a490e7aa6378034661da57a424f922c971d3db3f856f8d54b0784bcc5d7182905c4237153c5d250b8aee1d26410b1dca7b1cb73*48*74a060efbaf2c79d5523219d8162c425befbb2094fb46e7ffaedc7cd4f192e6f0c47d8aa91e0a3201346725d3ddadfff", "vilefault"}, {"$dmg$1*20*9c82b419bdac1b3e6b71f8a6b99a7501f34b6950*40*5da479e292e0acf67a9fa3e24d0a767cae2f645ff63836665068637188f4b80295de79aabdbc2536*48*9b136165ee73418631ccf28d5e77073788ae921df596649a7a7789585db0f13f446d5927967e2ede20ce8a4f5389185d", "vilefault"}, {"$dmg$2*20*839730be2331c69df4f729ffe8a10c26653bea94*32*1f24e25712c2d70d000000000000000000000000000000000000000000000000*48*3231e20aa642889a7e087cb87c84ba1cd52864007cfea677796a6f52e16b2609696dde9230aeb5603aeb1f70f6701be6*14*8192*75884a049d2b7a40c14002ab6e511bf3c73ca79a2bb8285a3d2ac1d5b9b0cbf92d4a483fb762bae8485dc3fc9cd7a54141da2b74a86ea833d253d56f52eecb9dd4d40b9f846690378cb8a5db74fbc6d756ef9fcdbb5d21805ed43a7fb45d6caf6b3d2564f4a7760030aad69ed9e56789e8b2699bebfaac3cd73130fae1d8ef7f003e765e86eb84e990f3c24780022fdff3ba283ece4fa8d31716e5cb1ea22e408431eeb2cda1460217efda86461e940cb10ae602a84ddd22be53064e66c0973a04405ff17afa020b24f1bb4ce42750b28cf4e98c4f542576e712f3c2fe0a0539a411290f65ca763a94d865fc24b1beeefbb6b055db453da38e62bc383e74b188b86c54b62f589334de8ce3ab2e4643f76eb4db95bfc088bea8c4e88cfccd19b89b818fb698982f73df634c8a8148e4c8d3ec2dab02aabcf48ec0a78686fe0b4f5e589a067d6c54f0732e559cf9db5b4ae1f0468f5681226d3b03002cb6ec528b96470f1d1aee5d3b51b4c5f45a2702830ea35056e02279e76fdd30b3ac174cd91b65fd6a26a192f6e632b0fae660d0861059a62bc512f610f4974c22993bbafa364fd2e8eb53d07244d165f990c876320d99070fbfa6fe7e0ca42c0ef2f17205ca" "7196376d4026a8a93fa83a99cd3b6cde354ed3122dfc07ffef91c24f2036b0d83467e120b85a92fa04120cc8f7af3196adb6420f519c610983d163964b0cbd048adfb89266d9ccf9845cd17ed04accff9d106b7bfffefb365e97357fdb9ab2d0956411c0c73bdf235a9ea4b50962c8f258583899ff2c0bad6602e8a3c14f3c870fa14686d15aa17f5cfd1ddeecc7b061cb5c00db7d198d083a690ecee97a1b4b0251349beab744c4bcb53a4c1702d1094f6591ee5ae15a29271ee3d3d22f0f833219c3676236c9e9620a206ab6ab08fe5fc663f4f2ccfdae6e34adc68e59fcba5363f44cbc5d8345f184ccb38d52bc2bbe6ad996c3d4316ce644698bba6044209d108c698c3d18f4b64161651224cb015052d2e9bee0079b779d77b6623e9669c4ff99988bc612c4099f6b8bc9719444cecbc5f87bf9ca6dc30f3b346c3cf20cc342cd4d156ed67c8be0f1801c3e672bfdf2fb9e6c6f1ef3570d059405a8a0c5bcfcd70f7bfc1d2417e3ca205be70a5ffc9b4d1d123ff64cf72b20df25e9861e1da57fd1311451e542c25100c19d1d70bba2c26752e4cf1c59a6373fceceebf2b4c392a45e2cc7151f4cc1c7292720b5f0716cf7ea752a8a44cfcb7f638c5387a410efbfae90598f2d99cc79baa298e30076d5ac8a2094dc14d81953c09fca8b41f88cbca2274158b93fe5a151b93bec1fdabe1a6c67807d5f9d46b2a19ba85f9540cfb54656fe473216ee1922046c5b6cd08b325e0c25a420765a61e5f7a266c9e0ea1148f0e62ec65736d4cacef77940a0eb" "24e93b7b656e3b591f5827e78b577b628da26c1e5bd7544dd439d15ca21a3fbe96d3833ab1bddbb03beb8f0fe39517958b7bf43afdbc68b5061b41145e151d228bb5e5220b31a86878be40060839855db438368e40dd6b8d534c5c39009455c0a783455b41b572f2864eed60e5dad80979b97efd6dd08549c154b76f748101396847efd56a97b82cf62a25e26ecaebfa35d545cdf886ecc22460cc0e2983b9da14ac41dd1e1dead58a2c29a85f6bc900268d755d1158939470c4793359b50da19addd3d8f722c0a889ebd8dc69bd955b524bbe452cc98834613ea48d7a73a9b93820c0ba718cf664d82a1745451a204a2845d4e2a846f0f18923ad0315896b1c1ac1942fbdcba119ceed9e02b0e707b28feaba44bac94888ba1a31670cdce6348d58d2072eb13ee805d569815fb28749c392d11eb06d8b1746ba8eef3313072fdb4685f1401717933fd18edbc99e3d89d08a4c7798bc1d724d6bca02a31642ca0ac6223884580c0be8f6508a6650b783a9ef24de3713f65fadcb2da6d68c4bbbdc216ff91ea7bd24bd7365b91087c14edf70dbd4eceb2676797ead7fbedae77a0add9d22a515e2a79d075958d8fb87aa62700c62df007abaa3a5e002403205fe04edaa4aac3da6d08ad9ba909974e9091148208db90f330b2c2c702521d4b1b32acc4fe6b7ffd9f96fdca05b6c404afcc789fb9ad8c52063fc0f9b9cb4116ee11f07aa17dff57b889a4f4abaedc51a07481c1e954d78ead32c6e808d3eafe7cfa9d2d4ab4886abcd2f64ba2df2d8d507cabfa8" "d01f785409d71896461adaeb4e34d18f9b2fa38779f0932c27ba2f3f75ece12f6eaf7a0d728dc02e97cd44ff175b592b8234c3e3b5491726c58dcf0a1b77698cd38d861fcd549aa793f8d2b58d6afd1d9b7bb96c8936c960eaa7072c00e69f68f948ee24494b8152bd8e5d6923c8eb26023dc660d202e41663888a8e8550092b5e1610452c79069b3cab41a2e7459dc0d361ded09c9f1589999623f6deacf276eb72996a355e4f7dc19a5217e9dcb2d6a3e4679bed9f980a5dc8f24a1c5f4eef00d706566e12ac8deeee964ab9501be5e57e326a6fcb794e4f4fe14922704206a343724913ca2e1d26e3d83cf994cb7aaaf9a916ea6eaa06987a9822c5a8e556b16ad72d5f5640b3490d6b0f290f9f2db7c3ead435e534406dee40366efb98f0b53930a83ff9bad177b84343d204a1083801f1d68b3aff78ec4246f670f924969e4608b419ea9f5aafec40d902492f62844d9a83d65f38af2531b875b964abc781b3537c708fe65f70a11552990447bf6db287412367ca918a39d9e2b2e228451807b01174afc33f5f67d45f9c765015da6abd318c980fc8bcba60ccd5193e7a8caa54193aa83bff7b77725be99780da88b3209a3cec620c17f979fb16e640473b0d98a2f492702ab99f2f0f83bbdcabc2a6dc4986476f420f112ffbc7bddac8cffe59e82ff558151b9160e2f99bf37a05654253321591ef31d01b32b8d69297b3bd57f127e9f574fd472b6d29b6e9a0e1fd43252bc1f1b2c8c959f3f4d80177b4fd6a77dde8fcbaf1eabcd5e7f6d38630f35d" "efc161ba7432cc9af6bc73baabcb343c469ab18e4cf88eee21e49311b4f20077bd6e30705338f047a9c7bbdbe4dfa6d7be3a827c92823a3c8f36909f9e4df4dd91426b75ac6b5d953357929b0bcd91ebd24e651a855755edca82c4664d3c89fca6001ba88688e5ec8d5e5c3fb145b963b29424192530601d74e3b815be85ca44640ca89c57ec4ac7084639b82e23f065ac561779c040cbfe63310ec846db02873203feccc3f88a28fa78d8d567905abc9f8f561b4a29ec5c380849ada42100c15efd3d73fc203e63a315cc27b82f62c4ca0df9ea213dbf7eb39552fcc38edfba0ce7e25dd097bfad5224369f1d2a175ab88ee5a3371daece3342e99c60cde76a1ff5dc7e5ebaa7e0fb59d4d088cfbe7704126b2697d62d7b82289a35ea778ea4ca347410513513084f1fa971686724761f711a916ae1e92402ff3d52f948fdbd9c1d961c6ad6923c8ae9cf3a4eae7a9369daa5cbdadfc786e873b90ed1e8f5933ebd011081ae7ea236c11f0c53e00c1c0f9206f91e6954123b5caa08c7615a787c1661dc17f297c8ed2ff6c90dfdd9a262ab5e9a4489d6ed7ac032f72bcbbc2248e7f1675e2b2da0bf85caf89921fcd8e78403f11a28970f673ec7adbea798b3eff87fec642ef77c15b3f3d19dfeb74d1ef6a38ab938692207133aaeaf722aec4f6082a4cd742bd37fba0f1f83f01cd2fad6a169c4716940f7d74b8f29001f406de5897a5e5d813b995df132cc57a5d9bdecdad9024dff7dee8b89189d35085a70bba2e5e0a8c1c71cc593238f3acbd1337b2c" "c5a8647ce6bbd669eb939279d3b964d661112752bd7fb877c4c6ccb5ef72ff5446410286fc69347841c5595a3408e0c73fed8984d0c0fdd2544a168ccfe41386702f6ab7b3675a78b57f9782f23e0471e6dceb176dc9eb871ddd92dc0b86b2a11293523189c75019200a45213f0cbd86823f65f28cbe6569a58512dd469431322b7ca5b9b8ca57e56a139dc4788ffbac10fb57441f2435584651fa572450a4719c8c9b4a322f3aaedd3693a55820c725b63096d3f211d830d39aa89be83d59b13145dea9231266ef6b1eb1fdef31203922308cff81b166426d662989a350ec712dba14ced58df7dda0d0fad05ad8d9c6b247307d481f79e6a3cffdb2ab9b21a8208d6d7faa72b6f22a505d2b950884474862f6f67effc81c6292f3550c4e8852c39c52d952648b256e961d478c0c6979300c5188c490ce5c1e34ff6dcfca63c0f0571ea616651ef6f9781f2d355dbca208e56948ab9e26c5d2d3f8509952bba3e93241837b11a89caef6c956c9354ac10425a6d8d4e82bd5d7411d18655393d7c542a7c914a5ea6aba717a226e0f51200cc949f38c703f4f6ce452cc1d7d6ee8acf26d34f74981f6850b11610c11d1c5e6689c1b6fcd6b6e997ea145851c6655560c33dcf5ed7315578263c39fe6a838c5de867f1b3cd482c0206f56ebea0617ae25b3ca8d7e13849bb2b58ea4e21409762d549636bb7cf5ec32d3216d827d94cba1f36e7632e3a43b3203fc596cdbf879d1aaee90804fa0cbf46d08ff4c40aff8fb2b46f7ba8ce21d17c2d3d025b67702054e" "9d76716fe7b5c9d2f43036d86e6a17924d2f160f91110ed1f3364a1177aa6193baf59878ec84f450914faad409618bf25cae17ba5545abd33833ebf408990fa4236d322089aa42eebea965e59456250fa14bdb61a32be8d70372891a83e7bf298168c5431e0b326229c36c667217bedbf64e3a07019534a087e84cd1a9cf35a889d9e65a7be63e8d638373774148e127b328734963437e7f00253d2fcce7bc0d798c09326ccd4f379f8a29f2d308ab2fece6fcadd653b1a3ba53a078e51a1a87e8dc03c5c118444d82d9166c0c4c1bfbe8ee09be6f8cd497a20132d4b6e1edd13683b363dc6587de2f11cdd51674ebdaafc41654d639b6cdbcc040f5889efb1f64e1b873442493ebffd8f867f0e1ba2cc629bc5239ded578336a9e88ee8b2d1b71f6d9303cbfb8a35e4015d2f9ec25eb4618c2ac17166e8964b68a66e60cb7b464e36a2251243a218ee542dac96062ec7db751273435dca23bf3e8aaea895ef1d6f6bdc98fcb6a9e0658dbe734450682cd1a3fe16161a9fbd035270fc86684971e20f1f1869546e1b77a481774c9449ac6499f376bc3c0f0efa589abe3bf676fb385ea50618c681eff6e5359678f078292da285c4b5e66d5ddb43499abc3558490aca6481299c351c6b053739d0065c187f59767e7de24f1b7bcd2d80d0ab2e7c789a9f5172a8411a88d2c69d8f9d2744ca7e42ba8478648df29919c23c0f4cf14e2428c792f2d8abae1073b97d86c2d5cf2e5beebc7fdfc449ec3804a81199d6c4f24d9b040bd1feeaf141b7eea626c1fa812" "e499b74e86dded2641ce3e11a04a35c8b8831a4de563c3614b4048eaa656d8dea460d2c46f6d748be434718e9f54934804756fad07d2a8ace694bccbd7bf2e33c09199a22a98726d2e1a690b2a9c33e39c8746d8125d93f675c571247b0a060114eff4c32231898a05e3ced4721edaaee9ebab9b46692c65f086d9fcd34b86a499685010ae0f4423625263d0a2a62672624662a6613bd4235b7402573af1b0571c364f7c14e277b84e4a102b1055a1456b912431f9ce9e875056f8b48345ab09bf06b3de6126fae32e2bd61d2fdea29a2f3cb46d963fa40694c02657352b9b9918bc50fd7e26584e51ab5e4bbcdcbc18b9bc17d3efc5935ae5077a269fb8e912dfc91a2c287686590c3e2671f6d29365c044fac2c077fb5ff280b0a4d69eee3b9538b4c8a029a3360902ee8291ca9f1088074f307392b70a7a43ceaa07c47d175b286c052e2412237da3f6acb1eb6b1ec386dbcdf5b49d2391615788f401ec234b58b112d296b389ede47243c01a1a6d18ca5dd3f2646d483b97e41370faa1c023118a1d2006694debebe35046f6e5852952bb520c9991cf9dfdcf89e51fe29d3cdad6f1091fc7c450782f06b09cb8aed1e1f95221af7ad369e49ed672fbbf2d255549d0fc0398dc6b4d37d038a8dc9e8d9b4d6faacf3c5fd10663107cec0e171ea6e1c26eb8a1534646e0813ab0fb449d15b4865eb2e9914d404d06c1e284f66e39d09e99eaf7c2f36997ac6ecb9197f8ea7fbdf7da38e427dd5179ef265f1471a096fd24d8ea2a2ec3b820c54356cd912f06" "9accfd370ca945e60c72b5d479b15d52a5c3c4423c73f4ec06d9201ddbfdaac2e304b1408674d40c203ed48fbf4b126904900349228b28fe262539c9a12270632f28241198381c6e7174d275227c99178ef4942655ec95acbc19a3b96fd1e07b5e0e91488c979e7e25be5ea733bc3171b2874801157c83a6de754ecd05cd78d6d2846e7ce19f641bdb53075dca078ad0ddfa871c16e47da96d007b5e2b2854d151dccfad21875fcd12df56dee7f4aed6a54fa248ba2721ab2f58c1157c85a3df8486f99295f2c9b8e8cd7a65145b69ca93d0ac4fe328e31c07bc1d0af2db886266def575d74be200ec9a4ccb0213743eace8d7d39f810e3877876082238d72c375a5cbdc4d7de36c2ad90904a173df80195cff86f19a0904d18a1f8a92cc4779e5997dacba58770c5091dab5b832dfaab2d0fd102b99e3b8a799ac6e7357b294a31db5f9bc3d04036a4a6e18dd47dc88b0f07e1c4271e5106f329731ce4dea9f56f6d63beddad788d7eeb955589a13990cbe3454b07f63477642613bd77f3bc5d024dbc5c55a0c7426ac7cfe63dd2da9f0d5a7e816dfe5856b646b648c302c16b50296882c62334c9b8e56ba6dab63a9c787fa153d04e5e64503c6bbb9bfc8957d2fa607ecdd3714123dd52b6f9c1a3a73f649dfe67fd7195857955cb8c5470a9f363116cbb580b793033280dfb63ae47b384e6aed677251b63a7a27447f37e9817f10f27c4a0560ef34c0255617cfb90769aea2e5971077cc89022f8a44493d5157ab2962946c7fe600a24f002cfc6108d345" "469a65f2f29b55e4da3f4c767324f173a11567ccc401628f2934989b29875ededce223de3134b7e99384f94436bed28329daff8da5690984b491d43f14d86d5a5e783545442f913dfa39f25f6360d2143fbe4c7e234a40f65b2c48ff5835c3fab67a92d0adbac9e63993db052a832b1c7b6045a495b82ed0d7f1068ec96fe1519493f7376a9f9f331f6ae89420fd1b523278df3e78c7b957f599767057113d5a1895801f1fff1b7021fde8360c4fc1ec8165132244b680645df7a1c0673728ca6323379739905856537091dba18f762b7be6f5f7e95212c402b005d73dce6a7775e90093f927edcf0d9ca24d04809f953ece372414d5f987ec2ae030dbb547db5ec17bef47dcb097fcd2fdd873eb93a99e2209425d4fbb589530fe41bdb5daf8ad8f83e48557a01d2ff6b658368e39bc8324cc2756160cdf56b8d7fe231aa03e82bf0b3f55eeaba71133a6bbf72342727a52ff7d158992895c61c0bab4cfe42ba5e4d5f239ef5efb6433dff84a02e2a5f12bfc35c1062e4103a3f8fdd1c5be28bc83725023c8a72d2cf5103a7c97a23b2d9903a1870726ad2bbaef7b7a6dac3e36c1b92769cb3f43eea1faf95c53db0cda2a8bea38efc1dd11695bb5de4baf583b175a32d49f98c37510e9e56f3d9e10bb4aff163abc91a36f24fb38d33d87fb4299d5ceb5144c69cb741b03d35436002d7740c38753e284a808a77cc1d4ff9e63b9ece720e778497c25b46ccf757449cb3b3fa8e5bb6d5a9f6eab58c97e9469cc6192b7b31362453faac839327067f41f25ff" "34c2cd40e9fee3a0b8133f266407587ac40db20e7d7d397e90558e54250111f540a44a70d427497b5a06c8ef87f6bba0082e00d42adc7eb38e890dcf5cd426c1bc2b4c781b07670382aa0d13e227e05c1987d3cd0241b5ad78387e19dfe4804189dd8a10cab05c79409b9414a6a384cfaadbefcbe8e3521fcbcaf52d92dcf1611ba3a824b576051aa24f42cadd7b7e9841375646740f2a6271d81d2d5f4819ae6a5d3f1feb6f7923f4252872c3a2709a8b8556b3977af8c4423bdbcf66ade1b3c4303539e06957e8930aea8ff70d6a202407aa44c6c8dab0232a33ff3f3ee9f61ed664bfadde8d294022da21b10e0aee583379d8dcdc078639cf3a1ee18d6ee1740bf1b917ff56070bf807b90d5a19f37a5c31214c6a19532f364d463595262ca057f5865f0d55636ce080acfd4e303f03372af014a3c32d2efec8f7f6cd6c825e5edf309ed16008e50aafa2584804c1897f6433e350cd91e155ac786dd9c3deb22a39d69e85331086842f32ba7cb6b4d4f13e08d90acaff24315020f7efb2b74214b14e840d739378afadcb06d45e7bcc17f2a03ed54d0da71d865508900334386ab96e11b88d2811c84539e4e2a93aa27d66620500789bb4d595a8b2e5972b1805d88af2b722e1e9b8aef10ca3dcf5ddbf3d20a6f101bf8f8a8cad825946dbf0c64193689f461bc0c62d138f902575ed601e26184a10ed9df17ad4be7c9672147c0158f132452ea502948a749b474cd0a63ae5cf942609e4864985b4060239d0cee6c78ce4dfdf5750b51ffbd5ee920967f5" "dcc52df6771e286eb83dac1c576f1a073687411cef3701ce6de66ed17bfe0fa5f03c63f96fb40ad70b478aae1e16efe22cb9e8c2aa57d5498803d35fde7f920b32ec686e6091a9ba6eb91fdd17b3302b760d084bda32244f704e14af619a5c9e72bd14c4e69f51177a26174c16d2e3eac934f184d460df5640fd84c3d3dbbc6785c249a501203374c0d58852d52c4c64a6d70ead2af1bca1d61f6f4cd00c3892565e085d3e603a0586d176f478062b092b205807fe7438a065ae7dbcb14f69c92cae4000dbd6804bf4eabf112813ff0599a29b1fd8bcf9d0ba7d9b14e40e38826b48204d8c0a50fd804167c88056cfe77e7a75ac36b5bd049571639b3f02a7e973abfaff1327080630a4bbaf6a096005ca2ccd54f076f2c3311e6e7b48bafbc9de38d01c8a01ee41d25ff0f775a2db4e34566e377683bad9a133482ab87907769bd783bd170b616d48974ad332e3defe94a2e7d6eccfb4cc43cad93b53c476e7795a087fe58cc074b591315daceee3c02af54d9beac8162b70dd9863bcd7702b7c8c72022856f78b2d249cacaea6c1dbf1317ca9e35664c518bf4155501ae77ecc3f47be6e7151c4d5fe56b893c69f1f939cdfd2b68830d9ea47a89fa7b3d4f620e0909d5a97f2637e2eaf223f25fb5ce7949e3ceb87d93db628872fc469f58a749e8b4841798ef505ef2712a3ba713386dc56b83e504c3d24d2ae8200698f9b3eca8d7971f7b82dbd5df6deb34865e2e6336fcd2fc3ff00bf9c8d04992f012dc9473e347ac05aff1040f010b1683c10dcd0bb" "49b7b5883ceb6c0bee4bd2ea6d275f884a37fc7151245274f208a457f4bcf180d793de68f09c7b03e7e430dd34e553362f91c4e721926eafd54d6c8464082d2d4a4c5b4b44495ddb06290f01913e68c7cd95963242df31741eae89eec41d0af689518ae335aae42c60041154356ce475ba0bc7f6c5ec798cd7c493aeac5e08d7ef554dc23832161a615a6b902e1d4f7bd076f3bf045360cdb73c3b2d7c158b74d2b718b95189225a0824a38836d1d4dbc5a2861e62f8a8c2723cbf1fe8951860f0cf7b4c6bc4c307cca509435e077f3947b8fcbb8ba1252b89d61b69b0328a2b1c31255c2c9df670bc244af42599cb5982878fa363627b321302255f2a20e04b70e8f4f63638af83a98ba40c55ecc46230798224de084d2cc203841d91c4f049c9b0a98535f3f905bb80b24679de883470c8225af80361031354483d879f98b78cdc5aeb07b371fea8355d146f9bbe16c9178f3d83ed63e2812048a386ef85d6c35ad696936a008a524f358ec8a2e40081c3c50b73fcdc6199f59e14b6ee213a8161f675d5938ce72a848ba9e7ed930198d9ae6c43dd86d94d88c5312be17b9dc590072e382607390e247869674ff446e8c37d89b7276aa61b5ebeb0ab18f500389a326341ee13283965dd4cce69b666d2c114372cb0e5b5d9921cfdb5e12aea0d95ec0a73c8d07b3b3e0dd8d159d323feb4bdaf6ea184bc2fbed75e7cc13bde26aa597ea7eaf0e37aa4be069c2c629af7debd8692befbf74d6c9939165e3238d8b2b573001ce957942b199e5c57935ecf5ae0" "c3b161b96f1f637605bc29bf5230fc65524041d9970e9b4bd6e7469e0c0bfb62e672b30a7094b014c27a06e3982d83a951ea4207a4d7b38eb155259b847ecba4675c3f82c48343a07e2d5fe16d3189c8dc0f4bb1fe2ca4abce4638a4462f0dd79d69c240eeac8ee4bea297bc1bd5683ca97a352712bb4461fd507f9125f895fc7ca8fc76c7f78207224d0fd142669137ccbac0f023fe1700eef77abc804e9b9da27ad5c3a767202a0d0a36f8fe86e2a8ac5f30303c39fad8b65a206239b881910f9d904f96edae31e4befce7822a7399ad06355bc3c7198eb1a4b2c7c8b4c92a604dfa4905109c35edb62dd3c817cbf5261f5069bccbcf98da9ee5ea192151237b31131953509157f833bb1b482cd011c361d768347b2d0da11b1dc43b392d609f0c4806d7325e92f9d76ecd278fcfb9d91e9993addffa55d66acf9211b7cdcf28c73bd4e7cf83a869532c90f9880bb963cec69cf40e117b3fdf9c0c5c9d6570a2458aa9d14716ecb8b6642a4cb1fe0fbcf8298ad0db3c676b9836910658f03bd47ded56ed210cb1e2f1088c87f4e225faabf29e2d450468ff6614f282e15b4a6fbcc9463a16f802d3ba071fa5b009403478f1088ca8a8d9eded648be7394aa6bb3590c0725ec87fdcc53c4d2afea49ba11f9f2b3231c912bdd9431ad941a7d89f70d8e1669e90553b047b5f4a033437fe3b84c05105227efb5390e6e99b597fa1c35a1940f513ee8aaef9485d1ffdf7ce94fd34dfccfa8f178dc113c32082e0345f6d39294ef283b6f9a566a87b1122e74411" "8e643cd6a2ecf14e47d68254d26942666fcf957586497c72c9e5814ab3371fe4b0f9a7fa1e5d9629d0dfe9e93fb388865a599076e7ba983365fb3bf574d335787416c099c545feeea69e3069d841b62e4db9833e6865e24cda78e2bc46ee83ad5d79bee507c44007200e64b5d1329930bd658e6f051cdefdf758e5b023650c2abda7a6827ca394c086057c617dfa8c161ea1f953446d8e0d5f6d5c76bedde8d596d1641a973e2b53bddb8f7bfcfbd0fbe4883f4d6d4e6f930e51d47ccc40148e6ed1b409705e9a777f1bf86af2621cb1f04ba160a5faad78a0949032e9dd7e34bbe6b2fa1c478a990d3b7c474a2f81af7f7246bdcc669df005adf397cef71869237c53126d1301ceab14011a529d4897cb00f7d93f35031facdcfda8110b9fb5d55a057ac9087a9cc8f1034e03f79a806db8a8e726e8afbfcb2c7c39d3315ecad3a2e542d94753b88717b7791c66c47a45f499885f6c096cb1093d9dd6082ba8eb2132e4a80e22ee309b7f74af55530e190d73315023fe4b52fca855a06fd111fbe1125910f4ace6dcf228447c007cf82fc50993de0202d28aed32ae795d2d75ba8c975b78c657af*0", "vilefault"}, {"$dmg$2*20*186673f316ce762e8f2b2595b3e8ea204aef584e*32*df036556654b76eb000000000000000000000000000000000000000000000000*48*71793cfc457320157f12b1351051f60e59fc80a728f82f0156cc8b3f20f75bfb4289c65e6c8c21589f3dc6187540551a*2*5953*3c25089e22f54dfa868b7460f43185a32b6988681952eca4a493ff4699e2340f8cccd06ba2df28334dd01b83f8bafa3754b7afce8f859ffaf64d33950a817d5ffa9671894f71d6ef35aefd00d237f7f8f413b8b8424db42e6fe7bf503d1d4222d77d5c3c2a16f26a1e15d7797cedd59fbeb45f70ff7731cf8be628895f13cc2937f82c92e0d5c6b6ee0214c668ad1ee4f41501dca668af0f83ef252bd6b6444f9028f12ce15134fcd8610426b5a6a75ac25fa938f93280143b5c991a683fb008a08e133a962dd4e3aa9ddb57e72955e3a840c3599b84d874d61cff4236fb487e2a344ee3311d30a531a20ec800ec591607edb97599b297ac67e173a4f7d98ce2d73b66c37659bc75becb65b799f0a1642a4282ad623ee574091821c971363128e307288b4377e1e90e831b800936f2b5eb05fd5d0e505d71e7e34311950812131c5b742ea238bcdfacaf35e23a4b5b9ee2a7c0da6aca0ff02595fd4229baaf700eab8ce7ea772e133bffd5665ea3ccde2edf61d11e64dbd1919454f977a31292416c86e3e11b762a3c6f0c27cf1a07ba3c4197f21c8959e0f04fae6a086be6e77b47495d0cbfcfce05e34ef361d45b1f8c5068f0174cbb2ec9a9f37eb6ae1fb0887" "17630b97bf46c801ca598878e6a8a96b232266479925e8f170bf76afa4acbcc6c7daa51c2b9a1821e5b5df170a8b57aa371019c240626b2f2a9d60587c34383ea7c12b300fb478e2b62ca9bf54b00f04f4970a68d6689c4087713e9b6be1e7c92ef16a7cd527d1ef33140d8d3994c07d8ae237e047bf478f164aee1c6300545bf986e570a403ef626c5fd14044611621bc5d5f37e417175a22288c2fb45b0e11e946f755fccdd774e5ace72bd2ba44be8f673235e9b49c0fd4d6a912493fa797bd97462de0402f77da7eee2ea6c0d02fa880ba57390eb1f73927d4616b95067d18103ad4b10af7a40b35e620211acf4c9f47fd12080b2df1d350d17afb649ea5e8a038157561b107e7d1d00284a59541c0b759bb424d2795ff1d3bfd7749461a9f67502df649d2d69e72036ab4f8869c7bb35fc999a9179612524e2f9bbb00e7dd5ef8fbdbfc486447ad5ea93b7220608aff49eebb98a1de88c68ce2b9846a63ac6b8878fd645bfc0c0fea6bb746b15301f58d2b9d2ace73828a623885fb495761be85780668b436fcaa6367776dee9e3af641ed5755f1cca7a931c97162f6879c7a3bf6eb47f98590d07654be8fd8582c5774f89bebf6fb113d75d28afe74443a64af360f41b9d243d8fb865039d924fff4586e3c76d9d0d43f8487200e802adb9e01460eb6ad5538d8549999c4b38c41dcd878b8dbd049b853aaa4426e74226fa19d3d501e6a93aa99dcea681f0044e15a05c2d08ae49f625ffe88181d2c1fe55e91b6f602409fdf961af1da851fff67f1e9" "c9ac10dd3960f460bb8f937ec415870cb9e99e150f5b2a2308f2136960d199ccf5900f130a3f4610cda347991cf34fe46717071dd5ab2e8dc5bc20757fe6357fa56a18a606b25c51612975f51cad52e5a20a8eb2cefc79732fe19baee7b8c65167e2949a4ddc8d1e262b47c97286c2d0fb7078b3f553453445053d82a865320ead1ff4bf4fea84cfd7ce21e7aee696a15f92da1f3d73c394d47a254247492fec3b6582c94cad0df1b1b097048c9c91bae6aa269f5a074b796bf86770059cc767aa07fcf84010b1686437042d16d693775a03d9832857bdde9f7d98392bbcc579db3bddbc58d8cf08f04064e3eb92d87829e6617efab245cfbb6d564c5fa333ef560d6105c525e39177ff5530dc154b691b1dabf14d0da99229a04ca5c6e7956d474c0ee578b1b287b0a5971506687670ea848820c44875c74e69a79b36eaa3cc2a5a27fd5098f0fd3c190089736a271ecf3f14b3259cab95b941bbebfb5be132d875328a1b0ddeed958e8ea454ef80724f878a2a690bef56fe3ea62f47cfb6db303ae608957dbbd57735195d6b1b2ed73e69d1ac4b4b4fb01c20eddcb29e8b44bbd71fc25515885a56b8b7e55edd4c21d5e8cc43417e94e57cc49f279d0ed740b286d4e27c0b909729c4250ea2d1857f3f7d801a87afcee46f455f8a53e211fa0a311006cdde262ad4bc47941bc52db89c4b454b7075bf29d9cad6c98b7e84318a071789a78d1a83ece7a24cbf17691aec06c5fb7bb8a832c0aa33b27a5b3a68ef36364fd85cbd19e8f75e184c3d1cbccaf7eb" "c71211506021ce0d38bf8c0885a205d7f4a60f7fbc972c7e2365b07d5a52fe8ae02608c7bfb1650ebdb4f2620f2698f5fc90c7b42a34a31732d2cdd12a4bcae3ce399623211946f74c67c5e82c0f53701bb4460504e17c1d6fa14288a63d97a86068be8ec36670adc16670b5cb3c09972b596cd441e4bb9b50471708bab77691417517e91883df9f0b353c2bea3d0acffe5410097edd2b3886592cc70ccaccbbf64d168637a8a3fff0d143e497e5311a9b13b4adcbe8d2625dd1fcb5ffe9c83ddd4a1cb3046616296faed945fe7b29ab6f912be6959f8768ce28958f2441a1e161147145a1621693b9f2d24fb9c7a89535456dab48dbe15c689709e2af6a6805edf923d8504f3d2cb8220ff9966f854c84e9ff04fbf45e42a5c73df4f719b9ed287695a4a03d5c0a3a964a7b6e95bcfc36a292b23774812e8567a02cb8a5baaf89afb900b3fb7be40c9e8432656307fbf2487c0d1f3baeda11e803f9f298e7e0c478f9fac11a43ca32e2cda46ca6491cc7b31aa1725d24805587722248dc326cf81fea4fc1ba9a58bdce9e34740e3732b96889b36e917cf029c7027c5cc985f8b3f0fa4e504325d56c7e653ce903e8410a6b06a2126b3aae2030404441273c1e486bc8285dc078c1874635e75cdb753a0fa821567e8116179b78039f8cc52675d538fe38a71f46792af445b125dcee671bf7789f2e874b25f05a431ce574a2d85762ceade5e5cfebfa5ff62b1ef5ee155fe418b16638c1562b29be425e05ef0237f03bb42181f55d4370272a13d5fbb353358d" "a434519cbd0e4fca54f9cad4a7735238098d3984b0cb9360eccfc63b3b4339e0ad2b2719552085d7445681c919f21a6b482402c271e34d7f9fbe4fbad68eaf825c57d22ec0a2c5ddec8c1273131b867a3760626abe779e37ee632f41f212e9a9aaf26fd5cb28df689d9c4875c49db62213faa1e18c35b5d2df1fec21852e7c35d20d6df85ca2a6b10898b244da31dbb6de3a3a8553601c0dabf1e5f4755fc77c1561223cf0b1ee43441c3aa9d855df0831db6a7f6949ff0ae1cdd465aee616b789c268417de07e9c0f0ddae6b07ce5186b3b83ef96fa1ba9fabda1bd79986efa852a348364e33e89458550049522e64491a9b24514665af058b4be4ba690299d3c2379b25ec97575a9312b38d3106f805e829bd77033f4d5f1b35ffc7289c118749b31f17babb56f48aec597049d635c055d056db0434493a379d15010f3325690444e1021abd622d18ea7e0b5d5b97054708ea9087b4721bf857e3504aafec84516feab2a6f6309a506cd3e931ef3ef47807feba8ff0b6dd56eb83349d99be8633675eed19be804c06d4d81b0a256ec95cfbb2b6565d7906537c5adc404713baa8fc2e0f425c577660df47198e91d2eb3ee7a9a5025641aaa759e7e1f3dfd85c83a17a6a59df4af62bc669f28d12544254f4e0527a6b10958664af9378e41aa9f88ef3041ee6880f23a858254b5d0fa7899655e9d06f12fa863b63c2c950a0c3eae774149502f0fa3c3a44d24add7f9426ceaa21dcdc5408f0b96d63dcfd97dc4a3ce03ccd56c8d48ccb253e82d50123e8a51" "76ae5d1b9cf6b6c11d2decea9f91e9ddfea605eec75391ffc4e01f4988c0ee78ccb3adb8a5e16644eb30e7e76ff251192fb3a8c48a68224a2cfee4aefa616ccbb68abea13d335a4b212b0b9841a42b418cf413fc868a842a26950e11061608a623a5dbd520aaebddfd1a559705e8cadf6abfa272925651f84130223b0056be28b618bfdfb164d2c5db86d82ac0eb2c457198a6cf8b0c2f2560eeac4441df45a9192cdef63a00adee0aafed7e0ab0bbb0c0b9a066f9f45f5e0c6a9376a069a45512081ee3edd2e9679d6c46d71e3740c5ada7457fc5d21610edccc2bef851d18f89e8307105855da15dfa749c44370b8149de48309f99fb5040d05d0739a64cf253855c185550339af73be6d5cc2de3186ff4b004ac816c1f4afcc83ec3ad66740c57b9cf660de7ab97b0771189fae5957751eec58a3aa6d3ec6121bf767d13533ff413c84c1ef47142f51ebf515c3d60a3c5cc3b9eaf9d43d2a84b94ce02db3f254862cf3c6330574fde5f8257c215c416ac3c9833839d5b33436fc12c21046025a4b0be90f18dbf002e001b8541b888835ad138def9910c4546fa0cf496bb4415463cb10004959dc6b0e379c18090bbd1aba6e9588fc21a89778ed1a1c0533049867569691aef6bc310fe4853e9e9bdd94a58943017a197526c70d2d278c66e94aa97abe5af8d9faceb0fd4e102bb69c824a1e4709be2125de420aebb11506bd62ae6b32eb1bb2cbcbc35dda3c992193086b11203775b33dcf4206a976b31222fcfd8b0e6beab7eed02f9f6d0dc2959929e1d" "30c856a672379ea1a20bdea6e023fb7ada31f6f9e02f354f464b2261879372c0c92ea462ad11a83d54bacfce3febcafe14753d697e905a7c77031beb83076444aebdb99cd1aa470d5774ed91cded7eeccf7fb18860fc39577a054b17aacae86d02c2dabbd3ab068c982cb095d135c11daedd863bf9abafe991656d1f7773cbc05aa66c4c800b5763fe845d06c3b19f4f73dedbcd50ea363aa11e8274d541ab754209fe7fc159e7bbe317f8d9ba602bde8fe02171f8daf608bcd4663eb401c7a3f2cc814bd8fc195cc192d4d6fefbb15b9d9738f5e6ade7826d65b9d8477ef500afe2e40077b6ecd7d3ed78233fe980332a313fb2fe854d6becf9ab4c1008cb1b16a513d3fbed8036ddaaf372e8891c59c6e9bcdaf2d88e22d528b975d1a36af2fa792028a3e1161a74545eab1cd6284079c2353ef1c49e3e1242ea52d22d8c7d64f553e4c396e7d62c4a6619ec698b56cf25cecb6673d8a3a703f65e480f1b8b91e4427e9f1e9dfa1939134d03cb3115167567835d449f50cc9bae06adc68e3211d8e0cc1faa34f7bda6e1cfb088fe980397f4643e89052d2bfeb233ad81c3cd466bca1b1007e2e6459e3aa1e51f1a326a2f5d89407c05946b0dc7741f458464b5e4ceea5e367a2e4f0d007e9e31b24f5b7bf69aecdef4ef57de58719cf9fb5e8f5366452013a5bb69c3f1807d83e26bb63493dc141ab1ae8eeea11c495650b346919de060c4af1a80823fb10b4cbc333b9d6d05c6a4c293a7fd524c5259a841500617ee442222ef2cfc71a0e4bffa87903ff5" "31898a44452ca2b132c4a633c91c7a24bbc885a01001988ab845e53a350c3b283dda71360c7a9b47ae40f72737ab6be068ed8ecbde1d0bcaecb729c5bea691ba0de6867e6e6879fdd99efec2b6de4c2691ec9031189491a01329fafb2f0d0cc28e26a22bf55be6ca866dd4a473153901f244c63967e829d9ae2ed83451a365558b697055a3b9a6bcb1bb40ae56f13d4b60defeb1a06cc6831e175ccbdb92a34462e786ea28e2ff25b813b63b30ea3b8d9a0921a5a5bf45576b39fbab6071fb1412670c936b5fc31d668026d297c5b84739021c4e763686e4011a2bb7e109db8e1d6bc853235a44ddd93f1012f7168ba3091a2a92a3e05bbc761fd97ebfa22265e6c1c2bccaa9d327d4ad61de87d3b5f0c5b29e604f79827064e05eede8b574c8982bcc0439db27b15bd7ea9a38923a1982fa7063f9f1572963c75168d53756803f6f60604ab33388ccc1294fb0ea143fa5e128a060da40f4dfa0382906b878a602c568f3c99809cf1d5912f224b2adfdcdda84df149217bf8edae18fb4bd825900ddc57ecca2eb7d209ac44e06e674c2b7c126756bdbad066dcf187344824050b16ff9414fe957c37a048c3a260a8dea72f7a12bf5b35e1c2205866bdf85367d94af939bf52a3027e2c560ca096a449b7297687bee98e4cc56e1449448461d028e435fef26f060097cd96bd605d5a1cf6b1cc95c49037401878b85d437ee43bcfbd7b2b8c145c05a33fe01226a637dd677bfd28c8acebc4a30494917c253957462cdd5a3d200e350f5d92c5c57bbbc7b2392e4" "569610f35e3707aae8a481b8500dc8dcfac689a018671a0f3634d18fc7bf4f7c58933da452308e348a446ade0bdd6f02d29cd8d273544ba46f1767873717fea45f0e0980339fc187acb7045612e95db5dd9c89169daccfef2e3a01c4d19984f8b1cc960d054285119f23e746d743a0db459bdd5803fcdbfe92137e80d47c84c547848ae563695cbf113253b8a96e368bdacf59ff73c023d043348c1dfaf143ed13424662c2da644c25b9d22598813e1973f30ab103c0ada9ed247ca038a056d18f2e7c8443fd2c95366b387e9ab972170cd2b4438455dc73619ab3444da0d64b0b2d3a9d640ea917b1c09d17c37fd587eedab367235e1748dad753e4cbc74dd53017ba65571a5a65269666df0a24bc694a2d24e862830e7808ea8ffc1fd6cf4b29564c8d77d9692d7fd55e496c69f5f17fe145abc0dd1818f2cf6eb979c33eaf41050901dbbe5a49c8bf9983b1284fce92703b45c4131b3204fb9edd58b6cda3918cc490051bf9d6751b7702e577b700230f1820238b959e46f7dc3a3abad842814c69a76be5376c1e7b35e3ad7318b3439008e4c3801bd6754fe67cc7aed658d89550a30cbb1193eb5d2144eb7f84c5c6ee9e13947daa3534ad4902ceb9cedcae471547bf95e2337760322b55af97457d23d174b1c6f3e1d3585feb000953e298e35aeb467e90342bc61bd05af59c72921b2fd4795c19bba268bc6bf4f18349ca91b89cbd6814a62dffd4684ab78e998f7e3833b51ffc495ca3e789e685417a0d972bf4192b0c50016a64ba839da14c3c5bdd" "58a74e96e56c66d73e2869323093892c5272aba5e6edff5a8976c5e04976c8bc1b8cefa630cd924b5bc7d28dbc67b8aac4d7571623c4d412acbfdf61603d2cdf1bed6fdcf8d88519a3ce3c4803317587c4a7dd33147f66aad06554d69138959fc3172298be9f5f83748b83c6618758bb45058fab1bbc1434b993890288a42910b91bd52ac1abe775acb09cf7173ff9fdf0e644ee94b000c8ac5cbce24d424800a9df431e03c650b3f4196115f100b49b7a41f68ce27e5dab5865b40a0977cc1be995d3504dd3bfcdc8db2a57765b1a80f6cdac0db795336bc9ffa4cc163df1d9d6e034d5b246cf59ffb2f81ec02ad4c48eb652be03c97a11427ab519d8fc8d704fea98d597e44cfeb168f3fc1385f1a1dc5926dfda78be4c3a3e1d024e4492e952cc8471ae1f26150cc065bef433c0431128c7df6c57bd79dbd409fb0684137465ec0687ec2ec45c6fb76eb88bb7bfb4df3fe69421dc7e0809e2474f987a59980fdd92b2a66ee31fb9560b4657a112ae523caec636642e44b507ed5a900fd65e29d35c89d252708b7f2c2daa29062b94577b0406ab9cda76c921694998192078e2ba7a90386e1544444c228db678f9c7da51a06b9c0a22ea26ebd3dbd8880a6e981decba2f659ddfcd15af8d06031e2d8ddc587417ab536fd4cef49372e0510c58060f2900e030fc894f1edb6aea502b0e2642a8cb1e0d22cc11a43cfe8eda906711e059d6e4a55959cc337dd54428eec2c123f5cfe185a78f442266f54213537af2f4b42176951bd9b0d1b70c61ef5e728acd" "1a5b0c8f0360fc3d4106d1f1a6a100326500e25cf6ce2c7f230e5e54526c3affad6bba78eb0a275ef942e441919384b0420571655eff68e32cd97a322e22765fe736eaf329f41b2ea005ad56acb4c092b7bcdbf2bf3e54b058827259bac8bd94ea73e1d61cba79deb078857c63e255da3b8ed4bf5d4f603d8e3e19813fbe997afbd272102aef06950ab6daab60139fae51f0fa8b48f3e056a360f074692f982aac57ac3472539e7484862997ed283dda8be4b22b83235299d1b20df4ccbf0fa24faf392a8433535d3f3cc3ad7453b9b150dae24b8c78f149b53f5394af065082540b46f6ec3e70e2428b873fa564b548cc1e39fb406ff897662ac7e901384b3094c328bd484980c120518a8504511644b0616215df50ce1ab6106762d52ef24d40b9851168c69b3068682525f1050fa3ae139c9500f89d1b5a96c35f71e25f8ac229518a79fbdbfafcd67d7356bfc3e9699f0e5a8c9fceb068f810cf2c8e3042b5fef34778a3edcda569dde4fbc240996038e50e233652eb5f303fca7f8f29c633684566f6548bbc311bd24d7e0ba95da8f02917048d9777e5f142f83cce4187ec1af72b6b6c3825e38646f9f29697f6fe3b3cd76*0", "password#"}, /* test vectors from CMIYC 2012 */ {"$dmg$2*20*dc39029a22b86bb4f930499578d0dc9eee69398e*32*bb47bff69b10ae67000000000000000000000000000000000000000000000000*48*c4559cada09552ab075e73dbefa4aea1aa21209011946e423ca707753a91c87f6c4cbed3beae20a244d33568f852068a*6*4315*504c0c37c600618fd54da114fc0eb24d6f24585568543126ac56c034cd8d7b3dd991f1418d0c95791e091921c02bf695b7835f7b0da2c1b96524e72b4bd3f671c592aa176b6a58de77a35a26bd1d0c313b2ca23581027fc52c7c63f37439404218d720171d3b178125e6ce0646bd6fa1033f2ab7b6849b3a35a430cbd1401f73b5deb478d6d0f58364579c208c613cb2349fb19adaf98be2d4a74a6030215793fe4f1129189626bb87c23d26dc2af51a98e1fabf2f58e106271c7759d104b9e5171d8f952ceeb14317614b7a14a5313029aa4068b898f7e0f5b68683feff0d375f2ada37f20135df443bae913c7e96a29c6c3388b4b51432add89ee22826ad0b1b0a4ca9233e691f71a5ae2c76b5e5a135dc793e081dc53781faa4f844928db94084b53b39f1820c8342b563e3f46b002bc52ced63e4588388e69c9e85e2002438a1a703de411717d24ea88adef3051b27def61e4b9a31548d3714c3bee39fed866254033a123429043d0c08a052d2999a171b010ffd119f90bf9222462508ac914e0a68daf93f63caaa0c4302c9b1f6447ac3856b09eb45096b3a294731f110b90826b0d611e6e045397b07e5aa64afd271f1c92664e648af648642f786c0c8aae" "6218f4282d8efa713dce232fb24df4073a0e04edc86d940e8ad22db8ca751143743f9f12585bd788551cc7b70821b5c42b133cb7781f60d1b9c345e9adb122ae444be456b8e49f9bab0e2033019b52f2ede4e7f56cc1d1dc3a48bf0666cc7a4dc6b4ffd5077673f2f6761688e4452a4c11b82598cc0ef57213f6c7c12ecc67164ae501b3e87e25a361d0615e48cde249f0193f2aa69a1eccf029340531becdee8eefbddca18905451b48c1085d4cb965786d3892d7144841300b8d2722e92af50fb828cdd8e825dbfb16328f7cf792f311f84078d45306fa570661e1ef2b34d5d36de2fc4b295f5e84fae8d55ca22bc15764932d0c5dd3cfd914b2b8f67477b2b5139c822ee2c511a03f7e9c717a5e8eca6c4b54f9c3b7d85765a78f03b29fb979811ff0c655522b341bb54ae3bc412eb760eb689c6b4c3bfb85a8ce794946214c574105e577acc01d3f8885e72db52075d05a75260a6e4a54872d087040ff38f8942cf150c3615088588cc53fed11040bed573c0e9ab14b987f9223ad089bb73284443f61ffdd61616b8a783e85618217e8bb491a31b7050421f4b0a0bfa5003775933db00e47e4452adc1433da2603f6dc5b9dfe58efe458da25699e512660ac6f1129dd9d7b176a24109c6e6e0c201d784addc9c7f8d4f309ef6fcfb02493abb7c836ba3a371e64fea941031a59adbcd4ef59f0dbf31f361f4282a0e60ced4d9d17675b0422faa1c2f932cb525ee07df7eb2643a67963aa99daf5b119884557ef1585d81eac5c8acf32438636a10d043bf" "47093fb53a5b3ad544a38fbc3588bea3ed616167a79b2133efd8c509f53626b9cd7b71828fbd5d61b1df6ef3713b5347f65e7c0770715ac1fae561cc548864f9cfe281c6e5770f053f68ace64702c81c97976f471ad11c7551789ca21a4d5480c5d3528503f2f7fcb268c34498888d5fd3edf1c71d12581c393db2ff863e22c1f6c037106e5928aac9118702b45bd36782b2295782f93458dc120e79cb3d1632c2c5e527e56060b79a751cb7653b8c0ed2acc32168b56fe5b50ff9e49a71dc9b82f812b53e095660cd7d59c04f31ee47773a04eabccd7a4a6455ebc7d719c9eaedc4e6c935fc99642acd3e60e0f564efae90d7d1308d6ddfe7eb89520c234cafca6bc7e8ac96ed401bf96e3c9de704ad124b0f9381f22d9ce846fad0b14eeb5f93eb0e0fd0657c480fd2a1109d735f3825db598e2aa7e624f282673947c38aee8832ec8d4dc5d6a7306e3477ab4e37588788109a3ed76741f8f2a796d0f5bef8247eb298fb973c4e5d13666d87b0bf5a7a553f208050dd7140f64fcc27793ea82cf58fd86ddf805a700065888bbf6b5037815afe8c03eaea355c90bbbb448de13773e977fa4c6f06e7695e80882cdac40301b537fe254eb1ee437a6ccf3efa68899a7188e6829b58977917a9d6124cd2af7cfa567fb85aac9c6b971423681a0b6658575ea0dd32054800e08be5683faf46165c56647e1c346961608bdd8e6f999eb033caf73f000a71961cf2fa8c319f4084c0ab499caab87d13aca3f057d17748522f08b36c56c1746e49d731f9355100879" "d7d114000293520c9ce71098d26b2114030615aeedabd5a6f7fb9a91f98b7ff00ec72c82136a00e5a19384084e0aebc78bb3cf05c3c1e3872f56e254c68694d930eeb46ca8e99329eb923ee0f1b5af0b7276e8600e25f18642247111eca41da427e5b9034a6a22627734ee024c2e2c4277edcb3a0309c3007c19416fa131086eccc6f73784e1a008dba5166e7c8aa4cf8efc3a4e14f59d665800982e46341b9b098508510c7dadde295a784f7a7085f5ddab5b6881b305f99d87ce3883e557280bf2a1f3adc69b7cc9d4f339623d21d569230e57a2bce611de7495d403adf451725d7ef11df4bde5a31a95bdda0d0c2a7869ddeedf2ca7e1986ef430ed44bff6ae6e44f740b2c65364477ade4dff6f4eacbffc67a2e0494c81e0424bc9220bf20aa795e2b20db6076667088b6863243ccd2bf897d4b6e1e58e2662cac593fb9a86220d65964e7f6e0f1987d07a4a8242c41c001ec38ed2442011d8a56919800b4d590338eb8db02833031ed0422bc08b11dd59b59f1d301e82154803076053464120217ca64bacc02465cdf629732cf709777452e177f4a4d1015fec4c36337ebdb8daf57f19bfeb247a27131ec5280038f3d1a766e071470ffb685cf4d9763b7e1b5776589874f3cbd4761d5fd35638918ad144a4a1bcedab9d652477951a716e4073cb36640fc257031f06e4d6f586a9a0b6172727933179e4cd433ba940571f3eb908535a12e9cc3ec1e8f8aa9975bc17241779d972a8fd8581dd3850905cec48061dd5fff1b295757e38ed8568c3a2967" "ba271e00fb507b10bdd5ac5b90426e48e596ed430b5a3c554ca1cd0d18a90809d8db18853e2580cf2b2ca52ff686b7cf360799bf69c008f87191ee372b44f96696a12632af003eba51adf1e6101628168b92c718c6f7aecb765125880f180047ec3b89fa23bf57e4fabbce38ef0fcba829123f0a3ff527dad6d6b5b0c4b0c4c4cd13787e98c829bec08728acc5e90ddc6bcfe2254eb29ae8450ae87841a39958ab80a38c8a742de64a44e25df0360a9e8672148347d7812bdfcd9037723edbc5fb4a8bba689dfe3baf113778a498e2689e8cf1ad194df422838a618b0cb222aaf020705fcfe1475a8c205690379cbe2d0b5f9a0de41a4d2e6ff85f1f19a97712bdbf49bb90051ab934407bdda9bdbc1a57b0e874f3b2a09df45b7d01bda15330ccc57a752deb2751e495e394471f09f33d98d8face401d418affeeab86be36cd8cfb0f435d9939822041f256ad860733ccf137e582e1cfb5a8b96ffe646d1928657c05c67b8589a90fb32e078697fdf8a3ec58dc6d350a7f50c83d09e5884317829d8e850b7fe17bd2ba4d7fd94b86d060a3a97880fb350b95cde4542cb7d1a2f44f8ea065ae30fd4d4b5fb24f787b8462115b3a918155bae098f0fd7ae2d4646d3731d228909f690cf0116e1ac15899513957834e0a74d8c07f0c696cd3268d631ce1292f66b2633a3287a7e058781aef9d3d566e4e41395fa7e1793aa9f669aff116b99660a5a29fe127a0459eacc3fefa4be95a13499dc844d9faf72dca38d8032932084faca23e4022869f2034ace2de0" "b286e71f2b569951214fd2eaa3d32da48a234265acec4967c74976b5b5d635eb12cff038a4a23d6c8e86a11a408aee5eedfa7209a8ce8d6bc10271e4b5627e16c5f8ce8000882c461de0113efd8ae9cec6ac4819ab2d6f8a9f189fa2929807fb20a895204edad9821d180c54e865548f9b3eafd8073a734e61d574923f0d1f69d266d970102434b0bab705465833ec9926b03798fa8a95ab98d35863b7490db07fa1abd600abcc3718d105f26f96d20e593ce0c82efc68ae65d03e4e2ed3faed27bc5799e359588fa884ac79c1ad4f5f8bcbc9a2a5605f97551710e2e416aacf149941265406490d32cc6bdde994943fac2102e57785dca3c20358cd431cee285768d9eed6ed32a9919e13f1a38304db6a57f637b6a5c8adf4e829baa82ce674ec7444fd9f7f1807b8f65d4b68ef7b6c3fe5bf653e81525f7900916f5d5809a52c070256e6b4cb332fced5e460c9a2f62bd73392bdf4522be7c211577559f59f62869e0a71f832ff493fab76bbe70f3c0b902fdf45cf49793afdb87558f1a6ec289018035d861990eca1dbfc412492cf86503af00c7db7a0a2c6374eed42b440293938a36f61e1c4c187cd50d974f2a0989b05b8ee207398560b516aea520044e37229fe0efa8b7038441fd584d79c010c0f31030d60eaa4dc1fbdb5a254c089198bb5eba6fe20655808c1d22b9604af1247e2b820823b3c622be2b01ca5f16f86af880908ace8765520c813afefef18e2c112a72fcd4760da91f7d1066cb5c8c902745b83be8defa193bc8b6b93a82efdf17" "13a223660c6ff4dbbbaccb1a4e5482cc238388448e8b9c24c9aa3acac9467e1f6d96d6deb1cbc9fbbf77b7e756068e22bc3b9e6c275987c5eb99da6a5e2d90a1e0558c4f9fc392371c07a7844cb947b19dd1a6d9c1ebb6496f36bdce2967bea2971cc1c6330b1c31054c07f8d853858a46ae9370ff1d6ab755beb120a61b4774fba521baec6fe8a079862a0471cdc5080c0f073f7e3d33f0f25978d098f61bcb4905c776ce6c0562dfe08d8b9f17de4bc2048d962ad7f4baf132cd0152a904fea9530e7c1f52a85c0188d6ca38ff9b692b2a68204a6dfbfbec06f2d800b4444503bf2dde736be4108845c5a28909cdb42391b5a0207c157003b8dbd4e43996ab5017c5f21cf0d4d9b3145c0cb70fefa767b4689cb750fa7657c4a788b7759f86496998fd4b99b2ad1b2918bf330c1a81e8986eab031e9f86cd93b7d623c72e1a394f0862a193f21eeb858524477c3192fdf5b61ce9dd5b0bf3b3d7adbfa828f1a9ecd4dabf5e318fc40262f0dd204f28b934d1af7b0d7cbcc20be21f1c7e04fdf76104767892404b14965bf8d53003ca9ff0a8f15f5d9b2e152a662ddd8eaf7902854d8561ff088fe2e880a18a036d06c29997dddbfaba32ae4ed70b47413c2a037122d830d55bfde89ba645562cfa1d29f428da108d93562bd291748a728d1b3090b8a7f56293a3135f05d6876021e92aeede437dc7ab610e1e5af0a00c880887754d76b42b059f32f9159d25ffc56a993661d06a7973d190fd10c4ac998c8627b494444389c529e41982726f47135212b67" "8b69ff36ad29e225856ad2081bd393249f469648e6ea4445e0011adfe320b4eb5cff1d9332c1779edae5d5d66931015e793f730be8482b5f488ca6372edfc71abc4b8aeaecf8051bbcc848d736eb0aa0d7ee4cdb9eaddfdcd4200c3e2f58a97a162565409abc44b8e982fb883b619fa80c7c4f2318954767ea1c63c70124f4342118f2c798adaa7ab5f6ebed1b0a15e12f40978ca8e5f0972a47cf397746f9f482902abdda10ee7f4c610935070f888b5ef8eeb07933e1d6ecaba243fb475b4c788cf8b453638ac43b9f6eb74654835678b47d9437a14300a12553fdb10daff3690e0802dab80fbffc401422a465e10e6414975358249d68e4ad5a1f1c93e295bc10b8c5c11ed98c7ca5773014a2739c0592dfa30d8756be1f66e4fcc01beb2dd58d87800e71d136c12b8f73298cd37b1bb5758376b2111921fa9f7040e69d3620415ace96ebf29fc1a87e392a9e701f4075208a1a8fda7a59b28997c017da70c18d2bbb5c91db86d701cae85a5742842fafec723be9d93b4225619c7188f5bd23c900ef3863068785363ab861b58aab8e91b562b26f72a812e7892ca0bb6ed91086a2935ba82938b367b34f70cbe40c02a8cea92a78588f90cddcabd2738c9a18450f6d3a87c7f827a1773c2c7629452f64e1528258a8ba75bc53245c705246963369f1179a765bed41d*0", "654321"}, {"$dmg$2*20*0e2a3f19e5f9a89ef8371580fc08738b0dd02ee9*32*57b5e138dcba821a000000000000000000000000000000000000000000000000*48*4a33cb05d5fc441fe39477724556bf2a3445d2826dab91031374075f9b5cda25084769a7af11b2e678d79514be8e5f63*2726*8192*585b8129cddff9f9f5875d62364faf4dccb0625867ebf2cf7ebe08913e340c8bc5b62e4c4152b2274a19c3fb7d0f6ee32e7b6c502073785bbc213c28890b9910c878702b2e16ea0c0b0ed1462b831b1eb02a0a5ef586de3e1bb7b5f70b64e713f2bfe7f401ccf0a4430981b89d23afd47d05d1d28d64917ad2895af8264350f306b7a0b67029f6da75fc60137b99131d3678cb8c596295bef4eee92110d09c52cb30486709fff75b80753378918af4db98e69905245ec52c2c6ce7e71ea62b6e530269af23836fb40cbe12a1498d3d4e66ac26b04c31d4a1cc169909f51c0468edd44d051d79c361f547d7f4891195b96950ebff98f70b36106772abb775308cd6d42fae3a60d748330dadf7ca90bd474d05cdc678a0cf41a5f4461285ce0ef0a6df3a400d0116d1d1f17cd10be2c8f164ffbc3797dc022ffe52b69f0303526d3a17c113a56e67e54b4de121787dc62977af8bcde3f4fb596762ce31460a6f97d3d07874ad42f97ace146ada9b63f579a411fca985d85d64bd3262d1d2ab5721119b0cf8348abacf7aae2f57d3b667a5997d0fa448d3da4c51a6f59c6686a92a35ff4d6d951dc74acab9d956e9a942d9356291f56046c612ff09d1e10d8a0c60" "bb2a4d273b03962f5399ff455ef480018dff09125f6c343f28b13acdbe7f0309e64406d2c453d57d6e78f10caf01d8dd274e0ca6e4a82a208750de92640ef97f67dddf90b0c6de767f185b6bf17a119a735cc97075b93fceeda807d0ec20bb4ed923ed8855202d7d285b767727bb5db55241cd21cd5a7353cc872f0d4a00fa0a50608eeb4cfbda71109a4a2ae97f2c01a40c4968c32ff2c01f05ee768b2ab22f12697805396916d8fbc1b06eeb320d619b0e472b763e7a72acd949e17620f69839543c3852c83e5c3b1cbdcfcfe0e3507a4fecfaf3f27118b6738ae8e33801cb1a2b4168f8f614dea5e673878964d6e27a1d8d8aede3bcf366400cd0155cf502cbc04234a2a418638531ef13c48917328d2bc1736e85be9cd80cf0d99b98d0baf9dd9bb3f840fd15d74788043be9f791540248b5dea621487810371995e5fff578de770699ed8de1f5190cfcd5d47320594299af29efaf204e0a411670c6f4f60652422a7e25ded5fcf26c1d83f805938c1ae578bcab6ea5c679939e5fc6593248d6b8fd55c454d2c69e8c756982c01ff76b4911ab494d90df56d7743f4d8017423a045eb4215963317164bdbb473620e8a17507a9cf26749c6141ab7b94af974db92c875ecfc4ba4421a37da4454867ea3f7d8580185eed9ae3271050d039c25f7b72e18024f91edbf3e1bba71f697c8451302b1ba97c8463b3699754fabf472ac399bd3a783b51cc945051ba1b411ea8093278606efe2b34b3992033fb773fc42cef45fb0482992d5f867416faac3912b82" "eaa852935b54c1c05d2b5be854fa75ee754235ff1e84a53564070de838fbea7704fc249a98c7fd8a4d4ffdc06d5fc0ca39071fc5be83b0e37591e14ee76379f4c5ac64b21f016517ac44a12161543c43d40a8f92237c99de44ec220fdb502d82e96f01f020eef2752279a5aa3d3928a4cb594c5e145d016375e3d7a89d2bf12d4daf3886393c31615fef9e4201cc0208821e932e8b26df396e7c29f2c0b74c9f59ab79fa44b4f9c1156741e3da93df51bb23b756657187f1902f3d5c79aed88190b4a5f814ee1010b2fe82a3edd867457dbbf0598566d80261f83db810d058e785261635cfd1260c6b3b43081deedbf0b2a30d801618090d07340a6ad528b73c7d652efdc48fed161b0a0529d5d1e80fb0a63411d53e75e9ea9873d25a3bcb243faa406293f53a21b37e80023a302682943a30c8f1a5804a3700fb92092677602c39235246f359503cb79d2e084cccd2b40840acc7ac7b18b4e1a665e3833f5b4aefb40f0b36b70dd6b125ac9999d113fed15e5cdcb6ea6043036df3dec7f5638379971758e50f1453af5e48ecddf1d46e575cd2cde1b2091c1797df41f152fa77621f69169d42398312155caa88850800f9a8792c364021463467248e385bf45cd40c7869efcd6e9a24152bcfc8370ae901c7757a19627573a8832e5ea62c344fcd60230a3915561b6fd957750af61ced54ca1ff1a8edfe5ebbad51a79777ebd4e66c63a248687220e66d923c746f56f009f9d3f1f186d987c057af87f7a70a213c9c6eb93867983c3191ee956c8991275c5" "5b07b2ef0eccb8b0287414a154afaca67f218ca43924fffe6e6161690756e3d6a19a29ca972987f603727397e5f4fa19d0c3f1e74f026d35c028bb81450c7b5493a7d837e83504ae7369a49b2354c6c6219c79ad8cf9f5bda3765541d9691b84d19cf1fb9534f859b58257e80a7548c12ca2c0fa34b8b6248b30213be0eb60de5bd04621c163e4ab00d80adec931ee00288fb98e5eaa8f6ec83af863b8a3634f955b54aff779725479d80f2fa51d25e721b159a3dd814db70836a32b3a4e55c4def271a1918805f31fd3af464c01006560b36e1ce0a745d3bb121710083101d1ee469b971400d49483b6c4d858cee24614786f227f320fe6105d61fa8cf21136e9160770167e1b7451a3d9171f56bc436f097d73dd4c21c245efd72b63fe21d1600213ab4f2250e6c5a16cfd3823de93c9c56ced668faddb77d60f4d4d9a9a3b3cb9de0eb5694410fb760b7421cbf6e40ca4e8bfd4577fc3528e0162ea4c9aef069b3e4f199120a10209a6acb1eb6e39fbb23896860eb1366c6eef023c2bd63edcf73aac6094d25cf3c1cb0caf82b1010503fc8e09bc537e8e690f8bbc0ef492f848f77442cbf28bdb42aa8932109ccefbd2ad6563fd3d315cb79a0a5f04772105e8564e01c1e22f1c2ab98813979da0a08ee8812acc1c18097b8f1fd95424ec0d1b63a85e84257d382400c5f44f570382ae8128fc0935a5f7f518ae3808b79ae7aed4990edd9257ccc74dd19adcde363d4c7e5a4594e3d3ce88d308cbb48fe26edad968cd54cb715e460c7b421f6debe9c70" "3bd684a52b6b9571a7cde4568d7656e9bbfc5559d2c60e11054cba9eb54120bdf13c4c5103fc777033014404d6b4a65ea0a716f76a1433ecb904e9ac28b0bb8ab5c5b0216f62c18aa29b685cbe1c9172d51bdef81e7ead1ebb5d6c7cb078fd32cd63c72b163d2848de4c6dd59b35e853d6ec578b681af969941c16692c9010576f6f3777a24e87084c4b78a8502d083c137237a60705080aa90b2441e2f01ef9eef5b0f2b25b2b745136cb143405fe5c7ca013f88392428868bd9f06bbe41872c4cb1f98b16d74d064e66b0c435b52913b8153d47f52fd95ee73ab1f25f1533febb72e9dbf65d11a7568a17d2e8ea2616019297846551c6a3248b0a23e91ac1f38b21878a28f828e8aeb19893478aa2ff2f16833d1b69fbffe68b569afdd1980cdf6d8d4ff52d9e2708568db1a1b50847c8310e4d85dc73b59ee31a63bc894712f2d2214973c2741f4db4f3ca9a337e1f6c4ed3858370626b62e975a85e94b498f8c3c2073e6d6fbedb40e8a356e6d6c77c2b5e13ee52fafab4c8d369ce17a5c40deb98c98b60f433889e092d7da5e7e991b73c15127364d70a879b16ae774d65834fd0029c3a1239143b6398bb19ecda0328f39f39ade7a090b2c5c4e75e4922c50f858195c7fad64e4305d04dea5b85d4dd5a52ac4e60681c2337d3a2eb0b47745563f69352e1c17b08a3625f7ba530dc5a393238b6a2b92bebe6b94966537763ef66179b5c622ac068acfaf796ed4f4214d7fbb36eba5c9216cd5ee1d42132c459042063c71a1323eaacca0a94dc119145" "cef90f744d16226d7168dc9abf46551dbe25ce179e85bd44cf15374ee498f3f3f8fb5800c6cbfc427a834e3f7b3b6b6c7333c5ed46eb2a0c93e4eaaa6f95072221d7cc27d36ad53fd5fee1e65d91e37957a9d34901602d5f49799db3cb4e47e2c5bcfe36008ff0fbf166d9e541504aeed187251b80cc72804687f58b646ca3893e8c9e4340c9580a2008d268e07f7a0705bf062c6b1ebb3a62a4c961ad2f65ec9d44c67ad3a39117d2427d9c3d067df7c089bbc905b319b30d61d099265de1ff42a97540bd08a1ec79a4cef4f692bbe54ca6f95d6ecb82d3ad2316d6cfaf9a66a8b5e5f00847b55509cdd344ccc3fc640da87be6cd4ad8ab3e510b31831d3151b2aea6675c97767076360bcfe1b317c3786dca2e4b3e90818064abb319cca7bae051390063bc6a0a0a133187a60a6eb82162a5061fba5fe17f157e9e589ad83d2f1760f4055879445b0934c954622476c29c9c577c053c723786c8d25829db7a896c66eec594a6b798ed278a824550795b0904e154fc06ce8783a773a8919b624dab70f92000b832475b77db27d0b5bbc5578765adaeac6f61166094fe11603f37a41fa047156f2e57d80a47d110901d96e33b5247a587552e37b7a0712cec420a5680ee8e5550ce5d0996b235b8898d67126415184bc9a0ec172d9f78f595182400c010d905fa73b5a6fef2f722b7f9dc51b9d21d85ec554c9f32612fcdd89577c47b3cb5203132e76ed5a39af7e9cfa2c92369464e14f8333fc29fe7a662b9373011f0d4627c9ba7b0ab0c050d0e67c625c" "dc83a0e244dcfc7f5b58ceb0d1ca2f16349ad8b16a48dbbd63da41eb5d0732a13ce5a7ee7c9088739eec6d63e0a410fb53f83cc75915c0b6353a75fd2d219986ee35bd3991161fd054f0d39c2c9da696ec2968e801cfe726cd512ddcb6cc28af65b1f8e542d1ad6a6d76dd1582dda6af4f6c9363ad7117e0ea0102cffc1ba0d94dd8abdb5ac37ef9b444387bfac2b811479086e550ce3452f77461febec72ce35d06ec70b94779b794dab1a3fba727f364bd0a65e7255da20d77ac6b85ffee926a1c3c635366a4d5c8233b798e565752103c66d5e7f18f315f7fe2641dec5944e51e373f19fbe1b34dd00f4604a4f741a5d4a8c720bf4e51511fb3316951ea63c3129c4f6242a9014a78a050e633ea5bf85960fe340c54043d9bffb969f8abe458a8c9dd02e9416e0f3504a5bdbf6cd0b4013b4b548bbe59a23149a24296e0c326d69affa61a878baff7525bea12a4bacaee6c216de31e22e218a3bffc996eb7a3b8570caa06193b56452ab7f3430c758c3b447db98c7a1faeafffa497d938d9b952e3ab3f6774333a02742375e7e1dc39cee15313d69e8cad1a251274ecf48f273cb79c58aac657adc8d77f7cd1755ad9a2fd43b69cad9d2f8bd77695dac3c43d2469e4ab34e26c7debaf33eb2ca6cb7fd0a963a37b7dfd5304b9d5f0bc1ae0940bb40375001e9920d4956f4011f4f1263c3b7cb38afa1d8f7c8c188bd226ac3e23867f3989d76a402a9476756e03c6c3bc4e3ce78095125ee11e7b47347bab7a638b0088a3b18f23abae9ab2f94650a30e2" "9abdbba8ae9d9d03cf5b12ab23f5a6464547bb7078b91f533ea06541941483359a8562e709608e0c5d1da2c7206c5af49be0df87a3244903293bbcc121fd2e20ff909a90ed836f1822ee2b40530084f02bd9c42b350a4703851d197d9c465485112f1bbb21aff46daef510159a1f354e5fb7b11508a3ffe12577b40d3bc16631f8a79191745fe828303cbe5b6d9578cd80f736971e1f108f02039e0bbcc12b42e8860cea15cc18505c3e4242ef481930f3e2c4b64ccedb5b4d9837461efc7c48f8b1a6dae1041e696b99fd8c9108ac1fa9d975b4d5a740c4e5bab92004b7c91cb64e80a67aff2596c919b73d88943538e0996a775b88857187e9f97828f8661f89252cd0c5577b27151b5b0021f17937a9abbfd8ac3946fec79a4063af00802d54eb08461f951cdbcec92f593eeba457f381a7a98f313ba28d21d2574fc751449e1c3b497e09b90f8e1840e7a56159915d98b36647dcc15e1b335102074741f1dba46f0df9e7114ca29d02a7e4581fc45c48e6b31cb291760a05774fdfdc0448abe313ca496bd2d1f011f4706072d69eb0207b0289f5dbe4d1f73355b206ab3d5c777d1d9dd65281a0dcdf598569109e8fc3b56af94e4340929457d2c45d9a9bbc37741dc031136a11955a465e0baea8c11c06ae9321dedadc498570efc3191e67354f0cae6a763e84aaf74597dc1d329c81231546df2fd965d2ce0fa2026e0ca896d48bf8cff97e9e1fc5e035a13a1dce07810a9e87c21988d7e9bf19dd68379f346d232f83d776c36791ed1ede88f8bdc1b" "62e3e7857fddb802ef7771be6a2428b7bb7e419cd95042d7de60359365efec7397b4d7fd32a4d7e8b924930606e7adc49333809812635939f79a20eae6066fc494ad27aa5be989663ed12f9f1c82d092b7a4af546f6dd33ab862fe21cc45c2c7c58842360070e206ac341c26ef2f92cc7629d873a219ea1177ac6354e7192f4c3f3aedb580c322e1644c92b9882a96addd01a35371c07b6cd3d7e4e38d089559ee41bdaeaf81650dc263a69fffa6d2713d3a8ffcadde7601cd2a87c23187463d3f3305a36ea01743d2cd846cc5ac96c89241c86b3c38ab97f1ab7b9685e68260fc116b7d02db8cff929b871dc02379d203aea4160c6302a7bad3379ce2b77effb3f9eb37d7826181ac8f606e67026fac0f43e39c72a04a6278f89d16a6c14c6d6e3dab80e9089a83c7a370726fffd0a2e6a9a6a950fad60982eb28b638ebf2315932911b91e465f076e97aacad4c6e19ec46a8ba9e7a19fca03b7796cd6d8efe6d2fbbb96b3fd3f85d4622fef029819efb34abc28143faf10ba4879fa69d493908649f03853ea84bf7d5bb21c6c541edf0c0aa96347b4102cde3c27a58ba0788ac02cdba243a3f52e0ce4d682d41d432e632635cdce5be1542b6b6a8708e144a6acf80ab3ff5842ca2db90e9d75401cfc99746a0919ed81983d2171b4093b1b07e5e5c45992f657c892e91c16cc6017a66af6466ade21f4b378a6fea6a8e4bf000ee986bbc0a170467548e7f6e797381ee89fc431f7aa562110555dfa5c275523c202744541d51701d70a8f3006ddbdfa5f72" "9563bc0234d0b2759efb747633221706cfe73d47743ce6e6077943ef6d0801729e1301ff9bbf37f50667909f1cdc70f95040c841106ce566de5dded0fa485ea539978a88ca8618e566e9da4f2e215d544ee62accbe75dc17ea26962d78bcad516e6bff3152642e346444db494a909478bf6d80aec53f3ffb3311c6283711eb96fdbdd8e6d94c71cbfb9d7ddc7f092df5092199dfd822b98e21239bb8dd17f0c101909bd38d309bb5456232f5a1b731990a4cce847394fc40b859a8d89c7c02c388e7d6ad42bcf4818de33d696ed6d6ace4c23d51fc9d7d82d0602dbea094aa2db51d9aa8ef5c1f4803e40f6f5fae44da3c3c6ce9b1003d95300871353762062d1ad49a31cae73d569bf07d147a0c8d212e60b1be486df08bc353a2e3ca7337b83e3db43be03147114c229fd32fc2eea5f64d5d5d9848709ad7335dab3909c1232d93e76eac218e7e0497ad5b7b1ca8d9ad5447879b20dd370398eb8ce4bc6805064ccdaa6d8ed1e98e259b7654a75848705dbf2c3804b455a9e3dd2890f8d74f0e968dd050ee81af2f98fdfbe831c16dae6589b9b2a16965713b8fa52e5d2d4df504411ad9c14929e560a5f7e74e98d72f71223a5eee41a40d85c177183c510881950bebd3f0ac907fbc5a4efe70a60da6bdfb6870d7fcefe04fdfffd1492c5033ec79b8de002c41895ea6e84393db391b9692983c84148928ba0fae6b2ee3aed2289a9e053d47340b5faa4870fa632c1b81c516a58a049728f941f57bc34ad53c236d33dc2ab6a196e896968d0a2bf651889" "825b8f358ef4874b0e75e39331e513c506b29a61495e78722bb25475ec2ddcda0816ff634062a54721c9fb425ff286336e7036928cfac29216dd0eacd3e5328b6979f831dccf403e87ccfc4346f5743d972d5047f6055bd86c98b8fb720a3cc3f459750ddb870a845c1ff4bc3499b1c92b6e591eca7e94f1f8d2fa3c57fc97b573a738f7f55e3b6cc975a813ffb7f897930b8de8382c5883ebffba463ce72b0c50c721db403cef01d5be035730ac3c6f6a3f78681218656f397966753c04507e08a09f7176c3e37de40b9c7faaef1b675fd083c9cced4261dbd4a289f6aa0ba04964e1a6d328ef05786933d67d6da009aaac7d4a8ca31df5a15e3874eb9b288edf7d794e1abdf9e411c5bb87f7fb27f76bd62968bba4d53844e76487818ddd38620854debdced8930ead6b46f3bce6009683d3ffedfff0be83cd8727bbcbf428c761b79a3c06a7c2de7b99394030b51eeb954cfa3fa307a37881a8dcbcedf9549e2600b72f3665946d14071d9d22894020346466bfd2062e092f21e38e920609df77e3b8ec024334c9708a415d3408e22645f06cd6d805e8da2f4005000aed542aa995816bbbf32597d9025daea32fd07733e080188d6c5c7af4ce8b7bb25d7c""50e9f3cec80e86a8f9f6d4e78a40ee20fc3c83bbbd07020f0092cdac8ffc2d52c24166d78da8ec32ebc49f815264c5ab29ab84f3b44ba75c06b80aba2966a617830efb08fd3fdda831fedeb67b7d593c661538d422e1a9fe378acf51b0f2a07f34d84624e0b90af172e5976a237a7dea10f" "a7cbfd3203d1b4985a1af6c2d2300136226b2edf519fdd2b7b5e3fb5b0c70f2e3160305fe9dd0c09b98d522666e5100532f516bfe24d12d46b5decb4d4cbdd5fe9cd647006c1c7eba14a56262fa7a3b7b6d7b22032c1d444fe023d66b7f51004c6176f4c198a2998beab66ca70e1343187ae697e9fbfa6ca6443d617552e6b7bb73c59613ce0a7cab58545bb40636f54ccdf89c507098680f4486f821b2fb2c7baa182686b0b6f893fc9575df701196b14255b547b925387cacd5f4a762b1d4b7f713e7aebe4f75ed648b8666e60a4f8d92f752451d704e19aa102bb3dda418c80f3b4f395965ec36fd9474088ac213b38220df73c8159401ff87751bbe392e0aab031de59691a0a77ba2ab7cfbf4daf09fa4d7d61dc5b456dfdbf7a60eab671ed1f1a67fd58bceb34e981a2dc3c3bb8a7a14fc8443b47a123662d96b4df2c584856ba257f39749d51caa70b147d50c68d4aafe51ee195f1ccb99b7015de726b5f0e85bf37617138d2b24d1cbe985d8d1cbb40a52e4c57e20c799e2f5ffc0557be9d3e2bc5b99dde628c4dffd5c8704c78689e967bc870c0fec80c3c69a2453b052a46e142309fb21bcbdad7c6c5a67df409bfb9899ec58ff0973e1813f47ec6428e35a932c117b5dc70a8f5b1a9fa402d59fa45714b4bd79bc214d488939f997add26d13c147aa4d4239d8aa0e3c70994eb4a8debb7cf292b3ff59bc36f97a9acad107fcc556c24a309c4a15dab16a47a71f31324dcc8183fdaabe1fbd1cb3808c1c35c311ea51188759d4e1533d39a9547f" "04054e2ef994c97e213669f08db02702dd8b54154e7376f256dedc67fcd3dc48f5e0be91f1f88766415d203bb4bb11c4a0f6d0888e0c98d3b8519aab741b20ced0e02a5638e40ad2ffc301318a77e57787995acea46eb8ff7edb535036c3b3781d63a02bce56499cd03ae75ba6610ef27124da36dce85ad406c82e72a0319dcd6e05dbc66523be5015036de859af45be32c664c18ad712bf09d361769be3e568d5f51c943ec2c9f74077cb9f5757de92c643a2963d69c2cc3f010908e661f3a6ce202d50d72a436319bb2337ab1babd4f2cf1bffc3de25a09dfc5cffb31c7080c5473b4ff673fdae11e64cd492a784a106beb65bfc01f9b7b97384d877d9f4440b7434240e98656703edd66279f1bd5b7cfacc8a6b511f1db9060e813f2e37a8be5de25087b0520e7729a873e125d7cba84b93cdd333e8756630d9dc9e1815832c8dba1a3c51776948b184a916ae44694664192af75a616387f47319bcd5da1d94fce857c8e76c3438ae5c7c810310058558e01b01cfb5676f1a5a5d027bcd1ec62428a82b78fdc9dfe69ae9c0301f6f2dbf1475e1cd1804d05cb04583ae62efe63a6f1d20d5c5675f4822ddb8f6f6af3d639f56839b1993dc40223341c04d829849dea53aba7d0d2a2db0a89881a2ecee4f66698aef5ebdbb3c6d65ff03cc1a00b714112f0b111e7a97ded2abde97767e0ea6e19a04f96d708d419f457022ac21715ca86305b8d5e4f45d6382c7ce8d87a8f0f2f1a18134deb9a33b334bc04697479c4f438f5e58a62a1b22b49580fd46eb4" "946d07c505e9c778dc56524880e8fb565487da236bb1340d92dbe21516f40a05dc3cec3fa4a56bc93ce57e7be50ef2fb38c94790acb9702dbf2ed30d6b5cc1e0173ed4c19e2822e79e711a523ecdeb6742d90353c904876e66b30fba8975d35418f0ef3fc8e5621d8d243973addf756d1e4621618fcae42af188a22f47f0f8bd0e821c16c8ca2a15e35d855ccc5c9660ebd2fe8966e6b86326905267b80358328483d0045fc63af4edda4020ecba5853f005b9058dbb81092cc12ebb3205ade902cef207f783a3921225f3a8a108eccf02cc303b11a2a7db60c897f31480db900fb1a6e1ccd1ba0aa61214037e50d8eb1ac777fc4a467ff9b9ffcaf34fe721300067d33a25f9acd43888ba09cbd26e8b269fe84065b5c44fdf734545fe21689b838eec4a00860f654df33f87d0f115a6fc1ba4f0de641f06eb8a19d2e75aad7dddc6f00c8d598015541fc8bd22540b9bd3babbbf3e41212d35cfef1236edfa5746b733de738c60901b87bfc3a4c7d49eb16e7fbb7ab93083cab5c225f79ef03db6d490169b5ecd2791fef9045e017f9dac41dbaf841f050729c6adf789b8008a82e61c80cc4d06207dbfd6b2a9cdfb67ac26280fa9ecc298dac1878fac6188066b9d8637f772136edaa7f64fa491b0bb4775656f5f1a3135686205b8217a590c088cf448892e134a29ef4cc61bd76886663afb18ad504b204ea52ef61782ce9ba44fbf2e18e1d59302a1b69717375be70a295517b069d26e161c91ec3a1a782e38efa6ac867dbe488cfddcf8c200135b059a0" "da4b4dbadda9b742b906266a879da79da144eba455fa7cc5062d326996acdddec0eba8666b0e1e6c7116a1e5f04f1e94e5d85b77b2d35deb45402a589d46734810ba3a74414eb53181f75c2f0bad61d9f4aaeb94f30a1051f5ba2b2b30f1445bfe889da81e550449d863cd5af77d49d344b63666df8206bc04686ebdaee954da5f14692bc2bf1b4b01cd6b2bfad93dcc7e5c08a5059d047f6ffe96a17c828244b234a2abf28674b15d14b735956c0a9bd438183666d6926912358edea95ac5b1b6a53784f47819a3cfd4ddb9af8e74f30e06c30e218edda9eb8207dc7cd931d6e926af59f8238225dd037b47c7a4c8af558d981a7c9a7dbae3fb66345874b27cb229f1c82b841cac0cad018e8f75d0731d5a8ea0c4d530f575de7d39d77fffde64c9d1fd87b9af3759d8a275d5a1d95f1d2d0bee007544f5c39ecf4013c80cd89821f79af3979f23dfff87d093b85b892b93bec546c5eccabf41d04c65bb571543f2312ed5e3596ec5d6bf8e57e9854164d34b48ca0ca4044a526e038332348eb801a6ff342bf25750abbcfc27e7cb5e7b026db3743b210b91d1fb688c8f16d4e40203d39272f22b5bd0f796f0fa09c90*1*b48bda800b2b3665adca330cfc990283a604b08074521335437c0ed7f2a997069c88d620b638ee988edb3f6f32be1ccd01ffb14b66b2c213d31aad92b25f66f226f2793b5e554475ce8c1a7f9541ce66c594379303ce730fd77a6591c97f5bdc400ba7e8cbd496c188c2112208778ff9699674b117631d8f385ebe45ed91dd60a" "4a657ca39c11c135e426c03ce2219392f55c635c1736f31b1a7a892273b6d9e2867864606aa0244b82c8be1748123f0b8478baa9402521583f24ac86c11801fe340e64628e8840aee6a093b1bf25aa05c74d1c1dd8ec48321b34a53bf78347a59fa9ee394a60b845cfd4c2f5bc53541065f1c5a0d3953d9808b26ee51d17dc026ea97a2ffae213bb9818f3c4009480ac0d1774e6237546204339db20ab366a805ba8c34304070959a16639006ced72bc3ba6430ef7e5a10e9a969ee233efc23b2d99bd8d49c3615f0da372cb98e077829f07e112a5bf4357a3cdee0268bbee69d31fea1ac66564d4b1c7c303f9b41e2b23b3c7825d1ef93ae1ca1aed1607177bf92cdce38fc68325a652efd3791e922a196eba24e9816c52afeb1d84577b8a22125c1d90beb57cacff4b2a637061d69bf7f1f006d102ca2acb8471909689d36196ec300691ddb9369868f3fd577e463d8b74c7a8e95fe2fd2954136f9650f7301d4a91d9c41f647675d37c1663d4b5c50cfb175facf30598a9be1ecc2f33fd4ec7e1ecc7dffbb1180a5b224b4eb6d0e0af4ecad6cbcb2a26cb3365a723caa2eacf9404083a427d5e7e62e967875e53a8eaf4f5873627717ce802b6b66d627f3390b50c0c950dac739ab46fad66920de3fb8edb0ad0a3c93e7b3beeb90a26a1553aecf4d1f3b17b7f852cf5441bd626012ca14d8e4aa2c43ef6a272f9f6990672b2ead99d839617069117aa10f840c379fc62de5ebf5c82ed59a5a1f76b0fec724ea809411709d88fd2f986c35edf9a562e3fd" "bb13577e2ac78bb854768ab38850daf931c1b8cc3e6f3c244fb339d288348f88f792954e90b68d664b7f941b634aec4b2d54995ba08b999d32d007e85e7e0df4dc6022b0d6d7a23ac5bcbfb2dd6cdc300fd0e4c9b4403a53a67a1c8979774833ba4b8f338b1932424b8654e02ff039967bb43c3f0661bf22f638a4caef57d50acce63e472f1316fdb93e75218d630d958c1aef855a9a7bc54122a26ff94d78e74d48aff82a485f584b8acbea147666712d35a7167dc5f92ef4059e42c28ba66fbdccaafe71efc630b8ce7fd840bd2802c2d69a4b09a11cf17c9321d9ccfb1623bfaa89786df732b405e2cf118611e9ff153dd2db2df1953fdd888f023e74e23f3a5595b81456b6ffb33e91d65f08fc8eab545412b18be47d14ab77827073286a735187bed1b12fbed879969f7d06c53041a6bd79bf6c5260342480cdb50cb617c2b4111da501ea98f368320094c5353a36df520824ec52dd15e818bec43d80b537c0d809845645429ea4f7635528cb7b8149924053a76d3c05b0c31e5970eaa014708c64c902be5272513111a73e682ed9f473c87b964a4957934424bf957d1e86c6c90a967a8643eec2b65f08d4c91252cb9663a4e5aa4ad9180166ac633c0e5f5170656373489126e6be09e9e8bd6f226f0833bd392884dfce749d68ad51b1f0e0ef5fc5a8876e54558e191abcfc4632409547a8a5c46c2b546db07ba324b4d327ebe86f87dac27b64d6e0c8250019c1114a4f8fa39523dc3f5d597aa33af245ecca15ea8cbef7604eca5ed804ac4f57c12" "6e335763925b88128b7289566270a5d7d1602481647f74d71bc1eafd0913851bcf07047dfef51b41fc02215d136885e647001f9f47546e9ea6ba0beab1d8a276cf9b85d780c05d4031f55d35d54c56f7fceeae9d62c58e7e928e591c2d6b1d14391f829f3e30bda6132bc513227cfad357be2c6f045bad7be72d01ceccd059327a72ce044edd534a5ddf71831bf07ebe84806feb621a5b8d71f4a608878e5e5daf3f8b4b3eda75f74f03d1ae5aebd029f037f66253f542aa06cd6c29ac5ed27ecdc7641fb6d54c98e71491772944303d3b6be683ac44b7bda5d49209133ff564cee31912b8e024cf628e0719522b11eff2e32874818f9a0ebde427657558a72943d6eb25c4b9d523336f37453af157035a3bc5ffd13847a928450d4e01f2ce7ca51d456939363c3e5a69b0d25311682c7b266cf86d12b63dcd322be77594c7f929a77467566a8d86a7d2b583b95f76626244738251fa762e0b2825c7668d6dde8ac5579c1a06318e5c5a6b2b1bc93bce6cd4853c50b6662482549290b15500722e3d6772c7541e3c864291dcbed84496dcc9ff4dddc974aa8b17b7ccea56c856f24ee2277a391c3c0c2c5584111ed24fe64e478e3c4d22380b8183222570fa3c70d29230aa21fd21808baacfd41e2430fed7c3316235e6b4c2c3331ee36d9e5c94ddbd73b351897cab7ede8a7c417c753d8023cf46694acbc9aa6ca556da7de108005330704cf54b1ec7bf7df02e36cd736237316b3523bca0a53a2472e68d30d95b1eb49282b27530bc69cd154b7a4dce75d" "a3efc65c12ce45de7a63632d340fc61a1789129df1554813a15c9a6ad101c07363ba8d967b70ae1767f8927440678bab989dbe994922779c3c277055a35bf12d6909caba8a4b6bec7f49dd32426d858e53164c8db77bd1b9321b31e6c1ad1e92596bec4ad39d5b6944c7585a5ad0c6f83f64727a7f6397f784d865ba3b9c85343f3a2828a0e71d75f19036ea0f17e265750d6a01513be2bee0bd0a837996971b87305dafda12679bc118a1df188888396e10074254e4aeecb6801e00e8f3ade2889b65aba9e29d2d146001740116c893df1899175dbbf88ec175216df3d93a88fb6957adf64a3849e26194edb91188c0373fdf9be85a520c173817ccac3e4e9c88ce0bd9448be3f6cf3eb92b9337ecf2e63db5887e1113ee31529c373e83ec02012ddaa8812fa5c6b8be8febe29d0c286fe03832aee79018fdbaedd8bec03345c05faa1231ad148bf4531679738a537ec490bdcf78a0d9dd13e6988e360273c388b91006a66176c93caf3594cb098d5f4287a37d79b636eb566eaeb73ef76a4a480fad73caad3378d17a9395bf71c6c43f643b04b4f1773939329470e51053467b67ed8ac0807b8806d26d16f6f4fc15b3f3cc197d24ea26418cf970a5e7009bd871aff96be823fd80efe1adcaa882c168692b53bdb47effc666a1768d04d0d8bf199d36604e82b72fcce53e86d063c347aeecc79a846f8e12cdec679b857f85a75fe59a1338a411950459443b3fec6511dcc78d5bb6dc60accd6013400c0ef71f19d7713b37777a75e96d0d341d416c9cd94" "7e3c442f6ddb31daec66bd96ca31b01d2dfb99d312a651ba5ec1765354de39d7aa4bb096ce7edbd93829d8ee2b7e3ff364f5d87f653a541f033db6c3266a03046f8612ad8d56a1c78912c9774c86a8d7e2eaa7f3bb1033470789ac2c32bd3c2ba1269bb01b176b167688f8fbe1f6094c3e2736bdc1cb1733364011681be98047cdad7d998241e121e6508cfd665c42b30f22bc442f940b5c7d93659f59abcb17aab1f28a02d0b59239f148211c525dd209cb932c54f24fa8a9541f0eab28b4c8df80845058e71e5447959bfc7f7d28e15542523410bc162f566875ed6d9d4fba519000b8c5d90f894f2bc74dc8307e26d4e0a9b418487d7470fbd64e97e660a3038a10a26a80e7cca09a3280ce3c87d07befd6f65127096d6075a18f30906828cee1f8b968dd3247210041078cf6d28f05977e5c172a9ecd83167873881e0ffcc56615ad0d64b0189ed8d559e43cccb1e2f8805df7156cb11f5df9dfbc067fce9fb3ee3230e28edfcf98741b9883f9f0f42913cc2be1036a0590107c69a9fadd4c9fc39df872f0db664ea7172fd72e0ad756be95417487d0c2bb38061c52124dcb2545f15a5bfd39d950b5878a067945733d8b1dc37cb85dd9393c98b0751c83d8e848fd1bd3ad243f6a8af7a8cb8cda7e1dc05324fa3932423fea0428131646534e74398f1604146da26a615045ee49ae2df3c8fcd16da64672845a946de4c26c1417c534a2b62a408a8c30c2e4f73ee44571259b628249c9e3f65e7b8d22002a170e7e53dc7c4cdc0073491db2cd6de20cd" "df07501ff08378ac1cfe3ef479491f3fc475f8aa1fb188706c264e276da3e0399e2bc17cffd6ad0ff94d2d3b9a3b46e8c1472c41fc1c002daa76634f94b3bdf8560cb3241352c6f1be21fee70cd54a1d96e31d71ef99589b93e7ca8d026abcb4a4fbfc8c0f57d59a6d9e760f02fd0a569702da7f59da495c2dd7f92d60fb3220cd7932a032d40ed29deaa5fe971128c6503eb9d1029a23ed6dc4fd5e8c5cf0347841424d60a5a07a9781d08c85222cf7241d199609762488332a6eafbc08cec42c876da9bd3fa287bca12f71b6e33c4453afb970b425a45b9baa9aa69ebb3907e06e6610f100b00c86752b2c106c2e0b71963f1933d315ceef89132c7744149db0c28f62b3d7b43d570d1f5c40bf4b7470b3b8de30b0d756b8326542743f2fa5cf3eff226b6a658ecbe44dc9a0e59f073f999d8c3340ba30ecff6f2fa4f3815f0d4c665b5109ce8984971e5cbec806888c2acdf73d2a330de9e5133787aa4950d08759f4cfcb55ec8efb43d421cf3a9f601a096677eb95f61e352a9adae7c0b971fb455f170c7ed95329b699d6e93f024786507e2e0acbeffb452c26d8c041cb88316d09a08af54ec48451f9bb685a23910e97ac82bb41f19f6b42fa10cfb75f9fa8edd61653c14a27b51544e3fb28009aab76d060135df2d097fd4c2f2e63dba1192c648215fdd1dace4824d71e038e23184ede7f61baefd747aed93b9807d0b3b7b4f7cb9eb171d1ba241b19cf1c74781eaaaca99a458253777522dedcf3d1db6bd4eec4459e59ad635904201b5d91c77bb" "b6e91f00f5a6f29794b35afde3dcd850f08ac5da097549ded05159567e9f7a023e08e49253766c0e151852714987201e90df675368ee638a947b7e6dc20bedf60656971170afe2d453662685dc1ceef8436ca8071680d0346239b41a6825839e9d5af12f9574d51b4672c5fa7f84bac497c8ba5fad2c10fbffe5ee713090b903d7723cd28c1b189a47c6a9fe9a88d0881dd60d1970c6e8a6d812bbd089c10841e5ced1417bef41f400118fa990d157bca93267d407989de017bd48f0231d43b9487526072e2755461274b3f5bf27847dda36c652a2b1fdd3815fd4ab93863426b31ecd1e6a9094dd2ed0190f8138e650dd2174fcc6b6ab1b8b91cc8020f2dcbb14855e7dd0bc1b5a01f55f81c0476daf1684cc4e72a68327120730ae92c45ab4e447c4ee900d61f79681667eec61343e4eebdd65c5b38a1ba5e3478f4d2f59d184ec39aca445a0f6edaa6840f04bfc19acf23db4507609cbdb44514b36aa5ef4ffe46577b711d1028970916eae919f1b4913d5894a24117cd7cc1aa8965840865554ce663af470455c0f756c795fb29eec04b727b12f7f3796f572ca2ec1e8771a88f68999e16b2acb235a7d9146f85f2be5a034babc3bdde750eb7895396d4777c144aee517a07310dcc8c9ce0ead93abb7f1eb4e34ed5036361d682c97eac1ad7c8158035e40a713f0f2e6f6e677d4b11ecc97e101a5b48420435dd218846ae622b416faeba7e0003bbbece71c2aa046715173b408c8ab2888b0b5dc4c34683f83ba9a83795f86122e6d80597d3a952a44f" "5a1edb6f294a0ceebefc3cb54db814cf91fe450ed4c71d0b4091a1fc7474", "goodjob"}, {NULL} }; #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 void create_clobj(size_t gws, struct fmt_main *self) { insize = sizeof(dmg_password) * gws; outsize = sizeof(dmg_hash) * gws; settingsize = sizeof(dmg_salt); cracked_size = sizeof(*cracked) * gws; inbuffer = mem_calloc(1, insize); outbuffer = mem_alloc(outsize); cracked = mem_calloc(1, 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) { if (cracked) { 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) { if (autotuned) { release_clobj(); HANDLE_CLERROR(clReleaseKernel(crypt_kernel), "Release kernel"); HANDLE_CLERROR(clReleaseProgram(program[gpu_id]), "Release Program"); autotuned--; } } static void init(struct fmt_main *_self) { self = _self; opencl_prepare_dev(gpu_id); } static void reset(struct db_main *db) { if (!autotuned) { 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(dmg_password), 0, db); // 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; char *p; int headerver; int res; if (strncmp(ciphertext, "$dmg$", 5) != 0) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 5; /* skip over "$dmg$" marker */ if ((p = strtokm(ctcopy, "*")) == NULL) goto err; headerver = atoi(p); if (headerver == 2) { if ((p = strtokm(NULL, "*")) == NULL) /* salt len */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* ivlen */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (atoi(p) > 32) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* iv */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* encrypted_keyblob_size */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 128) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* encrypted keyblob */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* chunk number */ goto err; if ((p = strtokm(NULL, "*")) == NULL) /* data_size */ goto err; if(!isdec(p)) goto err; res = atoi(p); if ((p = strtokm(NULL, "*")) == NULL) /* chunk */ goto err; if (hexlenl(p) != res*2) goto err; if (res > 8192) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* scp */ goto err; if(!isdec(p)) goto err; res = atoi(p); /* FIXME: which values are allowed here? */ if (res == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* zchunk */ goto err; if (strlen(p) != 4096 * 2) goto err; } } else if (headerver == 1) { if ((p = strtokm(NULL, "*")) == NULL) /* salt len */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 20) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* salt */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* len_wrapped_aes_key */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 296) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* wrapped_aes_key */ goto err; if (hexlenl(p) != res*2) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* len_hmac_sha1_key */ goto err; if(!isdec(p)) goto err; res = atoi(p); if (res > 300) goto err; if ((p = strtokm(NULL, "*")) == NULL) /* hmac_sha1_key */ goto err; if (strlen(p) / 2 != res) goto err; } else 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 += 5; p = strtokm(ctcopy, "*"); cs.headerver = atoi(p); if (cs.headerver == 2) { p = strtokm(NULL, "*"); cs.saltlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.ivlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.ivlen; i++) cs.iv[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.encrypted_keyblob_size = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.encrypted_keyblob_size; i++) cs.encrypted_keyblob[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.cno = atoi(p); p = strtokm(NULL, "*"); cs.data_size = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.data_size; i++) cs.chunk[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.scp = atoi(p); if (cs.scp == 1) { p = strtokm(NULL, "*"); for (i = 0; i < 4096; i++) cs.zchunk[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; } if ((p = strtokm(NULL, "*"))) cs.iterations = atoi(p); else cs.iterations = 1000; } else { p = strtokm(NULL, "*"); cs.saltlen = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.saltlen; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.len_wrapped_aes_key = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.len_wrapped_aes_key; i++) cs.wrapped_aes_key[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "*"); cs.len_hmac_sha1_key = atoi(p); p = strtokm(NULL, "*"); for (i = 0; i < cs.len_hmac_sha1_key; i++) cs.wrapped_hmac_sha1_key[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; if ((p = strtokm(NULL, "*"))) cs.iterations = atoi(p); else cs.iterations = 1000; } if (cs.iterations == 0) cs.iterations = 1000; 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, 20); currentsalt.length = 20; currentsalt.outlen = 32; currentsalt.iterations = cur_salt->iterations; currentsalt.skip_bytes = 0; HANDLE_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_setting, CL_FALSE, 0, settingsize, &currentsalt, 0, NULL, NULL), "Copy setting 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 apple_des3_ede_unwrap_key1(const unsigned char *wrapped_key, const int wrapped_key_len, const unsigned char *decryptKey) { DES_key_schedule ks1, ks2, ks3; unsigned char TEMP1[sizeof(cur_salt->wrapped_hmac_sha1_key)]; unsigned char TEMP2[sizeof(cur_salt->wrapped_hmac_sha1_key)]; unsigned char IV[8] = { 0x4a, 0xdd, 0xa2, 0x2c, 0x79, 0xe8, 0x21, 0x05 }; int outlen, i; DES_set_key((DES_cblock*)(decryptKey + 0), &ks1); DES_set_key((DES_cblock*)(decryptKey + 8), &ks2); DES_set_key((DES_cblock*)(decryptKey + 16), &ks3); DES_ede3_cbc_encrypt(wrapped_key, TEMP1, wrapped_key_len, &ks1, &ks2, &ks3, (DES_cblock*)IV, DES_DECRYPT); outlen = check_pkcs_pad(TEMP1, wrapped_key_len, 8); if (outlen < 0) return 0; for (i = 0; i < outlen; i++) TEMP2[i] = TEMP1[outlen - i - 1]; outlen -= 8; DES_ede3_cbc_encrypt(TEMP2 + 8, TEMP1, outlen, &ks1, &ks2, &ks3, (DES_cblock*)TEMP2, DES_DECRYPT); outlen = check_pkcs_pad(TEMP1, outlen, 8); if (outlen < 0) return 0; return 1; } static int hash_plugin_check_hash(unsigned char *derived_key) { unsigned char hmacsha1_key_[20]; unsigned char aes_key_[32]; int ret = 0; if (cur_salt->headerver == 1) { if (apple_des3_ede_unwrap_key1(cur_salt->wrapped_aes_key, cur_salt->len_wrapped_aes_key, derived_key) && apple_des3_ede_unwrap_key1(cur_salt->wrapped_hmac_sha1_key, cur_salt->len_hmac_sha1_key, derived_key)) { return 1; } } else { DES_key_schedule ks1, ks2, ks3; unsigned char TEMP1[sizeof(cur_salt->wrapped_hmac_sha1_key)]; AES_KEY aes_decrypt_key; unsigned char outbuf[8192 + 1]; unsigned char outbuf2[4096 + 1]; unsigned char iv[20]; #ifdef DMG_DEBUG unsigned char *r; #endif const char nulls[8] = { 0 }; DES_set_key((DES_cblock*)(derived_key + 0), &ks1); DES_set_key((DES_cblock*)(derived_key + 8), &ks2); DES_set_key((DES_cblock*)(derived_key + 16), &ks3); memcpy(iv, cur_salt->iv, 8); DES_ede3_cbc_encrypt(cur_salt->encrypted_keyblob, TEMP1, cur_salt->encrypted_keyblob_size, &ks1, &ks2, &ks3, (DES_cblock*)iv, DES_DECRYPT); memcpy(aes_key_, TEMP1, 32); memcpy(hmacsha1_key_, TEMP1, 20); hmac_sha1(hmacsha1_key_, 20, (unsigned char*)&cur_salt->cno, 4, iv, 20); if (cur_salt->encrypted_keyblob_size == 48) AES_set_decrypt_key(aes_key_, 128, &aes_decrypt_key); else AES_set_decrypt_key(aes_key_, 128 * 2, &aes_decrypt_key); AES_cbc_encrypt(cur_salt->chunk, outbuf, cur_salt->data_size, &aes_decrypt_key, iv, AES_DECRYPT); /* 8 consecutive nulls */ if (memmem(outbuf, cur_salt->data_size, (void*)nulls, 8)) { #ifdef DMG_DEBUG if (!bench_running) fprintf(stderr, "NULLS found!\n\n"); #endif ret = 1; } /* These tests seem to be obsoleted by the 8xNULL test */ #ifdef DMG_DEBUG /* </plist> is a pretty generic signature for Apple */ if (memmem(outbuf, cur_salt->data_size, (void*)"</plist>", 8)) { if (!bench_running) fprintf(stderr, "</plist> found!\n\n"); ret = 1; } /* Journalled HFS+ */ if (memmem(outbuf, cur_salt->data_size, (void*)"jrnlhfs+", 8)) { if (!bench_running) fprintf(stderr, "jrnlhfs+ found!\n\n"); ret = 1; } /* Handle compressed DMG files, CMIYC 2012 and self-made samples. Is this test obsoleted by the </plist> one? */ if ((r = memmem(outbuf, cur_salt->data_size, (void*)"koly", 4))) { unsigned int *u32Version = (unsigned int *)(r + 4); if (HTONL(*u32Version) == 4) { if (!bench_running) fprintf(stderr, "koly found!\n\n"); ret = 1; } } /* Handle VileFault sample images */ if (memmem(outbuf, cur_salt->data_size, (void*)"EFI PART", 8)) { if (!bench_running) fprintf(stderr, "EFI PART found!\n\n"); ret = 1; } /* Apple is a good indication but it's short enough to produce false positives */ if (memmem(outbuf, cur_salt->data_size, (void*)"Apple", 5)) { if (!bench_running) fprintf(stderr, "Apple found!\n\n"); ret = 1; } #endif /* DMG_DEBUG */ /* Second buffer test. If present, *this* is the very first block of the DMG */ if (cur_salt->scp == 1) { int cno = 0; hmac_sha1(hmacsha1_key_, 20, (unsigned char*)&cno, 4, iv, 20); if (cur_salt->encrypted_keyblob_size == 48) AES_set_decrypt_key(aes_key_, 128, &aes_decrypt_key); else AES_set_decrypt_key(aes_key_, 128 * 2, &aes_decrypt_key); AES_cbc_encrypt(cur_salt->zchunk, outbuf2, 4096, &aes_decrypt_key, iv, AES_DECRYPT); /* 8 consecutive nulls */ if (memmem(outbuf2, 4096, (void*)nulls, 8)) { #ifdef DMG_DEBUG if (!bench_running) fprintf(stderr, "NULLS found in alternate block!\n\n"); #endif ret = 1; } #ifdef DMG_DEBUG /* This test seem to be obsoleted by the 8xNULL test */ if (memmem(outbuf2, 4096, (void*)"Press any key to reboot", 23)) { if (!bench_running) fprintf(stderr, "MS-DOS UDRW signature found in alternate block!\n\n"); ret = 1; } #endif /* DMG_DEBUG */ } #ifdef DMG_DEBUG /* Write block as hex, strings or raw to a file. */ if (ret && !bench_running) { #if DMG_DEBUG == 4 int fd; if ((fd = open("dmg.debug.main", O_RDWR | O_CREAT | O_TRUNC, 0660)) == -1) perror("open()"); else { #if FCNTL_LOCKS struct flock lock = { 0 }; lock.l_type = F_WRLCK; while (fcntl(fd, F_SETLKW, &lock)) { if (errno != EINTR) pexit("fcntl(F_WRLCK)"); } #elif OS_FLOCK while (flock(fd, LOCK_EX)) { if (errno != EINTR) pexit("flock(LOCK_EX)"); } #endif if ((write(fd, outbuf, cur_salt->data_size) == -1)) perror("write()"); if (cur_salt->scp == 1) if ((write(fd, outbuf2, 4096) == -1)) perror("write()"); if (close(fd)) perror("close"); } #endif #if DMG_DEBUG == 3 dump_stuff(outbuf, cur_salt->data_size); if (cur_salt->scp == 1) { fprintf(stderr, "2nd block:\n"); dump_stuff(outbuf2, 4096); } #endif #if DMG_DEBUG == 2 dump_text(outbuf, cur_salt->data_size); if (cur_salt->scp == 1) { fprintf(stderr, "2nd block:\n"); dump_text(outbuf2, 4096); } #endif } #endif /* DMG_DEBUG */ } return ret; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index; size_t *lws = local_work_size ? &local_work_size : NULL; global_work_size = GET_MULTIPLE_OR_BIGGER(count, local_work_size); if (any_cracked) { memset(cracked, 0, cracked_size); any_cracked = 0; } /// Copy data to gpu BENCH_CLERROR(clEnqueueWriteBuffer(queue[gpu_id], mem_in, CL_FALSE, 0, insize, inbuffer, 0, NULL, multi_profilingEvent[0]), "Copy data to gpu"); /// Run kernel BENCH_CLERROR(clEnqueueNDRangeKernel(queue[gpu_id], crypt_kernel, 1, NULL, &global_work_size, lws, 0, NULL, multi_profilingEvent[1]), "Run kernel"); /// Read the result back BENCH_CLERROR(clEnqueueReadBuffer(queue[gpu_id], mem_out, CL_TRUE, 0, outsize, outbuffer, 0, NULL, multi_profilingEvent[2]), "Copy result back"); if (ocl_autotune_running) return count; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) if (hash_plugin_check_hash((unsigned char*)outbuffer[index].v) == 1) { 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; } static unsigned int iteration_count(void *salt) { struct custom_salt *my_salt; my_salt = salt; return (unsigned int) my_salt->iterations; } struct fmt_main fmt_opencl_dmg = { { FORMAT_LABEL, FORMAT_NAME, ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, #ifdef DMG_DEBUG FMT_NOT_EXACT | #endif #ifdef _OPENMP FMT_OMP | #endif FMT_CASE | FMT_8_BIT, { "iteration count", }, dmg_tests }, { init, done, reset, fmt_default_prepare, valid, fmt_default_split, fmt_default_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, 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 */
saxpy.c
/** * @file saxpy.c * * @mainpage saxpy * * @author Xin Wu (PC²) * @date 05.04.2020 * @copyright CC BY-SA 2.0 * * saxpy performs the \c saxpy operation on host as well as accelerator. * The performance (in MB/s) for different implementations is also compared. * * The \c saxpy operation is defined as: * * y := a * x + y * * where: * * - a is a scalar. * - x and y are single-precision vectors each with n elements. */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #include "hsaxpy.h" #include "asaxpy.h" #include "check1ns.h" #include "wtcalc.h" #define TWO26 (1 << 26) #define NLUP (32) /** * @brief Main entry point for saxpy. */ int main(int argc, char *argv[]) { int i, n, iret, ial; size_t nbytes; float a = 2.0f, *x, *y, *yhost, *yaccl, maxabserr; struct timespec rt[2]; double wt; // walltime /* * We need 1 ns time resolution. */ check1ns(); printf("The system supports 1 ns time resolution\n"); /* * check the number of accelerators */ if (0 == omp_get_num_devices()) { printf("No accelerator found ... exit\n"); exit(EXIT_FAILURE); } /* * preparation */ n = TWO26; nbytes = sizeof(float) * n; iret = 0; if (NULL == (x = (float *) malloc(nbytes))) iret = -1; if (NULL == (y = (float *) malloc(nbytes))) iret = -1; if (NULL == (yhost = (float *) malloc(nbytes))) iret = -1; if (NULL == (yaccl = (float *) malloc(nbytes))) iret = -1; if (0 != iret) { printf("error: memory allocation\n"); free(x); free(y); free(yhost); free(yaccl); exit(EXIT_FAILURE); } #pragma omp parallel for default(none) \ shared(a, x, y, yhost, yaccl, n) private(i) for (i = 0; i < n; ++i) { x[i] = rand() % 32 / 32.0f; y[i] = rand() % 32 / 32.0f; yhost[i] = a * x[i] + y[i]; // yhost will be used as reference value yaccl[i] = 0.0f; } printf("total size of x and y is %9.1f MB\n", 2.0 * nbytes / (1 << 20)); printf("tests are averaged over %2d loops\n", NLUP); /* * saxpy on host */ /* * See hsaxpy.c for details: */ memcpy(yaccl, y, nbytes); wtcalc = -1.0; // skip 1st run for timing hsaxpy(n, a, x, yaccl); // check yaccl maxabserr = -1.0f; for (i = 0; i < n; ++i) { maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr? fabsf(yaccl[i] - yhost[i]) : maxabserr; } // skip 2nd run for timing hsaxpy(n, a, x, yaccl); // timing : start wtcalc = 0.0; clock_gettime(CLOCK_REALTIME, rt + 0); for (int ilup = 0; ilup < 1; ++ilup) { hsaxpy(n, a, x, yaccl); } clock_gettime(CLOCK_REALTIME, rt + 1); wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec); printf("saxpy on host: %9.1f MB/s %9.1f MB/s maxabserr = %9.1f\n", 3.0 * nbytes / ((1 << 20) * wt), 3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr); /* * saxpy on accl */ for (ial = 0; ial < 6; ++ial) { /* * See asaxpy.c for details: * * ial: * * 0: <<<2^7 , 2^7 >>>, auto scheduling * 1: <<<2^16, 2^10>>>, manual scheduling * 2: <<<2^15, 2^7 >>>, manual scheduling, 16x loop unrolling (2^15*2^7*16==2^26) * 3: <<<2^12, 2^7 >>>, auto scheduling, 16x loop unrolling * 4: de-linearize the vector and then collapse the ji-loop. * otherwise: cublasSaxpy in CUBLAS */ memcpy(yaccl, y, nbytes); wtcalc = -1.0; // skip 1st run for timing asaxpy(n, a, x, yaccl, ial); // check yaccl maxabserr = -1.0f; for (i = 0; i < n; ++i) { maxabserr = fabsf(yaccl[i] - yhost[i]) > maxabserr? fabsf(yaccl[i] - yhost[i]) : maxabserr; } // skip 2nd run for timing asaxpy(n, a, x, yaccl, ial); // timing : start wtcalc = 0.0; clock_gettime(CLOCK_REALTIME, rt + 0); for (int ilup = 0; ilup < NLUP; ++ilup) { asaxpy(n, a, x, yaccl, ial); } clock_gettime(CLOCK_REALTIME, rt + 1); wt=(rt[1].tv_sec - rt[0].tv_sec) + 1.0e-9 * (rt[1].tv_nsec - rt[0].tv_nsec); printf("saxpy on accl (impl. %d)\ntotal: %9.1f MB/s kernel: %9.1f MB/s maxabserr = %9.1f\n\n", ial, NLUP * 3.0 * nbytes / ((1 << 20) * wt), NLUP * 3.0 * nbytes / ((1 << 20) * wtcalc), maxabserr); } /* * release memory */ free(x); free(y); free(yhost); free(yaccl); return 0; }
GB_subassign_02.c
//------------------------------------------------------------------------------ // GB_subassign_02: C(I,J) = A ; using S //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // Method 02: C(I,J) = A ; using S // M: NULL // Mask_comp: false // C_replace: false // accum: NULL // A: matrix // S: constructed // C: not bitmap or full: use GB_bitmap_assign instead // A: any sparsity structure. #include "GB_subassign_methods.h" GrB_Info GB_subassign_02 ( GrB_Matrix C, // input: const GrB_Index *I, const int64_t ni, const int64_t nI, const int Ikind, const int64_t Icolon [3], const GrB_Index *J, const int64_t nj, const int64_t nJ, const int Jkind, const int64_t Jcolon [3], const GrB_Matrix A, GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (!GB_IS_BITMAP (C)) ; ASSERT (!GB_IS_FULL (C)) ; ASSERT (!GB_aliased (C, A)) ; // NO ALIAS of C==A //-------------------------------------------------------------------------- // S = C(I,J) //-------------------------------------------------------------------------- GB_EMPTY_TASKLIST ; GB_OK (GB_subassign_symbolic (S, C, I, ni, J, nj, true, Context)) ; //-------------------------------------------------------------------------- // get inputs //-------------------------------------------------------------------------- GB_MATRIX_WAIT_IF_JUMBLED (A) ; GB_GET_C ; // C must not be bitmap GB_GET_A ; GB_GET_S ; GrB_BinaryOp accum = NULL ; //-------------------------------------------------------------------------- // Method 02: C(I,J) = A ; using S //-------------------------------------------------------------------------- // Time: Optimal. All entries in A+S must be examined, so the work is // Omega (nnz(A)+nnz(S)). // Method 02 and Method 04 are somewhat similar. They differ on how C is // modified when the entry is present in S but not A. // TODO: phase2 of Method 02 and 04 are identical and could be // done in a single function. //-------------------------------------------------------------------------- // Parallel: A+S (Methods 02, 04, 09, 10, 11, 12, 14, 16, 18, 20) //-------------------------------------------------------------------------- if (A_is_bitmap) { // all of IxJ must be examined GB_SUBASSIGN_IXJ_SLICE ; } else { // traverse all A+S GB_SUBASSIGN_TWO_SLICE (A, S) ; } //-------------------------------------------------------------------------- // phase 1: create zombies, update entries, and count pending tuples //-------------------------------------------------------------------------- if (A_is_bitmap) { //---------------------------------------------------------------------- // phase1: A is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE1 (iA_start, iA_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iA_start:iA_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; int64_t pA_start = j * Avlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j) //-------------------------------------------------------------- for (int64_t iA = iA_start ; iA < iA_end ; iA++) { int64_t pA = pA_start + iA ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ; bool Afound = Ab [pA] ; if (Sfound && !Afound) { // ----[C . 1] or [X . 1]------------------------------- // S (i,j) is present but A (i,j) is not // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still a zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } else if (!Sfound && Afound) { // ----[. A 1]------------------------------------------ // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) task_pending++ ; } else if (Sfound && Afound) { // ----[C A 1] or [X A 1]------------------------------- // both S (i,j) and A (i,j) present // [C A 1]: action: ( =A ): copy A into C, no accum // [X A 1]: action: ( undelete ): zombie lives GB_C_S_LOOKUP ; GB_noaccum_C_A_1_matrix ; GB_NEXT (S) ; } } } GB_PHASE1_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase1: A is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(+:nzombies) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE1 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get A(:,j) and S(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and A(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression // int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iA = GBI (Ai, pA, Avlen) ; if (iS < iA) { // ----[C . 1] or [X . 1]------------------------------- // S (i,j) is present but A (i,j) is not // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still a zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } else if (iA < iS) { // ----[. A 1]------------------------------------------ // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) task_pending++ ; GB_NEXT (A) ; } else { // ----[C A 1] or [X A 1]------------------------------- // both S (i,j) and A (i,j) present // [C A 1]: action: ( =A ): copy A into C, no accum // [X A 1]: action: ( undelete ): zombie lives GB_C_S_LOOKUP ; GB_noaccum_C_A_1_matrix ; GB_NEXT (S) ; GB_NEXT (A) ; } } // while list S (:,j) has entries. List A (:,j) exhausted. while (pS < pS_end) { // ----[C . 1] or [X . 1]----------------------------------- // S (i,j) is present but A (i,j) is not // [C . 1]: action: ( delete ): becomes zombie // [X . 1]: action: ( X ): still a zombie GB_C_S_LOOKUP ; GB_DELETE_ENTRY ; GB_NEXT (S) ; } // List A (:,j) has entries. List S (:,j) exhausted. task_pending += (pA_end - pA) ; } GB_PHASE1_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // phase 2: insert pending tuples //-------------------------------------------------------------------------- GB_PENDING_CUMSUM ; if (A_is_bitmap) { //---------------------------------------------------------------------- // phase2: A is bitmap //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_IXJ_TASK_DESCRIPTOR_PHASE2 (iA_start, iA_end) ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t j = kfirst ; j <= klast ; j++) { //-------------------------------------------------------------- // get S(iA_start:iA_end,j) //-------------------------------------------------------------- GB_GET_VECTOR_FOR_IXJ (S, iA_start) ; int64_t pA_start = j * Avlen ; //-------------------------------------------------------------- // do a 2-way merge of S(iA_start:iA_end,j) and A(ditto,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; for (int64_t iA = iA_start ; iA < iA_end ; iA++) { int64_t pA = pA_start + iA ; bool Sfound = (pS < pS_end) && (GBI (Si, pS, Svlen) == iA) ; bool Afound = Ab [pA] ; if (!Sfound && Afound) { // ----[. A 1]------------------------------------------ // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; GB_NEXT (A) ; } else if (Sfound) { // S (i,j) present GB_NEXT (S) ; } } } GB_PHASE2_TASK_WRAPUP ; } } else { //---------------------------------------------------------------------- // phase2: A is hypersparse, sparse, or full //---------------------------------------------------------------------- #pragma omp parallel for num_threads(nthreads) schedule(dynamic,1) \ reduction(&&:pending_sorted) for (taskid = 0 ; taskid < ntasks ; taskid++) { //------------------------------------------------------------------ // get the task descriptor //------------------------------------------------------------------ GB_GET_TASK_DESCRIPTOR_PHASE2 ; //------------------------------------------------------------------ // compute all vectors in this task //------------------------------------------------------------------ for (int64_t k = kfirst ; k <= klast ; k++) { //-------------------------------------------------------------- // get A(:,j) and S(:,j) //-------------------------------------------------------------- int64_t j = GBH (Zh, k) ; GB_GET_MAPPED (pA, pA_end, pA, pA_end, Ap, j, k, Z_to_X, Avlen); GB_GET_MAPPED (pS, pS_end, pB, pB_end, Sp, j, k, Z_to_S, Svlen); //-------------------------------------------------------------- // do a 2-way merge of S(:,j) and A(:,j) //-------------------------------------------------------------- // jC = J [j] ; or J is a colon expression int64_t jC = GB_ijlist (J, j, Jkind, Jcolon) ; // while both list S (:,j) and A (:,j) have entries while (pS < pS_end && pA < pA_end) { int64_t iS = GBI (Si, pS, Svlen) ; int64_t iA = GBI (Ai, pA, Avlen) ; if (iS < iA) { GB_NEXT (S) ; } else if (iA < iS) { // ----[. A 1]------------------------------------------ // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; GB_NEXT (A) ; } else { GB_NEXT (S) ; GB_NEXT (A) ; } } // ignore the remainder of S (:,j) // while list A (:,j) has entries. List S (:,j) exhausted. while (pA < pA_end) { // ----[. A 1]---------------------------------------------- // S (i,j) is not present, A (i,j) is present // [. A 1]: action: ( insert ) int64_t iA = GBI (Ai, pA, Avlen) ; int64_t iC = GB_ijlist (I, iA, Ikind, Icolon) ; GB_PENDING_INSERT (Ax +(pA*asize)) ; GB_NEXT (A) ; } } GB_PHASE2_TASK_WRAPUP ; } } //-------------------------------------------------------------------------- // finalize the matrix and return result //-------------------------------------------------------------------------- GB_SUBASSIGN_WRAPUP ; }
GB_builder.c
//------------------------------------------------------------------------------ // GB_builder: build a matrix from tuples //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // CALLED BY: GB_build, GB_wait, and GB_transpose // CALLS: Generated/GB_red_build__* workers // This function is called by GB_build to build a matrix T for GrB_Matrix_build // or GrB_Vector_build, by GB_wait to build a matrix T from the list of pending // tuples, and by GB_transpose to transpose a matrix or vector. Duplicates can // appear if called by GB_build or GB_wait, but not GB_transpose. // The indices are provided either as (I_input,J_input) or (I_work,J_work), not // both. The values are provided as S_input or S_work, not both. On return, // the *work arrays are either transplanted into T, or freed, since they are // temporary workspaces. // The work is done in major 5 Steps, some of which can be skipped, depending // on how the tuples are provided (*_work or *_input), and whether or not they // are sorted, or have duplicates. If vdim <= 1, some work is skipped (for // GrB_Vectors, and single-vector GrB_Matrices). Let e be the of tuples on // input. Let p be the # of threads used. // STEP 1: copy user input. O(e/p) read/write per thread, or skipped. // STEP 2: sort the tuples. Time: O((e log e)/p), read/write, or skipped if // the tuples are already sorted. // STEP 3: count vectors and duplicates. O(e/p) reads, per thread, if no // duplicates, or skipped if already done. O(e/p) read/writes // per thread if duplicates appear. // STEP 4: construct T->h and T->p. O(e/p) reads per thread, or skipped if // T is a vector. // STEP 5: assemble the tuples. O(e/p) read/writes per thread, or O(1) if the // values can be transplanted into T as-is. // For GrB_Matrix_build: If the input (I_input, J_input, S_input) is already // sorted with no duplicates, and no typecasting needs to be done, then Step 1 // still must be done (each thread does O(e/p) reads of (I_input,J_input) and // writes to I_work), but Step 1 also does the work for Step 3. Step 2 and 3 // are skipped. Step 4 does O(e/p) reads per thread (J_input only). Then // I_work is transplanted into T->i. Step 5 does O(e/p) read/writes per thread // to copy S into T->x. // For GrB_Vector_build: as GrB_Matrix_build, Step 1 does O(e/p) read/writes // per thread. The input is always a vector, so vdim == 1 always holds. Step // 2 is skipped if the indices are already sorted, and Step 3 does no work at // all unless duplicates appear. Step 4 takes no time, for any vector. Step 5 // does O(e/p) reads/writes per thread. // For GrB_reduce_to_vector: like GrB_Vector_build, but many duplicates are // likely, and the indices will not be sorted. The input is always a single // vector (vdim == 1). Step 1 only does a parallel memcpy, from I_input to // I_work. Step 2 takes O((e log e)/p) time to sort the (i,k) tuples. Step 3 // does O(e/p) read/writes. Step 4 takes no time. Step 5 does O(e/p) // read/writes per thread. // For GB_wait: the pending tuples are provided as I_work, J_work, and S_work, // so Step 1 is skipped (no need to check for invalid indices). The input // J_work may be null (vdim can be anything, since GB_wait is used for both // vectors and matrices). The tuples might be in sorted order already, which // is known precisely known from A->Pending->sorted. Step 2 does O((e log e)/p) // work to sort the tuples. Duplicates may appear, and out-of-order tuples are // likely. Step 3 does O(e/p) read/writes. Step 4 does O(e/p) reads per // thread of (I_work,J_work), or just I_work. Step 5 does O(e/p) read/writes // per thread, or O(1) time if S_work can be transplanted into T->x. // For GB_transpose: uses I_work, J_work, and either S_input (if no op applied // to the values) or S_work (if an op was applied to the A->x values). This is // only done for matrices, not vectors, so vdim > 1 will always hold. The // indices are valid so Step 1 is skipped. The tuples are not sorted, so Step // 2 takes O((e log e)/p) time to do the sort. There are no duplicates, so // Step 3 only does O(e/p) reads of J_work to count the vectors in each slice. // Step 4 only does O(e/p) reads of J_work to compute T->h and T->p. Step 5 // does O(e/p) read/writes per thread, but it uses the simpler case in // GB_reduce_build_template since no duplicates can appear. It is unlikely // able to transplant S_work into T->x since the input will almost always be // unsorted. #include "GB_build.h" #include "GB_sort.h" #ifndef GBCOMPACT #include "GB_red__include.h" #endif #define GB_I_WORK(t) (((t) < 0) ? -1 : I_work [t]) #define GB_J_WORK(t) (((t) < 0) ? -1 : ((J_work == NULL) ? 0 : J_work [t])) #define GB_K_WORK(t) (((t) < 0) ? -1 : ((K_work == NULL) ? t : K_work [t])) #define GB_FREE_WORK \ { \ GB_FREE_MEMORY (tstart_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (tnvec_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (tnz_slice, nthreads+1, sizeof (int64_t)) ; \ GB_FREE_MEMORY (kbad, nthreads, sizeof (int64_t)) ; \ GB_FREE_MEMORY (ilast_slice, nthreads, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*I_work_handle, ijslen, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*J_work_handle, ijslen, sizeof (int64_t)) ; \ GB_FREE_MEMORY (*S_work_handle, ijslen, ssize) ; \ GB_FREE_MEMORY (K_work, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W0, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; \ GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; \ } //------------------------------------------------------------------------------ // GB_builder //------------------------------------------------------------------------------ GrB_Info GB_builder // build a matrix from tuples ( GrB_Matrix *Thandle, // matrix T to build const GrB_Type ttype, // type of output matrix T const int64_t vlen, // length of each vector of T const int64_t vdim, // number of vectors in T const bool is_csc, // true if T is CSC, false if CSR int64_t **I_work_handle, // for (i,k) or (j,i,k) tuples int64_t **J_work_handle, // for (j,i,k) tuples GB_void **S_work_handle, // array of values of tuples, size ijslen bool known_sorted, // true if tuples known to be sorted bool known_no_duplicates, // true if tuples known to not have dupl int64_t ijslen, // size of I_work and J_work arrays const bool is_matrix, // true if T a GrB_Matrix, false if vector const bool ijcheck, // true if I_input,J_input must be checked const int64_t *GB_RESTRICT I_input,// original indices, size nvals const int64_t *GB_RESTRICT J_input,// original indices, size nvals const GB_void *GB_RESTRICT S_input,// array of values of tuples, size nvals const int64_t nvals, // number of tuples, and size of K_work const GrB_BinaryOp dup, // binary function to assemble duplicates, // if NULL use the SECOND operator to // keep the most recent duplicate. const GB_Type_code scode, // GB_Type_code of S_work or S_input array GB_Context Context ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- ASSERT (Thandle != NULL) ; ASSERT (nvals >= 0) ; ASSERT (scode <= GB_UDT_code) ; ASSERT_TYPE_OK (ttype, "ttype for builder", GB0) ; ASSERT_BINARYOP_OK_OR_NULL (dup, "dup for builder", GB0) ; ASSERT (I_work_handle != NULL) ; ASSERT (J_work_handle != NULL) ; ASSERT (S_work_handle != NULL) ; //-------------------------------------------------------------------------- // get S //-------------------------------------------------------------------------- GB_void *GB_RESTRICT S_work = (*S_work_handle) ; const GB_void *GB_RESTRICT S = (S_work == NULL) ? S_input : S_work ; size_t tsize = ttype->size ; size_t ssize = GB_code_size (scode, tsize) ; ASSERT (GB_IMPLIES (nvals > 0, S != NULL)) ; //========================================================================== // symbolic phase of the build ============================================= //========================================================================== // The symbolic phase sorts the tuples and finds any duplicates. The // output matrix T is constructed (not including T->i and T->x), and T->h // and T->p are computed. Then I_work is transplanted into T->i, or T->i is // allocated. T->x is then allocated. It is not computed until the // numeric phase. // When this function returns, I_work is either freed or transplanted into // T->i. J_work is freed, and the I_work and J_work pointers (in the // caller) are set to NULL by setting their handles to NULL. Note that // J_work may already be NULL on input, if T has one or zero vectors // (J_work_handle is always non-NULL however). GrB_Info info ; GrB_Matrix T = NULL ; (*Thandle) = NULL ; int64_t *GB_RESTRICT I_work = (*I_work_handle) ; int64_t *GB_RESTRICT J_work = (*J_work_handle) ; int64_t *GB_RESTRICT K_work = NULL ; int64_t *GB_RESTRICT W0 = NULL ; int64_t *GB_RESTRICT W1 = NULL ; int64_t *GB_RESTRICT W2 = NULL ; //-------------------------------------------------------------------------- // determine the number of threads to use //-------------------------------------------------------------------------- GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ; int nthreads = GB_nthreads (nvals, chunk, nthreads_max) ; //-------------------------------------------------------------------------- // allocate workspace //-------------------------------------------------------------------------- int64_t *GB_RESTRICT tstart_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT tnvec_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT tnz_slice = NULL ; // size nthreads+1 int64_t *GB_RESTRICT kbad = NULL ; // size nthreads int64_t *GB_RESTRICT ilast_slice = NULL ; // size [nthreads] GB_CALLOC_MEMORY (tstart_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (tnvec_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (tnz_slice, nthreads+1, sizeof (int64_t)) ; GB_CALLOC_MEMORY (kbad, nthreads, sizeof (int64_t)) ; GB_CALLOC_MEMORY (ilast_slice, nthreads, sizeof (int64_t)) ; if (tstart_slice == NULL || tnvec_slice == NULL || tnz_slice == NULL || kbad == NULL || ilast_slice == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } //-------------------------------------------------------------------------- // partition the tuples for the threads //-------------------------------------------------------------------------- // Thread tid handles tuples tstart_slice [tid] to tstart_slice [tid+1]-1. // Each thread handles about the same number of tuples. This partition // depends only on nvals. tstart_slice [0] = 0 ; for (int tid = 1 ; tid < nthreads ; tid++) { tstart_slice [tid] = GB_PART (tid, nvals, nthreads) ; } tstart_slice [nthreads] = nvals ; // tstart_slice [tid]: first tuple in slice tid // tnvec_slice [tid]: # of vectors that start in a slice. If a vector // starts in one slice and ends in another, it is // counted as being in the first slice. // tnz_slice [tid]: # of entries in a slice after removing duplicates // sentinel values for the final cumulative sum tnvec_slice [nthreads] = 0 ; tnz_slice [nthreads] = 0 ; // this becomes true if the first pass computes tnvec_slice and tnz_slice, // and if the (I_input,J_input) tuples were found to be already sorted with // no duplicates present. bool tnvec_and_tnz_slice_computed = false ; //-------------------------------------------------------------------------- // STEP 1: copy user input and check if valid //-------------------------------------------------------------------------- // If the indices are provided by (I_input,J_input), then import them into // (I_work,J_work) and check if they are valid, and sorted. If the input // happens to be already sorted, then duplicates are detected and the # of // vectors in each slice is counted. if (I_work == NULL) { //---------------------------------------------------------------------- // allocate I_work //---------------------------------------------------------------------- // allocate workspace to load and sort the index tuples: // vdim <= 1: I_work and K_work for (i,k) tuples, where i = I_input [k] // vdim > 1: also J_work for (j,i,k) tuples where i = I_input [k] and // j = J_input [k]. If the tuples are found to be already sorted on // input, then J_work is not allocated, and J_input is used instead. // The k value in the tuple gives the position in the original set of // tuples: I_input [k] and S [k] when vdim <= 1, and also J_input [k] // for matrices with vdim > 1. // The workspace I_work and J_work are allocated here but freed (or // transplanted) inside GB_builder. K_work is allocated, used, and // freed in GB_builder. ASSERT (J_work == NULL) ; GB_MALLOC_MEMORY (I_work, nvals, sizeof (int64_t)) ; (*I_work_handle) = I_work ; ijslen = nvals ; if (I_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } //---------------------------------------------------------------------- // create the tuples to sort, and check for any invalid indices //---------------------------------------------------------------------- known_sorted = true ; bool no_duplicates_found = true ; if (nvals == 0) { //------------------------------------------------------------------ // nothing to do //------------------------------------------------------------------ ; } else if (is_matrix) { //------------------------------------------------------------------ // C is a matrix; check both I_input and J_input //------------------------------------------------------------------ ASSERT (J_input != NULL) ; ASSERT (I_work != NULL) ; ASSERT (vdim >= 0) ; ASSERT (I_input != NULL) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(&&:known_sorted) reduction(&&:no_duplicates_found) for (tid = 0 ; tid < nthreads ; tid++) { kbad [tid] = -1 ; int64_t my_tnvec = 0 ; int64_t kstart = tstart_slice [tid] ; int64_t kend = tstart_slice [tid+1] ; int64_t ilast = (kstart == 0) ? -1 : I_input [kstart-1] ; int64_t jlast = (kstart == 0) ? -1 : J_input [kstart-1] ; for (int64_t k = kstart ; k < kend ; k++) { // get k-th index from user input: (i,j) int64_t i = I_input [k] ; int64_t j = J_input [k] ; if (i < 0 || i >= vlen || j < 0 || j >= vdim) { // halt if out of bounds kbad [tid] = k ; break ; } // check if the tuples are already sorted known_sorted = known_sorted && ((jlast < j) || (jlast == j && ilast <= i)) ; // check if this entry is a duplicate of the one before it no_duplicates_found = no_duplicates_found && (!(jlast == j && ilast == i)) ; // copy the tuple into I_work. J_work is done later. I_work [k] = i ; if (j > jlast) { // vector j starts in this slice (but this is // valid only if J_input is sorted on input) my_tnvec++ ; } // log the last index seen ilast = i ; jlast = j ; } // these are valid only if I_input and J_input are sorted on // input, with no duplicates present. tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = kend - kstart ; } // collect the report from each thread for (int tid = 0 ; tid < nthreads ; tid++) { if (kbad [tid] >= 0) { // invalid index int64_t i = I_input [kbad [tid]] ; int64_t j = J_input [kbad [tid]] ; int64_t row = is_csc ? i : j ; int64_t col = is_csc ? j : i ; int64_t nrows = is_csc ? vlen : vdim ; int64_t ncols = is_csc ? vdim : vlen ; GB_FREE_WORK ; return (GB_ERROR (GrB_INDEX_OUT_OF_BOUNDS, (GB_LOG, "index ("GBd","GBd") out of bounds," " must be < ("GBd", "GBd")", row, col, nrows, ncols))) ; } } // if the tuples were found to be already in sorted order, and if // no duplicates were found, then tnvec_slice and tnz_slice are now // valid, Otherwise, they can only be computed after sorting. tnvec_and_tnz_slice_computed = known_sorted && no_duplicates_found ; //------------------------------------------------------------------ // allocate J_work, if needed //------------------------------------------------------------------ if (vdim > 1 && !known_sorted) { // copy J_input into J_work, so the tuples can be sorted GB_MALLOC_MEMORY (J_work, nvals, sizeof (int64_t)) ; (*J_work_handle) = J_work ; if (J_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } GB_memcpy (J_work, J_input, nvals * sizeof (int64_t), nthreads); } else { // J_work is a shallow copy of J_input. The pointer is not // copied into (*J_work_handle), so it will not be freed. // J_input is not modified, even though it is typecast to the // int64_t *J_work, since J_work is not modified in this case. J_work = (int64_t *) J_input ; } } else if (ijcheck) { //------------------------------------------------------------------ // C is a typecasted GrB_Vector; check only I_input //------------------------------------------------------------------ ASSERT (I_input != NULL) ; ASSERT (J_input == NULL) ; ASSERT (vdim == 1) ; int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) \ reduction(&&:known_sorted) reduction(&&:no_duplicates_found) for (tid = 0 ; tid < nthreads ; tid++) { kbad [tid] = -1 ; int64_t kstart = tstart_slice [tid] ; int64_t kend = tstart_slice [tid+1] ; int64_t ilast = (kstart == 0) ? -1 : I_input [kstart-1] ; for (int64_t k = kstart ; k < kend ; k++) { // get k-th index from user input: (i) int64_t i = I_input [k] ; if (i < 0 || i >= vlen) { // halt if out of bounds kbad [tid] = k ; break ; } // check if the tuples are already sorted known_sorted = known_sorted && (ilast <= i) ; // check if this entry is a duplicate of the one before it no_duplicates_found = no_duplicates_found && (!(ilast == i)) ; // copy the tuple into the work arrays to be sorted I_work [k] = i ; // log the last index seen ilast = i ; } } // collect the report from each thread for (int tid = 0 ; tid < nthreads ; tid++) { if (kbad [tid] >= 0) { // invalid index int64_t i = I_input [kbad [tid]] ; GB_FREE_WORK ; return (GB_ERROR (GrB_INDEX_OUT_OF_BOUNDS, (GB_LOG, "index ("GBd") out of bounds, must be < ("GBd")", i, vlen))) ; } } } else { //------------------------------------------------------------------ // GB_reduce_to_vector: do not check I_input, assume not sorted //------------------------------------------------------------------ // Many duplicates are possible, since the tuples are being used to // construct a single vector. For a CSC format, each entry A(i,j) // becomes an (i,aij) tuple, with the vector index j discarded. All // entries in a single row i are reduced to a single entry in the // vector. The input is unlikely to be sorted, so do not bother to // check. GB_memcpy (I_work, I_input, nvals * sizeof (int64_t), nthreads) ; known_sorted = false ; } //---------------------------------------------------------------------- // determine if duplicates are possible //---------------------------------------------------------------------- // The input is now known to be sorted, or not. If it is sorted, and // if no duplicates were found, then it is known to have no duplicates. // Otherwise, duplicates might appear, but a sort is required first to // check for duplicates. known_no_duplicates = known_sorted && no_duplicates_found ; } //-------------------------------------------------------------------------- // STEP 2: sort the tuples in ascending order //-------------------------------------------------------------------------- // If the tuples are known to already be sorted, Step 2 is skipped. In // that case, K_work is NULL (not allocated), which implicitly means that // K_work [k] = k for all k = 0:nvals-1. if (!known_sorted) { // create the k part of each tuple GB_MALLOC_MEMORY (K_work, nvals, sizeof (int64_t)) ; if (K_work == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } // The k part of each tuple (i,k) or (j,i,k) records the original // position of the tuple in the input list. This allows an unstable // sorting algorith to be used. Since k is unique, it forces the // result of the sort to be stable regardless of whether or not the // sorting algorithm is stable. It also keeps track of where the // numerical value of the tuple can be found; it is in S[k] for the // tuple (i,k) or (j,i,k), regardless of where the tuple appears in the // list after it is sorted. int64_t k ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (k = 0 ; k < nvals ; k++) { K_work [k] = k ; } // determine # of threads to use in the parallel mergesort int nth = GB_MSORT_NTHREADS (nthreads) ; // sort all the tuples if (vdim > 1) { //------------------------------------------------------------------ // sort a set of (j,i,k) tuples //------------------------------------------------------------------ if (nth > 1) { GB_MALLOC_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W1, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W2, nvals, sizeof (int64_t)) ; if (W0 == NULL || W1 == NULL || W2 == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } GB_msort_3 (J_work, I_work, K_work, W0, W1, W2, nvals, nth) ; } else { //------------------------------------------------------------------ // sort a set of (i,k) tuples //------------------------------------------------------------------ if (nth > 1) { GB_MALLOC_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_MALLOC_MEMORY (W1, nvals, sizeof (int64_t)) ; if (W0 == NULL || W1 == NULL) { // out of memory GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } GB_msort_2 (I_work, K_work, W0, W1, nvals, nth) ; } GB_FREE_MEMORY (W0, nvals, sizeof (int64_t)) ; GB_FREE_MEMORY (W1, nvals, sizeof (int64_t)) ; GB_FREE_MEMORY (W2, nvals, sizeof (int64_t)) ; } //-------------------------------------------------------------------------- // STEP 3: count vectors and duplicates in each slice //-------------------------------------------------------------------------- // Duplicates are located, counted and their indices negated. The # of // vectors in each slice is counted. If the indices are known to not have // duplicates, then only the vectors are counted. Counting the # of // vectors is skipped if already done by Step 1. if (known_no_duplicates) { //---------------------------------------------------------------------- // no duplicates: just count # vectors in each slice //---------------------------------------------------------------------- // This is much faster, particularly if the # of vectors in each slice // has already been computed. #ifdef GB_DEBUG { // assert that there are no duplicates int64_t ilast = -1, jlast = -1 ; for (int64_t t = 0 ; t < nvals ; t++) { int64_t i = GB_I_WORK (t), j = GB_J_WORK (t) ; bool is_duplicate = (i == ilast && j == jlast) ; ASSERT (!is_duplicate) ; ilast = i ; jlast = j ; } } #endif if (vdim <= 1) { // all tuples appear in at most one vector, and there are no // duplicates, so there is no need to scan I_work or J_work. for (int tid = 0 ; tid < nthreads ; tid++) { int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; tnvec_slice [tid] = 0 ; tnz_slice [tid] = tend - tstart ; } tnvec_slice [0] = (nvals == 0) ? 0 : 1 ; } else { // count the # of unique vector indices in J_work. No need to scan // I_work since there are no duplicates to be found. Also no need // to compute them if already found in Step 1. if (!tnvec_and_tnz_slice_computed) { int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = 0 ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t j = J_work [t] ; if (j > jlast) { // vector j starts in this slice my_tnvec++ ; jlast = j ; } } tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = tend - tstart ; } } } } else { //---------------------------------------------------------------------- // look for duplicates and count # vectors in each slice //---------------------------------------------------------------------- for (int tid = 0 ; tid < nthreads ; tid++) { int64_t tstart = tstart_slice [tid] ; ilast_slice [tid] = GB_I_WORK (tstart-1) ; } int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = 0 ; int64_t my_ndupl = 0 ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t ilast = ilast_slice [tid] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t i = I_work [t] ; int64_t j = GB_J_WORK (t) ; // tuples are now sorted but there may be duplicates ASSERT ((jlast < j) || (jlast == j && ilast <= i)) ; // check if (j,i,k) is a duplicate if (i == ilast && j == jlast) { // flag the tuple as a duplicate I_work [t] = -1 ; my_ndupl++ ; // the sort places earlier duplicate tuples (with smaller // k) after later ones (with larger k). ASSERT (GB_K_WORK (t-1) < GB_K_WORK (t)) ; } else { // this is a new tuple if (j > jlast) { // vector j starts in this slice my_tnvec++ ; jlast = j ; } ilast = i ; } } tnvec_slice [tid] = my_tnvec ; tnz_slice [tid] = (tend - tstart) - my_ndupl ; } } //-------------------------------------------------------------------------- // find total # of vectors and duplicates in all tuples //-------------------------------------------------------------------------- // Replace tnvec_slice with its cumulative sum, after which each slice tid // will be responsible for the # vectors in T that range from tnvec_slice // [tid] to tnvec_slice [tid+1]-1. GB_cumsum (tnvec_slice, nthreads, NULL, 1) ; int64_t tnvec = tnvec_slice [nthreads] ; // Replace tnz_slice with its cumulative sum GB_cumsum (tnz_slice, nthreads, NULL, 1) ; // find the total # of final entries, after assembling duplicates int64_t tnz = tnz_slice [nthreads] ; int64_t ndupl = nvals - tnz ; //-------------------------------------------------------------------------- // allocate T; always hypersparse //-------------------------------------------------------------------------- // [ allocate T; allocate T->p and T->h but do not initialize them. // T is always hypersparse. GB_NEW (&T, ttype, vlen, vdim, GB_Ap_malloc, is_csc, GB_FORCE_HYPER, GB_ALWAYS_HYPER, tnvec, Context) ; if (info != GrB_SUCCESS) { // out of memory GB_FREE_WORK ; return (info) ; } ASSERT (T->is_hyper) ; ASSERT (T->nzmax == 0) ; // T->i and T->x not yet allocated ASSERT (T->x == NULL) ; ASSERT (T->i == NULL) ; (*Thandle) = T ; //-------------------------------------------------------------------------- // STEP 4: construct the vector pointers and hyperlist for T //-------------------------------------------------------------------------- // Step 4 scans the J_work indices and constructs T->h and T->p. int64_t *GB_RESTRICT Th = T->h ; int64_t *GB_RESTRICT Tp = T->p ; if (vdim <= 1) { //---------------------------------------------------------------------- // special case for vectors //---------------------------------------------------------------------- ASSERT (tnvec == 0 || tnvec == 1) ; if (tnvec > 0) { Th [0] = 0 ; Tp [0] = 0 ; } } else if (ndupl == 0) { //---------------------------------------------------------------------- // no duplicates appear //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnvec = tnvec_slice [tid] ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t j = GB_J_WORK (t) ; if (j > jlast) { // vector j starts in this slice Th [my_tnvec] = j ; Tp [my_tnvec] = t ; my_tnvec++ ; jlast = j ; } } } } else { //---------------------------------------------------------------------- // it is known that at least one duplicate appears //---------------------------------------------------------------------- int tid ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (tid = 0 ; tid < nthreads ; tid++) { int64_t my_tnz = tnz_slice [tid] ; int64_t my_tnvec = tnvec_slice [tid] ; int64_t tstart = tstart_slice [tid] ; int64_t tend = tstart_slice [tid+1] ; int64_t jlast = GB_J_WORK (tstart-1) ; for (int64_t t = tstart ; t < tend ; t++) { // get the t-th tuple int64_t i = I_work [t] ; int64_t j = GB_J_WORK (t) ; if (i >= 0) { // this is a new tuple if (j > jlast) { // vector j starts in this slice Th [my_tnvec] = j ; Tp [my_tnvec] = my_tnz ; my_tnvec++ ; jlast = j ; } my_tnz++ ; } } } } // log the end of the last vector T->nvec_nonempty = tnvec ; T->nvec = tnvec ; Tp [tnvec] = tnz ; ASSERT (T->nvec == T->plen) ; T->magic = GB_MAGIC ; // T->p and T->h are now valid ] //-------------------------------------------------------------------------- // free J_work if it exists //-------------------------------------------------------------------------- ASSERT (J_work_handle != NULL) ; GB_FREE_MEMORY (*J_work_handle, ijslen, sizeof (int64_t)) ; J_work = NULL ; //-------------------------------------------------------------------------- // allocate T->i //-------------------------------------------------------------------------- T->nzmax = GB_IMAX (tnz, 1) ; if (ndupl == 0) { // shrink I_work from size ijslen to size T->nzmax if (T->nzmax < ijslen) { // this cannot fail since the size is shrinking. bool ok ; GB_REALLOC_MEMORY (I_work, T->nzmax, ijslen, sizeof (int64_t), &ok); ASSERT (ok) ; } // transplant I_work into T->i T->i = I_work ; I_work = NULL ; (*I_work_handle) = NULL ; } else { // duplicates exist, so allocate a new T->i. I_work must be freed later GB_MALLOC_MEMORY (T->i, tnz, sizeof (int64_t)) ; if (T->i == NULL) { // out of memory GB_MATRIX_FREE (Thandle) ; GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } } int64_t *GB_RESTRICT Ti = T->i ; //========================================================================== // numerical phase of the build: assemble any duplicates //========================================================================== // The tuples have been sorted. Assemble any duplicates with a switch // factory of built-in workers, or four generic workers. The vector // pointers T->p and hyperlist T->h (if hypersparse) have already been // computed. // If there are no duplicates, T->i holds the row indices of the tuple. // Otherwise, the row indices are still in I_work. K_work holds the // positions of each tuple in the array S. The tuples are sorted so that // duplicates are adjacent to each other and they appear in the order they // appeared in the original tuples. This method assembles the duplicates // and computes T->i and T->x from I_work, K_work, and S. into T, becoming // T->i. If no duplicates appear, T->i is already computed, and S just // needs to be copied and permuted into T->x. // The (i,k,S[k]) tuples are held in two integer arrays: (1) I_work or T->i, // and (2) K_work, and an array S of numerical values. S has not been // sorted, nor even accessed yet. It is identical to the original unsorted // tuples. The (i,k,S[k]) tuple holds the row index i, the position k, and // the value S [k]. This entry becomes T(i,j) = S [k] in the matrix T, and // duplicates (if any) are assembled via the dup operator. //-------------------------------------------------------------------------- // get opcodes and check types //-------------------------------------------------------------------------- // With GB_build, there can be 1 to 2 different types. // T->type is identical to the types of x,y,z for z=dup(x,y). // dup is never NULL and all its three types are the same // The type of S (scode) can different but must be compatible // with T->type // With GB_wait, there can be 1 to 5 different types: // The pending tuples are in S, of type scode which must be // compatible with dup->ytype and T->type // z = dup (x,y): can be NULL or have 1 to 3 different types // T->type: must be compatible with all above types. // dup may be NULL, in which case it is assumed be the implicit SECOND // operator, with all three types equal to T->type GrB_Type xtype, ytype, ztype ; GxB_binary_function fdup ; #ifndef GBCOMPACT GB_Opcode opcode ; #endif GB_Type_code tcode = ttype->code ; bool op_2nd ; ASSERT_TYPE_OK (ttype, "ttype for build_factorize", GB0) ; if (dup == NULL) { //---------------------------------------------------------------------- // dup is the implicit SECOND operator //---------------------------------------------------------------------- // z = SECOND (x,y) where all three types are the same as ttype // T(i,j) = (ttype) S(k) will be done for all tuples. #ifndef GBCOMPACT opcode = GB_SECOND_opcode ; #endif ASSERT (GB_op_is_second (dup, ttype)) ; xtype = ttype ; ytype = ttype ; ztype = ttype ; fdup = NULL ; op_2nd = true ; } else { //---------------------------------------------------------------------- // dup is an explicit operator //---------------------------------------------------------------------- // T(i,j) = (ttype) S[k] will be done for the first tuple. // for subsequent tuples: T(i,j) += S[k], via the dup operator and // typecasting: // // y = (dup->ytype) S[k] // x = (dup->xtype) T(i,j) // z = (dup->ztype) dup (x,y) // T(i,j) = (ttype) z ASSERT_BINARYOP_OK (dup, "dup for build_factory", GB0) ; #ifndef GBCOMPACT opcode = dup->opcode ; #endif xtype = dup->xtype ; ytype = dup->ytype ; ztype = dup->ztype ; fdup = dup->function ; op_2nd = GB_op_is_second (dup, ttype) ; } //-------------------------------------------------------------------------- // get the sizes and codes of each type //-------------------------------------------------------------------------- GB_Type_code zcode = ztype->code ; GB_Type_code xcode = xtype->code ; GB_Type_code ycode = ytype->code ; ASSERT (GB_code_compatible (tcode, scode)) ; // T(i,j) = (ttype) S ASSERT (GB_code_compatible (ycode, scode)) ; // y = (ytype) S ASSERT (GB_Type_compatible (xtype, ttype)) ; // x = (xtype) T(i,j) ASSERT (GB_Type_compatible (ttype, ztype)) ; // T(i,j) = (ttype) z size_t zsize = ztype->size ; size_t xsize = xtype->size ; size_t ysize = ytype->size ; // no typecasting if all 5 types are the same bool nocasting = (tcode == scode) && (ttype == xtype) && (ttype == ytype) && (ttype == ztype) ; //-------------------------------------------------------------------------- // STEP 5: assemble the tuples //-------------------------------------------------------------------------- bool copy_S_into_T = (nocasting && known_sorted && ndupl == 0) ; if (copy_S_into_T && S_work != NULL) { //---------------------------------------------------------------------- // transplant S_work into T->x //---------------------------------------------------------------------- // No typecasting is needed, the tuples were originally in sorted // order, and no duplicates appear. All that is required is to copy S // into Tx. S can be directly transplanted into T->x since S is // provided as S_work. GB_builder must either transplant or free // S_work. The transplant can be used by GB_wait (whenever the tuples // are already sorted, with no duplicates, and no typecasting is // needed, since S_work is always A->Pending->x). This transplant can // rarely be used for GB_transpose (when op is NULL and the transposed // tuples happen to be sorted, which is unlikely). T->x = S_work ; S_work = NULL ; (*S_work_handle) = NULL ; } else { //---------------------------------------------------------------------- // allocate T->x //---------------------------------------------------------------------- GB_MALLOC_MEMORY (T->x, tnz, ttype->size) ; if (T->x == NULL) { // out of memory GB_MATRIX_FREE (Thandle) ; GB_FREE_WORK ; return (GB_OUT_OF_MEMORY) ; } GB_void *GB_RESTRICT Tx = T->x ; ASSERT (GB_IMPLIES (nvals > 0, S != NULL)) ; if (nvals == 0) { // nothing to do } else if (copy_S_into_T) { //------------------------------------------------------------------ // copy S into T->x //------------------------------------------------------------------ // No typecasting is needed, the tuples were originally in sorted // order, and no duplicates appear. All that is required is to // copy S into Tx. S cannot be transplanted into T->x since // S_work is NULL and S_input cannot be modified by GB_builder. ASSERT (S_work == NULL) ; ASSERT (S == S_input) ; GB_memcpy (Tx, S, nvals * tsize, nthreads) ; } else if (nocasting) { //------------------------------------------------------------------ // assemble the values, S, into T, no typecasting needed //------------------------------------------------------------------ // S (either S_work or S_input) must be permuted and copied into // T->x, since the tuples had to be sorted, or duplicates appear. // Any duplicates are now assembled. // There are 44 common cases of this function for built-in types // and 8 associative operators: MIN, MAX, PLUS, TIMES for 10 types // (all but boolean; and OR, AND, XOR, and EQ for boolean. // In addition, the FIRST and SECOND operators are hard-coded, for // another 22 workers, since SECOND is used by GB_wait and since // FIRST is useful for keeping the first tuple seen. It is // controlled by the GB_INCLUDE_SECOND_OPERATOR definition, so they // do not appear in GB_reduce_to_* where the FIRST and SECOND // operators are not needed. // Early exit cannot be exploited, so the terminal is ignored. #define GB_INCLUDE_SECOND_OPERATOR bool done = false ; #define GB_red(opname,aname) GB_red_build_ ## opname ## aname #define GB_RED_WORKER(opname,aname,atype) \ { \ info = GB_red (opname, aname) ((atype *) Tx, Ti, \ (atype *) S, nvals, ndupl, I_work, K_work, tstart_slice,\ tnz_slice, nthreads) ; \ done = (info != GrB_NO_VALUE) ; \ } \ break ; //------------------------------------------------------------------ // launch the switch factory //------------------------------------------------------------------ #ifndef GBCOMPACT // controlled by opcode and typecode GB_Type_code typecode = tcode ; #include "GB_red_factory.c" #endif //------------------------------------------------------------------ // generic worker //------------------------------------------------------------------ if (!done) { GB_BURBLE_N (nvals, "generic ") ; //-------------------------------------------------------------- // no typecasting, but use the fdup function pointer and memcpy //-------------------------------------------------------------- // Either the fdup operator or type of S and T are // user-defined, or fdup is not an associative operator handled // by the GB_red_factory, or some combination of these // conditions. User-defined types cannot be typecasted, so // this handles all user-defined types. // Tx [p] = (ttype) S [k], but with no typecasting #define GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ memcpy (Tx +((p)*tsize), S +((k)*tsize), tsize) ; if (op_2nd) { //---------------------------------------------------------- // dup is the SECOND operator, with no typecasting //---------------------------------------------------------- // Tx [p] += (ttype) S [k], but 2nd op and no typecasting #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) #include "GB_reduce_build_template.c" } else { //---------------------------------------------------------- // dup is another operator, with no typecasting needed //---------------------------------------------------------- // Tx [p] += (ttype) S [k], but with no typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ fdup (Tx +((p)*tsize), Tx +((p)*tsize), S +((k)*tsize)); #include "GB_reduce_build_template.c" } } } else { //------------------------------------------------------------------ // assemble the values S into T, typecasting as needed //------------------------------------------------------------------ GB_BURBLE_N (nvals, "generic ") ; // S (either S_work or S_input) must be permuted and copied into // T->x, since the tuples had to be sorted, or duplicates appear. // Any duplicates are now assembled. Not all of the 5 types are // the same, but all of them are built-in since user-defined types // cannot be typecasted. GB_cast_function cast_S_to_T = GB_cast_factory (tcode, scode) ; GB_cast_function cast_S_to_Y = GB_cast_factory (ycode, scode) ; GB_cast_function cast_T_to_X = GB_cast_factory (xcode, tcode) ; GB_cast_function cast_Z_to_T = GB_cast_factory (tcode, zcode) ; ASSERT (scode <= GB_FP64_code) ; ASSERT (tcode <= GB_FP64_code) ; ASSERT (xcode <= GB_FP64_code) ; ASSERT (ycode <= GB_FP64_code) ; ASSERT (zcode <= GB_FP64_code) ; // Tx [p] = (ttype) S [k], with typecasting #undef GB_CAST_ARRAY_TO_ARRAY #define GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ cast_S_to_T (Tx +((p)*tsize), S +((k)*ssize), ssize) ; if (op_2nd) { //-------------------------------------------------------------- // dup operator is the SECOND operator, with typecasting //-------------------------------------------------------------- // Tx [p] += (ttype) S [k], but 2nd op, with typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ GB_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) #include "GB_reduce_build_template.c" } else { //-------------------------------------------------------------- // dup is another operator, with typecasting required //-------------------------------------------------------------- // Tx [p] += S [k], with typecasting #undef GB_ADD_CAST_ARRAY_TO_ARRAY #define GB_ADD_CAST_ARRAY_TO_ARRAY(Tx,p,S,k) \ { \ /* ywork = (ytype) S [k] */ \ GB_void ywork [GB_VLA(ysize)] ; \ cast_S_to_Y (ywork, S +((k)*ssize), ssize) ; \ /* xwork = (xtype) Tx [p] */ \ GB_void xwork [GB_VLA(xsize)] ; \ cast_T_to_X (xwork, Tx +((p)*tsize), tsize) ; \ /* zwork = f (xwork, ywork) */ \ GB_void zwork [GB_VLA(zsize)] ; \ fdup (zwork, xwork, ywork) ; \ /* Tx [tnz-1] = (ttype) zwork */ \ cast_Z_to_T (Tx +((p)*tsize), zwork, zsize) ; \ } #include "GB_reduce_build_template.c" } } } //-------------------------------------------------------------------------- // free workspace and return result //-------------------------------------------------------------------------- GB_FREE_WORK ; ASSERT_MATRIX_OK (T, "T built", GB0) ; return (GrB_SUCCESS) ; }
transpose.h
// Copyright 2018 Xiaomi, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef MACE_KERNELS_TRANSPOSE_H_ #define MACE_KERNELS_TRANSPOSE_H_ #if defined(MACE_ENABLE_NEON) #include <arm_neon.h> #endif #include <vector> #include <algorithm> #include "mace/core/future.h" #include "mace/core/tensor.h" #include "mace/public/mace.h" #include "mace/utils/utils.h" namespace mace { namespace kernels { static void TransposeNHWCToNCHWC3(const float *input, float *output, const index_t height, const index_t width) { index_t image_size = height * width; #pragma omp parallel for for (index_t h = 0; h < height; ++h) { index_t in_offset = h * width * 3; index_t out_offset = h * width; #if defined(MACE_ENABLE_NEON) index_t w; for (w = 0; w + 3 < width; w += 4) { float32x4x3_t vi = vld3q_f32(input + in_offset); vst1q_f32(output + out_offset, vi.val[0]); vst1q_f32(output + out_offset + image_size, vi.val[1]); vst1q_f32(output + out_offset + image_size * 2, vi.val[2]); in_offset += 12; out_offset += 4; } for (; w < width; ++w) { for (index_t c = 0; c < 3; ++c) { output[h * width + image_size * c + w] = input[h * width * 3 + w * 3 + c]; } } #else for (index_t w = 0; w < width; ++w) { for (index_t c = 0; c < 3; ++c) { output[out_offset + c * image_size + w] = input[in_offset + w * 3 + c]; } } #endif } } static void TransposeNCHWToNHWCC2(const float *input, float *output, const index_t height, const index_t width) { index_t image_size = height * width; #pragma omp parallel for for (index_t h = 0; h < height; ++h) { index_t in_offset = h * width; index_t out_offset = h * width * 2; #if defined(MACE_ENABLE_NEON) index_t w; for (w = 0; w + 3 < width; w += 4) { float32x4_t vi0 = vld1q_f32(input + in_offset); float32x4_t vi1 = vld1q_f32(input + in_offset + image_size); float32x4x2_t vi = {vi0, vi1}; vst2q_f32(output + out_offset, vi); in_offset += 4; out_offset += 8; } for (; w < width; ++w) { for (index_t c = 0; c < 2; ++c) { output[h * width * 2 + w * 2 + c] = input[h * width + image_size * c + w]; } } #else for (index_t w = 0; w < width; ++w) { for (index_t c = 0; c < 2; ++c) { output[out_offset + w * 2 + c] = input[in_offset + c * image_size + w]; } } #endif } } template<DeviceType D, typename T> struct TransposeFunctor : OpKernel { TransposeFunctor(OpKernelContext *context, const std::vector<int> &dims) : OpKernel(context), dims_(dims) {} MaceStatus operator()(const Tensor *input, Tensor *output, StatsFuture *future) { MACE_UNUSED(future); Tensor::MappingGuard input_guard(input); Tensor::MappingGuard output_guard(output); const std::vector<index_t> &input_shape = input->shape(); const std::vector<index_t> &output_shape = output->shape(); const T *input_data = input->data<T>(); T *output_data = output->mutable_data<T>(); if (input->dim_size() == 2) { MACE_CHECK(dims_[0] == 1 && dims_[1] == 0, "no need transform"); index_t stride_i = input_shape[0]; index_t stride_j = input_shape[1]; index_t tile_size = input_shape[0] > 512 || input_shape[1] > 512 ? 64 : 32; #pragma omp parallel for collapse(2) for (index_t i = 0; i < input_shape[0]; i += tile_size) { for (index_t j = 0; j < input_shape[1]; j += tile_size) { index_t end_i = std::min(i + tile_size, input_shape[0]); index_t end_j = std::min(j + tile_size, input_shape[1]); for (index_t tile_i = i; tile_i < end_i; ++tile_i) { for (index_t tile_j = j; tile_j < end_j; ++tile_j) { output_data[tile_j * stride_i + tile_i] = input_data[tile_i * stride_j + tile_j]; } } } } } else if (input->dim_size() == 4) { std::vector<int> transpose_order_from_NHWC_to_NCHW{0, 3, 1, 2}; std::vector<int> transpose_order_from_NCHW_to_NHWC{0, 2, 3, 1}; index_t batch_size = input->dim(1) * input->dim(2) * input->dim(3); if (dims_ == transpose_order_from_NHWC_to_NCHW && input->dim(3) == 3) { for (index_t b = 0; b < input->dim(0); ++b) { TransposeNHWCToNCHWC3(input_data + b * batch_size, output_data + b * batch_size, input->dim(1), input->dim(2)); } } else if (dims_ == transpose_order_from_NCHW_to_NHWC && input->dim(1) == 2) { for (index_t b = 0; b < input->dim(0); ++b) { TransposeNCHWToNHWCC2(input_data + b * batch_size, output_data + b * batch_size, input->dim(2), input->dim(3)); } } else { std::vector<index_t> in_stride{input_shape[1] * input_shape[2] * input_shape[3], input_shape[2] * input_shape[3], input_shape[3], 1}; std::vector<index_t> out_stride{output_shape[1] * output_shape[2] * output_shape[3], output_shape[2] * output_shape[3], output_shape[3], 1}; std::vector<index_t> idim(4, 0); std::vector<index_t> odim(4, 0); for (odim[0] = 0; odim[0] < output_shape[0]; ++odim[0]) { for (odim[1] = 0; odim[1] < output_shape[1]; ++odim[1]) { for (odim[2] = 0; odim[2] < output_shape[2]; ++odim[2]) { for (odim[3] = 0; odim[3] < output_shape[3]; ++odim[3]) { idim[dims_[0]] = odim[0]; idim[dims_[1]] = odim[1]; idim[dims_[2]] = odim[2]; idim[dims_[3]] = odim[3]; output_data[odim[0] * out_stride[0] + odim[1] * out_stride[1] + odim[2] * out_stride[2] + odim[3]] = input_data[idim[0] * in_stride[0] + idim[1] * in_stride[1] + idim[2] * in_stride[2] + idim[3]]; } } } } } } else { MACE_NOT_IMPLEMENTED; } return MACE_SUCCESS; } std::vector<int> dims_; }; } // namespace kernels } // namespace mace #endif // MACE_KERNELS_TRANSPOSE_H_
gdal_metric_eta.c
#include<stdio.h> #include<omp.h> #include<math.h> #include "gdal.h" #include "metric_eta.h" #include "ogr_srs_api.h" #include "proj_api.h" void usage() { printf( "-----------------------------------------\n"); printf( "--Modis Processing chain--OpenMP code----\n"); printf( "-----------------------------------------\n"); printf( "./metric_eta inNdvi inLai inLst inAlb inDem\n"); printf( "\toutMetric_eta outMetric_evapfr outMetric_dtair outMetric_theta\n"); printf( "-----------------------------------------\n"); printf( "\tdoy Ta rh u z h eto_alf kc iteration\n"); printf( "\t[-mproj/-mcolrow/-mauto]\n"); printf( "\nBelow are wet/dry pixels modes\n"); printf( "---------------------------------------------\n"); printf( "-mproj projXwet ProjYwet projXdry projYdry\t Manual wet/dry pixel mode (projected)\n"); printf( "-mcolrow Xwet Ywet Xdry Ydry\t Manual wet/dry pixel mode (NOT projected)\n"); printf( "-mauto\t Automatic seek wet/dry pixel mode (Careful!)\n\n"); return; } int main( int argc, char *argv[] ) { if( argc < 18 ) { usage(); return 1; } int mproj=0, mcolrow=0, mauto=0; double projXwet,projYwet,projXdry,projYdry; double Xwet,Ywet,Xdry,Ydry; int col_wet, col_dry; int row_wet, row_dry; char *inB1 = argv[1]; //NDVI char *inB2 = argv[2]; //LAI char *inB3 = argv[3]; //LST char *inB4 = argv[4]; //ALBEDO char *inB5 = argv[5]; //DEM char *metric_etaF = argv[6]; char *metric_evapfrF = argv[7]; char *metric_dtairF = argv[8]; char *metric_thetaF = argv[9]; int doy = atoi(argv[10]); // Day Of Year [0-366] double ta = atof(argv[11]); // Air Temperature (K) double rh = atof(argv[12]); // Relative Humidity (-) double u = atof(argv[13]); // wind speed (m/s) at z height double z = atof(argv[14]); // z height (m) of anemometer double h = atof(argv[15]); // h (m) of vegetation under anemometer double eto_alf = atof(argv[16]); // Reference ET of Alfalfa double kc = atof(argv[17]); // Reference ET associated crop coefficient int iteration = atoi(argv[18]); // Iteration number for H //MDBA Farm A // double phase_max=sin(2*3.1415927*(doy+365/3.3)/365); // double tmax =31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_max); // double esat =6.11*exp(17.27*tmax/(tmax+237.3)); // double eact =rh*esat/100; // double phase_min=sin(2*3.1415927*(doy+365/3.5)/365); // double tmin =31.17+(36.9-24.1)/2*((1+1/3+1/5+1/7)*phase_min); // ta =tmin+(tmax-tmin)*0.8; double tsw=0; printf("NDVI=%s LAI=%s LST=%s ALBEDO=%s DEM=%s Out=%s\n",inB1,inB2,inB3,inB4,inB5,metric_etaF); printf("doy=%i Ta=%f u=%f z=%f h=%f eto_alf=%f kc=%f\n",doy,ta,u,z,h,eto_alf,kc); int c; for (c = 19; c <argc; c++) { // printf("argv[%i] = %s\n",c,argv[c]); /* Manual wet / dry input, projected */ if (!strcmp(argv[c],"-mproj")) { mproj=1; mcolrow=0; mauto=0; projXwet = atof( argv[c+1] ); projYwet = atof( argv[c+2] ); projXdry = atof( argv[c+3] ); projYdry = atof( argv[c+4] ); // printf("projXYwet=(%f,%f) projXYdry=(%f,%f)\n",projXwet,projYwet,projXdry,projYdry); } /* Manual wet / dry input row / col */ if (!strcmp(argv[c],"-mcolrow")) { mproj=0; mcolrow=1; mauto=0; col_wet = atoi( argv[c+1] ); row_wet = atoi( argv[c+2] ); col_dry = atoi( argv[c+3] ); row_dry = atoi( argv[c+4] ); } /* Automatic wet / dry input row / col */ if (!strcmp(argv[c],"-mauto")) { mproj=0; mcolrow=0; mauto=1; } } if (mproj==0 && mcolrow==0 && mauto==0){ printf("Choose a wet/dry pixel mode please\n"); exit(1); } GDALAllRegister(); GDALDatasetH hD1 = GDALOpen(inB1,GA_ReadOnly);//NDVI GDALDatasetH hD2 = GDALOpen(inB2,GA_ReadOnly);//LAI GDALDatasetH hD3 = GDALOpen(inB3,GA_ReadOnly);//LST GDALDatasetH hD4 = GDALOpen(inB4,GA_ReadOnly);//ALBEDO GDALDatasetH hD5 = GDALOpen(inB5,GA_ReadOnly);//DEM if(hD1==NULL||hD2==NULL||hD3==NULL ||hD4==NULL||hD5==NULL){ printf("One or more input files "); printf("could not be loaded\n"); exit(1); } char **options = NULL; options = CSLSetNameValue( options, "TILED", "YES" ); options = CSLSetNameValue( options, "COMPRESS", "DEFLATE" ); options = CSLSetNameValue( options, "PREDICTOR", "2" ); GDALDriverH hDr5 = GDALGetDatasetDriver(hD5); //Evapfr out GDALDatasetH hDOut0 = GDALCreateCopy( hDr5, metric_evapfrF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut0 = GDALGetRasterBand(hDOut0,1); //ETa out GDALDatasetH hDOut = GDALCreateCopy( hDr5, metric_etaF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut = GDALGetRasterBand(hDOut,1); //dTair out GDALDatasetH hDOut1 = GDALCreateCopy( hDr5, metric_dtairF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut1 = GDALGetRasterBand(hDOut1,1); //theta out GDALDatasetH hDOut2 = GDALCreateCopy( hDr5, metric_thetaF,hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBOut2 = GDALGetRasterBand(hDOut2,1); // //latitude temporary skeleton GDALDatasetH hDLat = GDALCreateCopy( hDr5, "latitude",hD5,FALSE,options,NULL,NULL); GDALRasterBandH hBLat = GDALGetRasterBand(hDLat,1); GDALRasterBandH hB1 = GDALGetRasterBand(hD1,1);//NDVI GDALRasterBandH hB2 = GDALGetRasterBand(hD2,1);//LAI GDALRasterBandH hB3 = GDALGetRasterBand(hD3,1);//LST GDALRasterBandH hB4 = GDALGetRasterBand(hD4,1);//ALBEDO GDALRasterBandH hB5 = GDALGetRasterBand(hD5,1);//DEM int nX = GDALGetRasterBandXSize(hB1); int nY = GDALGetRasterBandYSize(hB1); int N=nX*nY; float *mat1 = (float *) malloc(sizeof(float)*N); float *mat2 = (float *) malloc(sizeof(float)*N); float *mat3 = (float *) malloc(sizeof(float)*N); float *mat4 = (float *) malloc(sizeof(float)*N); float *mat5 = (float *) malloc(sizeof(float)*N); float *matOut2 = (float *) malloc(sizeof(float)*N); float *matOut1 = (float *) malloc(sizeof(float)*N); float *matOut0 = (float *) malloc(sizeof(float)*N); float *matOut = (float *) malloc(sizeof(float)*N); //Latitude matrix float *matLat = (float *) malloc(sizeof(float)*N); //tmp scanlines float *l1 = (float *) malloc(sizeof(float)*nX); float *l2 = (float *) malloc(sizeof(float)*nX); float *l3 = (float *) malloc(sizeof(float)*nX); float *l4 = (float *) malloc(sizeof(float)*nX); float *l5 = (float *) malloc(sizeof(float)*nX); float e0, kin, lin, lout, lnet, rnet, g_0, z_0m, h0 ; float metriceta, metricevapfr, metricdtair, pmeto, metrictheta; int i, row, col, rowcol; double a[10]={0.0}, b[10]={0.0}; // a = (double *) malloc(sizeof(double)*10); // b = (double *) malloc(sizeof(double)*10); // for (i=0;i<10;i++){ // a[i]=0.0; // b[i]=0.0; // } // printf("a[0]=%f\tb[0]=%f\n",a[0],b[0]); //Calculation of effective wind speed (initilasation of a unique point based ustar) float ustar_0 = ustar0(u, z, h); //Calculation of surface roughness of momentum z_0m=0.12*h; float u200 = ustar_0*log(200/z_0m)/0.41; //Calculation of aerodynamic resistance to heat flux momentum float rah_0 = rah0(ustar_0);//initialsation of rah calculation //Seed the wet and dry pixels variables double dem_wet=0,rnet_wet,g0_wet; double dem_dry=2000,rnet_dry,g0_dry; //LOAD DATA MATRICES //NDVI GDALRasterIO(hB1,GF_Read,0,0,nX,nY,mat1,nX,nY,GDT_Float32,0,0); //LAI GDALRasterIO(hB2,GF_Read,0,0,nX,nY,mat2,nX,nY,GDT_Float32,0,0); //LST GDALRasterIO(hB3,GF_Read,0,0,nX,nY,mat3,nX,nY,GDT_Float32,0,0); //ALBEDO GDALRasterIO(hB4,GF_Read,0,0,nX,nY,mat4,nX,nY,GDT_Float32,0,0); //DEM GDALRasterIO(hB5,GF_Read,0,0,nX,nY,mat5,nX,nY,GDT_Float32,0,0); // PROCESS DRY AND WET PIXELS //PROJ4 things for reproject lat/long pix into row/col projPJ proj4; projUV in, out; char *proj; char *pszWKT; OGRSpatialReferenceH hSRS; hSRS = OSRNewSpatialReference( NULL ); double coef; int temp; double geomx[6]={0.0}; double tempk_min, tempk_max; double t0dem_min, t0dem_max; double tempk_dry, tempk_wet; double t0dem_dry, t0dem_wet; double h_dry; double dailyN, t0dem, tadem; //LATITUDE MATRIX FILLING if((GDALGetProjectionRef( hD5 )) != NULL && strlen(GDALGetProjectionRef( hD5 ))>0){ pszWKT = (char *) GDALGetProjectionRef(hD5); printf( "Projection Info\n\t%s\n", pszWKT ); OSRImportFromWkt(hSRS, &pszWKT); OSRExportToProj4(hSRS, &proj); GDALGetGeoTransform(hD5,geomx); /* Do Nothing */ printf( "Origin (ULx,ULy) = (%.6f,%.6f)\n", geomx[0], geomx[3] ); printf( "Pixel Size = (%.6f,%.6f)\n", geomx[1], geomx[5] ); printf( "Rot0 = (%.6f,%.6f)\n", geomx[2], geomx[4] ); } else { printf("ERROR: Projection acquisition problem from SRTM\n"); exit(1); } // printf("Passed 2\n"); //if(pj_is_latlong(proj)){ for(row=0;row<nY;row++){ #pragma omp parallel for default(none) \ private(col) shared( row, geomx, nX, l1) for(col=0;col<nX;col++){ l1[col] = geomx[3]+geomx[4]*col+geomx[5]*row; } #pragma omp barrier GDALRasterIO(hBLat,GF_Write,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); } //LATITUDE MATRIX FILLING GDALRasterIO(hBLat,GF_Read,0,0,nX,nY,matLat,nX,nY,GDT_Float32,0,0); //} else { // printf("ERROR: Projection is NOT LAT/LONG\n"); // exit(1); //} //Accessing the data rowxrow if(mcolrow||mproj){ if(mcolrow){ row = row_dry; col = col_dry; } else if (mproj){ if((GDALGetProjectionRef( hD1 )) != NULL && strlen(GDALGetProjectionRef( hD1 ))>0){ pszWKT = (char *) GDALGetProjectionRef(hD1); // printf( "%s\n", pszWKT ); OSRImportFromWkt(hSRS, &pszWKT); OSRExportToProj4(hSRS, &proj); } proj4 = pj_init_plus(proj); if(pj_is_latlong(proj4)){ Xwet = projXwet; Ywet = projYwet; Xdry = projXdry; Ydry = projYdry; // printf("Xwet=%f Ywet=%f Xdry=%f Ydry=%f\n",Xwet,Ywet,Xdry,Ydry); }else{ //reproject wet pixels in.u = projXwet; in.v = projYwet; in.u *= DEG_TO_RAD; in.v *= DEG_TO_RAD; out = pj_inv(in, proj4); Xwet = out.u; Ywet = out.v; //reproject dry pixels in.u = projXdry; in.v = projYdry; in.u *= DEG_TO_RAD; in.v *= DEG_TO_RAD; out = pj_inv(in, proj4); Xdry = out.u; Ydry = out.v; } if(GDALGetGeoTransform(hD1,geomx)==CE_None){ /* Do Nothing */ // printf( "Origin (ULx,ULy) = (%.6f,%.6f)\n", geomx[0], geomx[3] ); // printf( "Pixel Size = (%.6f,%.6f)\n", geomx[1], geomx[5] ); // printf( "Rot0 = (%.6f,%.6f)\n", geomx[2], geomx[4] ); } else { printf("ERROR: Projection acquisition problem from Band1\n"); exit(1); } // printf( "Origin(ULx,ULy)= (%.6f,%.6f)\n", geomx[0], geomx[3] ); // printf( "Pixel Size= (%.6f,%.6f)\n", geomx[1], geomx[5] ); // printf( "Rot1= (%.6f,%.6f)\n", geomx[2], geomx[4] ); if(geomx[2]<=0.0001||(-geomx[4])<=0.0001){ col=(Xdry-geomx[0])/geomx[1]; row=(geomx[3]-Ydry)/(-geomx[5]); // printf("col1=%i row1=%i\n",col,row); }else { coef = geomx[5]/geomx[4]; // printf("coef_dry=%f\n",coef); col = (coef*Xdry-coef*geomx[0]-Ydry+geomx[3])/(coef*geomx[1]-geomx[2]); // printf("col=%i\n",col); row = (Xdry - (geomx[0] + geomx[1] * col))/geomx[2]; // printf("row=%i\n",row); } // projXdry = geomx[0] + geomx[1] * col_dry + geomx[2] * row_dry; // projYdry = geomx[3] + geomx[4] * col_dry + geomx[5] * row_dry; } /* Collect T0Dem_dry */ GDALRasterIO(hB3,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); tempk_dry = l1[col] * 0.02; GDALRasterIO(hB5,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); t0dem_dry = tempk_dry - 0.00625*l2[col] ; GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU tsw = 0.75 + 2 * pow(10,-5)*l5[col]; lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk_dry); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); //Net Radiation (Rnet = f(alb,lnet,kin) rnet_dry=Rnet(l4[col]*0.001,lnet,kin); //calculation of g_0 = f(rnet,lst,alb,ndvi) g0_dry=g0(rnet_dry,tempk_dry,l4[col]*0.001,l1[col]*0.0001); h_dry = rnet_dry - g0_dry ; row_dry=row; col_dry=col; if(mcolrow){ row = row_wet; col = col_wet; } else if (mproj){ if(geomx[2]<=0.0001||(-geomx[4])<=0.0001){ col=(Xwet-geomx[0])/geomx[1]; row=(geomx[3]-Ywet)/(-geomx[5]); // printf("col=%i row=%i\n",col,row); }else { coef = geomx[5]/geomx[4]; col = (coef*Xwet-coef*geomx[0]-Ywet+geomx[3])/(coef*geomx[1]-geomx[2]); row = (Xwet - (geomx[0] + geomx[1] * col))/geomx[2]; } // projXwet = geomx[0] + geomx[1] * col_wet + geomx[2] * row_wet; // projYwet = geomx[3] + geomx[4] * col_wet + geomx[5] * row_wet; } /* Collect T0Dem_wet */ GDALRasterIO(hB3,GF_Read,0,row,nX,1,l3,nX,1,GDT_Float32,0,0); tempk_wet = l3[col] * 0.02; GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); t0dem_wet = tempk_wet - 0.00625*l5[col] ; GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU tsw = 0.75 + 2 * pow(10,-5)*l5[col]; lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk_wet); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); //Net Radiation (Rnet = f(alb,lnet,kin) rnet_wet=Rnet(l4[col]*0.001,lnet,kin); //calculation of g0 = f(rnet,lst,alb,ndvi) g0_wet=g0(rnet_wet,tempk_wet,l4[col]*0.001,l1[col]*0.0001); row_wet=row; col_wet=col; } else { //--------------------------- // Dry/wet pixel AUTOMATIC seek //--------------------------- // printf("Started Heuristic\n"); tempk_min=400.0; tempk_max=0.0; t0dem_min=400.0; t0dem_max=0.0; col_dry = 0; row_dry = 0; col_wet = 0; row_wet = 0; /* Pick up wet and dry pixel values */ double h0, dem, albedo, t0dem, tempk ; double h0_min=1000.0; double h0_max=0.0; /*START Temperature minimum search */ /*This is correcting for un-Earthly temperatures*/ /*It finds when histogram is actually starting to pull up...*/ int peak1, peak2, peak3; int i_peak1, i_peak2, i_peak3; int bottom1a, bottom1b; int bottom2a, bottom2b; int bottom3a, bottom3b; int i_bottom1a, i_bottom1b; int i_bottom2a, i_bottom2b; int i_bottom3a, i_bottom3b; int histogramT[400]; for (i=0;i<400;i++){ histogramT[i]=0; } /****************************/ /* Process pixels histogram */ #pragma omp parallel for default(none) \ private(rowcol, temp)\ shared(N, mat3, mat5, histogramT) for(rowcol=0;rowcol<N;rowcol++){ temp = (int) (mat3[rowcol]*0.02-0.00625*mat5[rowcol]); if(temp>200||mat3[rowcol]!=-28768){ histogramT[temp]=histogramT[temp]+1.0; } } #pragma omp barrier // printf("Histogram of Temperature map"); // printf(" (if it has rogue values to clean)\n"); //int peak1, peak2, peak3; //int i_peak1, i_peak2, i_peak3; peak1=0; peak2=0; peak3=0; i_peak1=0; i_peak2=0; i_peak3=0; //int bottom1a, bottom1b; //int bottom2a, bottom2b; //int bottom3a, bottom3b; //int i_bottom1a, i_bottom1b; //int i_bottom2a, i_bottom2b; //int i_bottom3a, i_bottom3b; bottom1a=100000; bottom1b=100000; bottom2a=100000; bottom2b=100000; bottom3a=100000; bottom3b=100000; i_bottom1a=1000; i_bottom1b=1000; i_bottom2a=1000; i_bottom2b=1000; i_bottom3a=1000; i_bottom3b=1000; for(i=0;i<400;i++){ /* Search for highest peak of dataset (2) */ /* Highest Peak */ if(histogramT[i]>peak2){ peak2 = histogramT[i]; i_peak2=i; } } int stop=0; for(i=i_peak2;i>5;i--){ if(((histogramT[i]+histogramT[i-1]+histogramT[i-2]+histogramT[i-3]+histogramT[i-4])/5)<histogramT[i]&&stop==0){ bottom2a = histogramT[i]; i_bottom2a = i; } else if(((histogramT[i]+histogramT[i-1]+histogramT[i-2]+histogramT[i-3]+histogramT[i-4])/5)>histogramT[i]&&stop==0){ /*Search for peaks of datasets (1)*/ peak1 = histogramT[i]; i_peak1=i; stop=1; } } stop=0; for(i=i_peak2;i<395;i++){ if(((histogramT[i]+histogramT[i+1]+histogramT[i+2]+histogramT[i+3]+histogramT[i+4])/5)<histogramT[i]&&stop==0){ bottom2b = histogramT[i]; i_bottom2b = i; } else if(((histogramT[i]+histogramT[i+1]+histogramT[i+2]+histogramT[i+3]+histogramT[i+4])/5)>histogramT[i]&&stop==0){ /*Search for peaks of datasets (3)*/ peak3 = histogramT[i]; i_peak3=i; stop=1; } } /* First histogram lower bound */ for(i=250;i<i_peak1;i++){ if(histogramT[i]<bottom1a){ bottom1a = histogramT[i]; i_bottom1a = i; } } /* First histogram higher bound */ for(i=i_peak2;i>i_peak1;i--){ if(histogramT[i]<=bottom1b){ bottom1b = histogramT[i]; i_bottom1b = i; } } /* Third histogram lower bound */ for(i=i_peak2;i<i_peak3;i++){ if(histogramT[i]<bottom3a){ bottom3a = histogramT[i]; i_bottom3a = i; } } /* Third histogram higher bound */ for(i=399;i>i_peak3;i--){ if(histogramT[i]<bottom3b){ bottom3b = histogramT[i]; i_bottom3b = i; } } // printf("bottom1a: [%i]=>%i\n",i_bottom1a, bottom1a); // printf("peak1: [%i]=>%i\n",i_peak1, peak1); // printf("bottom1b: [%i]=>%i\n",i_bottom1b, bottom1b); // printf("bottom2a: [%i]=>%i\n",i_bottom2a, bottom2a); // printf("peak2: [%i]=>%i\n",i_peak2, peak2); // printf("bottom2b: [%i]=>%i\n",i_bottom2b, bottom2b); // printf("bottom3a: [%i]=>%i\n",i_bottom3a, bottom3a); // printf("peak3: [%i]=>%i\n",i_peak3, peak3); // printf("bottom3b: [%i]=>%i\n",i_bottom3b, bottom3b); rnet_dry=1000.0; dem_dry=2000.0; for(row=0;row<nY;row++){ //NDVI GDALRasterIO(hB1,GF_Read,0,row,nX,1,l1,nX,1,GDT_Float32,0,0); //LAI GDALRasterIO(hB2,GF_Read,0,row,nX,1,l2,nX,1,GDT_Float32,0,0); //LST GDALRasterIO(hB3,GF_Read,0,row,nX,1,l3,nX,1,GDT_Float32,0,0); //ALBEDO GDALRasterIO(hB4,GF_Read,0,row,nX,1,l4,nX,1,GDT_Float32,0,0); //DEM GDALRasterIO(hB5,GF_Read,0,row,nX,1,l5,nX,1,GDT_Float32,0,0); #pragma omp parallel for default(none) \ private(col, albedo, t0dem, tempk, dem, e0, lin, lout, lnet, kin, rnet, g_0, h0) \ shared(nX, row, geomx, tsw, doy, ta, t0dem_min, t0dem_max, tempk_min, tempk_max, \ tempk_wet, tempk_dry, t0dem_wet, t0dem_dry, \ g0_wet, g0_dry, rnet_wet, rnet_dry, dem_dry, \ row_wet, row_dry, col_wet, col_dry, h0_max, \ i_peak3, i_peak1, h0_min,\ l1, l2, l3, l4, l5) for(col=0;col<nX;col++){ if(l1[col]==-28768||l3[col]==-28768||l3[col]*0.02>200||l4[col]*0.001>0.001){ albedo = l4[col]*0.001; t0dem = l3[col]*0.02-0.00625*l5[col]; tempk = l3[col]*0.02; dem = l5[col]; // Surface emissivity calculations (e0=f(ndvi,lai)) e0=e_0(l1[col]*0.0001,l2[col]*0.1); // printf("e0=%f\n",e0); //Incoming longwave radiation (Lin). To be derived locally at CSU (AU) tsw = 0.75 + 2 * pow(10,-5) * l5[col]; //For Sri Lanka // tsw = 0.65 + 2 * pow(10,-5) * l5[col]; // printf("tsw=%f dem=%f\n", tsw, l5[col]); lin = Lin(tsw, ta); // printf("lin=%f\n", lin); //Outgoing longwave radiation (Lout=f(e0,lst)) lout=Lout(e0,tempk); // printf("lout=%f\n",lout); //Net longwave radiation (Lnet) lnet=Lnet(lout,lin); // printf("lnet=%f\n",lnet); //Solar shortwave incoming irradiance kin=Kin(doy,geomx[3]+geomx[4]*col+geomx[5]*row,tsw); // printf("lat=%f\n",geomx[3]+geomx[4]*col+geomx[5]*row); // printf("kin=%f\n",kin); //Net Radiation (Rnet = f(alb,lnet,kin) rnet=Rnet(l4[col]*0.001,lnet,kin); // printf("Alb=%f\n",l4[col]*0.001); // printf("rnet=%f\n",rnet); //calculation of g_0 = f(rnet,lst,alb,ndvi) g_0=g0(rnet,tempk,l4[col]*0.001,l1[col]*0.0001); // printf("g_0=%f\n",g_0); h0 = rnet - g_0; // printf("h0=%f\n",h0); if(t0dem>250&&t0dem<t0dem_min&&t0dem>274.0&&h0>0.0&&h0<h0_min&&g_0>0.0){ t0dem_min=t0dem; t0dem_wet=t0dem; tempk_min=tempk; tempk_wet=tempk; rnet_wet=rnet; g0_wet=g_0; h0_min=h0; col_wet=col; row_wet=row; } if(tempk>250&&tempk>=((double)i_peak1-5.0)&& tempk<((double)i_peak1+1.0)&&rnet>0.0&&albedo>0.1){ tempk_min=tempk; tempk_wet=tempk; t0dem_min=t0dem; t0dem_wet=t0dem; rnet_wet=rnet; g0_wet=g_0; h0_min=h0; col_wet=col; row_wet=row; } if(t0dem>t0dem_max&&rnet>0.0&&g_0>0.0&&dem<dem_dry&&rnet<rnet_dry){ t0dem_max=t0dem; t0dem_dry=t0dem; tempk_max=tempk; tempk_dry=tempk; rnet_dry=rnet; g0_dry=g_0; dem_dry=dem; col_dry=col; row_dry=row; } if(t0dem>=((double)i_peak3-0.0)&& t0dem<((double)i_peak3+7.0)&& h0>100.0&&h0>h0_max&& g_0>10.0&&rnet<rnet_dry&& albedo>0.35&&dem>0.0&&dem<dem_dry){ tempk_max=tempk; tempk_dry=tempk; t0dem_max=t0dem; t0dem_dry=t0dem; rnet_dry=rnet; g0_dry=g_0; h0_max=h0; dem_dry=dem; col_dry=col; row_dry=row; } }//END OF pafScanlineOut2 > 0.0 } #pragma omp barrier } printf("tempk_min=%f\ntempk_max=%f\n",tempk_min,tempk_max); } printf("row_wet=%d\tcol_wet=%d\n",row_wet,col_wet); printf("row_dry=%d\tcol_dry=%d\n\n",row_dry,col_dry); printf("t0dem_wet = %f\n",t0dem_wet); printf("tempk_wet=%f\n",tempk_wet); printf("g0_wet=%f\n",g0_wet); printf("rnet_wet=%f\n",rnet_wet); printf("LE_wet=%f\n\n",rnet_wet-g0_wet); printf("tempk_dry=%f\n",tempk_dry); printf("dem_dry=%f\n",dem_dry); printf("t0dem_dry=%f\n",t0dem_dry); printf("rnet_dry=%f\n",rnet_dry); printf("g0_dry=%f\n",g0_dry); // calculation of dTair (spreadsheet calculations) dTair(a,b,eto_alf,kc,dem_wet,t0dem_wet,rnet_wet,g0_wet,dem_dry,t0dem_dry,rnet_dry,g0_dry); // printf("***OUT***a[0]=%f\tb[0]=%f\n",a[0],b[0]); // PROCESS METRIC #pragma omp parallel for default(none) \ private(rowcol, e0, tsw, lin, lout, lnet, kin, \ rnet, g_0, z_0m, h0, t0dem, tadem, pmeto, dailyN, \ metricevapfr, metriceta, metricdtair, metrictheta)\ shared(N, rh, u, a, b, doy, ta, u200, rah_0, ustar_0, iteration, \ mat1, mat2, mat3, mat4, mat5, matOut2, matOut1, matOut0, matOut, matLat ) for(rowcol=0;rowcol<N;rowcol++){ if(mat1[rowcol]==-28768||mat3[rowcol]==-28768||mat4[rowcol]<=0|| mat3[rowcol]*0.02<250.0||mat3[rowcol]*0.02>360.0) { matOut[rowcol] = -28768; matOut0[rowcol] = -28768; matOut1[rowcol] = -28768; } else { // METRIC ETa (Allen, 2005) // Surface emissivity calculations (e0=f(ndvi,lai)) e0 = e_0(mat1[rowcol]*0.0001,mat2[rowcol]*0.1); //Incoming longwave radiation (Lin). To be derived locally at CSU //tsw=0.7;//Colombo? tsw = 0.75 + 2 * pow(10,-5)*mat5[rowcol]; lin = Lin(tsw, ta); //Outgoing longwave radiation (Lout=f(e0,lst)) lout = Lout(e0,mat3[rowcol]*0.02); // printf("lout=%f\n",lout); //Net longwave radiation (Lnet) lnet = Lnet(lout,lin); // printf("lnet=%f\n",lnet); //Solar shortwave incoming irradiance kin = Kin(doy,matLat[rowcol],tsw); // printf("kin=%f\n",kin); //Net Radiation (Rnet = f(alb,lnet,kin) rnet = Rnet(mat4[rowcol]*0.001,lnet,kin); // printf("rnet=%f\n",rnet); //calculation of g_0 = f(rnet,lst,alb,ndvi) g_0 = g0(rnet,mat3[rowcol]*0.02,mat4[rowcol]*0.001,mat1[rowcol]*0.0001); // printf("g_0=%f\n",g_0); //Calculation of surface roughness of momentum = f(lai) z_0m = z0m(mat2[rowcol]*0.01); // printf("z_0m=%f\n",z_0m); //Sensible Heat flux Calculations // printf("a[7]=%f,b[7]=%f,mat3*0.02=%f,rah_0=%f,z_0m=%f,ustar_0=%f,mat5=%f,u200=%f\n",a[7],b[7],mat3[rowcol]*0.02,rah_0,z_0m,ustar_0,mat5[rowcol],u200); h0 = metiter(a,b,mat3[rowcol]*0.02,rah_0,z_0m,ustar_0,mat5[rowcol],u200,iteration); // printf("h0=%f\n",h0); dailyN = daily_N(doy, matLat[rowcol]); t0dem = mat3[rowcol]*0.02-0.00625*mat5[rowcol]; tadem = t0dem-(a[iteration]*t0dem+b[iteration]); //Export dTair to raster file metricdtair = (a[iteration]*mat3[rowcol]*0.02)+b[iteration]; matOut1[rowcol] = metricdtair; //ETinst metriceta = ETinst(rnet,g_0,h0,tadem); matOut[rowcol] = metriceta; // printf("eta=%f\t",metriceta); pmeto = EToPM( mat3[rowcol]*0.02, mat5[rowcol], u, rnet*0.0864, rh, 0.6, dailyN); // printf("pmeto=%f\t",pmeto); metricevapfr = metriceta / pmeto; // printf("metricevapfr=%f\n",metricevapfr); if(metricevapfr < 0.0) matOut0[rowcol] = -28768; else matOut0[rowcol] = metricevapfr; if(metricevapfr < 0.0) metrictheta = -28768; else metrictheta = soilmoisture(metricevapfr); matOut2[rowcol] = metrictheta; } } #pragma omp barrier GDALRasterIO(hBOut2,GF_Write,0,0,nX,nY,matOut2,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut1,GF_Write,0,0,nX,nY,matOut1,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut0,GF_Write,0,0,nX,nY,matOut0,nX,nY,GDT_Float32,0,0); GDALRasterIO(hBOut,GF_Write,0,0,nX,nY,matOut,nX,nY,GDT_Float32,0,0); //free memory close unused files if(mat1 != NULL) free(mat1); if(mat2 != NULL) free(mat2); if(mat3 != NULL) free(mat3); if(mat4 != NULL) free(mat4); if(mat5 != NULL) free(mat5); if(matOut2 != NULL) free(matOut2); if(matOut1 != NULL) free(matOut1); if(matOut0 != NULL) free(matOut0); if(matOut != NULL) free(matOut); if(matLat != NULL) free(matLat); GDALClose(hD1); GDALClose(hD2); GDALClose(hD3); GDALClose(hD4); GDALClose(hD5); GDALClose(hDOut2); GDALClose(hDOut1); GDALClose(hDOut0); GDALClose(hDOut); GDALClose(hDLat); return(EXIT_SUCCESS); }
HSSGEMM.h
// // Created by Bangtian Liu on 8/23/19. // #ifndef PROJECT_HSSGEMM_H #define PROJECT_HSSGEMM_H #include <stdint.h> #include <mkl.h> #include <stdio.h> inline float float_from_bits(uint32_t bits) { union { uint32_t as_uint; float as_float; } u; u.as_uint = bits; return u.as_float; } int32_t seqHSSGEMM(double *D, double *B, double *VT, uint64_t *Dptr, uint64_t *Bptr, int32_t *VTptr, int32_t *lchildren, int32_t *rchildren, int32_t *levelset, int32_t *idx, double *mrhs, double *apres, int32_t nrhs, int32_t *Ddim, int32_t *wptr, int32_t *uptr, double *wskel, int32_t *wskeloffset, double *uskel, int32_t *uskeloffset, int32_t *lm, int32_t *slen, int32_t ncount, int32_t fcount, int32_t depth) { //#pragma omp parallel for for (int i = 0; i < ncount; i++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ddim[i],nrhs,Ddim[i], float_from_bits(1065353216 /* 1 */), &D[Dptr[i]], Ddim[i], &mrhs[wptr[i]], Ddim[i], float_from_bits(0 /* 0 */), &apres[uptr[i]], Ddim[i]); } // for i for (int i = depth-1; i >-1; i--) { int32_t _0 = i + 1; //#pragma omp parallel for for (int j = levelset[i]; j < levelset[_0]; j++) { // int32_t _1 = k + 1; // for (int j = wpart[k]; j < wpart[_1]; j++) // { // printf("idx=%d\n",idx[j]); int32_t _2 = (int32_t)(4294967295); bool _3 = lchildren[idx[j]] == _2; if (_3) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,Ddim[lm[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &mrhs[wptr[lm[idx[j]]]], Ddim[lm[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[lchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &wskel[wskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); int32_t _4 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _5 = _4 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[_5], slen[idx[j]], &wskel[wskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else // } // for j } // for k } // for i uint32_t _6 = (uint32_t)(1); uint32_t _7 = (uint32_t)(fcount); //#pragma omp parallel for for (int i = _6; i < _7+1; i++) { uint32_t _8 = (uint32_t)(1); int32_t _9 = i - _8; int32_t _10 = i + _8; int32_t _11 = i & 1; uint32_t _12 = (uint32_t)(0); bool _13 = _11 == _12; int32_t _14 = (int32_t)(_13 ? _9 : _10); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[i],nrhs,slen[_14], _8, &B[Bptr[_9]], slen[i], &wskel[wskeloffset[_14]], slen[_14], _12, &uskel[uskeloffset[i]], slen[i]); } // for i // int32_t _15 = 0 - 1; // int32_t _16 = depth - 1; for (int i = 0; i < depth; i++) { int32_t _17 = i + 1; //#pragma omp parallel for for (int j = levelset[i]; j < levelset[_17]; j++) { // int32_t _18 = wpart[k] - 1; // int32_t _19 = k + 1; // int32_t _20 = wpart[_19] - 1; // for (int j = _20; j > _18; j--) // { int32_t _21 = (int32_t)(4294967295); bool _22 = lchildren[idx[j]] == _21; if (_22) { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, Ddim[lm[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &apres[uptr[lm[idx[j]]]], Ddim[lm[idx[j]]]); } // if _22 else { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[lchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]]); int32_t _23 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _24 = _23 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[rchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[_24], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]]); } // if _22 else // } // for j } // for k } // for i return 0; } int32_t parHSSGEMM(double *D, double *B, double *VT, uint64_t *Dptr, uint64_t *Bptr, int32_t *VTptr, int32_t *lchildren, int32_t *rchildren, int32_t *levelset, int32_t *idx, double *mrhs, double *apres, int32_t nrhs, int32_t *Ddim, int32_t *wptr, int32_t *uptr, double *wskel, int32_t *wskeloffset, double *uskel, int32_t *uskeloffset, int32_t *lm, int32_t *slen, int32_t *wpart, int32_t *clevelset, int ncount, int fcount, int cdepth) { mkl_set_dynamic(false); #pragma omp parallel for for (int i = 0; i < ncount; i++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ddim[i],nrhs,Ddim[i], float_from_bits(1065353216 /* 1 */), &D[Dptr[i]], Ddim[i], &mrhs[wptr[i]], Ddim[i], float_from_bits(0 /* 0 */), &apres[uptr[i]], Ddim[i]); } // for i for (int i = 0; i < cdepth; i++) { int32_t _0 = i + 1; #pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_0]; k++) { int32_t _1 = k + 1; for (int j = wpart[k]; j < wpart[_1]; j++) { int32_t _2 = (int32_t)(4294967295); bool _3 = lchildren[idx[j]] == _2; if (_3) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,Ddim[lm[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &mrhs[wptr[lm[idx[j]]]], Ddim[lm[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[lchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &wskel[wskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); int32_t _4 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _5 = _4 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[_5], slen[idx[j]], &wskel[wskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else } // for j } // for k } // for i uint32_t _6 = (uint32_t)(1); uint32_t _7 = (uint32_t)(fcount+1); #pragma omp parallel for for (int i = _6; i < _7; i++) { uint32_t _8 = (uint32_t)(1); int32_t _9 = i - _8; int32_t _10 = i + _8; int32_t _11 = i & 1; uint32_t _12 = (uint32_t)(0); bool _13 = _11 == _12; int32_t _14 = (int32_t)(_13 ? _9 : _10); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[i],nrhs,slen[_14], _8, &B[Bptr[_9]], slen[i], &wskel[wskeloffset[_14]], slen[_14], _12, &uskel[uskeloffset[i]], slen[i]); } // for i for (int i = cdepth-1; i > -1; i--) { int32_t _17 = i + 1; #pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_17]; k++) { int32_t _18 = wpart[k] - 1; int32_t _19 = k + 1; int32_t _20 = wpart[_19] - 1; for (int j = _20; j > _18; j--) { int32_t _21 = (int32_t)(4294967295); bool _22 = lchildren[idx[j]] == _21; if (_22) { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, Ddim[lm[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &apres[uptr[lm[idx[j]]]], Ddim[lm[idx[j]]]); } // if _22 else { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[lchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]]); int32_t _23 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _24 = _23 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[rchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[_24], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]]); } // if _22 else } // for j } // for k } // for i } int32_t lowHSSGEMM(double *D, double *B, double *VT, uint64_t *Dptr, uint64_t *Bptr, int32_t *VTptr, int32_t *lchildren, int32_t *rchildren, int32_t *levelset, int32_t *idx, double *mrhs, double *apres, int32_t nrhs, int32_t *Ddim, int32_t *wptr, int32_t *uptr, double *wskel, int32_t *wskeloffset, double *uskel, int32_t *uskeloffset, int32_t *lm, int32_t *slen, int32_t *wpart, int32_t *clevelset, int ncount, int fcount, int cdepth) { int nstop = ncount/12*12; #pragma omp parallel for for (int i = 0; i < nstop; i++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ddim[i],nrhs,Ddim[i], float_from_bits(1065353216 /* 1 */), &D[Dptr[i]], Ddim[i], &mrhs[wptr[i]], Ddim[i], float_from_bits(0 /* 0 */), &apres[uptr[i]], Ddim[i]); } // for i mkl_set_dynamic(true); mkl_set_num_threads(12); if(nstop<ncount){ for (int i = nstop; i < ncount; i++) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, Ddim[i],nrhs,Ddim[i], float_from_bits(1065353216 /* 1 */), &D[Dptr[i]], Ddim[i], &mrhs[wptr[i]], Ddim[i], float_from_bits(0 /* 0 */), &apres[uptr[i]], Ddim[i]); } // for i } #pragma omp parallel for for(int k = clevelset[0]; k<clevelset[1]; k++) { for(int j = wpart[k]; j<wpart[k+1]; j++) { int32_t _2 = (int32_t)(4294967295); bool _3 = lchildren[idx[j]] == _2; if (_3) { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,Ddim[lm[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &mrhs[wptr[lm[idx[j]]]], Ddim[lm[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[lchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &wskel[wskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); int32_t _4 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _5 = _4 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[_5], slen[idx[j]], &wskel[wskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else } } for (int i = 1; i < cdepth-2; i++) { int32_t _0 = i + 1; #pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_0]; k++) { int32_t _1 = k + 1; for (int j = wpart[k]; j < wpart[_1]; j++) { { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[lchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &wskel[wskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); int32_t _4 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _5 = _4 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[_5], slen[idx[j]], &wskel[wskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else } // for j } // for k } // for i mkl_set_num_threads(12); for (int i = cdepth-2; i < cdepth; i++) { int32_t _0 = i + 1; //#pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_0]; k++) { int32_t _1 = k + 1; for (int j = wpart[k]; j < wpart[_1]; j++) { { cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[lchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &wskel[wskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]], float_from_bits(0 /* 0 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); int32_t _4 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _5 = _4 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[idx[j]],nrhs,slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &VT[_5], slen[idx[j]], &wskel[wskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]], float_from_bits(1065353216 /* 1 */), &wskel[wskeloffset[idx[j]]], slen[idx[j]]); } // if _3 else } // for j } // for k } // for i int _6 = (1); int fc = fcount/12*12; // int rfc = fcount - fc; int _61 = _6 + fc; int _7 = (fcount+1); #pragma omp parallel for for (int i = _6; i < _61; i++) { uint32_t _8 = (uint32_t)(1); int32_t _9 = i - _8; int32_t _10 = i + _8; int32_t _11 = i & 1; uint32_t _12 = (uint32_t)(0); bool _13 = _11 == _12; int32_t _14 = (int32_t)(_13 ? _9 : _10); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[i],nrhs,slen[_14], _8, &B[Bptr[_9]], slen[i], &wskel[wskeloffset[_14]], slen[_14], _12, &uskel[uskeloffset[i]], slen[i]); } // for i mkl_set_num_threads(12); for(int i=_61; i<_7; i++) { int32_t _8 = (int32_t)(1); int32_t _9 = i - _8; int32_t _10 = i + _8; int32_t _11 = i & 1; int32_t _12 = (int32_t)(0); bool _13 = _11 == _12; int32_t _14 = (int32_t)(_13 ? _9 : _10); cblas_dgemm(CblasColMajor, CblasNoTrans, CblasNoTrans, slen[i],nrhs,slen[_14], _8, &B[Bptr[_9]], slen[i], &wskel[wskeloffset[_14]], slen[_14], _12, &uskel[uskeloffset[i]], slen[i]); } for (int i = cdepth-1; i > cdepth-3; i--) { int32_t _17 = i + 1; //#pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_17]; k++) { int32_t _18 = wpart[k] - 1; int32_t _19 = k + 1; int32_t _20 = wpart[_19] - 1; for (int j = _20; j > _18; j--) { // int32_t _21 = (int32_t)(4294967295); // bool _22 = lchildren[idx[j]] == _21; // if (_22) // { // cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, // Ddim[lm[idx[j]]],nrhs,slen[idx[j]], // float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], // slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), // &apres[uptr[lm[idx[j]]]], Ddim[lm[idx[j]]]); // } // if _22 // else { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[lchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]]); int32_t _23 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _24 = _23 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[rchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[_24], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]]); } // if _22 else } // for j } // for k } // for i for (int i = cdepth-3; i > 0; i--) { int32_t _17 = i + 1; #pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_17]; k++) { int32_t _18 = wpart[k] - 1; int32_t _19 = k + 1; int32_t _20 = wpart[_19] - 1; for (int j = _20; j > _18; j--) { // int32_t _21 = (int32_t)(4294967295); // bool _22 = lchildren[idx[j]] == _21; // if (_22) // { // cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, // Ddim[lm[idx[j]]],nrhs,slen[idx[j]], // float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], // slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), // &apres[uptr[lm[idx[j]]]], Ddim[lm[idx[j]]]); // } // if _22 // else { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[lchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]]); int32_t _23 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _24 = _23 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[rchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[_24], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]]); } // if _22 else } // for j } // for k } // for i for (int i = 0; i > -1; i--) { int32_t _17 = i + 1; #pragma omp parallel for for (int k = clevelset[i]; k < clevelset[_17]; k++) { int32_t _18 = wpart[k] - 1; int32_t _19 = k + 1; int32_t _20 = wpart[_19] - 1; for (int j = _20; j > _18; j--) { int32_t _21 = (int32_t)(4294967295); bool _22 = lchildren[idx[j]] == _21; if (_22) { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, Ddim[lm[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &apres[uptr[lm[idx[j]]]], Ddim[lm[idx[j]]]); } // if _22 else { cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[lchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[VTptr[idx[j]]], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[lchildren[idx[j]]]], slen[lchildren[idx[j]]]); int32_t _23 = slen[idx[j]] * slen[lchildren[idx[j]]]; int32_t _24 = _23 + VTptr[idx[j]]; cblas_dgemm(CblasColMajor, CblasTrans, CblasNoTrans, slen[rchildren[idx[j]]],nrhs,slen[idx[j]], float_from_bits(1065353216 /* 1 */), &VT[_24], slen[idx[j]], &uskel[uskeloffset[idx[j]]], slen[idx[j]], float_from_bits(1065353216 /* 1 */), &uskel[uskeloffset[rchildren[idx[j]]]], slen[rchildren[idx[j]]]); } // if _22 else } // for j } // for k } // for i return 0; } #endif //PROJECT_HSSGEMM_H
convolution_sgemm_pack8to1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2022 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 im2col_sgemm_pack8to1_avx(const Mat& bottom_im2col, Mat& top_blob, const Mat& kernel, const Mat& _bias, const Option& opt) { // Mat bottom_im2col(size, maxk, inch, 4u * 8, 8, opt.workspace_allocator); const int size = bottom_im2col.w; const int maxk = bottom_im2col.h; const int inch = bottom_im2col.c; const int outch = top_blob.c; const float* bias = _bias; Mat tmp; if (size >= 8) tmp.create(8 * maxk, inch, size / 8 + size % 8, 4u * 8, 8, opt.workspace_allocator); else tmp.create(maxk, inch, size, 4u * 8, 8, opt.workspace_allocator); { int remain_size_start = 0; int nn_size = size >> 3; #pragma omp parallel for num_threads(opt.num_threads) for (int ii = 0; ii < nn_size; ii++) { int i = ii * 8; float* tmpptr = tmp.channel(i / 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { // transpose 8x8 __m256 _r0 = _mm256_load_ps(img0); __m256 _r1 = _mm256_load_ps(img0 + 8); __m256 _r2 = _mm256_load_ps(img0 + 8 * 2); __m256 _r3 = _mm256_load_ps(img0 + 8 * 3); __m256 _r4 = _mm256_load_ps(img0 + 8 * 4); __m256 _r5 = _mm256_load_ps(img0 + 8 * 5); __m256 _r6 = _mm256_load_ps(img0 + 8 * 6); __m256 _r7 = _mm256_load_ps(img0 + 8 * 7); __m256 _tmp0 = _mm256_unpacklo_ps(_r0, _r1); __m256 _tmp1 = _mm256_unpackhi_ps(_r0, _r1); __m256 _tmp2 = _mm256_unpacklo_ps(_r2, _r3); __m256 _tmp3 = _mm256_unpackhi_ps(_r2, _r3); __m256 _tmp4 = _mm256_unpacklo_ps(_r4, _r5); __m256 _tmp5 = _mm256_unpackhi_ps(_r4, _r5); __m256 _tmp6 = _mm256_unpacklo_ps(_r6, _r7); __m256 _tmp7 = _mm256_unpackhi_ps(_r6, _r7); __m256 _tmp8 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmp9 = _mm256_shuffle_ps(_tmp0, _tmp2, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpa = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpb = _mm256_shuffle_ps(_tmp1, _tmp3, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpc = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpd = _mm256_shuffle_ps(_tmp4, _tmp6, _MM_SHUFFLE(3, 2, 3, 2)); __m256 _tmpe = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(1, 0, 1, 0)); __m256 _tmpf = _mm256_shuffle_ps(_tmp5, _tmp7, _MM_SHUFFLE(3, 2, 3, 2)); _r0 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 2, 0, 0)); _r1 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 2, 0, 0)); _r2 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 2, 0, 0)); _r3 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 2, 0, 0)); _r4 = _mm256_permute2f128_ps(_tmp8, _tmpc, _MM_SHUFFLE(0, 3, 0, 1)); _r5 = _mm256_permute2f128_ps(_tmp9, _tmpd, _MM_SHUFFLE(0, 3, 0, 1)); _r6 = _mm256_permute2f128_ps(_tmpa, _tmpe, _MM_SHUFFLE(0, 3, 0, 1)); _r7 = _mm256_permute2f128_ps(_tmpb, _tmpf, _MM_SHUFFLE(0, 3, 0, 1)); _mm256_store_ps(tmpptr, _r0); _mm256_store_ps(tmpptr + 8, _r1); _mm256_store_ps(tmpptr + 8 * 2, _r2); _mm256_store_ps(tmpptr + 8 * 3, _r3); _mm256_store_ps(tmpptr + 8 * 4, _r4); _mm256_store_ps(tmpptr + 8 * 5, _r5); _mm256_store_ps(tmpptr + 8 * 6, _r6); _mm256_store_ps(tmpptr + 8 * 7, _r7); img0 += size * 8; tmpptr += 64; } } } remain_size_start += nn_size << 3; #pragma omp parallel for num_threads(opt.num_threads) for (int i = remain_size_start; i < size; i++) { float* tmpptr = tmp.channel(i / 8 + i % 8); for (int q = 0; q < inch; q++) { const float* img0 = (const float*)bottom_im2col.channel(q) + i * 8; for (int k = 0; k < maxk; k++) { __m256 _val = _mm256_load_ps(img0); _mm256_store_ps(tmpptr, _val); img0 += size * 8; tmpptr += 8; } } } } int nn_outch = outch / 8; int remain_outch_start = nn_outch * 8; #pragma omp parallel for num_threads(opt.num_threads) for (int pp = 0; pp < nn_outch; pp++) { int p = pp * 8; float* outptr0 = top_blob.channel(p); float* outptr1 = top_blob.channel(p + 1); float* outptr2 = top_blob.channel(p + 2); float* outptr3 = top_blob.channel(p + 3); float* outptr4 = top_blob.channel(p + 4); float* outptr5 = top_blob.channel(p + 5); float* outptr6 = top_blob.channel(p + 6); float* outptr7 = top_blob.channel(p + 7); const float zeros[8] = {0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f, 0.f}; const float* biasptr = bias ? bias + p : zeros; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); const float* kptr0 = kernel.channel(p / 8); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_broadcast_ss(biasptr); __m256 _sum1 = _mm256_broadcast_ss(biasptr + 1); __m256 _sum2 = _mm256_broadcast_ss(biasptr + 2); __m256 _sum3 = _mm256_broadcast_ss(biasptr + 3); __m256 _sum4 = _mm256_broadcast_ss(biasptr + 4); __m256 _sum5 = _mm256_broadcast_ss(biasptr + 5); __m256 _sum6 = _mm256_broadcast_ss(biasptr + 6); __m256 _sum7 = _mm256_broadcast_ss(biasptr + 7); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_load_ps(tmpptr); __m256 _w0 = _mm256_broadcast_ss(kptr0); __m256 _w1 = _mm256_broadcast_ss(kptr0 + 1); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); _sum1 = _mm256_comp_fmadd_ps(_val0, _w1, _sum1); __m256 _w2 = _mm256_broadcast_ss(kptr0 + 2); __m256 _w3 = _mm256_broadcast_ss(kptr0 + 3); _sum2 = _mm256_comp_fmadd_ps(_val0, _w2, _sum2); _sum3 = _mm256_comp_fmadd_ps(_val0, _w3, _sum3); __m256 _w4 = _mm256_broadcast_ss(kptr0 + 4); __m256 _w5 = _mm256_broadcast_ss(kptr0 + 5); _sum4 = _mm256_comp_fmadd_ps(_val0, _w4, _sum4); _sum5 = _mm256_comp_fmadd_ps(_val0, _w5, _sum5); __m256 _w6 = _mm256_broadcast_ss(kptr0 + 6); __m256 _w7 = _mm256_broadcast_ss(kptr0 + 7); _sum6 = _mm256_comp_fmadd_ps(_val0, _w6, _sum6); _sum7 = _mm256_comp_fmadd_ps(_val0, _w7, _sum7); tmpptr += 8; kptr0 += 8; } _mm256_storeu_ps(outptr0, _sum0); _mm256_storeu_ps(outptr1, _sum1); _mm256_storeu_ps(outptr2, _sum2); _mm256_storeu_ps(outptr3, _sum3); _mm256_storeu_ps(outptr4, _sum4); _mm256_storeu_ps(outptr5, _sum5); _mm256_storeu_ps(outptr6, _sum6); _mm256_storeu_ps(outptr7, _sum7); outptr0 += 8; outptr1 += 8; outptr2 += 8; outptr3 += 8; outptr4 += 8; outptr5 += 8; outptr6 += 8; outptr7 += 8; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + i % 8); const float* kptr0 = kernel.channel(p / 8); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum = _mm256_loadu_ps(biasptr); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_broadcast_ss(tmpptr); __m256 _w0 = _mm256_load_ps(kptr0); _sum = _mm256_comp_fmadd_ps(_val0, _w0, _sum); tmpptr += 1; kptr0 += 8; } float sum[8]; _mm256_storeu_ps(sum, _sum); outptr0[0] = sum[0]; outptr1[0] = sum[1]; outptr2[0] = sum[2]; outptr3[0] = sum[3]; outptr4[0] = sum[4]; outptr5[0] = sum[5]; outptr6[0] = sum[6]; outptr7[0] = sum[7]; outptr0 += 1; outptr1 += 1; outptr2 += 1; outptr3 += 1; outptr4 += 1; outptr5 += 1; outptr6 += 1; outptr7 += 1; } } #pragma omp parallel for num_threads(opt.num_threads) for (int p = remain_outch_start; p < outch; p++) { float* outptr0 = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; int i = 0; for (; i + 7 < size; i += 8) { const float* tmpptr = tmp.channel(i / 8); const float* kptr0 = kernel.channel(p / 8 + p % 8); int nn = inch * maxk * 8; // inch always > 0 __m256 _sum0 = _mm256_set1_ps(bias0); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_load_ps(tmpptr); __m256 _w0 = _mm256_broadcast_ss(kptr0); _sum0 = _mm256_comp_fmadd_ps(_w0, _val0, _sum0); tmpptr += 8; kptr0 += 1; } _mm256_storeu_ps(outptr0, _sum0); outptr0 += 8; } for (; i < size; i++) { const float* tmpptr = tmp.channel(i / 8 + i % 8); const float* kptr0 = kernel.channel(p / 8 + p % 8); int nn = inch * maxk; // inch always > 0 float sum0 = bias0; __m256 _sum0 = _mm256_setzero_ps(); for (int j = 0; j < nn; j++) { __m256 _val0 = _mm256_load_ps(tmpptr); __m256 _w0 = _mm256_load_ps(kptr0); _sum0 = _mm256_comp_fmadd_ps(_val0, _w0, _sum0); tmpptr += 8; kptr0 += 8; } sum0 += _mm256_reduce_add_ps(_sum0); outptr0[0] = sum0; outptr0 += 1; } } } static void convolution_im2col_sgemm_transform_kernel_pack8to1_avx(const Mat& _kernel, Mat& kernel_tm, int inch, int outch, int kernel_w, int kernel_h) { const int maxk = kernel_w * kernel_h; // interleave // src = maxk-inch-outch // dst = pb-pa-maxk-inch/pa-outch/pb Mat kernel = _kernel.reshape(maxk, inch, outch); kernel_tm.create(8 * 8 * maxk, inch / 8, outch / 8 + outch % 8); int q = 0; for (; q + 7 < outch; q += 8) { float* g00 = kernel_tm.channel(q / 8); for (int p = 0; p + 7 < inch; p += 8) { for (int k = 0; k < maxk; k++) { for (int i = 0; i < 8; i++) { for (int j = 0; j < 8; j++) { const float* k00 = kernel.channel(q + j).row(p + i); g00[0] = k00[k]; g00++; } } } } } for (; q < outch; q++) { const Mat k0 = kernel.channel(q); float* g00 = kernel_tm.channel(q / 8 + q % 8); for (int p = 0; p + 7 < inch; p += 8) { for (int k = 0; k < maxk; k++) { for (int j = 0; j < 8; j++) { const float* k00 = k0.row(p + j); g00[0] = k00[k]; g00++; } } } } } static void convolution_im2col_sgemm_pack8to1_avx(const Mat& bottom_blob, Mat& top_blob, const Mat& kernel, const Mat& _bias, int kernel_w, int kernel_h, int dilation_w, int dilation_h, int stride_w, int stride_h, const Option& opt) { int w = bottom_blob.w; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; const int size = outw * outh; const int maxk = kernel_w * kernel_h; // im2col Mat bottom_im2col(size, maxk, inch, 4u * 8, 8, opt.workspace_allocator); { const int gap = (w * stride_h - outw * stride_w) * 8; #pragma omp parallel for num_threads(opt.num_threads) for (int p = 0; p < inch; p++) { const Mat img = bottom_blob.channel(p); float* ptr = bottom_im2col.channel(p); for (int u = 0; u < kernel_h; u++) { for (int v = 0; v < kernel_w; v++) { const float* sptr = img.row(dilation_h * u) + dilation_w * v * 8; for (int i = 0; i < outh; i++) { int j = 0; for (; j < outw; j++) { __m256 _val = _mm256_load_ps(sptr); _mm256_store_ps(ptr, _val); sptr += stride_w * 8; ptr += 8; } sptr += gap; } } } } } im2col_sgemm_pack8to1_avx(bottom_im2col, top_blob, kernel, _bias, opt); }
argsort_op.h
/* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <algorithm> #include <utility> #include <vector> #include "paddle/fluid/framework/eigen.h" #include "paddle/fluid/framework/op_registry.h" #include "paddle/fluid/operators/transpose_op.h" namespace paddle { namespace operators { template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenMatrix = framework::EigenMatrix<T, MajorType, IndexType>; template <typename T, int MajorType = Eigen::RowMajor, typename IndexType = Eigen::DenseIndex> using EigenVector = framework::EigenVector<T, MajorType, IndexType>; using Tensor = framework::Tensor; template <typename T, typename Type> static void FullSort(Type input_height, Type input_width, int input_dim, const framework::Tensor* input, T* t_out, Type* t_indices, bool descending) { #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (Type i = 0; i < input_height; ++i) { std::vector<std::pair<T, Type>> col_vec; col_vec.reserve(input_width); if (input_dim == 1) { auto e_input = EigenVector<T>::Flatten(*input); for (Type j = 0; j < input_width; ++j) { col_vec.push_back(std::pair<T, Type>(e_input(j), j)); } } else { auto e_input = EigenMatrix<T>::Reshape(*input, input_dim - 1); for (Type j = 0; j < input_width; ++j) { col_vec.push_back(std::pair<T, Type>(e_input(i, j), j)); } } std::sort(col_vec.begin(), col_vec.end(), [&](const std::pair<T, Type>& l, const std::pair<T, Type>& r) { if (descending) return l.first > r.first; else return l.first < r.first; }); for (Type j = 0; j < input_width; ++j) { t_out[i * input_width + j] = col_vec[j].first; t_indices[i * input_width + j] = col_vec[j].second; } } } template <typename T, typename Type> static void FullAssign(Type input_height, Type input_width, int input_dim, const framework::Tensor* input, const framework::Tensor* indices, T* t_out) { #ifdef PADDLE_WITH_MKLML #pragma omp parallel for #endif for (Type i = 0; i < input_height; ++i) { if (input_dim == 1) { auto e_input = EigenVector<T>::Flatten(*input); auto e_indices = EigenVector<Type>::Flatten(*indices); for (Type j = 0; j < input_width; ++j) { t_out[i * input_width + e_indices(j)] = e_input(j); } } else { auto e_input = EigenMatrix<T>::Reshape(*input, input_dim - 1); auto e_indices = EigenMatrix<Type>::Reshape(*indices, input_dim - 1); for (Type j = 0; j < input_width; ++j) { t_out[i * input_width + e_indices(i, j)] = e_input(i, j); } } } } template <typename DeviceContext, typename T> class ArgsortKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* input = ctx.Input<framework::Tensor>("X"); auto* output = ctx.Output<framework::Tensor>("Out"); auto* indices = ctx.Output<framework::Tensor>("Indices"); int axis = ctx.Attr<int>("axis"); bool descending = ctx.Attr<bool>("descending"); auto in_dims = input->dims(); axis = (axis < 0) ? (in_dims.size() + axis) : axis; T* out_data = output->mutable_data<T>(ctx.GetPlace()); // Do full sort if (axis == -1 || axis + 1 == in_dims.size()) { const int64_t input_height = pten::product(pten::slice_ddim(in_dims, 0, in_dims.size() - 1)); const int64_t input_width = in_dims[in_dims.size() - 1]; int64_t* ids_data = indices->mutable_data<int64_t>(ctx.GetPlace()); FullSort<T, int64_t>(input_height, input_width, in_dims.size(), input, out_data, ids_data, descending); } else { // If not full sort do transpose std::vector<int> trans; for (int i = 0; i < axis; i++) { trans.push_back(i); } trans.push_back(in_dims.size() - 1); for (int i = axis + 1; i < in_dims.size() - 1; i++) { trans.push_back(i); } trans.push_back(axis); framework::DDim trans_dims(in_dims); for (size_t i = 0; i < trans.size(); i++) { trans_dims[i] = in_dims[trans[i]]; } Tensor trans_inp; trans_inp.mutable_data<T>(trans_dims, ctx.GetPlace()); int ndims = trans.size(); auto& dev_ctx = ctx.template device_context<platform::CPUDeviceContext>(); // Do transpose TransCompute<platform::CPUDeviceContext, T>(ndims, dev_ctx, *input, &trans_inp, trans); const int64_t input_height = pten::product(pten::slice_ddim(trans_dims, 0, trans_dims.size() - 1)); const int64_t input_width = trans_dims[trans_dims.size() - 1]; Tensor tmp_out; T* t_out = tmp_out.mutable_data<T>(trans_dims, ctx.GetPlace()); output->mutable_data<T>(ctx.GetPlace()); Tensor tmp_indices; auto* t_ind = tmp_indices.mutable_data<int64_t>(trans_dims, ctx.GetPlace()); FullSort<T, int64_t>(input_height, input_width, in_dims.size(), &trans_inp, t_out, t_ind, descending); indices->mutable_data<int64_t>(ctx.GetPlace()); TransCompute<platform::CPUDeviceContext, int64_t>( ndims, dev_ctx, tmp_indices, indices, trans); // transpose back TransCompute<platform::CPUDeviceContext, T>(ndims, dev_ctx, tmp_out, output, trans); } } }; template <typename DeviceContext, typename T> class ArgsortGradientKernel : public framework::OpKernel<T> { public: void Compute(const framework::ExecutionContext& ctx) const override { auto* indices = ctx.Input<Tensor>("Indices"); auto* dX = ctx.Output<Tensor>(framework::GradVarName("X")); auto* dO = ctx.Input<Tensor>(framework::GradVarName("Out")); int axis = ctx.Attr<int>("axis"); auto in_dims = indices->dims(); axis = (axis < 0) ? (in_dims.size() + axis) : axis; dX->mutable_data<T>(ctx.GetPlace()); auto dxt = framework::EigenVector<T>::Flatten(*dX); auto& place = *ctx.template device_context<platform::CPUDeviceContext>() .eigen_device(); dxt.device(place) = dxt.constant(static_cast<T>(0)); if (dO->numel() == 0) return; // Do full assign if (axis == -1 || axis + 1 == in_dims.size()) { const int64_t input_height = pten::product(pten::slice_ddim(in_dims, 0, in_dims.size() - 1)); const int64_t input_width = in_dims[in_dims.size() - 1]; FullAssign<T, int64_t>(input_height, input_width, in_dims.size(), dO, indices, dX->data<T>()); } else { // If not full assign do transpose std::vector<int> trans; for (int i = 0; i < axis; i++) { trans.push_back(i); } trans.push_back(in_dims.size() - 1); for (int i = axis + 1; i < in_dims.size() - 1; i++) { trans.push_back(i); } trans.push_back(axis); framework::DDim trans_dims(in_dims); for (size_t i = 0; i < trans.size(); i++) { trans_dims[i] = in_dims[trans[i]]; } Tensor trans_dO; trans_dO.mutable_data<T>(trans_dims, ctx.GetPlace()); Tensor trans_ind; trans_ind.mutable_data<int64_t>(trans_dims, ctx.GetPlace()); int ndims = trans.size(); auto& dev_ctx = ctx.template device_context<platform::CPUDeviceContext>(); // Do transpose TransCompute<platform::CPUDeviceContext, T>(ndims, dev_ctx, *dO, &trans_dO, trans); TransCompute<platform::CPUDeviceContext, int64_t>( ndims, dev_ctx, *indices, &trans_ind, trans); const int64_t input_height = pten::product(pten::slice_ddim(trans_dims, 0, trans_dims.size() - 1)); const int64_t input_width = trans_dims[trans_dims.size() - 1]; Tensor tmp_out; T* t_out = tmp_out.mutable_data<T>(trans_dims, ctx.GetPlace()); FullAssign<T, int64_t>(input_height, input_width, in_dims.size(), &trans_dO, &trans_ind, t_out); // transpose back TransCompute<platform::CPUDeviceContext, T>(ndims, dev_ctx, tmp_out, dX, trans); } } }; } // namespace operators } // namespace paddle
Example_target_struct_map.1.c
/* * @@name: target_struct_map.1c * @@type: C * @@compilable: yes * @@linkable: yes * @@expect: success * @@version: omp_5.0 */ #include <stdio.h> #include <stdlib.h> #define N 100 #define BAZILLION 2000000 struct foo { char buffera[BAZILLION]; char bufferb[BAZILLION]; float x; float a, b; float *p; }; #pragma omp declare target void saxpyfun(struct foo *S) { int i; for(i=0; i<N; i++) S->p[i] = S->p[i]*S->a + S->b; } #pragma omp end declare target int main() { struct foo S; int i; S.a = 2.0; S.b = 4.0; S.p = (float *)malloc(sizeof(float)*N); for(i=0; i<N; i++) S.p[i] = i; #pragma omp target map(alloc:S.p) map(S.p[:N]) map(to:S.a, S.b) saxpyfun(&S); printf(" %4.0f %4.0f\n", S.p[0], S.p[N-1]); // 4 202 <- output return 0; }
CacheGlue.h
/*************************************************************************** * Copyright (C) 2009-2013 by Florian Goth * * fgoth@wthp095 * * * * 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 <ORGANIZATION> 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. * ***************************************************************************/ #ifndef CACHE_GLUE_H #define CACHE_GLUE_H #include <map> #include <utility> #include <stdexcept> #include <valarray> #include "generalPhysics.h" #include "toFPType.h" #include "MTL/MTL_Macros.h" /** This structure encapsulates two Vertices and provides comparison operators */ template <class Vertex> struct VertexPair { Vertex v1;///< the first vertex Vertex v2;///< the second vertex /** Constructor for the vertex-pair @param a the first vertex @param b the second vertex */ VertexPair(Vertex a, Vertex b) : v1(a), v2(b) {} VertexPair(const VertexPair& rhs) : v1(rhs.v1), v2(rhs.v2) {} /** A comparison operator that probes for identity @param arg the other vertexpair to compare against @return true if the vertices in each VertexPair are the identical, else false */ inline bool operator==(const VertexPair& arg) const; /** A smaller-than operator to compare two vertices lexicographically @param arg the other Vertex-Pair to compare against @return true if the 'string' (v1,v2) is lexicographcally smaller than the same string arg. Else return false */ inline bool operator<(const VertexPair& arg) const; }; template <class T> inline VertexPair<T> make_Vertex_pair(T a, T b) { return VertexPair<T>(a,b); } template <class Configuration, class GreensFunction, typename FPType> class Wick { public: typedef typename GreensFunction::FreeGreensFunctionReturnValueType RetType; typedef typename Configuration::value_type Vertex; typedef Configuration Config; typedef GreensFunction GF; /** This function forwards the measurement to the Matrix-Container. The Matrix-Container can better decide which optimizations to make. */ inline RetType measure(const Configuration& configuration, const typename GreensFunction::Vertex& creator, const typename GreensFunction::Vertex& destructor) const { RetType retval = configuration.template measure<GreensFunction>(creator, destructor); return retval; } }; template <class Vertex, class GFRetVal> class DryRun;//forward declare DryRun template <class Vertex, class GFRetVal> class Cache { public: typedef typename std::map<VertexPair<Vertex>, GFRetVal >::iterator iterator; typedef typename std::map<VertexPair<Vertex>, GFRetVal >::const_iterator const_iterator; typedef std::valarray<std::pair<const VertexPair<Vertex>, GFRetVal>* > LinearType; inline std::size_t size() const throw() { return cache.size(); } inline GFRetVal get_key(const VertexPair<Vertex> vp) const MTL_PURE_FUNCTION { const_iterator it = cache.find(vp); if(unlikely(it == cache.end())) { std::cout<<"Vertices not found: "<<std::endl; std::cout<<vp.v1<<std::endl; std::cout<<vp.v2<<std::endl; std::cout<<"Aborting... Do something!!!!!"<<std::endl; exit(-1); } return it->second; } /** A function for obtaining a const_iterator to the beginning of the map @return a const_iterator to the beginning of the map */ inline const_iterator begin() const { return cache.begin(); } inline iterator begin() { return cache.begin(); } inline iterator end() { return cache.end(); } inline const_iterator end() const { return cache.end(); } inline LinearType linear_array() { LinearType ret(this->size()); int u = 0; for (typename std::map<VertexPair<Vertex>, GFRetVal>::iterator it = cache.begin(); it != cache.end(); ++it, ++u) ret[u] = &(*it); return ret; } inline void init() { #ifdef _OPENMP items.resize(this->size()); int u = 0; for (typename std::map<VertexPair<Vertex>, GFRetVal>::iterator it = cache.begin(); it != cache.end(); ++it, ++u) items[u] = &(*it); #endif } template <class T> inline void measure(const T& wick, const typename T::Config& conf) { #ifdef _OPENMP #pragma omp parallel for for (int u = 0; u < items.size(); ++u) { const Vertex& v1(items[u]->first.v1); const Vertex& v2(items[u]->first.v2); items[u]->second = wick.measure(conf, v1, v2); } #else for (typename std::map<VertexPair<Vertex>, GFRetVal >::iterator it = cache.begin(); it != cache.end(); ++it) { const Vertex& v1(it->first.v1); const Vertex& v2(it->first.v2); it->second = wick.measure(conf, v1, v2); } #endif } inline Cache(unsigned int) {} private: friend class DryRun<Vertex, GFRetVal>; inline void insert(VertexPair<Vertex>& arg) { cache.insert(std::make_pair(arg, GFRetVal(0.0))); } std::map<VertexPair<Vertex>, GFRetVal> cache;///< the cache with all the requested greensfunction values #ifdef _OPENMP LinearType items;///< some temporary space where we store the pointers into the map in a linear fashion #endif }; template <class GFRetVal, typename FPType> class Cache<Hubbard_Vertex<FPType>, GFRetVal>; template <class GFRetVal, typename FPType> class Cache_Iterator : std::iterator<std::input_iterator_tag, std::pair<VertexPair<Basic_Vertex<FPType> >, GFRetVal> > { public: inline Cache_Iterator& operator++()// equals ++it { ++it; if (it == cache[idx].end()) { ++idx; it = cache[idx].begin(); } return *this; } inline bool operator==(const Cache_Iterator& rhs) const { return (cache == rhs.cache) && (idx == rhs.idx) && (it == rhs.it); } inline bool operator!=(const Cache_Iterator& rhs) const { return !this->operator==(rhs); } inline std::pair<VertexPair<Basic_Vertex<FPType> >, GFRetVal>& operator*() { return *it; } private: unsigned int idx; typename std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal >::iterator it; Cache<Hubbard_Vertex<FPType>, GFRetVal>& cache; Cache_Iterator(Cache<Hubbard_Vertex<FPType>, GFRetVal>& arg) : idx(0), cache(arg), it( cache[idx].begin() ) {} }; template <class GFRetVal, typename FPType> class Cache<Hubbard_Vertex<FPType>, GFRetVal> { public: typedef Cache_Iterator<GFRetVal, FPType> iterator; typedef const Cache_Iterator<GFRetVal, FPType> const_iterator; inline std::size_t size() const throw() MTL_PURE_FUNCTION { std::size_t ret = 0; for (unsigned int k = 0; k < chain_len * chain_len; ++k) ret+= cache[k].size(); return ret; } inline GFRetVal get_key(const VertexPair<Hubbard_Vertex<FPType> > vp) const { return access(vp.v1.site, vp.v2.site).find(make_Vertex_pair(Basic_Vertex<FPType>(vp.v1.tau, vp.v1.spin), Basic_Vertex<FPType>(vp.v2.tau, vp.v2.spin)))->second; } inline const_iterator begin() const { return cache.begin(); } inline iterator begin() { return cache.begin(); } inline iterator end() { return cache.end(); } inline const_iterator end() const { return cache.end(); } inline Cache(const unsigned int len) : cache(new std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>[len * len]), chain_len(len) {} inline ~Cache() { delete [] cache; } /** A function to measure the greensfunction values that are stored in the cache @param wick The object that performs the measurement on a Configuration @param conf The configuration */ template <class W> inline void measure(const W& wick, const typename W::Config& conf) { std::cout<<"Beginning measurement of Greensfunctions"<<std::endl; //somehow playing with the chunk size could probably help with the scheduling... #pragma omp parallel for schedule(dynamic) for (unsigned int k = 0; k < chain_len*chain_len; ++k) { // for (unsigned int j = 0; j < chain_len; ++j) // { const uint idx_v1 = k/chain_len; const uint idx_v2 = k%chain_len; std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>& lm(access(idx_v1, idx_v2)); for (typename std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>::iterator it = lm.begin(); it != lm.end(); ++it) { const VertexPair<Basic_Vertex<FPType> >& vp(it->first); const Hubbard_Vertex<FPType> v1(idx_v1, vp.v1.tau, vp.v1.spin); const Hubbard_Vertex<FPType> v2(idx_v2, vp.v2.tau, vp.v2.spin); it->second = wick.measure(conf, v1, v2); } // } } std::cout<<"measurement of Greensfunctions done!"<<std::endl; } inline void init() { } private: inline void insert(VertexPair<Hubbard_Vertex<FPType> >& arg) { GFRetVal zero = 0; access(arg.v1.site, arg.v2.site).insert(std::make_pair(make_Vertex_pair(Basic_Vertex<FPType>(arg.v1.tau, arg.v1.spin), Basic_Vertex<FPType>(arg.v2.tau, arg.v2.spin)), zero)); } friend class DryRun<Hubbard_Vertex<FPType>, GFRetVal>; std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>* cache;///< the cache with all the requested greensfunction values unsigned int chain_len; inline const std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>& access(unsigned int i, unsigned int k) const { return cache[i*chain_len + k]; } inline std::map<VertexPair<Basic_Vertex<FPType> >, GFRetVal>& access(unsigned int i, unsigned int k) { return cache[i*chain_len + k]; } }; /** We need to provide the Greensfunctionvalue-cache with the necessary data which Greensfunction values we want to evaluate at every Configuration. For this, each observable provides a dryrun() method that takes a DryRun object which takes care of storing the Objects into the cache. */ template <class Vertex, class GFRetVal> class DryRun { public: typedef typename SignToFPType<GFRetVal>::Ret FPType; /** Constructor of the DryRun Object @param arg a reference to the storage of the cache */ inline DryRun(Cache<Vertex, GFRetVal>& arg) : cache(arg) {} /** This ()-operator takes the two Vertices at which to evaluate the Greensfunction and stores them in the cache @param v1 the first Vertex (the adjungated fermi-operator) @param v2 the second Vertex */ inline void operator()(Vertex v1, Vertex v2); /** A function that maps the previously used doWickonSector to the Cache architecture the template parameter selects the Spin sector @param site_i the site of the first Vertex @param tau_i the time of the first vertex @param site_j the site of the second vertex @param tau_j the time of the second vertex */ template<SPINS Spin> inline void onSector(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j); private: //declare certain things private to not allow copying this object DryRun(); DryRun(const DryRun&); DryRun& operator=(const DryRun&); Cache<Vertex, GFRetVal>& cache;///< A reference to the structure for the cache }; /** This class encapsulates the access from an observable to the cache. The Observables provide evaluate() methods that take this object, which will be used for evaluating the Greensfunctionvalues. */ template <class Vertex, class GFRetVal> class DoWick { public: typedef typename SignToFPType<GFRetVal>::Ret FPType; /** The constructor of the DoWick object @param arg a reference to the object that has the cached values */ inline DoWick(const Cache<Vertex, GFRetVal>& arg) : cache(arg) {} /** This ()-operator takes the two Vertices at which to evaluate the Greensfunction and stores them in the cache @param v1 the first Vertex (the adjungated fermi-operator) @param v2 the second Vertex */ inline GFRetVal operator()(Vertex v1, Vertex v2) const; /** This function mimicks the behaviour of the previously used doWickonSector function. It returns the value of the Greensfunction for the given values @param site_i the site of the first Vertex @param tau_i the time of the first vertex @param site_j the site of the second vertex @param tau_j the time of the second vertex @return the value of the Greensfunction for the given values */ template<SPINS Spin> inline GFRetVal onSector(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j) const; private: //declare certain things private to not allow copying this object DoWick(); DoWick(const DoWick&); DoWick& operator=(const DoWick&); const Cache<Vertex, GFRetVal>& cache; }; template <class Vertex, typename FPType> struct DryRunHelper { static inline VertexPair<Vertex> createPair(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j, SPINS spin); }; template <typename FPType> struct DryRunHelper<Basic_Vertex<FPType>, FPType> { static inline VertexPair<Basic_Vertex<FPType> > createPair(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j, SPINS spin) { return VertexPair<Basic_Vertex<FPType> >(Basic_Vertex<FPType>(tau_i, spin), Basic_Vertex<FPType>(tau_j, spin)); } }; template <typename FPType> struct DryRunHelper<Hubbard_Vertex<FPType>, FPType> { static inline VertexPair<Hubbard_Vertex<FPType> > createPair(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j, SPINS spin) { return VertexPair<Hubbard_Vertex<FPType> >(Hubbard_Vertex<FPType>(site_i, tau_i, spin), Hubbard_Vertex<FPType>(site_j, tau_j, spin)); } }; template< class Vertex, class GFRetVal> template<SPINS Spin> GFRetVal DoWick<Vertex, GFRetVal>::onSector(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j) const { return cache.get_key(DryRunHelper<Vertex, FPType>::createPair(site_i, tau_i, site_j, tau_j, Spin)); } template< class Vertex, class GFRetVal> template<SPINS Spin> void DryRun<Vertex, GFRetVal>::onSector(const int site_i, const FPType tau_i, const int site_j, const FPType tau_j) { VertexPair<Vertex> ce = DryRunHelper<Vertex, FPType>::createPair(site_i, tau_i, site_j, tau_j, Spin); this->cache.insert(ce); } template< class Vertex, class GFRetVal> GFRetVal DoWick<Vertex, GFRetVal>::operator()(Vertex v1, Vertex v2) const { VertexPair<Vertex> ce(v1, v2); return cache.get_key(ce); } template< class Vertex, class GFRetVal> void DryRun<Vertex, GFRetVal>::operator()(Vertex v1, Vertex v2) { VertexPair<Vertex> ce(v1, v2); this->cache.insert(ce); } template <class Vertex> bool VertexPair<Vertex>::operator<(const VertexPair& arg) const { if (!(v1 < arg.v1)) { //greater-than-branch if (v1 == arg.v1) { return v2 < arg.v2; } return false; } return true; } template <class Vertex> bool VertexPair<Vertex>::operator==(const VertexPair& arg) const { return (arg.v1 == v1) && (arg.v2 == v2); } #endif
GraphReconstructor.h
// // Copyright (C) 2015 Yahoo Japan 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 <unordered_map> #include <unordered_set> #include <list> #ifdef _OPENMP #include <omp.h> #else #warning "*** OMP is *NOT* available! ***" #endif namespace NGT { class GraphReconstructor { public: static void extractGraph(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &graphIndex) { graph.reserve(graphIndex.repository.size()); for (size_t id = 1; id < graphIndex.repository.size(); id++) { if (id % 1000000 == 0) { std::cerr << "GraphReconstructor::extractGraph: Processed " << id << " objects." << std::endl; } try { NGT::GraphNode &node = *graphIndex.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::ObjectDistances nd; nd.reserve(node.size()); for (auto n = node.begin(graphIndex.repository.allocator); n != node.end(graphIndex.repository.allocator); ++n) { nd.push_back(ObjectDistance((*n).id, (*n).distance)); } graph.push_back(nd); #else graph.push_back(node); #endif if (graph.back().size() != graph.back().capacity()) { std::cerr << "GraphReconstructor::extractGraph: Warning! The graph size must be the same as the capacity. " << id << std::endl; } } catch(NGT::Exception &err) { graph.push_back(NGT::ObjectDistances()); continue; } } } static void adjustPaths(NGT::Index &outIndex) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::cerr << "construct index is not implemented." << std::endl; exit(1); #else NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(outIndex.getIndex()); size_t rStartRank = 0; std::list<std::pair<size_t, NGT::GraphNode> > tmpGraph; for (size_t id = 1; id < outGraph.repository.size(); id++) { NGT::GraphNode &node = *outGraph.getNode(id); tmpGraph.push_back(std::pair<size_t, NGT::GraphNode>(id, node)); if (node.size() > rStartRank) { node.resize(rStartRank); } } size_t removeCount = 0; for (size_t rank = rStartRank; ; rank++) { bool edge = false; Timer timer; for (auto it = tmpGraph.begin(); it != tmpGraph.end();) { size_t id = (*it).first; try { NGT::GraphNode &node = (*it).second; if (rank >= node.size()) { it = tmpGraph.erase(it); continue; } edge = true; if (rank >= 1 && node[rank - 1].distance > node[rank].distance) { std::cerr << "distance order is wrong!" << std::endl; std::cerr << id << ":" << rank << ":" << node[rank - 1].id << ":" << node[rank].id << std::endl; } NGT::GraphNode &tn = *outGraph.getNode(id); volatile bool found = false; if (rank < 1000) { for (size_t tni = 0; tni < tn.size() && !found; tni++) { if (tn[tni].id == node[rank].id) { continue; } NGT::GraphNode &dstNode = *outGraph.getNode(tn[tni].id); for (size_t dni = 0; dni < dstNode.size(); dni++) { if ((dstNode[dni].id == node[rank].id) && (dstNode[dni].distance < node[rank].distance)) { found = true; break; } } } } else { #ifdef _OPENMP #pragma omp parallel for num_threads(10) #endif for (size_t tni = 0; tni < tn.size(); tni++) { if (found) { continue; } if (tn[tni].id == node[rank].id) { continue; } NGT::GraphNode &dstNode = *outGraph.getNode(tn[tni].id); for (size_t dni = 0; dni < dstNode.size(); dni++) { if ((dstNode[dni].id == node[rank].id) && (dstNode[dni].distance < node[rank].distance)) { found = true; } } } } if (!found) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) outGraph.addEdge(id, node.at(i, outGraph.repository.allocator).id, node.at(i, outGraph.repository.allocator).distance, true); #else tn.push_back(NGT::ObjectDistance(node[rank].id, node[rank].distance)); #endif } else { removeCount++; } } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; it++; continue; } it++; } if (edge == false) { break; } } #endif // NGT_SHARED_MEMORY_ALLOCATOR } static void adjustPathsEffectively(NGT::Index &outIndex, size_t minNoOfEdges = 0) { NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(outIndex.getIndex()); adjustPathsEffectively(outGraph, minNoOfEdges); } static bool edgeComp(NGT::ObjectDistance a, NGT::ObjectDistance b) { return a.id < b.id; } #if defined(NGT_SHARED_MEMORY_ALLOCATOR) static void insert(NGT::GraphNode &node, size_t edgeID, NGT::Distance edgeDistance, NGT::GraphIndex &graph) { NGT::ObjectDistance edge(edgeID, edgeDistance); GraphNode::iterator ni = std::lower_bound(node.begin(graph.repository.allocator), node.end(graph.repository.allocator), edge, edgeComp); node.insert(ni, edge, graph.repository.allocator); } static bool hasEdge(NGT::GraphIndex &graph, size_t srcNodeID, size_t dstNodeID) { NGT::GraphNode &srcNode = *graph.getNode(srcNodeID); GraphNode::iterator ni = std::lower_bound(srcNode.begin(graph.repository.allocator), srcNode.end(graph.repository.allocator), ObjectDistance(dstNodeID, 0.0), edgeComp); return (ni != srcNode.end(graph.repository.allocator)) && ((*ni).id == dstNodeID); } #else static void insert(NGT::GraphNode &node, size_t edgeID, NGT::Distance edgeDistance) { NGT::ObjectDistance edge(edgeID, edgeDistance); GraphNode::iterator ni = std::lower_bound(node.begin(), node.end(), edge, edgeComp); node.insert(ni, edge); } static bool hasEdge(NGT::GraphIndex &graph, size_t srcNodeID, size_t dstNodeID) { NGT::GraphNode &srcNode = *graph.getNode(srcNodeID); GraphNode::iterator ni = std::lower_bound(srcNode.begin(), srcNode.end(), ObjectDistance(dstNodeID, 0.0), edgeComp); return (ni != srcNode.end()) && ((*ni).id == dstNodeID); } #endif static void adjustPathsEffectively(NGT::GraphIndex &outGraph, size_t minNoOfEdges) { Timer timer; timer.start(); std::vector<NGT::GraphNode> tmpGraph; for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); tmpGraph.push_back(node); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else node.clear(); #endif } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) tmpGraph.push_back(NGT::GraphNode(outGraph.repository.allocator)); #else tmpGraph.push_back(NGT::GraphNode()); #endif } } if (outGraph.repository.size() != tmpGraph.size() + 1) { std::stringstream msg; msg << "GraphReconstructor: Fatal inner error. " << outGraph.repository.size() << ":" << tmpGraph.size(); NGTThrowException(msg); } timer.stop(); std::cerr << "GraphReconstructor::adjustPaths: graph preparing time=" << timer << std::endl; timer.reset(); timer.start(); std::vector<std::vector<std::pair<uint32_t, uint32_t> > > removeCandidates(tmpGraph.size()); int removeCandidateCount = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (size_t idx = 0; idx < tmpGraph.size(); ++idx) { auto it = tmpGraph.begin() + idx; size_t id = idx + 1; try { NGT::GraphNode &srcNode = *it; std::unordered_map<uint32_t, std::pair<size_t, double> > neighbors; for (size_t sni = 0; sni < srcNode.size(); ++sni) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) neighbors[srcNode.at(sni, outGraph.repository.allocator).id] = std::pair<size_t, double>(sni, srcNode.at(sni, outGraph.repository.allocator).distance); #else neighbors[srcNode[sni].id] = std::pair<size_t, double>(sni, srcNode[sni].distance); #endif } std::vector<std::pair<int, std::pair<uint32_t, uint32_t> > > candidates; for (size_t sni = 0; sni < srcNode.size(); sni++) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode &pathNode = tmpGraph[srcNode.at(sni, outGraph.repository.allocator).id - 1]; #else NGT::GraphNode &pathNode = tmpGraph[srcNode[sni].id - 1]; #endif for (size_t pni = 0; pni < pathNode.size(); pni++) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) auto dstNodeID = pathNode.at(pni, outGraph.repository.allocator).id; #else auto dstNodeID = pathNode[pni].id; #endif auto dstNode = neighbors.find(dstNodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) if (dstNode != neighbors.end() && srcNode.at(sni, outGraph.repository.allocator).distance < (*dstNode).second.second && pathNode.at(pni, outGraph.repository.allocator).distance < (*dstNode).second.second ) { #else if (dstNode != neighbors.end() && srcNode[sni].distance < (*dstNode).second.second && pathNode[pni].distance < (*dstNode).second.second ) { #endif #if defined(NGT_SHARED_MEMORY_ALLOCATOR) candidates.push_back(std::pair<int, std::pair<uint32_t, uint32_t> >((*dstNode).second.first, std::pair<uint32_t, uint32_t>(srcNode.at(sni, outGraph.repository.allocator).id, dstNodeID))); #else candidates.push_back(std::pair<int, std::pair<uint32_t, uint32_t> >((*dstNode).second.first, std::pair<uint32_t, uint32_t>(srcNode[sni].id, dstNodeID))); #endif removeCandidateCount++; } } } sort(candidates.begin(), candidates.end(), std::greater<std::pair<int, std::pair<uint32_t, uint32_t>>>()); removeCandidates[id - 1].reserve(candidates.size()); for (size_t i = 0; i < candidates.size(); i++) { removeCandidates[id - 1].push_back(candidates[i].second); } } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } timer.stop(); std::cerr << "GraphReconstructor::adjustPaths: extracting removed edge candidates time=" << timer << std::endl; timer.reset(); timer.start(); std::list<size_t> ids; for (size_t idx = 0; idx < tmpGraph.size(); ++idx) { ids.push_back(idx + 1); } int removeCount = 0; removeCandidateCount = 0; for (size_t rank = 0; ids.size() != 0; rank++) { for (auto it = ids.begin(); it != ids.end(); ) { size_t id = *it; size_t idx = id - 1; try { NGT::GraphNode &srcNode = tmpGraph[idx]; if (rank >= srcNode.size()) { if (!removeCandidates[idx].empty() && minNoOfEdges == 0) { std::cerr << "Something wrong! ID=" << id << " # of remaining candidates=" << removeCandidates[idx].size() << std::endl; abort(); } #if !defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode empty; tmpGraph[idx] = empty; #endif it = ids.erase(it); continue; } if (removeCandidates[idx].size() > 0 && ((*outGraph.getNode(id)).size() + srcNode.size() - rank) > minNoOfEdges) { removeCandidateCount++; bool pathExist = false; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode.at(rank, outGraph.repository.allocator).id)) { #else while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode[rank].id)) { #endif size_t path = removeCandidates[idx].back().first; size_t dst = removeCandidates[idx].back().second; removeCandidates[idx].pop_back(); if (removeCandidates[idx].empty()) { std::vector<std::pair<uint32_t, uint32_t>> empty; removeCandidates[idx] = empty; } if ((hasEdge(outGraph, id, path)) && (hasEdge(outGraph, path, dst))) { pathExist = true; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode.at(rank, outGraph.repository.allocator).id)) { #else while (!removeCandidates[idx].empty() && (removeCandidates[idx].back().second == srcNode[rank].id)) { #endif removeCandidates[idx].pop_back(); if (removeCandidates[idx].empty()) { std::vector<std::pair<uint32_t, uint32_t>> empty; removeCandidates[idx] = empty; } } break; } } if (pathExist) { removeCount++; it++; continue; } } NGT::GraphNode &outSrcNode = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) insert(outSrcNode, srcNode.at(rank, outGraph.repository.allocator).id, srcNode.at(rank, outGraph.repository.allocator).distance, outGraph); #else insert(outSrcNode, srcNode[rank].id, srcNode[rank].distance); #endif } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; it++; continue; } it++; } } for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::sort(node.begin(outGraph.repository.allocator), node.end(outGraph.repository.allocator)); #else std::sort(node.begin(), node.end()); #endif } catch(...) {} } } static void convertToANNG(std::vector<NGT::ObjectDistances> &graph) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::cerr << "convertToANNG is not implemented for shared memory." << std::endl; return; #else std::cerr << "convertToANNG begin" << std::endl; for (size_t idx = 0; idx < graph.size(); idx++) { NGT::GraphNode &node = graph[idx]; for (auto ni = node.begin(); ni != node.end(); ++ni) { graph[(*ni).id - 1].push_back(NGT::ObjectDistance(idx + 1, (*ni).distance)); } } for (size_t idx = 0; idx < graph.size(); idx++) { NGT::GraphNode &node = graph[idx]; if (node.size() == 0) { continue; } std::sort(node.begin(), node.end()); NGT::ObjectID prev = 0; for (auto it = node.begin(); it != node.end();) { if (prev == (*it).id) { it = node.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = node; node.swap(tmp); } std::cerr << "convertToANNG end" << std::endl; #endif } static void reconstructGraph(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &outGraph, size_t originalEdgeSize, size_t reverseEdgeSize) { if (reverseEdgeSize > 10000) { std::cerr << "something wrong. Edge size=" << reverseEdgeSize << std::endl; exit(1); } NGT::Timer originalEdgeTimer, reverseEdgeTimer, normalizeEdgeTimer; originalEdgeTimer.start(); size_t warningCount = 0; const size_t warningLimit = 10; for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &node = *outGraph.getNode(id); if (originalEdgeSize == 0) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else NGT::GraphNode empty; node.swap(empty); #endif } else { NGT::ObjectDistances n = graph[id - 1]; if (n.size() < originalEdgeSize) { warningCount++; if (warningCount <= warningLimit) { std::cerr << "GraphReconstructor: Warning. The edges are too few. " << n.size() << ":" << originalEdgeSize << " for " << id << std::endl; } if (warningCount == warningLimit) { std::cerr << "GraphReconstructor: Info. Too many warnings. Warning is disabled." << std::endl; } continue; } n.resize(originalEdgeSize); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.copy(n, outGraph.repository.allocator); #else node.swap(n); #endif } } catch(NGT::Exception &err) { warningCount++; if (warningCount <= warningLimit) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; } if (warningCount == warningLimit) { std::cerr << "GraphReconstructor: Info. Too many warnings. Warning is disabled." << std::endl; } continue; } } if (warningCount > warningLimit) { std::cerr << "GraphReconstructor: The total " << warningCount << " Warnings." << std::endl; } originalEdgeTimer.stop(); reverseEdgeTimer.start(); int insufficientNodeCount = 0; for (size_t id = 1; id <= graph.size(); ++id) { try { NGT::ObjectDistances &node = graph[id - 1]; size_t rsize = reverseEdgeSize; if (rsize > node.size()) { insufficientNodeCount++; rsize = node.size(); } for (size_t i = 0; i < rsize; ++i) { NGT::Distance distance = node[i].distance; size_t nodeID = node[i].id; try { NGT::GraphNode &n = *outGraph.getNode(nodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) n.push_back(NGT::ObjectDistance(id, distance), outGraph.repository.allocator); #else n.push_back(NGT::ObjectDistance(id, distance)); #endif } catch(...) {} } } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } reverseEdgeTimer.stop(); if (insufficientNodeCount != 0) { std::cerr << "# of the nodes edges of which are in short = " << insufficientNodeCount << std::endl; } normalizeEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); if (id % 100000 == 0) { std::cerr << "Processed " << id << " nodes" << std::endl; } #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::sort(n.begin(outGraph.repository.allocator), n.end(outGraph.repository.allocator)); #else std::sort(n.begin(), n.end()); #endif NGT::ObjectID prev = 0; #if defined(NGT_SHARED_MEMORY_ALLOCATOR) for (auto it = n.begin(outGraph.repository.allocator); it != n.end(outGraph.repository.allocator);) { #else for (auto it = n.begin(); it != n.end();) { #endif if (prev == (*it).id) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) it = n.erase(it, outGraph.repository.allocator); #else it = n.erase(it); #endif continue; } prev = (*it).id; it++; } #if !defined(NGT_SHARED_MEMORY_ALLOCATOR) NGT::GraphNode tmp = n; n.swap(tmp); #endif } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } normalizeEdgeTimer.stop(); std::cerr << "Reconstruction time=" << originalEdgeTimer.time << ":" << reverseEdgeTimer.time << ":" << normalizeEdgeTimer.time << std::endl; NGT::Property prop; outGraph.getProperty().get(prop); prop.graphType = NGT::NeighborhoodGraph::GraphTypeONNG; outGraph.getProperty().set(prop); } static void reconstructGraphWithConstraint(std::vector<NGT::ObjectDistances> &graph, NGT::GraphIndex &outGraph, size_t originalEdgeSize, size_t reverseEdgeSize, char mode = 'a') { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::cerr << "reconstructGraphWithConstraint is not implemented." << std::endl; abort(); #else NGT::Timer originalEdgeTimer, reverseEdgeTimer, normalizeEdgeTimer; if (reverseEdgeSize > 10000) { std::cerr << "something wrong. Edge size=" << reverseEdgeSize << std::endl; exit(1); } for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { std::cerr << "Processed " << id << std::endl; } try { NGT::GraphNode &node = *outGraph.getNode(id); if (node.size() == 0) { continue; } node.clear(); NGT::GraphNode empty; node.swap(empty); } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } NGT::GraphIndex::showStatisticsOfGraph(outGraph); std::vector<ObjectDistances> reverse(graph.size() + 1); for (size_t id = 1; id <= graph.size(); ++id) { try { NGT::GraphNode &node = graph[id - 1]; if (id % 100000 == 0) { std::cerr << "Processed (summing up) " << id << std::endl; } for (size_t rank = 0; rank < node.size(); rank++) { reverse[node[rank].id].push_back(ObjectDistance(id, node[rank].distance)); } } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } std::vector<std::pair<size_t, size_t> > reverseSize(graph.size() + 1); reverseSize[0] = std::pair<size_t, size_t>(0, 0); for (size_t rid = 1; rid <= graph.size(); ++rid) { reverseSize[rid] = std::pair<size_t, size_t>(reverse[rid].size(), rid); } std::sort(reverseSize.begin(), reverseSize.end()); std::vector<uint32_t> indegreeCount(graph.size(), 0); size_t zeroCount = 0; for (size_t sizerank = 0; sizerank <= reverseSize.size(); sizerank++) { if (reverseSize[sizerank].first == 0) { zeroCount++; continue; } size_t rid = reverseSize[sizerank].second; ObjectDistances &rnode = reverse[rid]; for (auto rni = rnode.begin(); rni != rnode.end(); ++rni) { if (indegreeCount[(*rni).id] >= reverseEdgeSize) { continue; } NGT::GraphNode &node = *outGraph.getNode(rid); if (indegreeCount[(*rni).id] > 0 && node.size() >= originalEdgeSize) { continue; } node.push_back(NGT::ObjectDistance((*rni).id, (*rni).distance)); indegreeCount[(*rni).id]++; } } reverseEdgeTimer.stop(); std::cerr << "The number of nodes with zero outdegree by reverse edges=" << zeroCount << std::endl; NGT::GraphIndex::showStatisticsOfGraph(outGraph); normalizeEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); if (id % 100000 == 0) { std::cerr << "Processed " << id << std::endl; } std::sort(n.begin(), n.end()); NGT::ObjectID prev = 0; for (auto it = n.begin(); it != n.end();) { if (prev == (*it).id) { it = n.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = n; n.swap(tmp); } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } normalizeEdgeTimer.stop(); NGT::GraphIndex::showStatisticsOfGraph(outGraph); originalEdgeTimer.start(); for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { std::cerr << "Processed " << id << std::endl; } NGT::GraphNode &node = graph[id - 1]; try { NGT::GraphNode &onode = *outGraph.getNode(id); bool stop = false; for (size_t rank = 0; (rank < node.size() && rank < originalEdgeSize) && stop == false; rank++) { switch (mode) { case 'a': if (onode.size() >= originalEdgeSize) { stop = true; continue; } break; case 'c': break; } NGT::Distance distance = node[rank].distance; size_t nodeID = node[rank].id; outGraph.addEdge(id, nodeID, distance, false); } } catch(NGT::Exception &err) { std::cerr << "GraphReconstructor: Warning. Cannot get the node. ID=" << id << ":" << err.what() << std::endl; continue; } } originalEdgeTimer.stop(); NGT::GraphIndex::showStatisticsOfGraph(outGraph); std::cerr << "Reconstruction time=" << originalEdgeTimer.time << ":" << reverseEdgeTimer.time << ":" << normalizeEdgeTimer.time << std::endl; #endif } // reconstruct a pseudo ANNG with a fewer edges from an actual ANNG with more edges. // graph is a source ANNG // index is an index with a reconstructed ANNG static void reconstructANNGFromANNG(std::vector<NGT::ObjectDistances> &graph, NGT::Index &index, size_t edgeSize) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) std::cerr << "reconstructANNGFromANNG is not implemented." << std::endl; abort(); #else NGT::GraphIndex &outGraph = dynamic_cast<NGT::GraphIndex&>(index.getIndex()); // remove all edges in the index. for (size_t id = 1; id < outGraph.repository.size(); id++) { if (id % 1000000 == 0) { std::cerr << "Processed " << id << " nodes." << std::endl; } try { NGT::GraphNode &node = *outGraph.getNode(id); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) node.clear(outGraph.repository.allocator); #else NGT::GraphNode empty; node.swap(empty); #endif } catch(NGT::Exception &err) { } } for (size_t id = 1; id <= graph.size(); ++id) { size_t edgeCount = 0; try { NGT::ObjectDistances &node = graph[id - 1]; NGT::GraphNode &n = *outGraph.getNode(id); NGT::Distance prevDistance = 0.0; assert(n.size() == 0); for (size_t i = 0; i < node.size(); ++i) { NGT::Distance distance = node[i].distance; if (prevDistance > distance) { NGTThrowException("Edge distance order is invalid"); } prevDistance = distance; size_t nodeID = node[i].id; if (node[i].id < id) { try { NGT::GraphNode &dn = *outGraph.getNode(nodeID); #if defined(NGT_SHARED_MEMORY_ALLOCATOR) n.push_back(NGT::ObjectDistance(nodeID, distance), outGraph.repository.allocator); dn.push_back(NGT::ObjectDistance(id, distance), outGraph.repository.allocator); #else n.push_back(NGT::ObjectDistance(nodeID, distance)); dn.push_back(NGT::ObjectDistance(id, distance)); #endif } catch(...) {} edgeCount++; } if (edgeCount >= edgeSize) { break; } } } catch(NGT::Exception &err) { } } for (size_t id = 1; id < outGraph.repository.size(); id++) { try { NGT::GraphNode &n = *outGraph.getNode(id); std::sort(n.begin(), n.end()); NGT::ObjectID prev = 0; for (auto it = n.begin(); it != n.end();) { if (prev == (*it).id) { it = n.erase(it); continue; } prev = (*it).id; it++; } NGT::GraphNode tmp = n; n.swap(tmp); } catch (...) { } } #endif } static void refineANNG(NGT::Index &index, bool unlog, float epsilon = 0.1, float accuracy = 0.0, int noOfEdges = 0, int exploreEdgeSize = INT_MIN, size_t batchSize = 10000) { NGT::StdOstreamRedirector redirector(unlog); redirector.begin(); try { refineANNG(index, epsilon, accuracy, noOfEdges, exploreEdgeSize, batchSize); } catch (NGT::Exception &err) { redirector.end(); throw(err); } } static void refineANNG(NGT::Index &index, float epsilon = 0.1, float accuracy = 0.0, int noOfEdges = 0, int exploreEdgeSize = INT_MIN, size_t batchSize = 10000) { #if defined(NGT_SHARED_MEMORY_ALLOCATOR) NGTThrowException("GraphReconstructor::refineANNG: Not implemented for the shared memory option."); #else auto prop = static_cast<GraphIndex&>(index.getIndex()).getGraphProperty(); NGT::ObjectRepository &objectRepository = index.getObjectSpace().getRepository(); NGT::GraphIndex &graphIndex = static_cast<GraphIndex&>(index.getIndex()); size_t nOfObjects = objectRepository.size(); bool error = false; std::string errorMessage; size_t noOfSearchedEdges = noOfEdges < 0 ? -noOfEdges : (noOfEdges > prop.edgeSizeForCreation ? noOfEdges : prop.edgeSizeForCreation); for (size_t bid = 1; bid < nOfObjects; bid += batchSize) { NGT::ObjectDistances results[batchSize]; // search #pragma omp parallel for for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (id % 100000 == 0) { std::cerr << "# of processed objects=" << id << std::endl; } if (objectRepository.isEmpty(id)) { continue; } NGT::SearchContainer searchContainer(*objectRepository.get(id)); searchContainer.setResults(&results[idx]); assert(prop.edgeSizeForCreation > 0); searchContainer.setSize(noOfSearchedEdges); if (accuracy > 0.0) { searchContainer.setExpectedAccuracy(accuracy); } else { searchContainer.setEpsilon(epsilon); } if (exploreEdgeSize != INT_MIN) { searchContainer.setEdgeSize(exploreEdgeSize); } if (!error) { try { index.search(searchContainer); } catch (NGT::Exception &err) { #pragma omp critical { error = true; errorMessage = err.what(); } } } } if (error) { std::stringstream msg; msg << "GraphReconstructor::refineANNG: " << errorMessage; NGTThrowException(msg); } // outgoing edges #pragma omp parallel for for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (objectRepository.isEmpty(id)) { continue; } NGT::GraphNode &node = *graphIndex.getNode(id); for (auto i = results[idx].begin(); i != results[idx].end(); ++i) { if ((*i).id != id) { node.push_back(*i); } } std::sort(node.begin(), node.end()); // dedupe ObjectID prev = 0; for (GraphNode::iterator ni = node.begin(); ni != node.end();) { if (prev == (*ni).id) { ni = node.erase(ni); continue; } prev = (*ni).id; ni++; } } // incomming edges if (noOfEdges != 0) { continue; } for (size_t idx = 0; idx < batchSize; idx++) { size_t id = bid + idx; if (id % 10000 == 0) { std::cerr << "# of processed objects=" << id << std::endl; } for (auto i = results[idx].begin(); i != results[idx].end(); ++i) { if ((*i).id != id) { NGT::GraphNode &node = *graphIndex.getNode((*i).id); graphIndex.addEdge(node, id, (*i).distance, false); } } } } if (noOfEdges > 0) { // prune to build knng size_t nedges = noOfEdges < 0 ? -noOfEdges : noOfEdges; #pragma omp parallel for for (ObjectID id = 1; id < nOfObjects; ++id) { if (objectRepository.isEmpty(id)) { continue; } NGT::GraphNode &node = *graphIndex.getNode(id); if (node.size() > nedges) { node.resize(nedges); } } } #endif // defined(NGT_SHARED_MEMORY_ALLOCATOR) } }; }; // NGT
phono3py.c
/* Copyright (C) 2021 Atsushi Togo */ /* All rights reserved. */ /* This file is part of phonopy. */ /* Redistribution and use in source and binary forms, with or without */ /* modification, are permitted provided that the following conditions */ /* are met: */ /* * Redistributions of source code must retain the above copyright */ /* notice, this list of conditions and the following disclaimer. */ /* * Redistributions in binary form must reproduce the above copyright */ /* notice, this list of conditions and the following disclaimer in */ /* the documentation and/or other materials provided with the */ /* distribution. */ /* * Neither the name of the phonopy project nor the names of its */ /* contributors may be used to endorse or promote products derived */ /* from this software without specific prior written permission. */ /* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS */ /* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT */ /* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS */ /* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE */ /* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, */ /* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, */ /* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; */ /* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER */ /* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT */ /* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN */ /* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE */ /* POSSIBILITY OF SUCH DAMAGE. */ #include "phono3py.h" #include <stdio.h> #include <stdlib.h> #include "bzgrid.h" #include "collision_matrix.h" #include "fc3.h" #include "grgrid.h" #include "imag_self_energy_with_g.h" #include "interaction.h" #include "isotope.h" #include "lagrid.h" #include "lapack_wrapper.h" #include "phonoc_array.h" #include "pp_collision.h" #include "real_self_energy.h" #include "tetrahedron_method.h" #include "triplet.h" #include "triplet_iw.h" long ph3py_get_interaction( Darray *fc3_normal_squared, const char *g_zero, const Darray *frequencies, const lapack_complex_double *eigenvectors, const long (*triplets)[3], const long num_triplets, const long (*bz_grid_addresses)[3], const long D_diag[3], const long Q[3][3], const double *fc3, const long is_compact_fc3, const double (*svecs)[3], const long multi_dims[2], const long (*multiplicity)[2], const double *masses, const long *p2s_map, const long *s2p_map, const long *band_indices, const long symmetrize_fc3_q, const double cutoff_frequency) { ConstBZGrid *bzgrid; long i, j; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = 0; for (j = 0; j < 3; j++) { bzgrid->Q[i][j] = Q[i][j]; } } itr_get_interaction(fc3_normal_squared, g_zero, frequencies, eigenvectors, triplets, num_triplets, bzgrid, fc3, is_compact_fc3, svecs, multi_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, symmetrize_fc3_q, cutoff_frequency); free(bzgrid); bzgrid = NULL; return 1; } long ph3py_get_pp_collision( double *imag_self_energy, const long relative_grid_address[24][4][3], /* thm */ const double *frequencies, const lapack_complex_double *eigenvectors, const long (*triplets)[3], const long num_triplets, const long *triplet_weights, const long (*bz_grid_addresses)[3], /* thm */ const long *bz_map, /* thm */ const long bz_grid_type, const long D_diag[3], const long Q[3][3], const double *fc3, const long is_compact_fc3, const double (*svecs)[3], const long multi_dims[2], const long (*multiplicity)[2], const double *masses, const long *p2s_map, const long *s2p_map, const Larray *band_indices, const Darray *temperatures, const long is_NU, const long symmetrize_fc3_q, const double cutoff_frequency) { ConstBZGrid *bzgrid; long i, j; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = 0; for (j = 0; j < 3; j++) { bzgrid->Q[i][j] = Q[i][j]; } } ppc_get_pp_collision( imag_self_energy, relative_grid_address, frequencies, eigenvectors, triplets, num_triplets, triplet_weights, bzgrid, fc3, is_compact_fc3, svecs, multi_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, temperatures, is_NU, symmetrize_fc3_q, cutoff_frequency); free(bzgrid); bzgrid = NULL; return 1; } long ph3py_get_pp_collision_with_sigma( double *imag_self_energy, const double sigma, const double sigma_cutoff, const double *frequencies, const lapack_complex_double *eigenvectors, const long (*triplets)[3], const long num_triplets, const long *triplet_weights, const long (*bz_grid_addresses)[3], const long D_diag[3], const long Q[3][3], const double *fc3, const long is_compact_fc3, const double (*svecs)[3], const long multi_dims[2], const long (*multiplicity)[2], const double *masses, const long *p2s_map, const long *s2p_map, const Larray *band_indices, const Darray *temperatures, const long is_NU, const long symmetrize_fc3_q, const double cutoff_frequency) { ConstBZGrid *bzgrid; long i, j; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = 0; for (j = 0; j < 3; j++) { bzgrid->Q[i][j] = Q[i][j]; } } ppc_get_pp_collision_with_sigma( imag_self_energy, sigma, sigma_cutoff, frequencies, eigenvectors, triplets, num_triplets, triplet_weights, bzgrid, fc3, is_compact_fc3, svecs, multi_dims, multiplicity, masses, p2s_map, s2p_map, band_indices, temperatures, is_NU, symmetrize_fc3_q, cutoff_frequency); free(bzgrid); bzgrid = NULL; return 1; } void ph3py_get_imag_self_energy_at_bands_with_g( double *imag_self_energy, const Darray *fc3_normal_squared, const double *frequencies, const long (*triplets)[3], const long *triplet_weights, const double *g, const char *g_zero, const double temperature, const double cutoff_frequency, const long num_frequency_points, const long frequency_point_index) { ise_get_imag_self_energy_at_bands_with_g( imag_self_energy, fc3_normal_squared, frequencies, triplets, triplet_weights, g, g_zero, temperature, cutoff_frequency, num_frequency_points, frequency_point_index); } void ph3py_get_detailed_imag_self_energy_at_bands_with_g( double *detailed_imag_self_energy, double *imag_self_energy_N, double *imag_self_energy_U, const Darray *fc3_normal_squared, const double *frequencies, const long (*triplets)[3], const long *triplet_weights, const long (*bz_grid_addresses)[3], const double *g, const char *g_zero, const double temperature, const double cutoff_frequency) { ise_get_detailed_imag_self_energy_at_bands_with_g( detailed_imag_self_energy, imag_self_energy_N, imag_self_energy_U, fc3_normal_squared, frequencies, triplets, triplet_weights, bz_grid_addresses, g, g_zero, temperature, cutoff_frequency); } void ph3py_get_real_self_energy_at_bands( double *real_self_energy, const Darray *fc3_normal_squared, const long *band_indices, const double *frequencies, const long (*triplets)[3], const long *triplet_weights, const double epsilon, const double temperature, const double unit_conversion_factor, const double cutoff_frequency) { rse_get_real_self_energy_at_bands(real_self_energy, fc3_normal_squared, band_indices, frequencies, triplets, triplet_weights, epsilon, temperature, unit_conversion_factor, cutoff_frequency); } void ph3py_get_real_self_energy_at_frequency_point( double *real_self_energy, const double frequency_point, const Darray *fc3_normal_squared, const long *band_indices, const double *frequencies, const long (*triplets)[3], const long *triplet_weights, const double epsilon, const double temperature, const double unit_conversion_factor, const double cutoff_frequency) { rse_get_real_self_energy_at_frequency_point( real_self_energy, frequency_point, fc3_normal_squared, band_indices, frequencies, triplets, triplet_weights, epsilon, temperature, unit_conversion_factor, cutoff_frequency); } void ph3py_get_collision_matrix( double *collision_matrix, const Darray *fc3_normal_squared, const double *frequencies, const long (*triplets)[3], const long *triplets_map, const long *map_q, const long *rotated_grid_points, const double *rotations_cartesian, const double *g, const long num_ir_gp, const long num_gp, const long num_rot, const double temperature, const double unit_conversion_factor, const double cutoff_frequency) { col_get_collision_matrix(collision_matrix, fc3_normal_squared, frequencies, triplets, triplets_map, map_q, rotated_grid_points, rotations_cartesian, g, num_ir_gp, num_gp, num_rot, temperature, unit_conversion_factor, cutoff_frequency); } void ph3py_get_reducible_collision_matrix( double *collision_matrix, const Darray *fc3_normal_squared, const double *frequencies, const long (*triplets)[3], const long *triplets_map, const long *map_q, const double *g, const long num_gp, const double temperature, const double unit_conversion_factor, const double cutoff_frequency) { col_get_reducible_collision_matrix( collision_matrix, fc3_normal_squared, frequencies, triplets, triplets_map, map_q, g, num_gp, temperature, unit_conversion_factor, cutoff_frequency); } void ph3py_get_isotope_scattering_strength( double *gamma, const long grid_point, const double *mass_variances, const double *frequencies, const lapack_complex_double *eigenvectors, const long num_grid_points, const long *band_indices, const long num_band, const long num_band0, const double sigma, const double cutoff_frequency) { iso_get_isotope_scattering_strength(gamma, grid_point, mass_variances, frequencies, eigenvectors, num_grid_points, band_indices, num_band, num_band0, sigma, cutoff_frequency); } void ph3py_get_thm_isotope_scattering_strength( double *gamma, const long grid_point, const long *ir_grid_points, const long *weights, const double *mass_variances, const double *frequencies, const lapack_complex_double *eigenvectors, const long num_ir_grid_points, const long *band_indices, const long num_band, const long num_band0, const double *integration_weights, const double cutoff_frequency) { iso_get_thm_isotope_scattering_strength( gamma, grid_point, ir_grid_points, weights, mass_variances, frequencies, eigenvectors, num_ir_grid_points, band_indices, num_band, num_band0, integration_weights, cutoff_frequency); } void ph3py_distribute_fc3(double *fc3, const long target, const long source, const long *atom_mapping, const long num_atom, const double *rot_cart) { fc3_distribute_fc3(fc3, target, source, atom_mapping, num_atom, rot_cart); } void ph3py_rotate_delta_fc2(double (*fc3)[3][3][3], const double (*delta_fc2s)[3][3], const double *inv_U, const double (*site_sym_cart)[3][3], const long *rot_map_syms, const long num_atom, const long num_site_sym, const long num_disp) { fc3_rotate_delta_fc2(fc3, delta_fc2s, inv_U, site_sym_cart, rot_map_syms, num_atom, num_site_sym, num_disp); } void ph3py_get_permutation_symmetry_fc3(double *fc3, const long num_atom) { fc3_set_permutation_symmetry_fc3(fc3, num_atom); } void ph3py_get_permutation_symmetry_compact_fc3( double *fc3, const long p2s[], const long s2pp[], const long nsym_list[], const long perms[], const long n_satom, const long n_patom) { fc3_set_permutation_symmetry_compact_fc3(fc3, p2s, s2pp, nsym_list, perms, n_satom, n_patom); } void ph3py_transpose_compact_fc3(double *fc3, const long p2s[], const long s2pp[], const long nsym_list[], const long perms[], const long n_satom, const long n_patom, const long t_type) { fc3_transpose_compact_fc3(fc3, p2s, s2pp, nsym_list, perms, n_satom, n_patom, t_type); } long ph3py_get_triplets_reciprocal_mesh_at_q( long *map_triplets, long *map_q, const long grid_point, const long D_diag[3], const long is_time_reversal, const long num_rot, const long (*rec_rotations)[3][3], const long swappable) { return tpl_get_triplets_reciprocal_mesh_at_q( map_triplets, map_q, grid_point, D_diag, is_time_reversal, num_rot, rec_rotations, swappable); } long ph3py_get_BZ_triplets_at_q(long (*triplets)[3], const long grid_point, const long (*bz_grid_addresses)[3], const long *bz_map, const long *map_triplets, const long num_map_triplets, const long D_diag[3], const long Q[3][3], const long bz_grid_type) { ConstBZGrid *bzgrid; long i, j, num_ir; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = 0; for (j = 0; j < 3; j++) { bzgrid->Q[i][j] = Q[i][j]; } } bzgrid->size = num_map_triplets; num_ir = tpl_get_BZ_triplets_at_q(triplets, grid_point, bzgrid, map_triplets); free(bzgrid); bzgrid = NULL; return num_ir; } /* relative_grid_addresses are given as P multipled with those from dataset, * i.e., * np.dot(relative_grid_addresses, P.T) */ long ph3py_get_integration_weight( double *iw, char *iw_zero, const double *frequency_points, const long num_band0, const long relative_grid_address[24][4][3], const long D_diag[3], const long (*triplets)[3], const long num_triplets, const long (*bz_grid_addresses)[3], const long *bz_map, const long bz_grid_type, const double *frequencies1, const long num_band1, const double *frequencies2, const long num_band2, const long tp_type, const long openmp_per_triplets, const long openmp_per_bands) { ConstBZGrid *bzgrid; long i; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; } tpl_get_integration_weight( iw, iw_zero, frequency_points, num_band0, relative_grid_address, triplets, num_triplets, bzgrid, frequencies1, num_band1, frequencies2, num_band2, tp_type, openmp_per_triplets, openmp_per_bands); free(bzgrid); bzgrid = NULL; return 1; } void ph3py_get_integration_weight_with_sigma( double *iw, char *iw_zero, const double sigma, const double sigma_cutoff, const double *frequency_points, const long num_band0, const long (*triplets)[3], const long num_triplets, const double *frequencies, const long num_band, const long tp_type) { tpl_get_integration_weight_with_sigma( iw, iw_zero, sigma, sigma_cutoff, frequency_points, num_band0, triplets, num_triplets, frequencies, num_band, tp_type); } /* From single address to grid index */ long ph3py_get_grid_index_from_address(const long address[3], const long D_diag[3]) { return grg_get_grid_index(address, D_diag); } void ph3py_get_gr_grid_addresses(long gr_grid_addresses[][3], const long D_diag[3]) { grg_get_all_grid_addresses(gr_grid_addresses, D_diag); } long ph3py_get_reciprocal_rotations(long rec_rotations[48][3][3], const long (*rotations)[3][3], const long num_rot, const long is_time_reversal) { return grg_get_reciprocal_point_group(rec_rotations, rotations, num_rot, is_time_reversal, 1); } /* Rotation matrices with respect to reciprocal basis vectors are * transformed to those for GRGrid. This set of the rotations are * used always in GRGrid handling. */ long ph3py_transform_rotations(long (*transformed_rots)[3][3], const long (*rotations)[3][3], const long num_rot, const long D_diag[3], const long Q[3][3]) { return grg_transform_rotations(transformed_rots, rotations, num_rot, D_diag, Q); } long ph3py_get_snf3x3(long D_diag[3], long P[3][3], long Q[3][3], const long A[3][3]) { return grg_get_snf3x3(D_diag, P, Q, A); } /* The rotations are those after proper transformation in GRGrid. */ long ph3py_get_ir_grid_map(long *ir_grid_map, const long D_diag[3], const long PS[3], const long (*grg_rotations)[3][3], const long num_rot) { long num_ir, i; grg_get_ir_grid_map(ir_grid_map, grg_rotations, num_rot, D_diag, PS); num_ir = 0; for (i = 0; i < D_diag[0] * D_diag[1] * D_diag[2]; i++) { if (ir_grid_map[i] == i) { num_ir++; } } return num_ir; } long ph3py_get_bz_grid_addresses(long (*bz_grid_addresses)[3], long *bz_map, long *bzg2grg, const long D_diag[3], const long Q[3][3], const long PS[3], const double rec_lattice[3][3], const long type) { BZGrid *bzgrid; long i, j, size; if ((bzgrid = (BZGrid *)malloc(sizeof(BZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->bzg2grg = bzg2grg; bzgrid->type = type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = PS[i]; for (j = 0; j < 3; j++) { bzgrid->Q[i][j] = Q[i][j]; bzgrid->reclat[i][j] = rec_lattice[i][j]; } } if (bzg_get_bz_grid_addresses(bzgrid)) { size = bzgrid->size; } else { size = 0; } free(bzgrid); bzgrid = NULL; return size; } long ph3py_rotate_bz_grid_index(const long bz_grid_index, const long rotation[3][3], const long (*bz_grid_addresses)[3], const long *bz_map, const long D_diag[3], const long PS[3], const long bz_grid_type) { ConstBZGrid *bzgrid; long i, rot_bz_gp; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; bzgrid->PS[i] = 0; } rot_bz_gp = bzg_rotate_grid_index(bz_grid_index, rotation, bzgrid); free(bzgrid); bzgrid = NULL; return rot_bz_gp; } void ph3py_symmetrize_collision_matrix(double *collision_matrix, const long num_column, const long num_temp, const long num_sigma) { double val; long i, j, k, l, adrs_shift; for (i = 0; i < num_sigma; i++) { for (j = 0; j < num_temp; j++) { adrs_shift = (i * num_column * num_column * num_temp + j * num_column * num_column); /* show_colmat_info(py_collision_matrix, i, j, adrs_shift); */ #ifdef _OPENMP #pragma omp parallel for schedule(guided) private(l, val) #endif for (k = 0; k < num_column; k++) { for (l = k + 1; l < num_column; l++) { val = (collision_matrix[adrs_shift + k * num_column + l] + collision_matrix[adrs_shift + l * num_column + k]) / 2; collision_matrix[adrs_shift + k * num_column + l] = val; collision_matrix[adrs_shift + l * num_column + k] = val; } } } } } void ph3py_expand_collision_matrix(double *collision_matrix, const long *rot_grid_points, const long *ir_grid_points, const long num_ir_gp, const long num_grid_points, const long num_rot, const long num_sigma, const long num_temp, const long num_band) { long i, j, k, l, m, n, p, adrs_shift, adrs_shift_plus, ir_gp, gp_r; long num_column, num_bgb; long *multi; double *colmat_copy; multi = (long *)malloc(sizeof(long) * num_ir_gp); colmat_copy = NULL; num_column = num_grid_points * num_band; num_bgb = num_band * num_grid_points * num_band; #ifdef _OPENMP #pragma omp parallel for schedule(guided) private(j, ir_gp) #endif for (i = 0; i < num_ir_gp; i++) { ir_gp = ir_grid_points[i]; multi[i] = 0; for (j = 0; j < num_rot; j++) { if (rot_grid_points[j * num_grid_points + ir_gp] == ir_gp) { multi[i]++; } } } for (i = 0; i < num_sigma; i++) { for (j = 0; j < num_temp; j++) { adrs_shift = (i * num_column * num_column * num_temp + j * num_column * num_column); #ifdef _OPENMP #pragma omp parallel for private(ir_gp, adrs_shift_plus, colmat_copy, l, gp_r, \ m, n, p) #endif for (k = 0; k < num_ir_gp; k++) { ir_gp = ir_grid_points[k]; adrs_shift_plus = adrs_shift + ir_gp * num_bgb; colmat_copy = (double *)malloc(sizeof(double) * num_bgb); for (l = 0; l < num_bgb; l++) { colmat_copy[l] = collision_matrix[adrs_shift_plus + l] / multi[k]; collision_matrix[adrs_shift_plus + l] = 0; } for (l = 0; l < num_rot; l++) { gp_r = rot_grid_points[l * num_grid_points + ir_gp]; for (m = 0; m < num_band; m++) { for (n = 0; n < num_grid_points; n++) { for (p = 0; p < num_band; p++) { collision_matrix [adrs_shift + gp_r * num_bgb + m * num_grid_points * num_band + rot_grid_points[l * num_grid_points + n] * num_band + p] += colmat_copy[m * num_grid_points * num_band + n * num_band + p]; } } } } free(colmat_copy); colmat_copy = NULL; } } } free(multi); multi = NULL; } /* tpi_get_neighboring_grid_points around multiple grid points for using openmp * * relative_grid_addresses are given as P multipled with those from dataset, * i.e., * np.dot(relative_grid_addresses, P.T) */ long ph3py_get_neighboring_gird_points( long *relative_grid_points, const long *grid_points, const long (*relative_grid_address)[3], const long D_diag[3], const long (*bz_grid_addresses)[3], const long *bz_map, const long bz_grid_type, const long num_grid_points, const long num_relative_grid_address) { long i; ConstBZGrid *bzgrid; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; } #ifdef _OPENMP #pragma omp parallel for #endif for (i = 0; i < num_grid_points; i++) { tpi_get_neighboring_grid_points( relative_grid_points + i * num_relative_grid_address, grid_points[i], relative_grid_address, num_relative_grid_address, bzgrid); } free(bzgrid); bzgrid = NULL; return 1; } /* thm_get_integration_weight at multiple grid points for using openmp * * relative_grid_addresses are given as P multipled with those from dataset, * i.e., * np.dot(relative_grid_addresses, P.T) */ long ph3py_get_thm_integration_weights_at_grid_points( double *iw, const double *frequency_points, const long num_frequency_points, const long num_band, const long num_gp, const long (*relative_grid_address)[4][3], const long D_diag[3], const long *grid_points, const long (*bz_grid_addresses)[3], const long *bz_map, const long bz_grid_type, const double *frequencies, const long *gp2irgp_map, const char function) { long i, j, k, bi; long vertices[24][4]; double freq_vertices[24][4]; ConstBZGrid *bzgrid; if ((bzgrid = (ConstBZGrid *)malloc(sizeof(ConstBZGrid))) == NULL) { warning_print("Memory could not be allocated."); return 0; } bzgrid->addresses = bz_grid_addresses; bzgrid->gp_map = bz_map; bzgrid->type = bz_grid_type; for (i = 0; i < 3; i++) { bzgrid->D_diag[i] = D_diag[i]; } #ifdef _OPENMP #pragma omp parallel for private(j, k, bi, vertices, freq_vertices) #endif for (i = 0; i < num_gp; i++) { for (j = 0; j < 24; j++) { tpi_get_neighboring_grid_points(vertices[j], grid_points[i], relative_grid_address[j], 4, bzgrid); } for (bi = 0; bi < num_band; bi++) { for (j = 0; j < 24; j++) { for (k = 0; k < 4; k++) { freq_vertices[j][k] = frequencies[gp2irgp_map[vertices[j][k]] * num_band + bi]; } } for (j = 0; j < num_frequency_points; j++) { iw[i * num_frequency_points * num_band + j * num_band + bi] = thm_get_integration_weight(frequency_points[j], freq_vertices, function); } } } free(bzgrid); bzgrid = NULL; return 1; }
kvstore_dist_server.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file mxnet_node.h * \brief implement mxnet nodes */ #ifndef MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_ #define MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_ #include <queue> #include <string> #include <mutex> #include <condition_variable> #include <memory> #include <functional> #include <future> #include <vector> #include "ps/ps.h" #include "mxnet/kvstore.h" #include "../operator/tensor/elemwise_binary_op-inl.h" #include "../operator/tensor/init_op.h" namespace mxnet { namespace kvstore { enum class CommandType { kController, kStopServer, kSyncMode, kSetGradientCompression }; enum class DataHandleType { kDefaultPushPull, kCompressedPushPull, kRowSparsePushPull }; /** * \brief executor runs a function using the thread called \ref Start */ class Executor { public: /** * \brief start the executor */ void Start() { std::unique_lock<std::mutex> lk(mu_); while (true) { cond_.wait(lk, [this]{return !queue_.empty();}); Block blk = std::move(queue_.front()); queue_.pop(); lk.unlock(); if (blk.f) { blk.f(); blk.p->set_value(); } else { blk.p->set_value(); break; } lk.lock(); } } /** * \brief function */ typedef std::function<void()> Func; /** * \brief let the thread called \ref Start to exec a function. threadsafe */ void Exec(const Func& func) { Block blk(func); auto fut = blk.p->get_future(); { std::lock_guard<std::mutex> lk(mu_); queue_.push(std::move(blk)); cond_.notify_one(); } fut.wait(); } /** * \brief stop the thread, threadsafe */ void Stop() { Exec(Func()); } private: struct Block { explicit Block(const Func& func) : f(func), p(std::make_shared<std::promise<void>>()) { } Func f; std::shared_ptr<std::promise<void>> p; }; std::queue<Block> queue_; std::mutex mu_; std::condition_variable cond_; }; class KVStoreDistServer { public: KVStoreDistServer() { using namespace std::placeholders; ps_server_ = new ps::KVServer<float>(0); static_cast<ps::SimpleApp*>(ps_server_)->set_request_handle( std::bind(&KVStoreDistServer::CommandHandle, this, _1, _2)); ps_server_->set_request_handle( std::bind(&KVStoreDistServer::DataHandleEx, this, _1, _2, _3)); sync_mode_ = false; gradient_compression_ = std::make_shared<GradientCompression>(); log_verbose_ = dmlc::GetEnv("MXNET_KVSTORE_DIST_ROW_SPARSE_VERBOSE", false); } ~KVStoreDistServer() { delete ps_server_; } void set_controller(const KVStore::Controller& controller) { CHECK(controller); controller_ = controller; } void set_updater(const KVStore::Updater& updater) { CHECK(updater); updater_ = updater; } /** * \brief blocked until received the command \a kSyncMode */ void Run() { exec_.Start(); } private: struct MergeBuf { std::vector<ps::KVMeta> request; NDArray array; }; void CommandHandle(const ps::SimpleData& recved, ps::SimpleApp* app) { CommandType recved_type = static_cast<CommandType>(recved.head); if (recved_type == CommandType::kStopServer) { exec_.Stop(); } else if (recved_type == CommandType::kSyncMode) { sync_mode_ = true; } else if (recved_type == CommandType::kSetGradientCompression) { gradient_compression_->DecodeParams(recved.body); } else { // this uses value 0 for message id from frontend // let the main thread to execute ctrl, which is necessary for python exec_.Exec([this, recved]() { CHECK(controller_); controller_(recved.head, recved.body); }); } app->Response(recved); } void DataHandleEx(const ps::KVMeta& req_meta, const ps::KVPairs<real_t>& req_data, ps::KVServer<real_t>* server) { DataHandleType recved_type = static_cast<DataHandleType>(req_meta.cmd); if (recved_type == DataHandleType::kRowSparsePushPull) { DataHandleRowSparse(req_meta, req_data, server); } else if (recved_type == DataHandleType::kCompressedPushPull) { DataHandleCompressed(req_meta, req_data, server); } else { DataHandleDefault(req_meta, req_data, server); } return; } inline void ApplyUpdates(const int key, MergeBuf *merged, NDArray *stored, ps::KVServer<real_t>* server) { if (merged->request.size() == (size_t) ps::NumWorkers()) { // let the main thread to execute updater_, which is necessary for python if (updater_) { exec_.Exec([this, key, merged, stored](){ CHECK(updater_); updater_(key, merged->array, stored); }); } else { // if no updater, just copy CopyFromTo(merged->array, stored); } if (log_verbose_) { LOG(INFO) << "sync response to " << merged->request.size() << " workers"; } for (const auto& req : merged->request) { server->Response(req); } merged->request.clear(); stored->WaitToRead(); } else { merged->array.WaitToRead(); } } void DecodeRowIds(const ps::SArray<ps::Key> &keys, int64_t *indices, const int64_t master_key, const int64_t num_rows) { indices[0] = 0; for (int64_t i = 1; i <= num_rows; i++) { int key = DecodeKey(keys[i]); auto row_id = key - master_key; indices[i - 1] = row_id; } } void DataHandleRowSparse(const ps::KVMeta& req_meta, const ps::KVPairs<real_t>& req_data, ps::KVServer<real_t>* server) { int master_key = DecodeKey(req_data.keys[0]); auto num_rows = req_data.keys.size() - 1; auto& stored = store_[master_key]; if (req_meta.push) { CHECK_GT(req_data.lens.size(), 0) << "req_data.lens cannot be empty"; CHECK_EQ(req_data.lens[0], 0); real_t* data = req_data.vals.data(); if (stored.is_none()) { if (log_verbose_) LOG(INFO) << "initial push: " << master_key; // initialization CHECK_GT(num_rows, 0) << "init with empty data is not supported"; auto unit_len = req_data.lens[1]; CHECK_GT(unit_len, 0); size_t ds[] = {num_rows, (size_t) unit_len}; TShape dshape(ds, ds + 2); CHECK_EQ(req_data.vals.size(), num_rows * unit_len); TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*) NDArray recved = NDArray(recv_blob, 0); stored = NDArray(kRowSparseStorage, dshape, Context()); Engine::Get()->PushAsync( [recved, stored](RunContext ctx, Engine::CallbackOnComplete on_complete) { NDArray rsp = stored; stored.CheckAndAlloc({mshadow::Shape1(recved.shape()[0])}); mshadow::Stream<cpu> *s = ctx.get_stream<cpu>(); using namespace mxnet::op; nnvm::dim_t nnr = rsp.shape()[0]; MSHADOW_IDX_TYPE_SWITCH(rsp.aux_type(rowsparse::kIdx), IType, { IType* idx = rsp.aux_data(rowsparse::kIdx).dptr<IType>(); mxnet_op::Kernel<PopulateFullIdxRspKernel, cpu>::Launch(s, nnr, idx); }); mshadow::Copy(rsp.data().FlatTo1D<cpu, float>(), recved.data().FlatTo1D<cpu, float>(), s); on_complete(); }, recved.ctx(), {recved.var()}, {stored.var()}, FnProperty::kNormal, 0, PROFILER_MESSAGE_FUNCNAME); stored.WaitToRead(); server->Response(req_meta); return; } // synced push if (sync_mode_) { if (log_verbose_) LOG(INFO) << "sync push: " << master_key << " " << req_data.keys; auto& merged = merge_buf_[master_key]; if (merged.array.is_none()) { merged.array = NDArray(kRowSparseStorage, stored.shape(), Context()); } if (num_rows == 0) { // reset to zeros if (merged.request.size() == 0) { merged.array = NDArray(kRowSparseStorage, stored.shape(), Context()); } else { // nothing to aggregate } merged.request.push_back(req_meta); ApplyUpdates(master_key, &merged, &stored, server); return; } auto unit_len = req_data.lens[1]; CHECK_GT(unit_len, 0); // indices std::vector<int64_t> indices(num_rows); DecodeRowIds(req_data.keys, indices.data(), master_key, num_rows); // data TBlob idx_blob(indices.data(), mshadow::Shape1(num_rows), cpu::kDevMask); size_t ds[] = {(size_t) num_rows, (size_t) unit_len}; TShape dshape(ds, ds + 2); TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*) // row_sparse NDArray NDArray recved(kRowSparseStorage, stored.shape(), recv_blob, {idx_blob}, 0); if (merged.request.size() == 0) { CopyFromTo(recved, &merged.array, 0); } else { NDArray out(kRowSparseStorage, stored.shape(), Context()); // accumulate row_sparse gradients // TODO(haibin) override + operator for row_sparse NDArray // instead of calling BinaryComputeRspRsp directly using namespace mshadow; Engine::Get()->PushAsync( [recved, merged, out](RunContext ctx, Engine::CallbackOnComplete on_complete) { op::ElemwiseBinaryOp::ComputeEx<cpu, op::mshadow_op::plus>( {}, {}, {recved, merged.array}, {kWriteTo}, {out}); on_complete(); }, recved.ctx(), {recved.var(), merged.array.var()}, {out.var()}, FnProperty::kNormal, 0, PROFILER_MESSAGE_FUNCNAME); CopyFromTo(out, &merged.array, 0); } merged.request.push_back(req_meta); ApplyUpdates(master_key, &merged, &stored, server); } else { // async push if (log_verbose_) LOG(INFO) << "async push: " << master_key; if (num_rows == 0) { server->Response(req_meta); return; } auto unit_len = req_data.lens[1]; CHECK_GT(unit_len, 0); // indices std::vector<int64_t> indices(num_rows); DecodeRowIds(req_data.keys, indices.data(), master_key, num_rows); TBlob idx_blob(indices.data(), mshadow::Shape1(num_rows), cpu::kDevMask); size_t ds[] = {(size_t) num_rows, (size_t) unit_len}; TShape dshape(ds, ds + 2); TBlob recv_blob(data, dshape, cpu::kDevMask); // NOLINT(*) NDArray recved(kRowSparseStorage, stored.shape(), recv_blob, {idx_blob}, 0); exec_.Exec([this, master_key, &recved, &stored](){ CHECK(updater_); updater_(master_key, recved, &stored); }); server->Response(req_meta); stored.WaitToRead(); } } else { // pull if (log_verbose_) LOG(INFO) << "pull: " << master_key; ps::KVPairs<real_t> response; if (num_rows == 0) { std::vector<int> lens(req_data.keys.size(), 0); response.keys = req_data.keys; response.lens.CopyFrom(lens.begin(), lens.end()); server->Response(req_meta, response); return; } CHECK(!stored.is_none()) << "init " << master_key << " first"; auto shape = stored.shape(); auto unit_len = shape.ProdShape(1, shape.ndim()); const float* data = stored.data().dptr<float>(); auto len = unit_len * num_rows; // concat values response.vals.resize(len); #pragma omp parallel for for (size_t i = 1; i <= num_rows; i++) { int key = DecodeKey(req_data.keys[i]); int64_t row_id = key - master_key; const auto src = data + row_id * unit_len; auto begin = (i - 1) * unit_len; auto end = i * unit_len; response.vals.segment(begin, end).CopyFrom(src, unit_len); } // setup response response.keys = req_data.keys; std::vector<int> lens(req_data.keys.size(), unit_len); lens[0] = 0; response.lens.CopyFrom(lens.begin(), lens.end()); server->Response(req_meta, response); } } void DefaultStorageResponse(int key, const NDArray& stored, const ps::KVMeta& req_meta, const ps::KVPairs<real_t> &req_data, ps::KVServer<real_t>* server) { ps::KVPairs<real_t> response; CHECK(!stored.is_none()) << "init " << key << " first"; auto len = stored.shape().Size(); response.keys = req_data.keys; response.lens = {len}; // TODO(mli) try to remove this CopyFrom response.vals.CopyFrom(static_cast<const float*>(stored.data().dptr_), len); server->Response(req_meta, response); } void DataHandleCompressed(const ps::KVMeta& req_meta, const ps::KVPairs<real_t> &req_data, ps::KVServer<real_t>* server) { if (req_meta.push) { // there used several WaitToRead, this is because \a recved's memory // could be deallocated when this function returns. so we need to make sure // the operators with \a NDArray are actually finished // first for dummy key which represents original size of array, whose len is 0 CHECK_EQ(req_data.keys.size(), (size_t)2); CHECK_EQ(req_data.lens.size(), (size_t)2); CHECK_EQ(req_data.vals.size(), (size_t)req_data.lens[1]); int original_size = DecodeKey(req_data.keys[0]); int key = DecodeKey(req_data.keys[1]); auto& stored = store_[key]; size_t ds[] = {(size_t)req_data.lens[1]}; TShape dshape(ds, ds + 1); TBlob recv_blob((real_t*) req_data.vals.data(), // NOLINT(*) dshape, cpu::kDevMask); NDArray recved = NDArray(recv_blob, 0); NDArray decomp_buf = decomp_buf_[key]; dshape = TShape{(int64_t) original_size}; if (decomp_buf.is_none()) { decomp_buf = NDArray(dshape, Context()); } if (stored.is_none()) { stored = NDArray(dshape, Context()); gradient_compression_->Dequantize(recved, &stored, 0); server->Response(req_meta); stored.WaitToRead(); } else if (sync_mode_) { // synced push auto& merged = merge_buf_[key]; if (merged.array.is_none()) { merged.array = NDArray(dshape, Context()); } if (merged.request.size() == 0) { gradient_compression_->Dequantize(recved, &merged.array, 0); } else { gradient_compression_->Dequantize(recved, &decomp_buf, 0); merged.array += decomp_buf; } merged.request.push_back(req_meta); ApplyUpdates(key, &merged, &stored, server); } else { // async push gradient_compression_->Dequantize(recved, &decomp_buf, 0); exec_.Exec([this, key, &decomp_buf, &stored]() { CHECK(updater_); updater_(key, decomp_buf, &stored); }); server->Response(req_meta); stored.WaitToRead(); } } else { // pull CHECK_EQ(req_data.keys.size(), (size_t)1); CHECK_EQ(req_data.lens.size(), (size_t)0); int key = DecodeKey(req_data.keys[0]); DefaultStorageResponse(key, store_[key], req_meta, req_data, server); } } void DataHandleDefault(const ps::KVMeta& req_meta, const ps::KVPairs<real_t> &req_data, ps::KVServer<real_t>* server) { CHECK_EQ(req_meta.cmd, static_cast<int>(DataHandleType::kDefaultPushPull)); // do some check CHECK_EQ(req_data.keys.size(), (size_t)1); if (req_meta.push) { CHECK_EQ(req_data.lens.size(), (size_t)1); CHECK_EQ(req_data.vals.size(), (size_t)req_data.lens[0]); } int key = DecodeKey(req_data.keys[0]); auto& stored = store_[key]; // there used several WaitToRead, this is because \a recved's memory // could be deallocated when this function returns. so we need to make sure // the operators with \a NDArray are actually finished if (req_meta.push) { size_t ds[] = {(size_t)req_data.lens[0]}; TShape dshape(ds, ds + 1); TBlob recv_blob((real_t*)req_data.vals.data(), // NOLINT(*) dshape, cpu::kDevMask); NDArray recved = NDArray(recv_blob, 0); if (stored.is_none()) { // initialization stored = NDArray(dshape, Context()); CopyFromTo(recved, &stored, 0); server->Response(req_meta); stored.WaitToRead(); } else if (sync_mode_) { // synced push auto& merged = merge_buf_[key]; if (merged.array.is_none()) { merged.array = NDArray(dshape, Context()); } if (merged.request.size() == 0) { CopyFromTo(recved, &merged.array, 0); } else { merged.array += recved; } merged.request.push_back(req_meta); ApplyUpdates(key, &merged, &stored, server); } else { // async push exec_.Exec([this, key, &recved, &stored](){ CHECK(updater_); updater_(key, recved, &stored); }); server->Response(req_meta); stored.WaitToRead(); } } else { DefaultStorageResponse(key, stored, req_meta, req_data, server); } } int DecodeKey(ps::Key key) { auto kr = ps::Postoffice::Get()->GetServerKeyRanges()[ps::MyRank()]; return key - kr.begin(); } /** * \brief user defined mode for push */ bool sync_mode_; KVStore::Controller controller_; KVStore::Updater updater_; /** * \brief store_ contains the value at kvstore for each key */ std::unordered_map<int, NDArray> store_; /** * \brief merge_buf_ is a buffer used if sync_mode is true. It represents * values from different workers being merged. The store will be updated * to this value when values from all workers are pushed into this buffer. */ std::unordered_map<int, MergeBuf> merge_buf_; /** * \brief decomp_buf_ is a buffer into which compressed values are * decompressed before merging to the store. used when compress_!='none' */ std::unordered_map<int, NDArray> decomp_buf_; Executor exec_; ps::KVServer<float>* ps_server_; // whether to LOG verbose information bool log_verbose_; /** * \brief gradient compression object. * starts with none, used after SetGradientCompression sets the type * currently there is no support for unsetting gradient compression */ std::shared_ptr<kvstore::GradientCompression> gradient_compression_; }; } // namespace kvstore } // namespace mxnet #endif // MXNET_KVSTORE_KVSTORE_DIST_SERVER_H_
ten_tusscher_2004_epi_S2_19.c
//Original Ten Tusscher #include <assert.h> #include <stdlib.h> #include "ten_tusscher_2004_epi_S2_19.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.5110986392742,0.00130591158765005,0.778304597988111,0.778190083712180,0.000176141600174844,0.484495378655116,0.00295228963782625,0.999998329695130,1.95198204949961e-08,1.90553223501749e-05,0.999768478047086,1.00656738617877,0.999980520529342,5.74063440693430e-05,0.608088033062619,9.96205488133323,139.557924801650}; 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.2952631571165,0.000223357550203231,0.000139823866607541,0.000468830572859158,0.267957668347321,0.123807265230240,0.209206424884521,4.97611368106475,0.0181339958455722,1.93368689237664,1099.98460468133,0.000558564959599142,0.298337407980113,0.0142073923928152,0.00109951928325625,6.37440120865430e-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; }
merge.c
/**********************************************************/ /** * 234Compositor - Image data merging library * * Copyright (c) 2013-2015 Advanced Institute for Computational Science, RIKEN. * All rights reserved. * **/ /**********************************************************/ // @file merge.c // @brief Image data merging routines for 234Compositor // @author Jorji Nonaka (jorji@riken.jp) #ifndef COMPOSITOR234_H_INCLUDE #include "234compositor.h" #define COMPOSITOR234_H_INCLUDE #endif #ifndef COMPOSITOR234_MISC_H_INCLUDE #include "misc.h" #define COMPOSITOR234_MISC_H_INCLUDE #endif #include "merge.h" /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA32 Pixels) * * @param under_image [in] Image to be alpha blended * @param over_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba32 \ ( BYTE* restrict under_image, \ BYTE* restrict over_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32 \ ( BYTE* under_image, \ BYTE* over_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; float one_minus_alpha; float one_alpha; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, one_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { over_a = (BYTE)over_image[ i + 3 ]; under_a = (BYTE)under_image[ i + 3 ]; if ( over_a == 0 ) { blend_a = under_a; blend_r = (BYTE)under_image[ i ]; blend_g = (BYTE)under_image[ i + 1 ]; blend_b = (BYTE)under_image[ i + 2 ]; } else if ( over_a == 255 ) { blend_a = over_a; blend_r = (BYTE)over_image[ i ]; blend_g = (BYTE)over_image[ i + 1 ]; blend_b = (BYTE)over_image[ i + 2 ]; } else { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; // ======================================================= one_alpha = (float)( over_a / 255.0f ); one_minus_alpha = (float)( 1.0f - ( over_a / 255.0f )); blend_r = saturate_add((BYTE)( over_r * one_alpha ), (BYTE)( under_r * one_minus_alpha )); blend_g = saturate_add((BYTE)( over_g * one_alpha ), (BYTE)( under_g * one_minus_alpha )); blend_b = saturate_add((BYTE)( over_b * one_alpha ), (BYTE)( under_b * one_minus_alpha )); blend_a = saturate_add((BYTE)( over_a * one_alpha ), (BYTE)( under_a * one_minus_alpha )); // ======================================================= // one_minus_alpha = (float)( 1.0f - ( over_a / 255.0f )); // blend_r = saturate_add((BYTE)( over_r ), (BYTE)( under_r * one_minus_alpha )); // blend_g = saturate_add((BYTE)( over_g ), (BYTE)( under_g * one_minus_alpha )); // blend_b = saturate_add((BYTE)( over_b ), (BYTE)( under_b * one_minus_alpha )); // blend_a = saturate_add((BYTE)( over_a ), (BYTE)( under_a * one_minus_alpha )); // ======================================================= } blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); } return EXIT_SUCCESS; } #ifdef C99 int composite_alpha_rgbaz64 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz64 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; float over_z_f; float under_z_f; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; float blend_z; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ64; // 8 BYTES //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBAZ64; // 8 BYTES #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, \ over_r, over_g, over_b, over_a, over_z_f, \ under_r, under_g, under_b, under_a, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ64 ) // SKIP 8 BYTES { over_r = (BYTE)over_image_ptr[ i ]; over_g = (BYTE)over_image_ptr[ i + 1 ]; over_b = (BYTE)over_image_ptr[ i + 2 ]; over_a = (BYTE)over_image_ptr[ i + 3 ]; over_image_f_ptr = (float *)&over_image_ptr[ i + 4 ]; over_z_f = (float)over_image_f_ptr[ 0 ]; under_r = (BYTE)under_image_ptr[ i ]; under_g = (BYTE)under_image_ptr[ i + 1 ]; under_b = (BYTE)under_image_ptr[ i + 2 ]; under_a = (BYTE)under_image_ptr[ i + 3 ]; under_image_f_ptr = (float *)&under_image_ptr[ i + 4 ]; under_z_f = (float)under_image_f_ptr[ 0 ]; // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = under_r; blend_g = under_g; blend_b = under_b; blend_a = under_a; blend_z = under_z_f; } else { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z_f; } blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)blend_z; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA32 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba32f \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32f \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_a = (BYTE)over_image[ i + 3 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_a = (BYTE)under_image[ i + 3 ]; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float)( over_a / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float)( under_a / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = (float)( 1.0f - over_a_f ); // ======================================================= blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0f, 1.0f ); blend_g = clamp_float( blend_g, 0.0f, 1.0f ); blend_b = clamp_float( blend_b, 0.0f, 1.0f ); blend_a = clamp_float( blend_a, 0.0f, 1.0f ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a * 255 ); } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ64 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz64f \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz64f \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ64; // 8 BYTES //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBAZ64; // 8 BYTES #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, over_z_f, \ under_r, under_g, under_b, under_a, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ64 ) // SKIP 8 BYTES { over_r = (BYTE)over_image_ptr[ i ]; over_g = (BYTE)over_image_ptr[ i + 1 ]; over_b = (BYTE)over_image_ptr[ i + 2 ]; over_a = (BYTE)over_image_ptr[ i + 3 ]; over_image_f_ptr = (float *)&over_image_ptr[ i + 4 ]; over_z_f = (float)over_image_f_ptr[ 0 ]; under_r = (BYTE)under_image_ptr[ i ]; under_g = (BYTE)under_image_ptr[ i + 1 ]; under_b = (BYTE)under_image_ptr[ i + 2 ]; under_a = (BYTE)under_image_ptr[ i + 3 ]; under_image_f_ptr = (float *)&under_image_ptr[ i + 4 ]; under_z_f = (float)under_image_f_ptr[ 0 ]; // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a = under_a; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float)( over_a / 255.0f) ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float)( under_a / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a * 255 ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)over_z_f; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA56 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba56 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba56 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE under_r; BYTE under_g; BYTE under_b; float under_a; BYTE over_r; BYTE over_g; BYTE over_b; float over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA56; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA56 ) // SKIP 7 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_image_f_ptr = (float *)&over_image[ i + 3 ]; over_a = (float)*over_image_f_ptr; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_image_f_ptr = (float *)&under_image[ i + 3 ]; under_a = (float)*under_image_f_ptr; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float) over_a ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float) under_a ; // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float)( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); blend_image_f_ptr = (float *)&blend_image_ptr[ i + 3 ]; *blend_image_f_ptr = (float) blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA64 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba64 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba64 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE under_r; BYTE under_g; BYTE under_b; float under_a; BYTE over_r; BYTE over_g; BYTE over_b; float over_a; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA64; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA64 ) // SKIP 8 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_image_f_ptr = (float *)&over_image[ i + 4 ]; over_a = (float)*over_image_f_ptr; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_image_f_ptr = (float *)&under_image[ i + 4 ]; under_a = (float)*under_image_f_ptr; // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); over_a_f = (float) over_a ; under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); under_a_f = (float) under_a ; // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= // Clamp RGB component values if necessary blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); // R blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image_ptr[ i + 3 ] = (BYTE)0; // X blend_image_f_ptr = (float *)&blend_image_ptr[ i + 4 ]; // A *blend_image_f_ptr = (float) blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ88 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz88 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz88 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE* over_image_ptr; BYTE* under_image_ptr; BYTE* blend_image_ptr; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE under_r; BYTE under_g; BYTE under_b; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_ptr = (BYTE *)blend_image; over_image_ptr = (BYTE *)over_image; under_image_ptr = (BYTE *)under_image; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; blend_z = 0; full_image_size = image_size * RGBAZ88; // 11 BYTES //===================================== // Depth Sorting //===================================== over_image_f_ptr = (float *)&over_image_ptr[ 3 ]; over_z_f = (float) over_image_f_ptr[ 1 ]; // Z under_image_f_ptr = (float *)&under_image_ptr[ 3 ]; under_z_f = (float)under_image_f_ptr[ 1 ]; // Z //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r_f, over_g_f, over_b_f, over_a_f, over_z_f, \ under_r, under_g, under_b_f, under_a_f, under_z_f,\ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ88 ) // SKIP 11 BYTES { over_r = (BYTE)over_image_ptr[ i ]; // R over_g = (BYTE)over_image_ptr[ i + 1 ]; // G over_b = (BYTE)over_image_ptr[ i + 2 ]; // B over_image_f_ptr = (float *)&over_image_ptr[ i + 3 ]; over_a_f = (float)over_image_f_ptr[ 0 ]; // A over_z_f = (float)over_image_f_ptr[ 1 ]; // Z under_r = (BYTE)under_image_ptr[ i ]; // R under_g = (BYTE)under_image_ptr[ i + 1 ]; // G under_b = (BYTE)under_image_ptr[ i + 2 ]; // B under_image_f_ptr = (float *)&under_image_ptr[ i + 3 ]; under_a_f = (float)under_image_f_ptr[ 0 ]; // A under_z_f = (float)under_image_f_ptr[ 1 ]; // Z // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a_f; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a_f = under_a_f; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a_f = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image_ptr[ i ] = (BYTE)( blend_r * 255 ); // R blend_image_ptr[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image_ptr[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image_f_ptr = (float *)&blend_image_ptr[ i + 3 ]; blend_image_f_ptr[ 0 ] = (float)blend_a; // A blend_image_f_ptr[ 1 ] = (float)over_z_f; // Z } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ96 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz96 \ ( BYTE* restrict over_image, \ BYTE* restrict under_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz96 \ ( BYTE* over_image, \ BYTE* under_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float* over_image_f_ptr; float* under_image_f_ptr; float* blend_image_f_ptr; BYTE over_r; BYTE over_g; BYTE over_b; BYTE under_r; BYTE under_g; BYTE under_b; float over_r_f; float over_g_f; float over_b_f; float over_a_f; float over_z_f; float under_r_f; float under_g_f; float under_b_f; float under_a_f; float under_z_f; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_image_f_ptr = (float *)blend_image; over_image_f_ptr = (float *)over_image; under_image_f_ptr = (float *)under_image; full_image_size = image_size * RGBAZ96; // 12 BYTES //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_image_f_ptr, under_image_f_ptr, blend_image_f_ptr, \ over_r, over_g, over_b, \ under_r, under_g, under_b, \ over_r_f, over_g_f, over_b_f, over_a_f, over_z_f, \ under_r_f, under_g_f, under_b_f, under_a_f, under_z_f, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBAZ96 ) // SKIP 12 BYTES { over_r = (BYTE)over_image[ i ]; // R over_g = (BYTE)over_image[ i + 1 ]; // G over_b = (BYTE)over_image[ i + 2 ]; // B over_image_f_ptr = (float *)&over_image[ i + 4 ]; over_a_f = (float)over_image_f_ptr[ 0 ]; // A over_z_f = (float)over_image_f_ptr[ 1 ]; // Z under_r = (BYTE)under_image[ i ]; // R under_g = (BYTE)under_image[ i + 1 ]; // G under_b = (BYTE)under_image[ i + 2 ]; // B under_image_f_ptr = (float *)&under_image[ i + 4 ]; under_a_f = (float)under_image_f_ptr[ 0 ]; // A under_z_f = (float)under_image_f_ptr[ 1 ]; // Z // Depth sorting if necessary if ( over_z_f > under_z_f ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a_f; blend_z = over_z_f; over_r = under_r; over_g = under_g; over_b = under_b; over_a_f = under_a_f; over_z_f = under_z_f; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a_f = blend_a; under_z_f = blend_z; } // Convert BYTE to Float (Range: 0.0 - 1.0) over_r_f = (float)( over_r / 255.0f ); over_g_f = (float)( over_g / 255.0f ); over_b_f = (float)( over_b / 255.0f ); under_r_f = (float)( under_r / 255.0f ); under_g_f = (float)( under_g / 255.0f ); under_b_f = (float)( under_b / 255.0f ); // Pre-calculate 1 - Src_A one_minus_alpha = 1.0f - over_a_f; // Calculate Final alpha value blend_a = (float) ( over_a_f + ( under_a_f * one_minus_alpha )); blend_r = (float)( over_r_f + ( under_r_f * one_minus_alpha )); blend_g = (float)( over_g_f + ( under_g_f * one_minus_alpha )); blend_b = (float)( over_b_f + ( under_b_f * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (BYTE)( blend_r * 255 ); // R blend_image[ i + 1 ] = (BYTE)( blend_g * 255 ); // G blend_image[ i + 2 ] = (BYTE)( blend_b * 255 ); // B blend_image[ i + 3 ] = (BYTE)0; // X blend_image_f_ptr = (float *)&blend_image[ i + 4 ]; blend_image_f_ptr[ 0 ] = (float)blend_a; // A blend_image_f_ptr[ 1 ] = (float)over_z_f; // Z } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBA128 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgba128 \ ( float* restrict over_image, \ float* restrict under_image, \ float* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba128 \ ( float* over_image, \ float* under_image, \ float* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float under_r; float under_g; float under_b; float under_a; float over_r; float over_g; float over_b; float over_a; float blend_r; float blend_g; float blend_b; float blend_a; float one_minus_alpha; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA; // 4 elements #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements(FLOAT) { // Separate R, G, B and A values of both // the foreground and background colors over_r = (float)over_image[ i ]; over_g = (float)over_image[ i + 1 ]; over_b = (float)over_image[ i + 2 ]; over_a = (float)over_image[ i + 3 ]; under_r = (float)under_image[ i ]; under_g = (float)under_image[ i + 1 ]; under_b = (float)under_image[ i + 2 ]; under_a = (float)under_image[ i + 3 ]; // ============================================= // Eliminate branching for compiler optimization // ============================================= // Pre-calculate 1 - Src_A one_minus_alpha = (float)(1.0f - over_a); // Calculate Final alpha value blend_a = (float)( over_a + ( under_a * one_minus_alpha )); blend_r = (float)( over_r + ( under_r * one_minus_alpha )); blend_g = (float)( over_g + ( under_g * one_minus_alpha )); blend_b = (float)( over_b + ( under_b * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (float)blend_r; blend_image[ i + 1 ] = (float)blend_g; blend_image[ i + 2 ] = (float)blend_b; blend_image[ i + 3 ] = (float)blend_a; } return EXIT_SUCCESS; } /*========================================================*/ /** * @brief Alpha-blend compositing (RGBAZ160 Pixels) * Back-to-Front Order * * @param over_image [in] Image to be alpha blended * @param under_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*========================================================*/ #ifdef C99 int composite_alpha_rgbaz160 \ ( float* restrict over_image, \ float* restrict under_image, \ float* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgbaz160 \ ( float* over_image, \ float* under_image, \ float* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; float under_r; float under_g; float under_b; float under_a; float under_z; float over_r; float over_g; float over_b; float over_a; float over_z; float blend_r; float blend_g; float blend_b; float blend_a; float blend_z; float one_minus_alpha; blend_z = 0.0f; full_image_size = image_size * RGBAZ; // 5 elements //===================================== // Shared Memory Parallelism //===================================== #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, one_minus_alpha, \ over_r, over_g, over_b, over_a, over_z, \ under_r, under_g, under_b, under_a, under_z, \ blend_r, blend_g, blend_b, blend_a, blend_z ) #endif for ( i = 0; i < full_image_size; i += RGBAZ ) // SKIP 5 elements(FLOAT) { // Separate R, G, B and A values of both // the foreground and background colors over_r = (float)over_image[ i ]; over_g = (float)over_image[ i + 1 ]; over_b = (float)over_image[ i + 2 ]; over_a = (float)over_image[ i + 3 ]; over_z = (float)over_image[ i + 4 ]; under_r = (float)under_image[ i ]; under_g = (float)under_image[ i + 1 ]; under_b = (float)under_image[ i + 2 ]; under_a = (float)under_image[ i + 3 ]; under_z = (float)under_image[ i + 4 ]; // Depth sorting if necessary if ( over_z > under_z ) { blend_r = over_r; blend_g = over_g; blend_b = over_b; blend_a = over_a; blend_z = over_z; over_r = under_r; over_g = under_g; over_b = under_b; over_a = under_a; over_z = under_z; under_r = blend_r; under_g = blend_g; under_b = blend_b; under_a = blend_a; under_z = blend_z; } // ======================================================= // Pre-calculate 1 - Src_A one_minus_alpha = (float)(1.0f - over_a); // Calculate Final alpha value blend_a = (float)( over_a + ( under_a * one_minus_alpha )); blend_r = (float)( over_r + ( under_r * one_minus_alpha )); blend_g = (float)( over_g + ( under_g * one_minus_alpha )); blend_b = (float)( over_b + ( under_b * one_minus_alpha )); // ======================================================= blend_r = clamp_float( blend_r, 0.0, 1.0 ); blend_g = clamp_float( blend_g, 0.0, 1.0 ); blend_b = clamp_float( blend_b, 0.0, 1.0 ); blend_a = clamp_float( blend_a, 0.0, 1.0 ); blend_image[ i ] = (float)blend_r; blend_image[ i + 1 ] = (float)blend_g; blend_image[ i + 2 ] = (float)blend_b; blend_image[ i + 3 ] = (float)blend_a; blend_image[ i + 4 ] = (float)over_z; } return EXIT_SUCCESS; } // ================================================================= // ALPHA BLENDING IMAGE COMPOSITION // ================================================================= // Optimization based on LUT (HP Image Compositing Library) // // Parallel Compositing Library // http://sourceforge.net/projects/paracomp // ================================================================= /* BEGINPARACOMPCOPYRIGHT * The Parallel Compositing Library * Copyright (c) 2007 Hewlett-Packard Development Company, L.P. * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or (at your option) * any later version. * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * ENDPARACOMPCOPYRIGHT */ /*===========================================================================*/ /** * @brief Generate look up tables for alpha blending operation. */ /*===========================================================================*/ void Create_AlphaBlend_LUT ( void ) { unsigned int Alpha; unsigned int Color; unsigned int Saturation; unsigned int Color_Val1, Color_Val2; unsigned int Alpha_Div_256; unsigned int Alpha_Sub_255; // Generate Product Lookup Table for ( Alpha = 0; Alpha < 256; Alpha++ ) { Alpha_Div_256 = Alpha << 8; Alpha_Sub_255 = 255 - Alpha; for ( Color = 0; Color < 256; Color++ ) { Color_Val1 = (unsigned int)(( Alpha_Sub_255 * Color ) + 0x80 ) >> 8; Color_Val2 = (unsigned int)(( Alpha * Color ) + 0x80 ) >> 8; LUT_Mult1[ Alpha_Div_256 | Color ] = ( BYTE )Color_Val1; LUT_Mult2[ Alpha_Div_256 | Color ] = ( BYTE )Color_Val2; } } // Generate Saturation Lookup Table for ( Saturation = 0; Saturation < 512; Saturation++ ) { LUT_Sat[ Saturation ] = (BYTE)(( Saturation > 255 ) ? 255 : Saturation); } } /*===========================================================================*/ /** * @brief Alpha-blend compositing. * * @param under_image [in] Image to be alpha blended * @param over_image [in] Image to be alpha blended * @param blend_image [in] Image to be alpha blended * @param image_size [in] Image size */ /*===========================================================================*/ #ifdef C99 int composite_alpha_rgba32_LUT \ ( BYTE* restrict under_image, \ BYTE* restrict over_image, \ BYTE* restrict blend_image, \ unsigned int image_size ) #else int composite_alpha_rgba32_LUT \ ( BYTE* under_image, \ BYTE* over_image, \ BYTE* blend_image, \ unsigned int image_size ) #endif { unsigned int i; unsigned int full_image_size; BYTE *blend_image_ptr; BYTE under_r; BYTE under_g; BYTE under_b; BYTE under_a; BYTE over_r; BYTE over_g; BYTE over_b; BYTE over_a; BYTE blend_r; BYTE blend_g; BYTE blend_b; BYTE blend_a; unsigned int Alpha_Div_256; blend_image_ptr = (BYTE *)blend_image; //===================================== // Shared Memory Parallelism //===================================== full_image_size = image_size * RGBA32; #if defined ( _OPENMP ) #pragma omp parallel for \ private( i, Alpha_Div_256, \ over_r, over_g, over_b, over_a, \ under_r, under_g, under_b, under_a, \ blend_r, blend_g, blend_b, blend_a ) #endif for ( i = 0; i < full_image_size; i += RGBA ) // SKIP 4 elements { // Separate R, G, B and A values of both // the foreground and background colors over_r = (BYTE)over_image[ i ]; over_g = (BYTE)over_image[ i + 1 ]; over_b = (BYTE)over_image[ i + 2 ]; over_a = (BYTE)over_image[ i + 3 ]; under_r = (BYTE)under_image[ i ]; under_g = (BYTE)under_image[ i + 1 ]; under_b = (BYTE)under_image[ i + 2 ]; under_a = (BYTE)under_image[ i + 3 ]; Alpha_Div_256 = ((unsigned int)over_a) << 8; // ======================================================= blend_r = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult1[ \ Alpha_Div_256 | ((unsigned int)under_r ) ] ) \ + ((unsigned int)LUT_Mult2[ Alpha_Div_256 | (unsigned int) over_r ]) ]; blend_g = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult1[ \ Alpha_Div_256 | ((unsigned int)under_g) ] ) \ + ((unsigned int)LUT_Mult2[ Alpha_Div_256 | (unsigned int) over_g ]) ]; blend_b = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult1[ \ Alpha_Div_256 | ((unsigned int)under_b ) ] ) \ + ((unsigned int)LUT_Mult2[ Alpha_Div_256 | (unsigned int) over_b ]) ]; blend_a = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult1[ \ Alpha_Div_256 | ((unsigned int)under_a) ] ) \ + ((unsigned int)LUT_Mult2[ Alpha_Div_256 | (unsigned int) over_a ]) ]; // ======================================================= /* blend_r = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_r ) ] ) \ + ((unsigned int)over_r ) ]; blend_g = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_g) ] ) \ + ((unsigned int)over_g ) ]; blend_b = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_b ) ] ) \ + ((unsigned int)over_b ) ]; blend_a = (BYTE)LUT_Sat[ ((unsigned int)LUT_Mult[ \ Alpha_Div_256 | ((unsigned int)under_a) ] ) \ + ((unsigned int)over_a ) ]; */ // ======================================================= blend_image_ptr[ i ] = (BYTE)( blend_r ); blend_image_ptr[ i + 1 ] = (BYTE)( blend_g ); blend_image_ptr[ i + 2 ] = (BYTE)( blend_b ); blend_image_ptr[ i + 3 ] = (BYTE)( blend_a ); } return EXIT_SUCCESS; }
energy.h
#pragma once #include "bonds.h" #include "externalpotential.h" // Energybase implemented here #include <range/v3/view.hpp> #include <Eigen/Dense> #ifdef ENABLE_POWERSASA #include <power_sasa.h> #endif namespace Faunus { namespace ReactionCoordinate { struct ReactionCoordinateBase; } namespace Potential { struct PairPotentialBase; } namespace Energy { class Hamiltonian; /** * @brief Check for overlap between atoms and the simulation container * * If found infinite energy is returned. Not needed for cuboidal geometry * as there's nover any overlap due to PBC. */ struct ContainerOverlap : public Energybase { const Space &spc; ContainerOverlap(const Space &spc) : spc(spc) { name = "ContainerOverlap"; } double energy(Change &change) override; }; /** * This holds Ewald setup and must *not* depend on particle type, nor depend on Space */ struct EwaldData { typedef std::complex<double> Tcomplex; Eigen::Matrix3Xd kVectors; // k-vectors, 3xK Eigen::VectorXd Aks; // 1xK, to minimize computational effort (Eq.24,DOI:10.1063/1.481216) Eigen::VectorXcd Qion, Qdip; // 1xK double alpha, rc, kc, check_k2_zero, lB; double const_inf, eps_surf, kappa, kappa2; bool spherical_sum = true; bool ipbc = false; int kVectorsInUse = 0; Point L; //!< Box dimensions EwaldData(const json &); void update(const Point &box); }; void to_json(json &, const EwaldData &); #ifdef DOCTEST_LIBRARY_INCLUDED TEST_CASE("[Faunus] Ewald - EwaldData") { using doctest::Approx; EwaldData data(R"({ "ipbc": false, "epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0, "kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json); data.update(Point(10, 10, 10)); CHECK(data.ipbc == false); CHECK(data.const_inf == 1); CHECK(data.alpha == 0.894427190999916); CHECK(data.kVectors.cols() == 2975); CHECK(data.Qion.size() == data.kVectors.cols()); data.ipbc = true; data.update(Point(10, 10, 10)); CHECK(data.kVectors.cols() == 846); CHECK(data.Qion.size() == data.kVectors.cols()); } #endif /** * @brief recipe or policies for ion-ion ewald * @todo * - eliminate raw pointers * - undefined bahevior if ipbc==true adn eigenopt==true */ template <bool eigenopt = false /** use Eigen matrix ops where possible */> struct PolicyIonIon { typedef typename ParticleVector::iterator iter; Space *spc; Space *old = nullptr; // set only if key==NEW at first call to `sync()` PolicyIonIon(Space &spc) : spc(&spc) {} /** * @brief Updates the reciprocal space terms 'Q^q' and 'A_k'. See eqs. 24 and 25 in ref. for PBC Ewald, and eq. 2 in doi:10/css8 for IPBC Ewald. */ void updateComplex(EwaldData &data) const { auto active = spc->activeParticles(); if (eigenopt) { // calculate using Eigen operations. Faster for large systems? if(data.ipbc) { auto pos = asEigenMatrix(active.begin().base(), active.end().base(), &Space::Tparticle::pos); // N x 3 auto charge = asEigenVector(active.begin().base(), active.end().base(), &Space::Tparticle::charge); // N x 1 data.Qion.real() = ( data.kVectors.array().cwiseProduct(pos).array().cos().prod() * charge ).colwise().sum(); // see eq. 2 in doi:10/css8 } else { auto pos = asEigenMatrix(active.begin().base(), active.end().base(), &Space::Tparticle::pos); // N x 3 auto charge = asEigenVector(active.begin().base(), active.end().base(), &Space::Tparticle::charge); // N x 1 Eigen::MatrixXd kr = pos.matrix() * data.kVectors; // ( N x 3 ) * ( 3 x K ) = N x K data.Qion.real() = (kr.array().cos().colwise() * charge).colwise().sum(); // real part of 'Q^q', see eq. 25 in ref. data.Qion.imag() = kr.array().sin().colwise().sum(); // imaginary part of 'Q^q', see eq. 25 in ref. } } else { // calculate using generic loops for (int k = 0; k < data.kVectors.cols(); k++) { const Point &kv = data.kVectors.col(k); EwaldData::Tcomplex Q(0, 0); if (data.ipbc) for (auto &i : active) Q += kv.cwiseProduct(i.pos).array().cos().prod() * i.charge; // see eq. 2 in doi:10/css8 else { for (auto &i : active) { double dot = kv.dot(i.pos); Q += i.charge * EwaldData::Tcomplex(std::cos(dot), std::sin(dot)); // 'Q^q', see eq. 25 in ref. } } data.Qion[k] = Q; } } } //!< Update all k vectors void updateComplex(EwaldData &data, Change &change) const { assert(old != nullptr); assert(spc->p.size() == old->p.size()); for (int k = 0; k < data.kVectors.cols(); k++) { auto &Q = data.Qion[k]; Point q = data.kVectors.col(k); if (data.ipbc) { for (auto cg : change.groups) { auto g_new = spc->groups.at(cg.index); auto g_old = old->groups.at(cg.index); for (auto i : cg.atoms) { if (i < g_new.size()) Q += q.cwiseProduct((g_new.begin() + i)->pos).array().cos().prod() * (g_new.begin() + i)->charge; if (i < g_old.size()) Q -= q.cwiseProduct((g_old.begin() + i)->pos).array().cos().prod() * (g_old.begin() + i)->charge; } } } else { for (auto cg : change.groups) { auto g_new = spc->groups.at(cg.index); auto g_old = old->groups.at(cg.index); for (auto i : cg.atoms) { if (i < g_new.size()) { double _new = q.dot((g_new.begin() + i)->pos); Q += (g_new.begin() + i)->charge * EwaldData::Tcomplex(std::cos(_new), std::sin(_new)); } if (i < g_old.size()) { double _old = q.dot((g_old.begin() + i)->pos); Q -= (g_old.begin() + i)->charge * EwaldData::Tcomplex(std::cos(_old), std::sin(_old)); } } } } } } //!< Optimized update of k subset. Require access to old positions through `old` pointer // selfEnergies should be handled by the real-space pair-potential // todo: this should not be used, but replaced by selfEnergy in PairPotential double selfEnergy(const EwaldData &d, Change &change) { double Eq = 0; if (change.dN) { for (auto cg : change.groups) { auto g = spc->groups.at(cg.index); for (auto i : cg.atoms) if (i < g.size()) Eq += std::pow((g.begin() + i)->charge, 2); } } else if (change.all and not change.dV) { for (auto g : spc->groups) for (auto i : g) Eq += i.charge * i.charge; } return -d.alpha * Eq / std::sqrt(pc::pi) * d.lB; } double surfaceEnergy(const EwaldData &d, Change &change) { if (d.const_inf < 0.5) return 0; Point qr(0, 0, 0); if (change.all or change.dV) for (auto g : spc->groups) for (auto i : g) qr += i.charge * i.pos; else if (change.groups.size() > 0) { for (auto cg : change.groups) { auto g = spc->groups.at(cg.index); for (auto i : cg.atoms) if (i < g.size()) qr += (g.begin() + i)->charge * (g.begin() + i)->pos; } } return d.const_inf * 2 * pc::pi / ((2 * d.eps_surf + 1) * spc->geo.getVolume()) * qr.dot(qr) * d.lB; } double reciprocalEnergy(const EwaldData &d) { double E = 0; if (eigenopt) // known at compile time E = d.Aks.cwiseProduct(d.Qion.cwiseAbs2()).sum(); else for (int k = 0; k < d.Qion.size(); k++) E += d.Aks[k] * std::norm(d.Qion[k]); return 2 * pc::pi / spc->geo.getVolume() * E * d.lB; } }; #ifdef DOCTEST_LIBRARY_INCLUDED TEST_CASE("[Faunus] Ewald - IonIonPolicy") { using doctest::Approx; Space spc; spc.p.resize(2); spc.geo = R"( {"type": "cuboid", "length": 10} )"_json; spc.p[0] = R"( {"pos": [0,0,0], "q": 1.0} )"_json; spc.p[1] = R"( {"pos": [1,0,0], "q": -1.0} )"_json; Group<Particle> g(spc.p.begin(), spc.p.end()); spc.groups.push_back(g); EwaldData data = R"({ "epsr": 1.0, "alpha": 0.894427190999916, "epss": 1.0, "kcutoff": 11.0, "spherical_sum": true, "cutoff": 5.0})"_json; Change c; c.all = true; data.ipbc = false; // PBC Ewald (http://dx.doi.org/10.1063/1.481216) data.update(spc.geo.getLength()); SUBCASE("standard loop") { PolicyIonIon<false> ionion(spc); ionion.updateComplex(data); CHECK(ionion.selfEnergy(data, c) == Approx(-1.0092530088080642 * data.lB)); CHECK(ionion.surfaceEnergy(data, c) == Approx(0.0020943951023931952 * data.lB)); CHECK(ionion.reciprocalEnergy(data) == Approx(0.21303063979675319 * data.lB)); data.ipbc = true; // IPBC Ewald data.update(spc.geo.getLength()); ionion.updateComplex(data); CHECK(ionion.selfEnergy(data, c) == Approx(-1.0092530088080642 * data.lB)); CHECK(ionion.surfaceEnergy(data, c) == Approx(0.0020943951023931952 * data.lB)); CHECK(ionion.reciprocalEnergy(data) == Approx(0.0865107467 * data.lB)); } SUBCASE("eigen operations") { data.ipbc = false; data.update(spc.geo.getLength()); PolicyIonIon<true> ionion(spc); ionion.updateComplex(data); CHECK(ionion.selfEnergy(data, c) == Approx(-1.0092530088080642 * data.lB)); CHECK(ionion.surfaceEnergy(data, c) == Approx(0.0020943951023931952 * data.lB)); CHECK(ionion.reciprocalEnergy(data) == Approx(0.21303063979675319 * data.lB)); } } #endif /** @brief Ewald summation reciprocal energy */ template <class Policy = PolicyIonIon<>> class Ewald : public Energybase { private: EwaldData data; Policy policy; Space &spc; public: Ewald(const json &j, Space &spc) : data(j), policy(spc), spc(spc) { name = "ewald"; cite = "doi:10.1063/1.481216"; init(); } void init() override { data.update(spc.geo.getLength()); policy.updateComplex(data); // brute force. todo: be selective } double energy(Change &change) override { double u = 0; if (change) { // If the state is NEW (trial state), then update all k-vectors if (key == NEW) { if (change.all or change.dV) { // everything changes data.update(spc.geo.getLength()); policy.updateComplex(data); // update all (expensive!) } else { if (change.groups.size() > 0) policy.updateComplex(data, change); } } // todo: omit selfEnergy() call as this should be added as a separate term in `Hamiltonian` u = policy.surfaceEnergy(data, change) + policy.reciprocalEnergy(data) + policy.selfEnergy(data, change); } return u; } void sync(Energybase *basePtr, Change &) override { auto other = dynamic_cast<decltype(this)>(basePtr); assert(other); if (other->key == OLD) policy.old = &(other->spc); // give NEW access to OLD space for optimized updates data = other->data; // copy everything! } //!< Called after a move is rejected/accepted as well as before simulation void to_json(json &j) const override { j = data; } }; class Isobaric : public Energybase { private: Space &spc; double P; // P/kT public: Isobaric(const json &, Space &); double energy(Change &) override; void to_json(json &) const override; }; /** * @brief Constrain system using reaction coordinates * * If outside specified `range`, infinity energy is returned, causing rejection. */ class Constrain : public Energybase { private: std::string type; std::shared_ptr<ReactionCoordinate::ReactionCoordinateBase> rc = nullptr; public: Constrain(const json &, Space &); double energy(Change &) override; void to_json(json &) const override; }; /* * The keys of the `intra` map are group index and the values * is a vector of `BondData`. For bonds between groups, fill * in `inter` which is evaluated for every update of call to * `energy`. * * @todo Optimize. */ class Bonded : public Energybase { private: Space &spc; typedef std::vector<std::shared_ptr<Potential::BondData>> BondVector; BondVector inter; // inter-molecular bonds std::map<int, BondVector> intra; // intra-molecular bonds private: void update_intra(); // finds and adds all intra-molecular bonds of active molecules double sum_energy(const BondVector &) const; // sum energy in vector of BondData double sum_energy(const BondVector &, const std::vector<int> &) const; // sum energy in vector of BondData for matching particle indices public: Bonded(const json &, Space &); void to_json(json &) const override; double energy(Change &) override; // brute force -- refine this! }; /** * @brief Nonbonded energy using a pair-potential */ template <typename Tpairpot> class Nonbonded : public Energybase { private: double g2gcnt = 0, g2gskip = 0; PairMatrix<double> cutoff2; // matrix w. group-to-group cutoff std::vector<const Particle *> i_interact_with_these; protected: typedef typename Space::Tgroup Tgroup; double Rc2_g2g = pc::infty; // control of when OpenMP should be used bool omp_enable = false; bool omp_i2all = false; bool omp_g2g = false; bool omp_p2p = false; void to_json(json &j) const override { j["pairpot"] = pairpot; if (omp_enable) { json _a = json::array(); if (omp_p2p) _a.push_back("p2p"); if (omp_g2g) _a.push_back("g2g"); if (omp_i2all) _a.push_back("i2all"); j["openmp"] = _a; } j["cutoff_g2g"] = json::object(); auto &_j = j["cutoff_g2g"]; for (auto &a : Faunus::molecules) for (auto &b : Faunus::molecules) if (a.id() >= b.id()) _j[a.name + " " + b.name] = sqrt(cutoff2(a.id(), b.id())); } template <typename T> inline bool cut(const T &g1, const T &g2) { g2gcnt++; if (g1.atomic || g2.atomic) return false; if (spc.geo.sqdist(g1.cm, g2.cm) < cutoff2(g1.id, g2.id)) return false; g2gskip++; return true; } //!< true if group<->group interaction can be skipped template <typename T> inline double i2i(const T &a, const T &b) { assert(&a != &b && "a and b cannot be the same particle"); return pairpot(a, b, spc.geo.vdist(a.pos, b.pos)); } /* * Internal energy in group, calculating all with all or, if `index` * is given, only a subset. Index specifies the internal index (starting * from zero) of changed particles within the group. */ double g_internal(const Tgroup &g, const std::vector<int> &index = std::vector<int>()) { using namespace ranges; double u = 0; if (index.empty() and not molecules.at(g.id).rigid) // assume that all atoms have changed for (auto i = g.begin(); i != g.end(); ++i) for (auto j = i; ++j != g.end();) u += i2i(*i, *j); else { // only a subset has changed auto fixed = view::ints(0, int(g.size())) | view::remove_if([&index](int i) { return std::binary_search(index.begin(), index.end(), i); }); for (int i : index) { // moved<->static for (int j : fixed) { u += i2i(*(g.begin() + i), *(g.begin() + j)); } } for (int i : index) // moved<->moved for (int j : index) if (j > i) u += i2i(*(g.begin() + i), *(g.begin() + j)); } return u; } /* * Calculates the interaction energy of a particle, `i`, * and checks (1) if it is already part of Space, or (2) * external to space. */ double i2all(const typename Space::Tparticle &i) { if (omp_enable and omp_i2all) return i2all_parallel(i); double u = 0; auto it = spc.findGroupContaining(i); // iterator to group if (it != spc.groups.end()) { // check if i belongs to group in space for (size_t ig = 0; ig < spc.groups.size(); ig++) { auto &g = spc.groups[ig]; if (&g != &(*it)) // avoid self-interaction if (not cut(g, *it)) // check g2g cut-off for (auto &j : g) // loop over particles in other group u += i2i(i, j); } for (auto &j : *it) // i with all particles in own group if (&j != &i) u += i2i(i, j); } else // particle does not belong to any group for (auto &g : spc.groups) // i with all other *active* particles for (auto &j : g) // (this will include only active particles) u += i2i(i, j); return u; } double i2all_parallel(const typename Space::Tparticle &i) { i_interact_with_these.clear(); double u = 0; auto it = spc.findGroupContaining(i); // iterator to group if (it != spc.groups.end()) { // check if i belongs to group in space for (size_t ig = 0; ig < spc.groups.size(); ig++) { auto &g = spc.groups[ig]; if (&g != &(*it)) // avoid self-interaction if (not cut(g, *it)) // check g2g cut-off for (auto &j : g) // loop over particles in other group i_interact_with_these.push_back(&j); // u += i2i(i, j); } for (auto &j : *it) // i with all particles in own group if (&j != &i) i_interact_with_these.push_back(&j); // u += i2i(i, j); } else // particle does not belong to any group for (auto &g : spc.groups) // i with all other *active* particles for (auto &j : g) // (this will include only active particles) i_interact_with_these.push_back(&j); // u += i2i(i, j); #pragma omp parallel for reduction(+ : u) if (omp_enable and omp_i2all) for (size_t k = 0; k < i_interact_with_these.size(); k++) u += i2i(i, *i_interact_with_these[k]); return u; } /* * Group-to-group energy. A subset of `g1` can be given with `index` which refers * to the internal index (starting at zero) of the first group, `g1 * NOTE: the interpretation of this function is extended to also consider the mutual interactions * of a subset of each group and in such case returns sub1 <-> 2 and !sub1<->sub2, * hence excluding !sub1 <-> !sub2 in comparision to calling onconstrained g2g. In absence * of sub1 any sub2 is ignored. */ virtual double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index = std::vector<int>(), const std::vector<int> &jndex = std::vector<int>()) { using namespace ranges; double u = 0; if (not cut(g1, g2)) { if (index.empty() && jndex.empty()) // if index is empty, assume all in g1 have changed #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_p2p) for (size_t i = 0; i < g1.size(); i++) for (size_t j = 0; j < g2.size(); j++) u += i2i(*(g1.begin() + i), *(g2.begin() + j)); else { // only a subset of g1 for (auto i : index) for (auto j = g2.begin(); j != g2.end(); ++j) u += i2i(*(g1.begin() + i), *j); if (not jndex.empty()) { auto fixed = view::ints(0, int(g1.size())) | view::remove_if([&index](int i) { return std::binary_search(index.begin(), index.end(), i); }); for (auto i : jndex) // moved2 <-| for (auto j : fixed) // static1 <-| u += i2i(*(g2.begin() + i), *(g1.begin() + j)); } } } return u; } // add self energy term to Hamiltonian if appropriate void addPairPotentialSelfEnergy() { if (pairpot.selfEnergy) // only add if self energy is defined pot.push_back<Energy::ParticleSelfEnergy>(spc, pairpot.selfEnergy); } void configureOpenMP(const json &j) { auto it = j.find("openmp"); if (it != j.end()) if (it->is_array()) if (it->size() > 0) { omp_enable = true; for (const std::string &k : *it) if (k == "g2g") omp_g2g = true; else if (k == "p2p") omp_p2p = true; else if (k == "i2all") omp_i2all = true; #ifndef _OPENMP std::cerr << "warning: nonbonded requests unavailable OpenMP." << endl; #endif } } public: Space &spc; //!< Space to operate on BasePointerVector<Energybase> &pot; Tpairpot pairpot; //!< Pair potential Nonbonded(const json &j, Space &spc, BasePointerVector<Energybase> &pot) : spc(spc), pot(pot) { name = "nonbonded"; pairpot = j; // some pair-potentials give rise to self-energies (Wolf etc.) // which are added here if needed addPairPotentialSelfEnergy(); configureOpenMP(j); // disable all group-to-group cutoffs by setting infinity for (auto &i : Faunus::molecules) for (auto &j : Faunus::molecules) cutoff2.set(i.id(), j.id(), pc::infty); auto it = j.find("cutoff_g2g"); if (it != j.end()) { // old style input w. only a single cutoff if (it->is_number()) { Rc2_g2g = std::pow(it->get<double>(), 2); for (auto &i : Faunus::molecules) for (auto &j : Faunus::molecules) cutoff2.set(i.id(), j.id(), Rc2_g2g); } // new style input w. multiple cutoffs between molecules else if (it->is_object()) { // ensure that there is a default, fallback cutoff Rc2_g2g = std::pow(it->at("default").get<double>(), 2); for (auto &i : Faunus::molecules) for (auto &j : Faunus::molecules) cutoff2.set(i.id(), j.id(), Rc2_g2g); // loop for space separated molecule pairs in keys for (auto &i : it->items()) { auto v = words2vec<std::string>(i.key()); if (v.size() == 2) { int id1 = (*findName(Faunus::molecules, v[0])).id(); int id2 = (*findName(Faunus::molecules, v[1])).id(); cutoff2.set(id1, id2, std::pow(i.value().get<double>(), 2)); } } } } } /** * Calculates the force on all particles * @todo Change to reflect only active particle, see Space::activeParticles() */ void force(std::vector<Point> &forces) override { auto &p = spc.p; // alias to particle vector (reference) assert(forces.size() == p.size() && "the forces size must match the particle size"); for (size_t i = 0; i < p.size() - 1; i++) { for (size_t j = i + 1; j < p.size(); j++) { Point r = spc.geo.vdist(p[i].pos, p[j].pos); // minimum distance vector Point f = pairpot.force(p[i], p[j], r.squaredNorm(), r); forces[i] += f; forces[j] -= f; } } } double energy(Change &change) override { using namespace ranges; double u = 0; if (change) { // there's a change in system volume if (change.dV) { #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g) for (auto i = spc.groups.begin(); i < spc.groups.end(); ++i) { for (auto j = i; ++j != spc.groups.end();) u += g2g(*i, *j); if (i->atomic) u += g_internal(*i); } return u; } // did everything change? if (change.all) { #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g) for (auto i = spc.groups.begin(); i < spc.groups.end(); ++i) { for (auto j = i; ++j != spc.groups.end();) u += g2g(*i, *j); u += g_internal(*i); } // more todo here... return u; } // if exactly ONE molecule is changed if (change.groups.size() == 1 && not change.dN) { auto &d = change.groups[0]; auto gindex = spc.groups.at(d.index).to_index(spc.p.begin()).first; // exactly one atom has move if (d.atoms.size() == 1) return i2all(spc.p.at(gindex + d.atoms[0])); // more atoms moved auto &g1 = spc.groups.at(d.index); // for (auto &g2 : spc.groups) #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g) for (size_t i = 0; i < spc.groups.size(); i++) { auto &g2 = spc.groups[i]; if (&g1 != &g2) u += g2g(g1, g2, d.atoms); } if (d.internal) u += g_internal(g1, d.atoms); return u; } auto moved = change.touchedGroupIndex(); // index of moved groups auto fixed = view::ints(0, int(spc.groups.size())) | view::remove_if([&moved](int i) { return std::binary_search(moved.begin(), moved.end(), i); }); // index of static groups if (change.dN) { /*auto moved = change.touchedGroupIndex(); // index of moved groups std::vector<int> Moved; for (auto i: moved) { Moved.push_back(i); } std::sort( Moved.begin(), Moved.end() ); auto fixed = view::ints( 0, int(spc.groups.size()) ) | view::remove_if( [&Moved](int i){return std::binary_search(Moved.begin(), Moved.end(), i);} ); // index of static groups*/ for (auto cg1 = change.groups.begin(); cg1 < change.groups.end(); ++cg1) { // Loop over all changed groups std::vector<int> ifiltered, jfiltered; // Active atoms auto g1 = &spc.groups.at(cg1->index); for (auto i : cg1->atoms) { if (i < g1->size()) ifiltered.push_back(i); } // Skip if the group is empty if (not ifiltered.empty()) for (auto j : fixed) u += g2g(*g1, spc.groups[j], ifiltered, jfiltered); for (auto cg2 = cg1; ++cg2 != change.groups.end();) { for (auto i : cg2->atoms) if (i < spc.groups.at(cg2->index).size()) jfiltered.push_back(i); // Skip if both groups are empty if (not(ifiltered.empty() && jfiltered.empty())) u += g2g(*g1, spc.groups.at(cg2->index), ifiltered, jfiltered); jfiltered.clear(); } if (not ifiltered.empty() and not molecules.at(g1->id).rigid) { if (cg1->all) { u += g_internal(*g1); } else u += g_internal(*g1, ifiltered); } } return u; } // moved<->moved if (change.moved2moved) { for (auto i = moved.begin(); i != moved.end(); ++i) for (auto j = i; ++j != moved.end();) u += g2g(spc.groups[*i], spc.groups[*j]); } // moved<->static if (omp_enable and omp_g2g) { std::vector<std::pair<int, int>> pairs(size(moved) * size(fixed)); size_t cnt = 0; for (auto i : moved) for (auto j : fixed) pairs[cnt++] = {i, j}; #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (omp_enable and omp_g2g) for (size_t i = 0; i < pairs.size(); i++) u += g2g(spc.groups[pairs[i].first], spc.groups[pairs[i].second]); } else for (auto i : moved) for (auto j : fixed) u += g2g(spc.groups[i], spc.groups[j]); // more todo! } return u; } }; //!< Nonbonded, pair-wise additive energy term template <typename Tpairpot> class NonbondedCached : public Nonbonded<Tpairpot> { private: typedef Nonbonded<Tpairpot> base; typedef typename Space::Tgroup Tgroup; Eigen::MatrixXf cache; Space &spc; #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" double g2g(const Tgroup &g1, const Tgroup &g2, const std::vector<int> &index = std::vector<int>(), const std::vector<int> &jndex = std::vector<int>()) override { #pragma GCC diagnostic pop int i = &g1 - &base::spc.groups.front(); int j = &g2 - &base::spc.groups.front(); if (j < i) std::swap(i, j); if (base::key == Energybase::NEW) { // if this is from the trial system, double u = 0; if (not base::cut(g1, g2)) { for (auto &i : g1) for (auto &j : g2) u += base::i2i(i, j); } cache(i, j) = u; } return cache(i, j); // return (cached) value } public: NonbondedCached(const json &j, Space &spc, BasePointerVector<Energybase> &pot) : base(j, spc, pot), spc(spc) { base::name += "EM"; init(); } void init() override { cache.resize(spc.groups.size(), spc.groups.size()); cache.setZero(); for (auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i) { for (auto j = i; ++j != base::spc.groups.end();) { int k = &(*i) - &base::spc.groups.front(); int l = &(*j) - &base::spc.groups.front(); if (l < k) std::swap(k, l); double u = 0; if (!base::cut(*i, *j)) { for (auto &k : *i) for (auto &l : *j) u += base::i2i(k, l); } cache(k, l) = u; } } } //!< Cache pair interactions in matrix double energy(Change &change) override { using namespace ranges; double u = 0; if (change) { if (change.all || change.dV) { #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable) for (auto i = base::spc.groups.begin(); i < base::spc.groups.end(); ++i) { for (auto j = i; ++j != base::spc.groups.end();) u += g2g(*i, *j); } return u; } // if exactly ONE molecule is changed if (change.groups.size() == 1) { auto &d = change.groups[0]; auto &g1 = base::spc.groups.at(d.index); #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable and this->omp_g2g) for (size_t i = 0; i < spc.groups.size(); i++) { auto &g2 = spc.groups[i]; if (&g1 != &g2) u += g2g(g1, g2, d.atoms); } return u; } auto moved = change.touchedGroupIndex(); // index of moved groups auto fixed = view::ints(0, int(base::spc.groups.size())) | view::remove_if([&moved](int i) { return std::binary_search(moved.begin(), moved.end(), i); }); // index of static groups // moved<->moved if (change.moved2moved) for (auto i = moved.begin(); i != moved.end(); ++i) for (auto j = i; ++j != moved.end();) u += g2g(base::spc.groups[*i], base::spc.groups[*j]); // moved<->static if (this->omp_enable and this->omp_g2g) { std::vector<std::pair<int, int>> pairs(size(moved) * size(fixed)); size_t cnt = 0; for (auto i : moved) for (auto j : fixed) pairs[cnt++] = {i, j}; #pragma omp parallel for reduction(+ : u) schedule(dynamic) if (this->omp_enable and this->omp_g2g) for (size_t i = 0; i < pairs.size(); i++) u += g2g(spc.groups[pairs[i].first], spc.groups[pairs[i].second]); } else for (auto i : moved) for (auto j : fixed) u += g2g(base::spc.groups[i], base::spc.groups[j]); // more todo! } return u; } void sync(Energybase *basePtr, Change &change) override { auto other = dynamic_cast<decltype(this)>(basePtr); assert(other); if (change.all || change.dV) cache.triangularView<Eigen::StrictlyUpper>() = (other->cache).template triangularView<Eigen::StrictlyUpper>(); else for (auto &d : change.groups) { for (int i = 0; i < d.index; i++) cache(i, d.index) = other->cache(i, d.index); for (size_t i = d.index + 1; i < base::spc.groups.size(); i++) cache(d.index, i) = other->cache(d.index, i); } } //!< Copy energy matrix from other }; //!< Nonbonded with cached energies (Energy Matrix) #ifdef ENABLE_POWERSASA /* * @todo: * - can only a subset of sasa be calculated? Note that it's the * `update_coord()` function that takes up most time. * - delegate to GPU? In the PowerSasa paper this is mentioned */ class SASAEnergy : public Energybase { public: std::vector<double> sasa, radii; private: Space &spc; double probe; // sasa probe radius (angstrom) double conc = 0; // co-solute concentration (mol/l) Average<double> avgArea; // average surface area std::shared_ptr<POWERSASA::PowerSasa<double, Point>> ps = nullptr; void updateSASA(const ParticleVector &p); void to_json(json &j) const override; /* * @note * This is not enough as the PowerSasa object contains data * that also need syncing. It works due to the `update` (expensive!) * call in `energy`. */ void sync(Energybase *basePtr, Change &c) override; public: SASAEnergy(const json &j, Space &spc); void init() override; double energy(Change &) override; }; //!< SASA energy from transfer free energies #endif struct Example2D : public Energybase { Point &i; // reference to 1st particle in the system Example2D(const json &, Space &spc); double energy(Change &change) override; }; class Hamiltonian : public Energybase, public BasePointerVector<Energybase> { protected: double maxenergy = pc::infty; //!< Maximum allowed energy change void to_json(json &j) const override; void addEwald(const json &j, Space &spc); //!< Adds an instance of reciprocal space Ewald energies (if appropriate) public: Hamiltonian(Space &spc, const json &j); double energy(Change &change) override; //!< Energy due to changes void init() override; void sync(Energybase *basePtr, Change &change) override; }; //!< Aggregates and sum energy terms } // namespace Energy } // namespace Faunus