source
stringlengths
3
92
c
stringlengths
26
2.25M
test.c
#include <stdio.h> #define M (1024*1024) #define BUFF_SIZE (1*M) #define N (8*BUFF_SIZE) int b[N]; int Test(int start, int size) { int i; int errors = 0; for(i=0; i<start; i++) b[i] = -1; for(i=start; i<size; i++) b[i] = i; for(i=size; i<N; i++) b[i] = -1; #pragma omp target parallel for for(int i=start; i<size; i++) b[i] += 1; for(i=0; i<start && errors<25; i++) { if (b[i] != -1) printf("%4i: before, got %d, expected %d, %d error\n", i, b[i], -1, ++errors); } for(i=start; i<size && errors<25; i++) { if (b[i] != i+1) printf("%4i: in, got %d, expected %d, %d error\n", i, b[i], i+1, ++errors); } for(i=size; i<N && errors<25; i++) { if (b[i] != -1) printf("%4i: after, got %d, expected %d, %d error\n", i, b[i], -1, ++errors); } if (errors>0) { printf("success with start %d, size %d (%d mod buff size)\n\n", start, size, size % BUFF_SIZE); } else { printf("%d errors with start %d, size %d (%d mod buff size)\n\n", errors, start, size, size % BUFF_SIZE); } return (errors>0); } int main() { int offset[] = {0, 1, 2, BUFF_SIZE/2, BUFF_SIZE-2, BUFF_SIZE-1}; int onum = 6; int errors = 0; for(int s1=0; s1<6; s1++) { for(int s2=0; s2<6; s2++) { errors += Test(offset[s1], N-offset[s2]); if (errors>20) { printf("abort due to errors\n"); return errors; } } } printf("finished with %d errors\n", errors); return errors; }
collision.c
#include "helper.h" #include "collision.h" #include <omp.h> /* Dotprod function, calcuales the dot product of two vectors */ float dotProd (const float * array1, float * array2, int length){ int i; float product =0; for (i = 0; i < length; ++i){ product += array1[i] * array2[i]; } return product; } /* computeExternal : Calculates the influence of external forces in the lattices */ float computeExternal (int i, float density, float * extForces){ return dotProd(LATTICEVELOCITIES[i], extForces, D) * density * LATTICEWEIGHTS[i]; } /** computes the post-collision distribution functions according to the BGK update rule and * stores the results again at the same position. */ void computePostCollisionDistributions(int *node, float * currentCell, int* flagField, float* fractionField, const float * const tau_inv, const float *const feq, const float *const feqAtm, float density, float * extForces, int * n){ int i; float fi; for (i=0; i<Q; i++) { fi = currentCell[i]; currentCell[i] = fi - (fi - feq[i]) * (*tau_inv) + computeExternal(i, density, extForces); } } void doCollision(float *collideField, int *flagField, float * massField, float * fractionField, const float * const tau, int * length, float * extForces, int n_threads){ float density, densityAtm =1; float velocity[D]; float feq[Q], feqAtm[Q]; float * currentCell; int x, y, z, node[3], flag, isFluid; int n[3] = { length[0] + 2, length[1] + 2, length[2] + 2 }; const float tau_inv = 1 / *tau; #pragma omp parallel for collapse(2) schedule(dynamic) private(x, node, density, feq, velocity, densityAtm, feqAtm, isFluid, flag, currentCell) num_threads(n_threads) // Loop over inner cells for (z = 1; z <= length[2]; z++) { for (y = 1; y <= length[1]; y++) { node[2] = z; node[1] = y; for (x = 1; x <= length[0]; x++) { node[0] = x; flag = *getFlag(flagField, node, n); isFluid = flag == FLUID; /* Perform the colision step just for fluid or interface cells */ if (isFluid || flag == INTERFACE) { /* Calculate the density velocity, and equilibrium distributions * for the density calculated an the atmosferic density * with all that data calculate the postcollision distributions for the cell*/ currentCell = getEl(collideField, node, 0, n); computeDensity(currentCell, &density); computeVelocity(currentCell, &density, velocity); computeFeq(&density, velocity, feq); computeFeq(&densityAtm, velocity, feqAtm); computePostCollisionDistributions(node, currentCell, flagField, fractionField, &tau_inv, feq, feqAtm, density, extForces, n); /* Update fluid fraction */ if (isFluid) { *getMass(massField, node, n) = density; *getFraction(fractionField, node, n) = 1; } else { *getFraction(fractionField, node, n) = *getMass(massField, node, n) / density; } } } } } }
convolution_1x1.h
// Tencent is pleased to support the open source community by making ncnn available. // // Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved. // // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except // in compliance with the License. You may obtain a copy of the License at // // https://opensource.org/licenses/BSD-3-Clause // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #if defined(__ARM_NEON) static void conv1x1s1_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { // int w = bottom_blob.w; // int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; int size = outw * outh; #if defined(__ARM_NEON) int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if defined(__ARM_NEON) float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); float32x4_t _p1 = vld1q_f32(r1); float32x4_t _p1n = vld1q_f32(r1+4); _outp = vfmaq_f32(_outp, _p1, _k1); _outpn = vfmaq_f32(_outpn, _p1n, _k1); float32x4_t _p2 = vld1q_f32(r2); float32x4_t _p2n = vld1q_f32(r2+4); _outp = vfmaq_f32(_outp, _p2, _k2); _outpn = vfmaq_f32(_outpn, _p2n, _k2); float32x4_t _p3 = vld1q_f32(r3); float32x4_t _p3n = vld1q_f32(r3+4); _outp = vfmaq_f32(_outp, _p3, _k3); _outpn = vfmaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; r1 += 8; r2 += 8; r3 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q3, %q12 \n" "pld [%3, #256] \n" "vld1.f32 {d4-d7}, [%3 :128]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q3, %q13 \n" "pld [%4, #256] \n" "vld1.f32 {d4-d7}, [%4 :128]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q3, %q14 \n" "pld [%5, #256] \n" "vld1.f32 {d4-d7}, [%5 :128]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q3, %q15 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0++; r1++; r2++; r3++; outptr++; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; int size = outw * outh; #if defined(__ARM_NEON) int nn = size >> 3; int remain = size & 7; #else int remain = size; #endif // __ARM_NEON #if defined(__ARM_NEON) float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4_t _p = vld1q_f32(r0); float32x4_t _outp = vld1q_f32(outptr); float32x4_t _pn = vld1q_f32(r0+4); float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vfmaq_f32(_outp, _p, _k0); _outpn = vfmaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 8; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1 :128] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q3, %q6 \n" "pld [%2, #256] \n" "vld1.f32 {d4-d7}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1 :128]! \n" "bne 0b \n" "sub %2, #32 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0++; outptr++; } } } } static void conv1x1s2_neon(const Mat& bottom_blob, Mat& top_blob, const Mat& _kernel, const Mat& _bias) { int w = bottom_blob.w; // int h = bottom_blob.h; int inch = bottom_blob.c; int outw = top_blob.w; int outh = top_blob.h; int outch = top_blob.c; const int tailstep = w - 2*outw + w; const float* kernel = _kernel; const float* bias = _bias; #pragma omp parallel for for (int p=0; p<outch; p++) { Mat out = top_blob.channel(p); const float bias0 = bias ? bias[p] : 0.f; out.fill(bias0); int q = 0; for (; q+3<inch; q+=4) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* img1 = bottom_blob.channel(q+1); const float* img2 = bottom_blob.channel(q+2); const float* img3 = bottom_blob.channel(q+3); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float k1 = kernel0[1]; const float k2 = kernel0[2]; const float k3 = kernel0[3]; const float* r0 = img0; const float* r1 = img1; const float* r2 = img2; const float* r3 = img3; for (int i = 0; i < outh; i++) { #if defined(__ARM_NEON) int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if defined(__ARM_NEON) float32x4_t _k0 = vdupq_n_f32(k0); float32x4_t _k1 = vdupq_n_f32(k1); float32x4_t _k2 = vdupq_n_f32(k2); float32x4_t _k3 = vdupq_n_f32(k3); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); float32x4x2_t _p1x2 = vld2q_f32(r1); float32x4_t _p1 = _p1x2.val[0]; float32x4x2_t _p1nx2 = vld2q_f32(r1+8); float32x4_t _p1n = _p1nx2.val[0]; _outp = vmlaq_f32(_outp, _p1, _k1); _outpn = vmlaq_f32(_outpn, _p1n, _k1); float32x4x2_t _p2x2 = vld2q_f32(r2); float32x4_t _p2 = _p2x2.val[0]; float32x4x2_t _p2nx2 = vld2q_f32(r2+8); float32x4_t _p2n = _p2nx2.val[0]; _outp = vmlaq_f32(_outp, _p2, _k2); _outpn = vmlaq_f32(_outpn, _p2n, _k2); float32x4x2_t _p3x2 = vld2q_f32(r3); float32x4_t _p3 = _p3x2.val[0]; float32x4x2_t _p3nx2 = vld2q_f32(r3+8); float32x4_t _p3n = _p3nx2.val[0]; _outp = vmlaq_f32(_outp, _p3, _k3); _outpn = vmlaq_f32(_outpn, _p3n, _k3); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 16; r1 += 16; r2 += 16; r3 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q12 \n" "vmla.f32 q1, q8, %q12 \n" "pld [%3, #512] \n" "vld2.f32 {d4-d7}, [%3]! \n" "vld2.f32 {d16-d19}, [%3]! \n" "vmla.f32 q0, q2, %q13 \n" "vmla.f32 q1, q8, %q13 \n" "pld [%4, #512] \n" "vld2.f32 {d4-d7}, [%4]! \n" "vld2.f32 {d16-d19}, [%4]! \n" "vmla.f32 q0, q2, %q14 \n" "vmla.f32 q1, q8, %q14 \n" "pld [%5, #512] \n" "vld2.f32 {d4-d7}, [%5]! \n" "vld2.f32 {d16-d19}, [%5]! \n" "vmla.f32 q0, q2, %q15 \n" "vmla.f32 q1, q8, %q15 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0), // %2 "=r"(r1), // %3 "=r"(r2), // %4 "=r"(r3) // %5 : "0"(nn), "1"(outptr), "2"(r0), "3"(r1), "4"(r2), "5"(r3), "w"(_k0), // %12 "w"(_k1), // %13 "w"(_k2), // %14 "w"(_k3) // %15 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; float sum1 = *r1 * k1; float sum2 = *r2 * k2; float sum3 = *r3 * k3; *outptr += sum + sum1 + sum2 + sum3; r0 += 2; r1 += 2; r2 += 2; r3 += 2; outptr++; } r0 += tailstep; r1 += tailstep; r2 += tailstep; r3 += tailstep; } } for (; q<inch; q++) { float* outptr = out; const float* img0 = bottom_blob.channel(q); const float* kernel0 = kernel + p*inch + q; const float k0 = kernel0[0]; const float* r0 = img0; for (int i = 0; i < outh; i++) { #if defined(__ARM_NEON) int nn = outw >> 3; int remain = outw & 7; #else int remain = outw; #endif // __ARM_NEON #if defined(__ARM_NEON) float32x4_t _k0 = vdupq_n_f32(k0); #if __aarch64__ for (; nn>0; nn--) { float32x4x2_t _px2 = vld2q_f32(r0); float32x4_t _p = _px2.val[0]; float32x4_t _outp = vld1q_f32(outptr); float32x4x2_t _pnx2 = vld2q_f32(r0+8); float32x4_t _pn = _pnx2.val[0]; float32x4_t _outpn = vld1q_f32(outptr+4); _outp = vmlaq_f32(_outp, _p, _k0); _outpn = vmlaq_f32(_outpn, _pn, _k0); vst1q_f32(outptr, _outp); vst1q_f32(outptr+4, _outpn); r0 += 16; outptr += 8; } #else if (nn > 0) { asm volatile( "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "0: \n" "pld [%1, #256] \n" "vld1.f32 {d0-d3}, [%1] \n" "vmla.f32 q0, q2, %q6 \n" "vmla.f32 q1, q8, %q6 \n" "pld [%2, #512] \n" "vld2.f32 {d4-d7}, [%2]! \n" "vld2.f32 {d16-d19}, [%2]! \n" "subs %0, #1 \n" "vst1.f32 {d0-d3}, [%1]! \n" "bne 0b \n" "sub %2, #64 \n" : "=r"(nn), // %0 "=r"(outptr), // %1 "=r"(r0) // %2 : "0"(nn), "1"(outptr), "2"(r0), "w"(_k0) // %6 : "cc", "memory", "q0", "q1", "q2", "q3", "q8", "q9" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { float sum = *r0 * k0; *outptr += sum; r0 += 2; outptr++; } r0 += tailstep; } } } } #endif // __ARM_NEON
sync.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 <stdlib.h> #include <stdio.h> #include <assert.h> #include <stdint.h> #include <omp.h> #include <arch/x86/barrelfish_kpi/asm_inlines_arch.h> #define GANG_SCHEDULING #undef MEASURE_SYNC #define MEASURE #define WORK_PERIOD 5000000000UL #define STACK_SIZE (64 * 1024) int main(int argc, char *argv[]) { uint64_t now, start; volatile uint64_t workcnt, workload = 0; int64_t workmax = 1000; int64_t i; if(argc == 1) { printf("calibrating...\n"); do { workload = 0; workmax *= 2; start = rdtsc(); #pragma omp parallel private(i,workload) for(i = 0; i < workmax; i++) { #pragma omp barrier workload++; } now = rdtsc(); } while(now - start < WORK_PERIOD); printf("workmax = %ld\n", workmax); return 0; } else { workmax = atol(argv[1]); } int nthreads = omp_get_max_threads(); if(argc == 3) { nthreads = atoi(argv[2]); assert(!"REVISE!!!"); bomp_bomp_init(nthreads); omp_set_num_threads(nthreads); } printf("threads %d, workmax %ld, CPUs %d\n", nthreads, workmax, omp_get_num_procs()); #ifdef MEASURE_SYNC uint64_t waits[16] = { 0, 1000, 1000000, 1000000000, 500, 5000000, 5000000000, 3000000, 0, 1000, 1000000, 1000000000, 500, 5000000, 5000000000, 3000000 }; uint64_t ts[16][10]; printf("before sync:\n"); #pragma omp parallel private(workcnt) { for(int j = 0; j < waits[omp_get_thread_num()]; j++) { workcnt++; } for(int j = 0; j < 10; j++) { ts[omp_get_thread_num()][j] = rdtsc(); } } for(int j = 0; j < 10; j++) { printf("timestamp %d: ", j); for(int n = 1; n < nthreads; n++) { printf("%ld ", ts[n][j] - ts[n - 1][j]); } printf("\n"); } printf("after sync:\n"); #pragma omp parallel { bomp_synchronize(); for(int j = 0; j < 10; j++) { ts[omp_get_thread_num()][j] = rdtsc(); } } for(int j = 0; j < 10; j++) { printf("timestamp %d: ", j); for(int n = 1; n < nthreads; n++) { printf("%ld ", ts[n][j] - ts[n - 1][j]); } printf("\n"); } #endif #ifdef GANG_SCHEDULING #pragma omp parallel { // bomp_synchronize(); } #endif start = rdtsc(); #ifdef MEASURE # define MAXTHREADS 16 # define WORKMAX 10000 static uint64_t starta[MAXTHREADS][WORKMAX]; static uint64_t end1[MAXTHREADS][WORKMAX]; static uint64_t end2[MAXTHREADS][WORKMAX]; #endif // Do some work #pragma omp parallel private(workcnt,i) for(i = 0; i < workmax; i++) { #ifdef MEASURE starta[omp_get_thread_num()][i < WORKMAX ? i : WORKMAX] = rdtsc(); #endif workcnt++; #ifdef MEASURE end1[omp_get_thread_num()][i < WORKMAX ? i : WORKMAX] = rdtsc(); #endif #pragma omp barrier #ifdef MEASURE end2[omp_get_thread_num()][i < WORKMAX ? i : WORKMAX] = rdtsc(); #endif } now = rdtsc(); #ifdef MEASURE printf("avg compute time: "); for(int n = 0; n < nthreads; n++) { uint64_t sum = 0, min = end1[0][0], max = 0; for(i = 0; i < WORKMAX; i++) { uint64_t val = end1[n][i] - starta[n][i]; sum += val; min = val < min ? val : min; max = val > max ? val : max; } printf("%lu(%lu,%lu) ", sum / WORKMAX, min, max); } printf("\n"); #if 0 printf("wait time dump:\n"); for(i = 0; i < WORKMAX; i++) { for(int n = 0; n < nthreads; n++) { uint64_t val = end2[n][i] - end1[n][i]; printf("%lu ", val); } printf("\n"); } #endif printf("avg wait time: "); for(int n = 0; n < nthreads; n++) { uint64_t sum = 0, min = end2[0][0], max = 0; for(i = 0; i < WORKMAX; i++) { uint64_t val = end2[n][i] - end1[n][i]; sum += val; min = val < min ? val : min; max = val > max ? val : max; } printf("%lu(%lu,%lu) ", sum / WORKMAX, min, max); } printf("\n"); #endif printf("%s: threads %d, compute time %lu ticks\n", argv[0], nthreads, now - start); for(;;); return 0; }
omp_getEnvInfo.c
/****************************************************************************** * FILE: omp_getEnvInfo.c * DESCRIPTION: * OpenMP Example - Get Environment Information - C/C++ Version * The master thread queries and prints selected environment information. * AUTHOR: Blaise Barney 7/06 * LAST REVISED: 05/18/16 ******************************************************************************/ #include <omp.h> #include <stdio.h> #include <stdlib.h> int main (int argc, char *argv[]) { int nthreads, tid, procs, maxt, inpar, dynamic, nested; /* Start parallel region */ #pragma omp parallel private(nthreads, tid) { /* Obtain thread number */ tid = omp_get_thread_num(); /* Only master thread does this */ if (tid == 0) { printf("Thread %d getting environment info...\n", tid); /* Get environment information */ procs = omp_get_num_procs(); nthreads = omp_get_num_threads(); maxt = omp_get_max_threads(); inpar = omp_in_parallel(); dynamic = omp_get_dynamic(); nested = omp_get_nested(); /* Print environment information */ printf("Number of processors = %d\n", procs); printf("Number of threads = %d\n", nthreads); printf("Max threads = %d\n", maxt); printf("In parallel? = %d\n", inpar); printf("Dynamic threads enabled? = %d\n", dynamic); printf("Nested parallelism enabled? = %d\n", nested); } } /* Done */ }
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-d30}, [%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-d30}, [%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-d30}, [%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]; } } } } // optimized layout for winograd4 // interleave weights int nn_outch = outch >> 2; int remain_outch_start = nn_outch << 2; Mat kernel_tm2(8*8 * inch * 4, 1, nn_outch + (outch % 4 + 3) / 4); #pragma omp parallel for for (int pp=0; pp<nn_outch; pp++) { int p = pp * 4; float* ktm2 = kernel_tm2.channel(pp); 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); int q=0; #if __ARM_NEON && __aarch64__ for (; q+3<inch; q+=4) { const float* k00 = kernel0_tm.row(q); const float* k01 = kernel0_tm.row(q+1); const float* k02 = kernel0_tm.row(q+2); const float* k03 = kernel0_tm.row(q+3); const float* k10 = kernel1_tm.row(q); const float* k11 = kernel1_tm.row(q+1); const float* k12 = kernel1_tm.row(q+2); const float* k13 = kernel1_tm.row(q+3); const float* k20 = kernel2_tm.row(q); const float* k21 = kernel2_tm.row(q+1); const float* k22 = kernel2_tm.row(q+2); const float* k23 = kernel2_tm.row(q+3); const float* k30 = kernel3_tm.row(q); const float* k31 = kernel3_tm.row(q+1); const float* k32 = kernel3_tm.row(q+2); const float* k33 = kernel3_tm.row(q+3); for (int r=0; r<16; r++) { // split into two asm blocks for gcc reject over 30 oprands :( asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "ld1 {v2.4s}, [%3], #16 \n" "ld1 {v3.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "ld1 {v2.4s}, [%7], #16 \n" "ld1 {v3.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k02), // %3 "=r"(k03), // %4 "=r"(k10), // %5 "=r"(k11), // %6 "=r"(k12), // %7 "=r"(k13) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k02), "4"(k03), "5"(k10), "6"(k11), "7"(k12), "8"(k13) : "cc", "memory", "v0", "v1", "v2", "v3" ); asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "ld1 {v2.4s}, [%3], #16 \n" "ld1 {v3.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "ld1 {v2.4s}, [%7], #16 \n" "ld1 {v3.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s, v2.4s, v3.4s}, [%0], #64 \n" : "=r"(ktm2), // %0 "=r"(k20), // %1 "=r"(k21), // %2 "=r"(k22), // %3 "=r"(k23), // %4 "=r"(k30), // %5 "=r"(k31), // %6 "=r"(k32), // %7 "=r"(k33) // %8 : "0"(ktm2), "1"(k20), "2"(k21), "3"(k22), "4"(k23), "5"(k30), "6"(k31), "7"(k32), "8"(k33) : "cc", "memory", "v0", "v1", "v2", "v3" ); } } #endif // __ARM_NEON && __aarch64__ for (; q+1<inch; q+=2) { 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); const float* k20 = kernel2_tm.row(q); const float* k21 = kernel2_tm.row(q+1); const float* k30 = kernel3_tm.row(q); const float* k31 = kernel3_tm.row(q+1); for (int r=0; r<16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%3], #16 \n" "ld1 {v1.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%5], #16 \n" "ld1 {v1.4s}, [%6], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%7], #16 \n" "ld1 {v1.4s}, [%8], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k10), // %3 "=r"(k11), // %4 "=r"(k20), // %5 "=r"(k21), // %6 "=r"(k30), // %7 "=r"(k31) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k10), "4"(k11), "5"(k20), "6"(k21), "7"(k30), "8"(k31) : "cc", "memory", "v0", "v1" ); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vld1.f32 {d2-d3}, [%2 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%3 :128]! \n" "vld1.f32 {d2-d3}, [%4 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%5 :128]! \n" "vld1.f32 {d2-d3}, [%6 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%7 :128]! \n" "vld1.f32 {d2-d3}, [%8 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k01), // %2 "=r"(k10), // %3 "=r"(k11), // %4 "=r"(k20), // %5 "=r"(k21), // %6 "=r"(k30), // %7 "=r"(k31) // %8 : "0"(ktm2), "1"(k00), "2"(k01), "3"(k10), "4"(k11), "5"(k20), "6"(k21), "7"(k30), "8"(k31) : "cc", "memory", "q0", "q1" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { ktm2[0 +m] = k00[m]; ktm2[4 +m] = k01[m]; ktm2[8 +m] = k10[m]; ktm2[12+m] = k11[m]; ktm2[16+m] = k20[m]; ktm2[20+m] = k21[m]; ktm2[24+m] = k30[m]; ktm2[28+m] = k31[m]; } k00 += 4; k01 += 4; k10 += 4; k11 += 4; k20 += 4; k21 += 4; k30 += 4; k31 += 4; ktm2 += 32; #endif // __ARM_NEON } } for (; q<inch; q++) { 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); for (int r=0; r<16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "ld1 {v1.4s}, [%2], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" "ld1 {v0.4s}, [%3], #16 \n" "ld1 {v1.4s}, [%4], #16 \n" "st1 {v0.4s, v1.4s}, [%0], #32 \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k10), // %2 "=r"(k20), // %3 "=r"(k30) // %4 : "0"(ktm2), "1"(k00), "2"(k10), "3"(k20), "4"(k30) : "cc", "memory", "v0", "v1" ); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vld1.f32 {d2-d3}, [%2 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" "vld1.f32 {d0-d1}, [%3 :128]! \n" "vld1.f32 {d2-d3}, [%4 :128]! \n" "vst1.f32 {d0-d3}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00), // %1 "=r"(k10), // %2 "=r"(k20), // %3 "=r"(k30) // %4 : "0"(ktm2), "1"(k00), "2"(k10), "3"(k20), "4"(k30) : "cc", "memory", "q0", "q1" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { ktm2[0 +m] = k00[m]; ktm2[4 +m] = k10[m]; ktm2[8 +m] = k20[m]; ktm2[12+m] = k30[m]; } k00 += 4; k10 += 4; k20 += 4; k30 += 4; ktm2 += 16; #endif // __ARM_NEON } } } #pragma omp parallel for for (int p = remain_outch_start; p<outch; p++) { float* ktm2 = (float*)kernel_tm2.channel(nn_outch) + 8*8 * inch * (p-remain_outch_start); const Mat kernel0_tm = kernel_tm.channel(p); int q = 0; for (; q<inch; q++) { const float* k00 = kernel0_tm.row(q); for (int r=0; r<16; r++) { #if __ARM_NEON #if __aarch64__ asm volatile( "ld1 {v0.4s}, [%1], #16 \n" "st1 {v0.4s}, [%0], #16 \n" : "=r"(ktm2), // %0 "=r"(k00) // %1 : "0"(ktm2), "1"(k00) : "cc", "memory", "v0" ); #else asm volatile( "vld1.f32 {d0-d1}, [%1 :128]! \n" "vst1.f32 {d0-d1}, [%0 :128]! \n" : "=r"(ktm2), // %0 "=r"(k00) // %1 : "0"(ktm2), "1"(k00) : "cc", "memory", "q0" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { ktm2[m] = k00[m]; } k00 += 4; ktm2 += 4; #endif // __ARM_NEON } } } kernel_tm = kernel_tm2; } #if 0//TODO remove old code sometime later 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 } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); const float* k00 = kernel0_tm.row(q); const float* k10 = kernel1_tm.row(q); 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 _k10 = vld1q_f32(k10); float32x4_t _k10n = vld1q_f32(k10+4); #else float32x4_t _k00; float32x4_t _k00n; float32x4_t _k10; float32x4_t _k10n; 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"(k10), // %1 "=w"(_k00), // %2 "=w"(_k00n), // %3 "=w"(_k10), // %4 "=w"(_k10n) // %5 : "0"(k00), "1"(k10) : "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); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); 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); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); 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); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); 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); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); 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, %q8 \n" "vmla.f32 q9, q13, %q9 \n" "pld [%2, #256] \n" "vld1.f32 {d20-d23}, [%2 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :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" "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, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :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" "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, %q10 \n" "vmla.f32 q11, q13, %q11 \n" "pld [%3, #256] \n" "vld1.f32 {d24-d27}, [%3 :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" "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, %q10 \n" "vmla.f32 q11, q13, %q11 \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 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(r0), "w"(_k00), // %8 "w"(_k00n), // %9 "w"(_k10), // %10 "w"(_k10n) // %11 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13" ); } #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); r0 += 8; _output0_tm = vmlaq_f32(_output0_tm, _r0, _k00); _output0_tmn = vmlaq_f32(_output0_tmn, _r0n, _k00n); _output1_tm = vmlaq_f32(_output1_tm, _r0, _k10); _output1_tmn = vmlaq_f32(_output1_tmn, _r0n, _k10n); 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, %q6 \n" "vmla.f32 q9, q13, %q7 \n" "pld [%1, #256] \n" "vld1.f32 {d20-d23}, [%1 :128] \n"// q10 q11 = _output1_tm "vmla.f32 q10, q12, %q8 \n" "vmla.f32 q11, q13, %q9 \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 : "0"(output0_tm), "1"(output1_tm), "2"(r0), "w"(_k00), // %6 "w"(_k00n), // %7 "w"(_k10), // %8 "w"(_k10n) // %9 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13" ); #endif // __aarch64__ #else for (int m=0; m<8; m++) { output0_tm[m] += r0[m] * k00[m]; output1_tm[m] += r0[m] * k10[m]; } r0 += 8; output0_tm += 8; output1_tm += 8; #endif // __ARM_NEON } #if __ARM_NEON #if __aarch64__ k00 += 8; k10 += 8; #endif // __aarch64__ #else k00 += 8; k10 += 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); } #endif static void conv3x3s1_winograd64_neon4(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(4, 16 * 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_0 = img0_tm.row(i * w_tm/8 + j); float* r0_tm0_4 = img0_tm.row(i * w_tm/8 + j + tiles); float* r0_tm1_0 = img0_tm.row(i * w_tm/8 + j + tiles * 2); float* r0_tm1_4 = img0_tm.row(i * w_tm/8 + j + tiles * 3); float* r0_tm2_0 = img0_tm.row(i * w_tm/8 + j + tiles * 4); float* r0_tm2_4 = img0_tm.row(i * w_tm/8 + j + tiles * 5); float* r0_tm3_0 = img0_tm.row(i * w_tm/8 + j + tiles * 6); float* r0_tm3_4 = img0_tm.row(i * w_tm/8 + j + tiles * 7); float* r0_tm4_0 = img0_tm.row(i * w_tm/8 + j + tiles * 8); float* r0_tm4_4 = img0_tm.row(i * w_tm/8 + j + tiles * 9); float* r0_tm5_0 = img0_tm.row(i * w_tm/8 + j + tiles * 10); float* r0_tm5_4 = img0_tm.row(i * w_tm/8 + j + tiles * 11); float* r0_tm6_0 = img0_tm.row(i * w_tm/8 + j + tiles * 12); float* r0_tm6_4 = img0_tm.row(i * w_tm/8 + j + tiles * 13); float* r0_tm7_0 = img0_tm.row(i * w_tm/8 + j + tiles * 14); float* r0_tm7_4 = img0_tm.row(i * w_tm/8 + j + tiles * 15); 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_0[8] = { r0_tm0_0, r0_tm1_0, r0_tm2_0, r0_tm3_0, r0_tm4_0, r0_tm5_0, r0_tm6_0, r0_tm7_0 }; float* r0_tms_4[8] = { r0_tm0_4, r0_tm1_4, r0_tm2_4, r0_tm3_4, r0_tm4_4, r0_tm5_4, r0_tm6_4, r0_tm7_4 }; for (int m=0; m<8; m++) { const float* tmp0 = tmp[m]; float* r0_tm_0 = r0_tms_0[m]; float* r0_tm_4 = r0_tms_4[m]; r0_tm_0[0] = tmp0[0] - tmp0[6] + (tmp0[4] - tmp0[2]) * 5.25; r0_tm_4[3] = 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_0[1] = tmp12a + tmp12b; r0_tm_0[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_0[3] = tmp34a + tmp34b; r0_tm_4[0] = 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_4[1] = tmp56a + tmp56b; r0_tm_4[2] = 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(4, 16 * w_tm/8 * h_tm/8, outch); const int tiles = h_tm/8 * w_tm/8; 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 float* ktm = kernel_tm.channel(pp); out0_tm.fill(0.f); out1_tm.fill(0.f); out2_tm.fill(0.f); out3_tm.fill(0.f); int q = 0; #if __ARM_NEON && __aarch64__ 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); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; for (int r=0; r<16; r++) { register float32x4_t _k00 asm("v0"); register float32x4_t _k01 asm("v1"); register float32x4_t _k02 asm("v2"); register float32x4_t _k03 asm("v3"); register float32x4_t _k10 asm("v4"); register float32x4_t _k11 asm("v5"); register float32x4_t _k12 asm("v6"); register float32x4_t _k13 asm("v7"); register float32x4_t _k20 asm("v8"); register float32x4_t _k21 asm("v9"); register float32x4_t _k22 asm("v10"); register float32x4_t _k23 asm("v11"); register float32x4_t _k30 asm("v12"); register float32x4_t _k31 asm("v13"); register float32x4_t _k32 asm("v14"); register float32x4_t _k33 asm("v15"); asm volatile( "prfm pldl1keep, [%16, #512] \n" "ld1 {%0.4s, %1.4s, %2.4s, %3.4s}, [%16], #64 \n" "prfm pldl1keep, [%16, #512] \n" "ld1 {%4.4s, %5.4s, %6.4s, %7.4s}, [%16], #64 \n" "prfm pldl1keep, [%16, #512] \n" "ld1 {%8.4s, %9.4s, %10.4s, %11.4s}, [%16], #64 \n" "prfm pldl1keep, [%16, #512] \n" "ld1 {%12.4s, %13.4s, %14.4s, %15.4s}, [%16], #64\n" : "=w"(_k00), "=w"(_k01), "=w"(_k02), "=w"(_k03), "=w"(_k10), "=w"(_k11), "=w"(_k12), "=w"(_k13), "=w"(_k20), "=w"(_k21), "=w"(_k22), "=w"(_k23), "=w"(_k30), "=w"(_k31), "=w"(_k32), "=w"(_k33) : "r"(ktm) : "cc", "memory" ); // tile int nn = tiles >> 2; int remain = tiles & 3; #ifdef __clang__ // gcc reject over 30 oprands :( if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v20.4s}, [%1] \n" "add x4, %1, #16 \n" "fmla v20.4s, v16.4s, %18.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v21.4s}, [%2] \n" "add x5, %2, #16 \n" "fmla v21.4s, v16.4s, %22.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v22.4s}, [%3] \n" "add x6, %3, #16 \n" "fmla v22.4s, v16.4s, %26.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v23.4s}, [%4] \n" "add x7, %4, #16 \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v17.4s}, [%6], #16 \n" "fmla v23.4s, v16.4s, %30.4s \n" "prfm pldl1keep, [x4, #128] \n" "ld1 {v24.4s}, [x4] \n" "fmla v20.4s, v17.4s, %19.4s \n" "fmla v21.4s, v17.4s, %23.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v18.4s}, [%7], #16 \n" "fmla v22.4s, v17.4s, %27.4s \n" "fmla v23.4s, v17.4s, %31.4s \n" "prfm pldl1keep, [x5, #128] \n" "ld1 {v25.4s}, [x5] \n" "fmla v20.4s, v18.4s, %20.4s \n" "fmla v21.4s, v18.4s, %24.4s \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v19.4s}, [%8], #16 \n" "fmla v22.4s, v18.4s, %28.4s \n" "fmla v23.4s, v18.4s, %32.4s \n" "prfm pldl1keep, [x6, #128] \n" "ld1 {v26.4s}, [x6] \n" "fmla v20.4s, v19.4s, %21.4s \n" "fmla v21.4s, v19.4s, %25.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "fmla v22.4s, v19.4s, %29.4s \n" "fmla v23.4s, v19.4s, %33.4s \n" /////// "prfm pldl1keep, [x7, #128] \n" "ld1 {v27.4s}, [x7] \n" "st1 {v20.4s}, [%1] \n" "add %1, %1, #32 \n" "fmla v24.4s, v16.4s, %18.4s \n" "fmla v25.4s, v16.4s, %22.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v17.4s}, [%6], #16 \n" "fmla v26.4s, v16.4s, %26.4s \n" "fmla v27.4s, v16.4s, %30.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v20.4s}, [%1] \n" "st1 {v21.4s}, [%2] \n" "add %2, %2, #32 \n" "fmla v24.4s, v17.4s, %19.4s \n" "fmla v25.4s, v17.4s, %23.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v18.4s}, [%7], #16 \n" "fmla v26.4s, v17.4s, %27.4s \n" "fmla v27.4s, v17.4s, %31.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v21.4s}, [%2] \n" "st1 {v22.4s}, [%3] \n" "add %3, %3, #32 \n" "fmla v24.4s, v18.4s, %20.4s \n" "fmla v25.4s, v18.4s, %24.4s \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v19.4s}, [%8], #16 \n" "fmla v26.4s, v18.4s, %28.4s \n" "fmla v27.4s, v18.4s, %32.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v22.4s}, [%3] \n" "st1 {v23.4s}, [%4] \n" "add %4, %4, #32 \n" "fmla v24.4s, v19.4s, %21.4s \n" "fmla v25.4s, v19.4s, %25.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "fmla v26.4s, v19.4s, %29.4s \n" "fmla v27.4s, v19.4s, %33.4s \n" /////// "prfm pldl1keep, [%4, #128] \n" "ld1 {v23.4s}, [%4] \n" "st1 {v24.4s}, [x4] \n" "add x4, x4, #32 \n" "fmla v20.4s, v16.4s, %18.4s \n" "fmla v21.4s, v16.4s, %22.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v17.4s}, [%6], #16 \n" "fmla v22.4s, v16.4s, %26.4s \n" "fmla v23.4s, v16.4s, %30.4s \n" "prfm pldl1keep, [x4, #128] \n" "ld1 {v24.4s}, [x4] \n" "st1 {v25.4s}, [x5] \n" "add x5, x5, #32 \n" "fmla v20.4s, v17.4s, %19.4s \n" "fmla v21.4s, v17.4s, %23.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v18.4s}, [%7], #16 \n" "fmla v22.4s, v17.4s, %27.4s \n" "fmla v23.4s, v17.4s, %31.4s \n" "prfm pldl1keep, [x5, #128] \n" "ld1 {v25.4s}, [x5] \n" "st1 {v26.4s}, [x6] \n" "add x6, x6, #32 \n" "fmla v20.4s, v18.4s, %20.4s \n" "fmla v21.4s, v18.4s, %24.4s \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v19.4s}, [%8], #16 \n" "fmla v22.4s, v18.4s, %28.4s \n" "fmla v23.4s, v18.4s, %32.4s \n" "prfm pldl1keep, [x6, #128] \n" "ld1 {v26.4s}, [x6] \n" "st1 {v27.4s}, [x7] \n" "add x7, x7, #32 \n" "fmla v20.4s, v19.4s, %21.4s \n" "fmla v21.4s, v19.4s, %25.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "fmla v22.4s, v19.4s, %29.4s \n" "fmla v23.4s, v19.4s, %33.4s \n" /////// "prfm pldl1keep, [x7, #128] \n" "ld1 {v27.4s}, [x7] \n" "st1 {v20.4s}, [%1] \n" "fmla v24.4s, v16.4s, %18.4s \n" "fmla v25.4s, v16.4s, %22.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v17.4s}, [%6], #16 \n" "fmla v26.4s, v16.4s, %26.4s \n" "fmla v27.4s, v16.4s, %30.4s \n" "st1 {v21.4s}, [%2] \n" "fmla v24.4s, v17.4s, %19.4s \n" "fmla v25.4s, v17.4s, %23.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v18.4s}, [%7], #16 \n" "fmla v26.4s, v17.4s, %27.4s \n" "fmla v27.4s, v17.4s, %31.4s \n" "st1 {v22.4s}, [%3] \n" "fmla v24.4s, v18.4s, %20.4s \n" "fmla v25.4s, v18.4s, %24.4s \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v19.4s}, [%8], #16 \n" "fmla v26.4s, v18.4s, %28.4s \n" "fmla v27.4s, v18.4s, %32.4s \n" "st1 {v23.4s}, [%4] \n" "fmla v24.4s, v19.4s, %21.4s \n" "fmla v25.4s, v19.4s, %25.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "fmla v26.4s, v19.4s, %29.4s \n" "fmla v27.4s, v19.4s, %33.4s \n" "st1 {v24.4s}, [x4], #16 \n" "mov %1, x4 \n" "st1 {v25.4s}, [x5], #16 \n" "mov %2, x5 \n" "subs %w0, %w0, #1 \n" "st1 {v26.4s}, [x6], #16 \n" "mov %3, x6 \n" "st1 {v27.4s}, [x7], #16 \n" "mov %4, x7 \n" "bne 0b \n" "sub %5, %5, #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k00), // %18 "w"(_k01), // %19 "w"(_k02), // %20 "w"(_k03), // %21 "w"(_k10), // %22 "w"(_k11), // %23 "w"(_k12), // %24 "w"(_k13), // %25 "w"(_k20), // %26 "w"(_k21), // %27 "w"(_k22), // %28 "w"(_k23), // %29 "w"(_k30), // %30 "w"(_k31), // %31 "w"(_k32), // %32 "w"(_k33) // %33 : "cc", "memory", "x4", "x5", "x6", "x7", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27" ); } #else for (; nn>0; nn--) { 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); r0 += 4; r1 += 4; r2 += 4; r3 += 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); _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); _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); _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; _output0_tm = vld1q_f32(output0_tm); _output1_tm = vld1q_f32(output1_tm); _output2_tm = vld1q_f32(output2_tm); _output3_tm = vld1q_f32(output3_tm); _r0 = vld1q_f32(r0); _r1 = vld1q_f32(r1); _r2 = vld1q_f32(r2); _r3 = vld1q_f32(r3); r0 += 4; r1 += 4; r2 += 4; r3 += 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); _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); _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); _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; _output0_tm = vld1q_f32(output0_tm); _output1_tm = vld1q_f32(output1_tm); _output2_tm = vld1q_f32(output2_tm); _output3_tm = vld1q_f32(output3_tm); _r0 = vld1q_f32(r0); _r1 = vld1q_f32(r1); _r2 = vld1q_f32(r2); _r3 = vld1q_f32(r3); r0 += 4; r1 += 4; r2 += 4; r3 += 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); _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); _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); _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; _output0_tm = vld1q_f32(output0_tm); _output1_tm = vld1q_f32(output1_tm); _output2_tm = vld1q_f32(output2_tm); _output3_tm = vld1q_f32(output3_tm); _r0 = vld1q_f32(r0); _r1 = vld1q_f32(r1); _r2 = vld1q_f32(r2); _r3 = vld1q_f32(r3); r0 += 4; r1 += 4; r2 += 4; r3 += 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); _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); _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); _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; } #endif for (; remain>0; remain--) { #ifdef __clang__ // gcc reject over 30 oprands :( asm volatile( "prfm pldl1keep, [%5, #128] \n" "ld1 {v16.4s}, [%5], #16 \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v20.4s}, [%1] \n" "fmla v20.4s, v16.4s, %18.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v21.4s}, [%2] \n" "fmla v21.4s, v16.4s, %22.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v22.4s}, [%3] \n" "fmla v22.4s, v16.4s, %26.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v23.4s}, [%4] \n" "fmla v23.4s, v16.4s, %30.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v17.4s}, [%6], #16 \n" "fmla v20.4s, v17.4s, %19.4s \n" "fmla v21.4s, v17.4s, %23.4s \n" "fmla v22.4s, v17.4s, %27.4s \n" "fmla v23.4s, v17.4s, %31.4s \n" "prfm pldl1keep, [%7, #128] \n" "ld1 {v18.4s}, [%7], #16 \n" "fmla v20.4s, v18.4s, %20.4s \n" "fmla v21.4s, v18.4s, %24.4s \n" "fmla v22.4s, v18.4s, %28.4s \n" "fmla v23.4s, v18.4s, %32.4s \n" "prfm pldl1keep, [%8, #128] \n" "ld1 {v19.4s}, [%8], #16 \n" "fmla v20.4s, v19.4s, %21.4s \n" "fmla v21.4s, v19.4s, %25.4s \n" "fmla v22.4s, v19.4s, %29.4s \n" "fmla v23.4s, v19.4s, %33.4s \n" "st1 {v20.4s}, [%1], #16 \n" "st1 {v21.4s}, [%2], #16 \n" "st1 {v22.4s}, [%3], #16 \n" "st1 {v23.4s}, [%4], #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(r1), // %6 "=r"(r2), // %7 "=r"(r3) // %8 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(r1), "7"(r2), "8"(r3), "w"(_k00), // %18 "w"(_k01), // %19 "w"(_k02), // %20 "w"(_k03), // %21 "w"(_k10), // %22 "w"(_k11), // %23 "w"(_k12), // %24 "w"(_k13), // %25 "w"(_k20), // %26 "w"(_k21), // %27 "w"(_k22), // %28 "w"(_k23), // %29 "w"(_k30), // %30 "w"(_k31), // %31 "w"(_k32), // %32 "w"(_k33) // %33 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23"//, "v24", "v25", "v26", "v27" ); #else 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); r0 += 4; r1 += 4; r2 += 4; r3 += 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); _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); _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); _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; #endif } } } #endif // __ARM_NEON && __aarch64__ for (; q+1<inch; q+=2) { const float* r0 = bottom_blob_tm.channel(q); const float* r1 = bottom_blob_tm.channel(q+1); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; for (int r=0; r<16; r++) { #if __ARM_NEON #if __aarch64__ register float32x4_t _k00 asm("v0"); register float32x4_t _k01 asm("v1"); register float32x4_t _k10 asm("v2"); register float32x4_t _k11 asm("v3"); register float32x4_t _k20 asm("v4"); register float32x4_t _k21 asm("v5"); register float32x4_t _k30 asm("v6"); register float32x4_t _k31 asm("v7"); asm volatile( "prfm pldl1keep, [%8, #256] \n" "ld1 {%0.4s, %1.4s}, [%8], #32 \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {%2.4s, %3.4s}, [%8], #32 \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {%4.4s, %5.4s}, [%8], #32 \n" "prfm pldl1keep, [%8, #256] \n" "ld1 {%6.4s, %7.4s}, [%8], #32 \n" : "=w"(_k00), "=w"(_k01), "=w"(_k10), "=w"(_k11), "=w"(_k20), "=w"(_k21), "=w"(_k30), "=w"(_k31) : "r"(ktm) : "cc", "memory" ); #else register float32x4_t _k00 asm("q0"); register float32x4_t _k01 asm("q1"); register float32x4_t _k10 asm("q2"); register float32x4_t _k11 asm("q3"); register float32x4_t _k20 asm("q4"); register float32x4_t _k21 asm("q5"); register float32x4_t _k30 asm("q6"); register float32x4_t _k31 asm("q7"); asm volatile( "pld [%8, #256] \n" "vld1.f32 {%e0-%f1}, [%8 :128]! \n" "pld [%8, #256] \n" "vld1.f32 {%e2-%f3}, [%8 :128]! \n" "pld [%8, #256] \n" "vld1.f32 {%e4-%f5}, [%8 :128]! \n" "pld [%8, #256] \n" "vld1.f32 {%e6-%f7}, [%8 :128]! \n" : "=w"(_k00), "=w"(_k01), "=w"(_k10), "=w"(_k11), "=w"(_k20), "=w"(_k21), "=w"(_k30), "=w"(_k31) : "r"(ktm) : "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__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%5, #128] \n" "ld1 {v20.4s}, [%5], #16 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v16.4s}, [%1] \n" "fmla v16.4s, v20.4s, %14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v17.4s}, [%2] \n" "fmla v17.4s, v20.4s, %16.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v18.4s}, [%3] \n" "fmla v18.4s, v20.4s, %18.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v19.4s}, [%4] \n" "fmla v19.4s, v20.4s, %20.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v21.4s}, [%6], #16 \n" "fmla v16.4s, v21.4s, %15.4s \n" "fmla v17.4s, v21.4s, %17.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v20.4s}, [%5], #16 \n" "fmla v18.4s, v21.4s, %19.4s \n" "fmla v19.4s, v21.4s, %21.4s \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" //// "prfm pldl1keep, [%1, #128] \n" "ld1 {v16.4s}, [%1] \n" "fmla v16.4s, v20.4s, %14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v17.4s}, [%2] \n" "fmla v17.4s, v20.4s, %16.4s \n" "st1 {v18.4s}, [%3], #16 \n" "st1 {v19.4s}, [%4], #16 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v18.4s}, [%3] \n" "fmla v18.4s, v20.4s, %18.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v19.4s}, [%4] \n" "fmla v19.4s, v20.4s, %20.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v21.4s}, [%6], #16 \n" "fmla v16.4s, v21.4s, %15.4s \n" "fmla v17.4s, v21.4s, %17.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v20.4s}, [%5], #16 \n" "fmla v18.4s, v21.4s, %19.4s \n" "fmla v19.4s, v21.4s, %21.4s \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" //// "prfm pldl1keep, [%1, #128] \n" "ld1 {v16.4s}, [%1] \n" "fmla v16.4s, v20.4s, %14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v17.4s}, [%2] \n" "fmla v17.4s, v20.4s, %16.4s \n" "st1 {v18.4s}, [%3], #16 \n" "st1 {v19.4s}, [%4], #16 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v18.4s}, [%3] \n" "fmla v18.4s, v20.4s, %18.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v19.4s}, [%4] \n" "fmla v19.4s, v20.4s, %20.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v21.4s}, [%6], #16 \n" "fmla v16.4s, v21.4s, %15.4s \n" "fmla v17.4s, v21.4s, %17.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v20.4s}, [%5], #16 \n" "fmla v18.4s, v21.4s, %19.4s \n" "fmla v19.4s, v21.4s, %21.4s \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" //// "prfm pldl1keep, [%1, #128] \n" "ld1 {v16.4s}, [%1] \n" "fmla v16.4s, v20.4s, %14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v17.4s}, [%2] \n" "fmla v17.4s, v20.4s, %16.4s \n" "st1 {v18.4s}, [%3], #16 \n" "st1 {v19.4s}, [%4], #16 \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v18.4s}, [%3] \n" "fmla v18.4s, v20.4s, %18.4s \n" "prfm pldl1keep, [%4, #128] \n" "ld1 {v19.4s}, [%4] \n" "fmla v19.4s, v20.4s, %20.4s \n" "prfm pldl1keep, [%6, #128] \n" "ld1 {v21.4s}, [%6], #16 \n" "fmla v16.4s, v21.4s, %15.4s \n" "fmla v17.4s, v21.4s, %17.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v20.4s}, [%5], #16 \n" "fmla v18.4s, v21.4s, %19.4s \n" "fmla v19.4s, v21.4s, %21.4s \n" "st1 {v16.4s}, [%1], #16 \n" "st1 {v17.4s}, [%2], #16 \n" "subs %w0, %w0, #1 \n" "st1 {v18.4s}, [%3], #16 \n" "st1 {v19.4s}, [%4], #16 \n" "bne 0b \n" "sub %5, %5, #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(r1) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(r1), "w"(_k00), // %14 "w"(_k01), // %15 "w"(_k10), // %16 "w"(_k11), // %17 "w"(_k20), // %18 "w"(_k21), // %19 "w"(_k30), // %20 "w"(_k31) // %21 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21" ); } #else if (nn > 0) { asm volatile( "pld [%5, #128] \n" "vld1.f32 {d24-d25}, [%5 :128]! \n"// q12 = _r0 "0: \n" "pld [%1, #128] \n" "vld1.f32 {d16-d17}, [%1 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q14 \n" "pld [%2, #128] \n" "vld1.f32 {d18-d19}, [%2 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q16 \n" "pld [%3, #128] \n" "vld1.f32 {d20-d21}, [%3 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q18 \n" "pld [%4, #128] \n" "vld1.f32 {d22-d23}, [%4 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q20 \n" "pld [%6, #128] \n" "vld1.f32 {d26-d27}, [%6 :128]! \n"// q13 = _r1 "vmla.f32 q8, q13, %q15 \n" "vmla.f32 q9, q13, %q17 \n" "pld [%5, #128] \n" "vld1.f32 {d24-d25}, [%5 :128]! \n"// q12 = _r0 "vmla.f32 q10, q13, %q19 \n" "vmla.f32 q11, q13, %q21 \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" "vst1.f32 {d18-d19}, [%2 :128]! \n" //// "pld [%1, #128] \n" "vld1.f32 {d16-d17}, [%1 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q14 \n" "pld [%2, #128] \n" "vld1.f32 {d18-d19}, [%2 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q16 \n" "vst1.f32 {d20-d21}, [%3 :128]! \n" "vst1.f32 {d22-d23}, [%4 :128]! \n" "pld [%3, #128] \n" "vld1.f32 {d20-d21}, [%3 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q18 \n" "pld [%4, #128] \n" "vld1.f32 {d22-d23}, [%4 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q20 \n" "pld [%6, #128] \n" "vld1.f32 {d26-d27}, [%6 :128]! \n"// q13 = _r1 "vmla.f32 q8, q13, %q15 \n" "vmla.f32 q9, q13, %q17 \n" "pld [%5, #128] \n" "vld1.f32 {d24-d25}, [%5 :128]! \n"// q12 = _r0 "vmla.f32 q10, q13, %q19 \n" "vmla.f32 q11, q13, %q21 \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" "vst1.f32 {d18-d19}, [%2 :128]! \n" //// "pld [%1, #128] \n" "vld1.f32 {d16-d17}, [%1 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q14 \n" "pld [%2, #128] \n" "vld1.f32 {d18-d19}, [%2 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q16 \n" "vst1.f32 {d20-d21}, [%3 :128]! \n" "vst1.f32 {d22-d23}, [%4 :128]! \n" "pld [%3, #128] \n" "vld1.f32 {d20-d21}, [%3 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q18 \n" "pld [%4, #128] \n" "vld1.f32 {d22-d23}, [%4 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q20 \n" "pld [%6, #128] \n" "vld1.f32 {d26-d27}, [%6 :128]! \n"// q13 = _r1 "vmla.f32 q8, q13, %q15 \n" "vmla.f32 q9, q13, %q17 \n" "pld [%5, #128] \n" "vld1.f32 {d24-d25}, [%5 :128]! \n"// q12 = _r0 "vmla.f32 q10, q13, %q19 \n" "vmla.f32 q11, q13, %q21 \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" "vst1.f32 {d18-d19}, [%2 :128]! \n" //// "pld [%1, #128] \n" "vld1.f32 {d16-d17}, [%1 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q14 \n" "pld [%2, #128] \n" "vld1.f32 {d18-d19}, [%2 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q16 \n" "vst1.f32 {d20-d21}, [%3 :128]! \n" "vst1.f32 {d22-d23}, [%4 :128]! \n" "pld [%3, #128] \n" "vld1.f32 {d20-d21}, [%3 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q18 \n" "pld [%4, #128] \n" "vld1.f32 {d22-d23}, [%4 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q20 \n" "pld [%6, #128] \n" "vld1.f32 {d26-d27}, [%6 :128]! \n"// q13 = _r1 "vmla.f32 q8, q13, %q15 \n" "vmla.f32 q9, q13, %q17 \n" "pld [%5, #128] \n" "vld1.f32 {d24-d25}, [%5 :128]! \n"// q12 = _r0 "vmla.f32 q10, q13, %q19 \n" "vmla.f32 q11, q13, %q21 \n" "vst1.f32 {d16-d17}, [%1 :128]! \n" "vst1.f32 {d18-d19}, [%2 :128]! \n" "subs %0, #1 \n" "vst1.f32 {d20-d21}, [%3 :128]! \n" "vst1.f32 {d22-d23}, [%4 :128]! \n" "bne 0b \n" "sub %5, %5, #16 \n" : "=r"(nn), // %0 "=r"(output0_tm), // %1 "=r"(output1_tm), // %2 "=r"(output2_tm), // %3 "=r"(output3_tm), // %4 "=r"(r0), // %5 "=r"(r1) // %6 : "0"(nn), "1"(output0_tm), "2"(output1_tm), "3"(output2_tm), "4"(output3_tm), "5"(r0), "6"(r1), "w"(_k00), // %14 "w"(_k01), // %15 "w"(_k10), // %16 "w"(_k11), // %17 "w"(_k20), // %18 "w"(_k21), // %19 "w"(_k30), // %20 "w"(_k31) // %21 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13" ); } #endif // __aarch64__ #endif // __ARM_NEON for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%4, #128] \n" "ld1 {v20.4s}, [%4], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v20.4s, %12.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1] \n" "fmla v17.4s, v20.4s, %14.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v18.4s}, [%2] \n" "fmla v18.4s, v20.4s, %16.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v19.4s}, [%3] \n" "fmla v19.4s, v20.4s, %18.4s \n" "prfm pldl1keep, [%5, #128] \n" "ld1 {v21.4s}, [%5], #16 \n" "fmla v16.4s, v21.4s, %13.4s \n" "fmla v17.4s, v21.4s, %15.4s \n" "fmla v18.4s, v21.4s, %17.4s \n" "fmla v19.4s, v21.4s, %19.4s \n" "st1 {v16.4s}, [%0], #16 \n" "st1 {v17.4s}, [%1], #16 \n" "st1 {v18.4s}, [%2], #16 \n" "st1 {v19.4s}, [%3], #16 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "w"(_k00), // %12 "w"(_k01), // %13 "w"(_k10), // %14 "w"(_k11), // %15 "w"(_k20), // %16 "w"(_k21), // %17 "w"(_k30), // %18 "w"(_k31) // %19 : "cc", "memory", "v16", "v17", "v18", "v19", "v20", "v21" ); #else asm volatile( "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n"// q12 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q12 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q14 \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q16 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q18 \n" "pld [%5, #128] \n" "vld1.f32 {d26-d27}, [%5 :128]! \n"// q13 = _r1 "vmla.f32 q8, q13, %q13 \n" "vmla.f32 q9, q13, %q15 \n" "vmla.f32 q10, q13, %q17 \n" "vmla.f32 q11, q13, %q19 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0), // %4 "=r"(r1) // %5 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "5"(r1), "w"(_k00), // %12 "w"(_k01), // %13 "w"(_k10), // %14 "w"(_k11), // %15 "w"(_k20), // %16 "w"(_k21), // %17 "w"(_k30), // %18 "w"(_k31) // %19 : "cc", "memory", "q8", "q9", "q10", "q11", "q12", "q13" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { output0_tm[m] += r0[m] * ktm[0 +m]; output0_tm[m] += r1[m] * ktm[4 +m]; output1_tm[m] += r0[m] * ktm[8 +m]; output1_tm[m] += r1[m] * ktm[12+m]; output2_tm[m] += r0[m] * ktm[16+m]; output2_tm[m] += r1[m] * ktm[20+m]; output3_tm[m] += r0[m] * ktm[24+m]; output3_tm[m] += r1[m] * ktm[28+m]; } r0 += 4; r1 += 4; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; #endif // __ARM_NEON } #if !__ARM_NEON ktm += 32; #endif // __ARM_NEON } } for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); float* output0_tm = out0_tm; float* output1_tm = out1_tm; float* output2_tm = out2_tm; float* output3_tm = out3_tm; for (int r=0; r<16; r++) { #if __ARM_NEON #if __aarch64__ register float32x4_t _k00 asm("v0"); register float32x4_t _k10 asm("v1"); register float32x4_t _k20 asm("v2"); register float32x4_t _k30 asm("v3"); asm volatile( "prfm pldl1keep, [%4, #256] \n" "ld1 {%0.4s, %1.4s}, [%4], #32 \n" "prfm pldl1keep, [%4, #256] \n" "ld1 {%2.4s, %3.4s}, [%4], #32 \n" : "=w"(_k00), "=w"(_k10), "=w"(_k20), "=w"(_k30) : "r"(ktm) : "cc", "memory" ); #else register float32x4_t _k00 asm("q0"); register float32x4_t _k10 asm("q1"); register float32x4_t _k20 asm("q2"); register float32x4_t _k30 asm("q3"); asm volatile( "pld [%4, #256] \n" "vld1.f32 {%e0-%f1}, [%4 :128]! \n" "pld [%4, #256] \n" "vld1.f32 {%e2-%f3}, [%4 :128]! \n" : "=w"(_k00), "=w"(_k10), "=w"(_k20), "=w"(_k30) : "r"(ktm) : "cc", "memory" ); #endif // __aarch64__ #endif // __ARM_NEON // tile int remain = tiles; for (; remain>0; remain--) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%4, #128] \n" "ld1 {v16.4s}, [%4], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v17.4s}, [%0] \n" "fmla v17.4s, v16.4s, %10.4s \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v18.4s}, [%1] \n" "fmla v18.4s, v16.4s, %11.4s \n" "prfm pldl1keep, [%2, #128] \n" "ld1 {v19.4s}, [%2] \n" "fmla v19.4s, v16.4s, %12.4s \n" "prfm pldl1keep, [%3, #128] \n" "ld1 {v20.4s}, [%3] \n" "fmla v20.4s, v16.4s, %13.4s \n" "st1 {v17.4s}, [%0], #16 \n" "st1 {v18.4s}, [%1], #16 \n" "st1 {v19.4s}, [%2], #16 \n" "st1 {v20.4s}, [%3], #16 \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0) // %4 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "w"(_k00), // %10 "w"(_k10), // %11 "w"(_k20), // %12 "w"(_k30) // %13 : "cc", "memory", "v16", "v17", "v18", "v19", "v20" ); #else asm volatile( "pld [%4, #128] \n" "vld1.f32 {d24-d25}, [%4 :128]! \n"// q12 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q12, %q10 \n" "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128] \n"// q9 = _output1_tm "vmla.f32 q9, q12, %q11 \n" "pld [%2, #128] \n" "vld1.f32 {d20-d21}, [%2 :128] \n"// q10 = _output2_tm "vmla.f32 q10, q12, %q12 \n" "pld [%3, #128] \n" "vld1.f32 {d22-d23}, [%3 :128] \n"// q11 = _output3_tm "vmla.f32 q11, q12, %q13 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" "vst1.f32 {d18-d19}, [%1 :128]! \n" "vst1.f32 {d20-d21}, [%2 :128]! \n" "vst1.f32 {d22-d23}, [%3 :128]! \n" : "=r"(output0_tm), // %0 "=r"(output1_tm), // %1 "=r"(output2_tm), // %2 "=r"(output3_tm), // %3 "=r"(r0) // %4 : "0"(output0_tm), "1"(output1_tm), "2"(output2_tm), "3"(output3_tm), "4"(r0), "w"(_k00), // %10 "w"(_k10), // %11 "w"(_k20), // %12 "w"(_k30) // %13 : "cc", "memory", "q8", "q9", "q10", "q11", "q12" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { output0_tm[m] += r0[m] * ktm[0 +m]; output1_tm[m] += r0[m] * ktm[4 +m]; output2_tm[m] += r0[m] * ktm[8 +m]; output3_tm[m] += r0[m] * ktm[12+m]; } r0 += 4; output0_tm += 4; output1_tm += 4; output2_tm += 4; output3_tm += 4; #endif // __ARM_NEON } #if !__ARM_NEON ktm += 16; #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 float* ktm = (const float*)kernel_tm.channel(nn_outch) + 8*8 * inch * (p-remain_outch_start); out0_tm.fill(0.f); int q = 0; for (; q<inch; q++) { const float* r0 = bottom_blob_tm.channel(q); float* output0_tm = out0_tm; for (int r=0; r<16; r++) { #if __ARM_NEON float32x4_t _k00 = vld1q_f32(ktm); ktm += 4; #endif // __ARM_NEON // tile for (int i=0; i<tiles; i++) { #if __ARM_NEON #if __aarch64__ asm volatile( "prfm pldl1keep, [%1, #128] \n" "ld1 {v17.4s}, [%1], #16 \n" "prfm pldl1keep, [%0, #128] \n" "ld1 {v16.4s}, [%0] \n" "fmla v16.4s, v17.4s, %4.4s \n" "st1 {v16.4s}, [%0], #16 \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00) // %4 : "cc", "memory", "v16", "v17" ); #else asm volatile( "pld [%1, #128] \n" "vld1.f32 {d18-d19}, [%1 :128]! \n"// q9 = _r0 "pld [%0, #128] \n" "vld1.f32 {d16-d17}, [%0 :128] \n"// q8 = _output0_tm "vmla.f32 q8, q9, %q4 \n" "vst1.f32 {d16-d17}, [%0 :128]! \n" : "=r"(output0_tm), // %0 "=r"(r0) // %1 : "0"(output0_tm), "1"(r0), "w"(_k00) // %4 : "cc", "memory", "q8", "q9" ); #endif // __aarch64__ #else for (int m=0; m<4; m++) { output0_tm[m] += r0[m] * ktm[m]; } r0 += 4; output0_tm += 4; #endif // __ARM_NEON } #if !__ARM_NEON ktm += 4; #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_0 = out0_tm.row(i * w_tm/8 + j); const float* output0_tm0_4 = out0_tm.row(i * w_tm/8 + j + tiles); const float* output0_tm1_0 = out0_tm.row(i * w_tm/8 + j + tiles * 2); const float* output0_tm1_4 = out0_tm.row(i * w_tm/8 + j + tiles * 3); const float* output0_tm2_0 = out0_tm.row(i * w_tm/8 + j + tiles * 4); const float* output0_tm2_4 = out0_tm.row(i * w_tm/8 + j + tiles * 5); const float* output0_tm3_0 = out0_tm.row(i * w_tm/8 + j + tiles * 6); const float* output0_tm3_4 = out0_tm.row(i * w_tm/8 + j + tiles * 7); const float* output0_tm4_0 = out0_tm.row(i * w_tm/8 + j + tiles * 8); const float* output0_tm4_4 = out0_tm.row(i * w_tm/8 + j + tiles * 9); const float* output0_tm5_0 = out0_tm.row(i * w_tm/8 + j + tiles * 10); const float* output0_tm5_4 = out0_tm.row(i * w_tm/8 + j + tiles * 11); const float* output0_tm6_0 = out0_tm.row(i * w_tm/8 + j + tiles * 12); const float* output0_tm6_4 = out0_tm.row(i * w_tm/8 + j + tiles * 13); const float* output0_tm7_0 = out0_tm.row(i * w_tm/8 + j + tiles * 14); const float* output0_tm7_4 = out0_tm.row(i * w_tm/8 + j + tiles * 15); float* output0 = out0.row(i * 6) + j * 6; const float* output0_tms_0[8] = { output0_tm0_0, output0_tm1_0, output0_tm2_0, output0_tm3_0, output0_tm4_0, output0_tm5_0, output0_tm6_0, output0_tm7_0 }; const float* output0_tms_4[8] = { output0_tm0_4, output0_tm1_4, output0_tm2_4, output0_tm3_4, output0_tm4_4, output0_tm5_4, output0_tm6_4, output0_tm7_4 }; for (int m=0; m<8; m++) { const float* output0_tm_0 = output0_tms_0[m]; const float* output0_tm_4 = output0_tms_4[m]; float tmp024a = output0_tm_0[1] + output0_tm_0[2]; float tmp135a = output0_tm_0[1] - output0_tm_0[2]; float tmp024b = output0_tm_0[3] + output0_tm_4[0]; float tmp135b = output0_tm_0[3] - output0_tm_4[0]; float tmp024c = output0_tm_4[1] + output0_tm_4[2]; float tmp135c = output0_tm_4[1] - output0_tm_4[2]; tmp[0][m] = output0_tm_0[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_4[3] + 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__ if (nn > 0) { asm volatile( "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "0: \n" "prfm pldl1keep, [%1, #128] \n" "ld1 {v0.4s}, [%1] \n" "fmla v0.4s, v2.4s, %10.s[0] \n" "fmul v10.4s, v3.4s, %10.s[1] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v8.4s, v9.4s}, [%2] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmul v11.4s, v1.4s, %10.s[2] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v2.4s, v3.4s}, [%3], #32 \n" "fmla v0.4s, v2.4s, %11.s[0] \n" "fmla v10.4s, v3.4s, %11.s[1] \n" "prfm pldl1keep, [%3, #256] \n" "ld2 {v8.4s, v9.4s}, [%3] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %11.s[2] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v2.4s, v3.4s}, [%4], #32 \n" "fmla v0.4s, v2.4s, %12.s[0] \n" "fmla v10.4s, v3.4s, %12.s[1] \n" "prfm pldl1keep, [%4, #256] \n" "ld2 {v8.4s, v9.4s}, [%4] \n" "ext v1.16b, v2.16b, v8.16b, #4 \n" "fmla v11.4s, v1.4s, %12.s[2] \n" "prfm pldl1keep, [%2, #256] \n" "ld2 {v2.4s, v3.4s}, [%2], #32 \n" "fadd v0.4s, v0.4s, v10.4s \n" "fadd v0.4s, v0.4s, v11.4s \n" "subs %w0, %w0, #1 \n" "st1 {v0.4s}, [%1], #16 \n" "bne 0b \n" "sub %2, %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", "v0", "v1", "v2", "v3", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15" ); } #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; } } }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 24; tile_size[1] = 24; tile_size[2] = 32; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
relative_fm.h
/* Copyright (c) 2015, 2016, 2017 Genome Research Ltd. Copyright (c) 2014 Jouni Siren Author: Jouni Siren <jouni.siren@iki.fi> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef _RELATIVE_FM_RELATIVE_FM_H #define _RELATIVE_FM_RELATIVE_FM_H #include "simple_fm.h" namespace relative { //------------------------------------------------------------------------------ struct align_parameters { const static size_type BLOCK_SIZE = 1024; // Split the BWTs into blocks of this size or less. const static size_type MAX_LENGTH = 32; // Maximum length of a pattern used to split the BWTs. const static size_type SEED_LENGTH = 4; // Generate all patterns of this length before parallelizing. const static int MAX_D = 8192; // Number of diagonals to consider in Myers' algorithm. const static size_type SA_SAMPLE_RATE = 0; // Sample rate for relative FM. const static size_type ISA_SAMPLE_RATE = 0; // Sample rate for relative FM. // Default size for on demand LCS buffer; enough for d = 100. const static size_type BUFFER_SIZE = 103 * 101; // Default sample rate with a BWT-invariant subsequence. const static size_type SECONDARY_SA_SAMPLE_RATE = 257; const static size_type SECONDARY_ISA_SAMPLE_RATE = 512; align_parameters() : block_size(BLOCK_SIZE), max_length(MAX_LENGTH), seed_length(SEED_LENGTH), max_d(MAX_D), sa_sample_rate(SA_SAMPLE_RATE), isa_sample_rate(ISA_SAMPLE_RATE), sorted_alphabet(true), preallocate(false), invariant(false) { } size_type block_size, max_length, seed_length; int max_d; size_type sa_sample_rate, isa_sample_rate; bool sorted_alphabet; // comp values are sorted by character values, making partitioning a bit faster. bool preallocate; // Use preallocated arrays in Myers' algorithm. bool invariant; // Find a BWT-invariant subsequence that supports relative SA samples. }; //------------------------------------------------------------------------------ template<class ReferenceBWTType, class SequenceType> void getComplement(const ReferenceBWTType& bwt, SequenceType& output, const sdsl::bit_vector& positions, size_type n); template<class ReferenceType> void alignBWTs(const ReferenceType& ref, const ReferenceType& seq, sdsl::bit_vector& ref_lcs, sdsl::bit_vector& seq_lcs, size_type& lcs, const align_parameters& parameters, bool print); template<class ReferenceType> void alignBWTs(const ReferenceType& ref, const ReferenceType& seq, sdsl::bit_vector& bwt_ref_lcs, sdsl::bit_vector& bwt_seq_lcs, sdsl::bit_vector& text_ref_lcs, sdsl::bit_vector& text_seq_lcs, size_type& lcs, sdsl::int_vector<0>& sa_samples, sdsl::int_vector<0>& isa_samples, const align_parameters& parameters, bool print); template<class IndexType, class VectorType> void getSortedLCS(const IndexType& index, const VectorType& lcs, sdsl::bit_vector& sorted_lcs, sdsl::int_vector<64>& lcs_C); //------------------------------------------------------------------------------ const std::string RELATIVE_FM_EXTENSION = ".rfm"; const std::string RELATIVE_SELECT_EXTENSION = ".select"; /* The two indexes must have identical or sorted alphabets. */ template<class ReferenceBWTType = bwt_type, class SequenceType = bwt_type> class RelativeFM { public: typedef SimpleFM<ReferenceBWTType> reference_type; //------------------------------------------------------------------------------ RelativeFM(const reference_type& ref, const reference_type& seq, const align_parameters parameters = align_parameters(), bool print = false) : reference(ref) { this->m_size = 0; this->sa_sample_rate = parameters.sa_sample_rate; this->isa_sample_rate = parameters.isa_sample_rate; size_type lcs_length = 0; sdsl::bit_vector bwt_ref_lcs, bwt_seq_lcs, text_ref_lcs, text_seq_lcs; if(parameters.invariant) { if(!(ref.supportsLocate(true)) || !(seq.supportsLocate(true))) { std::cerr << "RelativeFM::RelativeFM(): Both indexes must have SA samples with this construction option!" << std::endl; return; } alignBWTs(ref, seq, bwt_ref_lcs, bwt_seq_lcs, text_ref_lcs, text_seq_lcs, lcs_length, this->sa_samples, this->isa_samples, parameters, print); } else { alignBWTs(ref, seq, bwt_ref_lcs, bwt_seq_lcs, lcs_length, parameters, print); this->buildSamples(seq); } getComplement(ref.bwt, this->ref_minus_lcs, bwt_ref_lcs, lcs_length); getComplement(seq.bwt, this->seq_minus_lcs, bwt_seq_lcs, lcs_length); sdsl::util::assign(this->bwt_lcs, LCS(bwt_ref_lcs, bwt_seq_lcs, lcs_length)); sdsl::util::clear(bwt_ref_lcs); sdsl::util::clear(bwt_seq_lcs); if(parameters.invariant) { sdsl::util::assign(this->text_lcs, LCS(text_ref_lcs, text_seq_lcs, lcs_length)); sdsl::util::clear(text_ref_lcs); sdsl::util::clear(text_seq_lcs); } this->alpha = seq.alpha; this->m_size = seq.size(); } RelativeFM(const reference_type& ref, const std::string& base_name) : reference(ref) { std::string filename = base_name + RELATIVE_FM_EXTENSION; std::ifstream input(filename.c_str(), std::ios_base::binary); if(!input) { std::cerr << "RelativeFM::RelativeFM(): Cannot open input file " << filename << std::endl; return; } this->loadFrom(input); input.close(); } RelativeFM(const SimpleFM<>& ref, std::istream& input) : reference(ref) { this->loadFrom(input); } ~RelativeFM() { } //------------------------------------------------------------------------------ inline size_type size() const { return this->m_size; } inline size_type sequences() const { return this->alpha.C[1]; } size_type reportSize(bool print = false) const { size_type ref_bytes = sdsl::size_in_bytes(this->ref_minus_lcs); size_type seq_bytes = sdsl::size_in_bytes(this->seq_minus_lcs); size_type bwt_bytes = ref_bytes + seq_bytes; size_type bwt_lcs_bytes = sdsl::size_in_bytes(this->bwt_lcs); size_type text_lcs_bytes = sdsl::size_in_bytes(this->text_lcs); size_type sa_bytes = sdsl::size_in_bytes(this->sa_samples); size_type isa_bytes = sdsl::size_in_bytes(this->isa_samples); size_type select_bytes = this->selectSize(); #ifdef REPORT_RUNS size_type ref_runs = 0, seq_runs = 0; size_type ref_gap0 = 0, ref_gap1 = 0, ref_run = 0, ref_delta = 0; size_type seq_gap0 = 0, seq_gap1 = 0, seq_run = 0, seq_delta = 0; if(print) { countRuns(this->bwt_lcs.ref, ref_runs, ref_gap0, ref_gap1, ref_run, ref_delta); countRuns(this->bwt_lcs.seq, seq_runs, seq_gap0, seq_gap1, seq_run, seq_delta); } #endif size_type bytes = bwt_bytes + bwt_lcs_bytes + text_lcs_bytes + sdsl::size_in_bytes(this->alpha) + sizeof(this->m_size) + sizeof(this->sa_sample_rate) + sa_bytes + sizeof(this->isa_sample_rate) + isa_bytes + select_bytes; if(print) { #ifdef VERBOSE_OUTPUT printSize("ref_minus_lcs", ref_bytes, this->size()); printSize("seq_minus_lcs", seq_bytes, this->size()); printSize("bwt_lcs", bwt_lcs_bytes, this->size()); if(this->text_lcs.size() > 0) { printSize("text_lcs", text_lcs_bytes, this->size()); } if(this->sa_sample_rate > 0) { printSize("SA samples", sa_bytes, this->size()); } if(this->isa_sample_rate > 0) { printSize("ISA samples", isa_bytes, this->size()); } if(this->fastSelect()) { printSize("Select", select_bytes, this->size()); } #endif #ifdef REPORT_RUNS std::cout << std::string(16, ' ') << "Ref: " << ref_runs << " runs (gap0 " << (inMegabytes(ref_gap0) / 8) << " MB, gap1 " << (inMegabytes(ref_gap1) / 8) << " MB, run " << (inMegabytes(ref_run) / 8) << " MB, delta " << inMegabytes(ref_delta) << " MB)" << std::endl; std::cout << std::string(16, ' ') << "Seq: " << seq_runs << " runs (gap0 " << (inMegabytes(seq_gap0) / 8) << " MB, gap1 " << (inMegabytes(seq_gap1) / 8) << " MB, run " << (inMegabytes(seq_run) / 8) << " MB, delta " << inMegabytes(seq_delta) << " MB)" << std::endl; #endif printSize("Relative FM", bytes, this->size()); } return bytes; } void writeTo(const std::string& base_name) const { std::string filename = base_name + RELATIVE_FM_EXTENSION; std::ofstream output(filename.c_str(), std::ios_base::binary); if(!output) { std::cerr << "RelativeFM::writeTo(): Cannot open output file " << filename << std::endl; return; } this->writeTo(output); output.close(); } void writeTo(std::ostream& output) const { this->ref_minus_lcs.serialize(output); this->seq_minus_lcs.serialize(output); this->bwt_lcs.serialize(output); this->text_lcs.serialize(output); this->alpha.serialize(output); sdsl::write_member(this->sa_sample_rate, output); this->sa_samples.serialize(output); sdsl::write_member(this->isa_sample_rate, output); this->isa_samples.serialize(output); } //------------------------------------------------------------------------------ inline range_type LF(range_type range, char_type c) const { size_type begin = cumulative(this->alpha, c); return range_type(begin + this->rank(range.first, c), begin + this->rank(range.second + 1, c) - 1); } inline range_type LF(size_type i) const { size_type lcs_bits = this->bwt_lcs.seq_rank(i + 1); // Up to position i in seq. size_type ref_pos = (lcs_bits > 0 ? this->bwt_lcs.ref_select(lcs_bits) : 0); comp_type ref_c = 0, seq_c = 0; bool lcs_pos = this->bwt_lcs.seq[i]; if(lcs_pos) { ref_c = this->reference.bwt[ref_pos]; seq_c = this->alpha.char2comp[this->reference.alpha.comp2char[ref_c]]; } else { seq_c = this->seq_minus_lcs[i - lcs_bits]; ref_c = this->reference.alpha.char2comp[this->alpha.comp2char[seq_c]]; } return this->LF(i, lcs_bits, ref_pos, ref_c, seq_c, lcs_pos); } size_type Psi(size_type i) const { if(i >= this->size()) { return this->size(); } size_type c = relative::findChar(this->alpha, i); return this->select(i + 1 - cumulative(this->alpha, c), c); } /* Iterate Psi k times; returns size() if SA[i]+k >= size(). Use force = true if the index does not support locate() and extract(). NOTE: The divisor of the threshold has been selected by experimenting with different values. Basic threshold is the average distance to the nearest SA and ISA samples. If k >= threshold, it is cheaper to use locate() and inverse() than iterate Psi(). With slow select(), iteration is so expensive that it is always a bad idea. With fast select(), one step with Psi() is comparable to 1.5 steps with LF() in the relative index or 10 steps in the reference. We assume that a locate() / inverse() query does two steps in the relative index and the remaining steps in the reference. */ size_type Psi(size_type i, size_type k, bool force = false) const { size_type threshold = (force ? ~(size_type)0 : 1); if(!force && this->fastSelect()) { threshold = 2 + (this->reference.sa_sample_rate + this->reference.isa_sample_rate) / 20; } return relative::Psi(*this, i, k, threshold); } //------------------------------------------------------------------------------ template<class Iter> range_type find(Iter begin, Iter end) const { range_type res(0, this->size() - 1); while(begin != end) { --end; if(!hasChar(this->alpha, *end)) { return Range::empty_range(); } res = this->LF(res, *end); if(Range::empty(res)) { return Range::empty_range(); } } return res; } bool supportsLocate(bool print = false) const { if(this->text_lcs.size() == 0 && this->sa_sample_rate == 0) { if(print) { std::cerr << "RelativeFM::supportsLocate(): The index does not contain text_lcs or SA samples." << std::endl; } return false; } return true; } // Call supportsLocate() first. size_type locate(size_type i) const { if(this->text_lcs.size() == 0) { return relative::locate(*this, i); } if(i >= this->size()) { return 0; } // Find an SA sample or an LCS position in BWT(seq). size_type steps = 0; while(this->bwt_lcs.seq[i] == 0) { if(this->sa_sample_rate > 0 && i % this->sa_sample_rate == 0) { return this->sa_samples[i / this->sa_sample_rate] + steps; } range_type temp = this->LF_complement(i); if(temp.second == 0) { return steps; } i = temp.first; steps++; } // Map the LCS position into the corresponding position in BWT(ref). i = this->bwt_lcs.ref_select(this->bwt_lcs.seq_rank(i) + 1); // Locate the position in ref and convert it into a position in seq. // Note that it is the previous position in the reference that is an LCS position. i = this->reference.locate(i); i = this->text_lcs.seq_select(this->text_lcs.ref_rank(i)) + 1; return i + steps; } bool supportsExtract(bool print = false) const { if(this->text_lcs.size() == 0) { if(this->isa_sample_rate == 0) { if(print) { std::cerr << "RelativeFM::supportsExtract(): The index does not contain text_lcs or ISA samples." << std::endl; } return false; } } else if(this->isa_sample_rate == 0 && !(this->reference.supportsExtract(false))) { if(print) { std::cerr << "RelativeFM::supportsExtract(): The index contains text_lcs, but the reference does not support extract." << std::endl; } return false; } return true; } // Call supportsExtract() first. inline std::string extract(range_type range) const { return relative::extract(*this, range); } // Call supportsExtract() first. inline std::string extract(size_type from, size_type to) const { return relative::extract(*this, range_type(from, to)); } // Returns ISA[i]. Call supportsExtract() first. inline size_type inverse(size_type i) const { if(i >= this->size()) { return this->size(); } size_type bwt_pos = 0, text_pos = this->size() - 1; // The end of seq. if(this->isa_sample_rate > 0) // Is there an ISA sample before the end? { text_pos = ((i + this->isa_sample_rate - 1) / this->isa_sample_rate) * this->isa_sample_rate; if(text_pos >= this->size()) { text_pos = this->size() - 1; } else { bwt_pos = this->isa_samples[text_pos / this->isa_sample_rate]; } } if(this->text_lcs.size() > 0) // Is there an LCS position before text_pos? { size_type lcs_pos = this->text_lcs.seq_rank(i); size_type next_pos = this->text_lcs.seq_select(lcs_pos + 1); if(next_pos + 1 < text_pos) { text_pos = next_pos + 1; // +1 because the matching BWT positions are one step forward. size_type ref_pos = this->text_lcs.ref_select(lcs_pos + 1); bwt_pos = this->reference.inverse(ref_pos + 1); bwt_pos = this->bwt_lcs.seq_select(this->bwt_lcs.ref_rank(bwt_pos) + 1); } } // Move backwards from the starting position. while(text_pos > i) { bwt_pos = this->LF(bwt_pos).first; text_pos--; } return bwt_pos; } // FIXME Specialize for RLSequence? template<class ByteVector> void extractBWT(range_type range, ByteVector& buffer) const { if(Range::empty(range) || range.second >= this->size()) { return; } // Extract the relevant range of the reference. ByteVector ref_buffer; sdsl::bit_vector ref_lcs; size_type lcs_pos = this->bwt_lcs.seq_rank(range.first); size_type lcs_end = this->bwt_lcs.seq_rank(range.second + 1); if(lcs_end > lcs_pos) { range_type ref_range(this->bwt_lcs.ref_select(lcs_pos + 1), this->bwt_lcs.ref_select(lcs_end)); this->reference.extractBWT(ref_range, ref_buffer); extractBits(this->bwt_lcs.ref, ref_range, ref_lcs); } // Do the actual work. sdsl::bit_vector seq_lcs; sdsl::util::assign(buffer, ByteVector(Range::length(range), 0)); extractBits(this->bwt_lcs.seq, range, seq_lcs); size_type complement_pos = range.first - lcs_pos, ref_pos = 0; for(size_type i = 0; i < buffer.size(); i++) { if(seq_lcs[i] == 1) { while(ref_lcs[ref_pos] == 0) { ref_pos++; } buffer[i] = ref_buffer[ref_pos]; ref_pos++; } else { buffer[i] = this->alpha.comp2char[this->seq_minus_lcs[complement_pos]]; complement_pos++; } } } //------------------------------------------------------------------------------ inline bool fastSelect() const { return (this->sorted_lcs.size() > 0); } void buildSelect() { if(this->fastSelect()) { this->clearSelect(); } sdsl::bit_vector ref_lcs, seq_lcs; #pragma omp parallel for schedule(static) for(size_type i = 0; i < 2; i++) { if(i == 0) { getSortedLCS(this->reference, this->bwt_lcs.ref, ref_lcs, this->ref_lcs_C); } else { getSortedLCS(*this, this->bwt_lcs.seq, seq_lcs, this->seq_lcs_C); } } sdsl::util::assign(this->sorted_lcs, LCS(ref_lcs, seq_lcs, this->bwt_lcs.size())); sdsl::util::init_support(this->complement_select, &(this->bwt_lcs.seq)); } size_type selectSize() const { return sdsl::size_in_bytes(this->sorted_lcs) + sdsl::size_in_bytes(this->ref_lcs_C) + sdsl::size_in_bytes(this->seq_lcs_C); } void clearSelect() { sdsl::util::clear(this->sorted_lcs); sdsl::util::clear(this->complement_select); sdsl::util::clear(this->ref_lcs_C); sdsl::util::clear(this->seq_lcs_C); } /* Returns true if successful. */ bool loadSelect(const std::string& base_name) { std::string filename = base_name + RELATIVE_SELECT_EXTENSION; std::ifstream in(filename.c_str(), std::ios_base::binary); if(!in) { return false; } this->loadSelect(in); in.close(); return true; } void loadSelect(std::ifstream& in) { this->sorted_lcs.load(in); this->complement_select.load(in, &(this->bwt_lcs.seq)); this->ref_lcs_C.load(in); this->seq_lcs_C.load(in); } void writeSelect(const std::string& base_name) const { std::string filename = base_name + RELATIVE_SELECT_EXTENSION; std::ofstream out(filename.c_str(), std::ios_base::binary); if(!out) { std::cerr << "RelativeFM::writeSelect(): Cannot open output file " << filename << std::endl; return; } this->writeSelect(out); out.close(); } void writeSelect(std::ofstream& out) const { this->sorted_lcs.serialize(out); this->complement_select.serialize(out); this->ref_lcs_C.serialize(out); this->seq_lcs_C.serialize(out); } //------------------------------------------------------------------------------ const reference_type& reference; SequenceType ref_minus_lcs, seq_minus_lcs; LCS bwt_lcs, text_lcs; Alphabet alpha; size_type m_size; size_type sa_sample_rate, isa_sample_rate; sdsl::int_vector<0> sa_samples, isa_samples; // An optional select() structure that can be generated quickly when needed. LCS sorted_lcs; LCS::vector_type::select_0_type complement_select; sdsl::int_vector<64> ref_lcs_C, seq_lcs_C; // The C arrays for the common subsequence. //------------------------------------------------------------------------------ private: void loadFrom(std::istream& input) { this->ref_minus_lcs.load(input); this->seq_minus_lcs.load(input); this->bwt_lcs.load(input); this->text_lcs.load(input); this->alpha.load(input); this->m_size = this->reference.size() + this->seq_minus_lcs.size() - this->ref_minus_lcs.size(); sdsl::read_member(this->sa_sample_rate, input); this->sa_samples.load(input); sdsl::read_member(this->isa_sample_rate, input); this->isa_samples.load(input); } void buildSamples(const reference_type& seq) { bool sample_sa = (this->sa_sample_rate > 0), sample_isa = (this->isa_sample_rate > 0); if(this->sa_sample_rate == seq.sa_sample_rate) { this->sa_samples = seq.sa_samples; sample_sa = false; } if(this->isa_sample_rate == seq.isa_sample_rate) { this->isa_samples = seq.isa_samples; sample_isa = false; } if(sample_sa) { sdsl::util::assign(this->sa_samples, sdsl::int_vector<0>((this->size() + this->sa_sample_rate - 1) / this->sa_sample_rate, 0, bit_length(this->size() - 1))); } if(sample_isa) { sdsl::util::assign(this->isa_samples, sdsl::int_vector<0>((this->size() + this->isa_sample_rate - 1) / this->isa_sample_rate, 0, bit_length(this->size() - 1))); } if(!sample_sa && !sample_isa) { return; } size_type text_pos = this->size(), bwt_pos = 0; while(text_pos > 0) { text_pos--; if(sample_sa && bwt_pos % this->sa_sample_rate == 0) { this->sa_samples[bwt_pos / this->sa_sample_rate] = text_pos; } if(sample_isa && text_pos % this->isa_sample_rate == 0) { this->isa_samples[text_pos / this->isa_sample_rate] = bwt_pos; } bwt_pos = seq.LF(bwt_pos).first; } } //------------------------------------------------------------------------------ /* The straightforward implementation counts the number of c's up to position i. To get the proper result, we need to check whether position i is in LCS or its complement, and ignore the last position when doing rank in that sequence. Note that c is a real character. */ inline size_type rank(size_type i, char_type c) const { size_type res = 0; comp_type ref_c = this->reference.alpha.char2comp[c], seq_c = this->alpha.char2comp[c]; size_type lcs_bits = this->bwt_lcs.seq_rank(i + 1); // Number of LCS bits up to i in seq. bool check_lcs = (this->bwt_lcs.seq[i] == 1); // Is position i in LCS. if(lcs_bits < i + 1) // There are i + 1 - lcs_bits non-LCS bits in seq. { res += this->seq_minus_lcs.rank(i + check_lcs - lcs_bits, seq_c); } if(lcs_bits > 0) { size_type ref_pos = this->bwt_lcs.ref_select(lcs_bits); // Select is 1-based. res += this->reference.bwt.rank(ref_pos + 1 - check_lcs, ref_c); if(lcs_bits < ref_pos + 1) // At least one non-LCS bit in ref. { res -= this->ref_minus_lcs.rank(ref_pos + 1 - lcs_bits, ref_c); } } return res; } /* Compute select() by either binary searching rank() or using the separate select() structures. Note that i is 1-based and c is a real character. */ size_type select(size_type i, char_type c) const { if(this->fastSelect()) { comp_type ref_c = this->reference.alpha.char2comp[c], seq_c = this->alpha.char2comp[c]; size_type lf_pos = this->alpha.C[seq_c] + i - 1; size_type lcs_rank = this->sorted_lcs.seq_rank(lf_pos) - this->seq_lcs_C[seq_c]; if(this->sorted_lcs.seq[lf_pos] == 1) // The i'th occurrence of c is in LCS. { size_type ref_rank = this->sorted_lcs.ref_select(this->ref_lcs_C[ref_c] + lcs_rank + 1) - this->reference.alpha.C[ref_c]; size_type ref_pos = this->reference.bwt.select(ref_rank + 1, ref_c); size_type lcs_pos = this->bwt_lcs.ref_rank(ref_pos); return this->bwt_lcs.seq_select(lcs_pos + 1); } else // The i'th occurrence of c is in the complement. { size_type comp_rank = (lf_pos - this->alpha.C[seq_c]) - lcs_rank; size_type comp_pos = this->seq_minus_lcs.select(comp_rank + 1, seq_c); return this->complement_select(comp_pos + 1); } } else { i--; // Select is 1-based, while ranks are 0-based. size_type low = 0, high = this->size() - 1; while(low < high) // select(i, c) is the last position j with rank(j, c) == i. { size_type mid = low + (high + 1 - low) / 2; size_type candidate = this->rank(mid, c); if(candidate < i) { low = mid + 1; } else if(candidate == i) { low = mid; } else { high = mid - 1; } } return low; } } /* The actual implementation of LF. The first function is a special case for positions that are known to be in seq_minus_lcs, while the second one contains the core functionality. */ inline range_type LF_complement(size_type i) const { size_type lcs_bits = this->bwt_lcs.seq_rank(i); // Up to position i in seq. size_type ref_pos = (lcs_bits > 0 ? this->bwt_lcs.ref_select(lcs_bits) : 0); comp_type seq_c = this->seq_minus_lcs[i - lcs_bits]; comp_type ref_c = this->reference.alpha.char2comp[this->alpha.comp2char[seq_c]]; return this->LF(i, lcs_bits, ref_pos, ref_c, seq_c, false); } // This function contains the core functionality of all varieties of LF. inline range_type LF(size_type i, size_type lcs_bits, size_type ref_pos, comp_type ref_c, comp_type seq_c, bool lcs_pos) const { size_type res = this->alpha.C[seq_c]; if(lcs_bits < i + lcs_pos) { res += this->seq_minus_lcs.rank(i + lcs_pos - lcs_bits, seq_c); } if(lcs_bits > 0) { res += this->reference.bwt.rank(ref_pos + 1 - lcs_pos, ref_c); if(lcs_bits < ref_pos + 1) // At least one non-LCS position in ref. { res -= this->ref_minus_lcs.rank(ref_pos + 1 - lcs_bits, ref_c); } } return range_type(res, seq_c); } //------------------------------------------------------------------------------ RelativeFM(); RelativeFM(const RelativeFM&); RelativeFM(RelativeFM&&); RelativeFM& operator=(const RelativeFM&); RelativeFM& operator==(RelativeFM&); }; //------------------------------------------------------------------------------ template<class ReferenceBWTType, class SequenceType> void getComplement(const ReferenceBWTType& bwt, SequenceType& output, const sdsl::bit_vector& positions, size_type n) { #ifdef VERBOSE_STATUS_INFO double timestamp = readTimer(); #endif sdsl::int_vector<8> buffer(bwt.size() - n, 0); for(size_type i = 0, j = 0; i < bwt.size(); i++) { if(positions[i] == 0) { buffer[j] = bwt[i]; j++; } } directConstruct(output, buffer); #ifdef VERBOSE_STATUS_INFO #pragma omp critical (stderr) { std::cerr << "Extracted complement of length " << buffer.size() << " in " << (readTimer() - timestamp) << " seconds" << std::endl; } #endif } //------------------------------------------------------------------------------ /* Ranges in ref and seq matching the pattern. */ struct record_type { range_type left, right; std::string pattern; bool onlyNs, endmarker; record_type(range_type lt, range_type rt, const std::string& p, bool n, bool e) : left(lt), right(rt), pattern(p), onlyNs(n), endmarker(e) { } }; // Sort by longest average length in descending order. struct record_comparator { inline bool operator() (const record_type& a, const record_type& b) { return (Range::length(a.left) + Range::length(a.right) > Range::length(b.left) + Range::length(b.right)); } }; inline std::ostream& operator<<(std::ostream& stream, const record_type& record) { return stream << "(" << record.left << ", " << record.right << ")"; } struct short_record_type { public: short_record_type(range_type lt, range_type rt, bool n, bool e) : left(lt), right(rt) { this->right.first = (this->right.first << 1) | n; this->right.second = (this->right.second << 1) | e; } short_record_type(const record_type& source) : left(source.left), right(source.right) { this->right.first = (this->right.first << 1) | source.onlyNs; this->right.second = (this->right.second << 1) | source.endmarker; } inline range_type first() const { return this->left; } inline range_type second() const { return range_type(this->right.first >> 1, this->right.second >> 1); } inline bool onlyNs() const { return this->right.first & 1; } inline bool endmarker() const { return this->right.second & 1; } private: range_type left, right; }; struct short_record_comparator { inline bool operator() (const short_record_type& a, const short_record_type& b) { return (a.first() < b.first()); } }; /* Eugene W. Myers: An O(ND) Difference Algorithm and Its Variations. Algorithmica, 1986. The implementation assumes that offsets fit into int. If OpenMP is used, bitvectors should have the same length as the corresponding ranges, plus some padding to make the word boundaries match with the original bitvectors. Without OpenMP, they are the global bitvectors, and the function updates the range specified by ref_range/seq_range. The return value is (LCS length, heuristic losses). max_d specifies the maximum diagonal in LCS computation. If further diagonals would be needed, only the most frequent character in the ranges will be matched. Maximal memory usage will be around 4 * MAX_D * MAX_D bytes (+ SimpleFM for the reference and the target sequence and the current intervals as std::vector<uint8_t>). To use a preallocated buffer, set parameters.preallocated and pass a pointer to a buffer of size at least (max_d + 3) * (max_d + 1). */ range_type greedyLCS(const std::vector<uint8_t>& ref_extract, const std::vector<uint8_t>& seq_extract, sdsl::bit_vector& ref_lcs, sdsl::bit_vector& seq_lcs, short_record_type& record, const uint8_t* alphabet, size_type sigma, const align_parameters& parameters, std::vector<int>* buf); //------------------------------------------------------------------------------ template<class ReferenceType> void processSubtree(const record_type& root, uint8_t* alphabet, size_type sigma, const ReferenceType& ref, const ReferenceType& seq, std::vector<short_record_type>& results, const align_parameters& parameters) { std::stack<record_type> record_stack; record_stack.push(root); while(!(record_stack.empty())) { record_type curr = record_stack.top(); record_stack.pop(); if(Range::length(curr.left) <= parameters.block_size || Range::length(curr.right) <= parameters.block_size || curr.endmarker) { results.push_back(short_record_type(curr)); continue; } if(curr.pattern.length() >= parameters.max_length) { #ifdef VERBOSE_STATUS_INFO #pragma omp critical (stderr) { std::cerr << "Pattern length became " << curr.pattern.length() << " on ranges " << std::make_pair(curr.left, curr.right) << std::endl; std::cerr << " Range lengths: " << std::make_pair(Range::length(curr.left), Range::length(curr.right)) << std::endl; std::cerr << " The pattern was: " << curr.pattern << std::endl; } #endif results.push_back(short_record_type(curr)); continue; } std::string pattern = curr.pattern + " "; for(size_type i = sigma; i > 0; i--) { pattern[pattern.length() - 1] = (unsigned char)(alphabet[i - 1]); range_type left = ref.find(pattern.begin(), pattern.end()); if(Range::empty(left)) { continue; } range_type right = seq.find(pattern.begin(), pattern.end()); if(Range::empty(right)) { continue; } bool onlyNs = (curr.onlyNs && alphabet[i - 1] == 'N'), endmarker = (i == 1); record_stack.push(record_type(left, right, pattern, onlyNs, endmarker)); } } } template<class ReferenceType> void generatePatterns(std::vector<record_type>& record_array, uint8_t* alphabet, size_type sigma, const ReferenceType& ref, const ReferenceType& seq, size_type seed_length) { std::stack<record_type> record_stack; record_stack.push(record_type(range_type(0, ref.size() - 1), range_type(0, seq.size() - 1), "", true, false)); record_array.clear(); while(!(record_stack.empty())) { record_type curr = record_stack.top(); record_stack.pop(); if(curr.pattern.length() >= seed_length) { record_array.push_back(curr); continue; } std::string pattern = curr.pattern + " "; for(size_type i = sigma; i > 0; i--) { pattern[pattern.length() - 1] = (unsigned char)(alphabet[i - 1]); range_type left = ref.find(pattern.begin(), pattern.end()); if(Range::empty(left)) { continue; } range_type right = seq.find(pattern.begin(), pattern.end()); if(Range::empty(right)) { continue; } bool onlyNs = (curr.onlyNs && alphabet[i - 1] == 'N'), endmarker = (i == 1); record_stack.push(record_type(left, right, pattern, onlyNs, endmarker)); } } // Load balancing works better when long ranges are processed first. record_comparator comp; sequentialSort(record_array.begin(), record_array.end(), comp); } /* Copy the last Range::length(range) bits from source to target[range]. We assume that source has been paddes so that word boundaries are in the same positions in both bitvectors. */ void copyBits(const sdsl::bit_vector& source, sdsl::bit_vector& target, range_type range); template<class ReferenceType> void alignBWTs(const ReferenceType& ref, const ReferenceType& seq, sdsl::bit_vector& ref_lcs, sdsl::bit_vector& seq_lcs, size_type& lcs, const align_parameters& parameters, bool print) { if(print) { std::cout << "Reference size: " << ref.size() << std::endl; std::cout << "Target size: " << seq.size() << std::endl; } sdsl::util::clear(ref_lcs); sdsl::util::clear(seq_lcs); size_type sigma = 0; uint8_t alphabet[256]; if(parameters.sorted_alphabet) // Use the intersection of the alphabets. { for(size_type c = 0; c < 256; c++) { if(hasChar(ref.alpha, c) && hasChar(seq.alpha, c)) { alphabet[sigma] = c; sigma++; } } } else // Use the alphabet from seq. { sigma = seq.alpha.sigma; for(size_type c = 0; c < sigma; c++) { alphabet[c] = seq.alpha.comp2char[c]; } } // Partition the BWTs. double timestamp = readTimer(); size_type intersection = 0; std::vector<short_record_type> results; { std::vector<record_type> record_array; generatePatterns(record_array, alphabet, sigma, ref, seq, parameters.seed_length); #pragma omp parallel for schedule(dynamic, 1) for(size_type i = 0; i < record_array.size(); i++) { std::vector<short_record_type> result_buffer; processSubtree(record_array[i], alphabet, sigma, ref, seq, result_buffer, parameters); #pragma omp critical (alignbwts) { results.insert(results.end(), result_buffer.begin(), result_buffer.end()); } } short_record_comparator comp; parallelMergeSort(results.begin(), results.end(), comp); } if(print) { size_type ref_missed = 0, seq_missed = 0, ref_expect = 0, seq_expect = 0, ref_overlap = 0, seq_overlap = 0; for(size_type i = 0; i < results.size(); i++) { range_type first = results[i].first(), second = results[i].second(); intersection += std::min(Range::length(first), Range::length(second)); if(first.first < ref_expect) { ref_overlap++; } ref_missed += first.first - ref_expect; ref_expect = first.second + 1; if(second.first < seq_expect) { seq_overlap++; } seq_missed += second.first - seq_expect; seq_expect = second.second + 1; } ref_missed += ref.size() - ref_expect; seq_missed += seq.size() - seq_expect; std::cout << "Found " << results.size() << " ranges with intersection length " << intersection << " in " << (readTimer() - timestamp) << " seconds" << std::endl; std::cout << "Partitioning misses: reference " << ref_missed << ", target " << seq_missed << std::endl; std::cout << "Partitioning losses: reference " << (ref.size() - intersection - ref_missed) << ", target " << (seq.size() - intersection - seq_missed) << std::endl; if(ref_overlap > 0 || seq_overlap > 0) { std::cout << "Overlapping ranges: reference " << ref_overlap << ", target " << seq_overlap << std::endl; std::cout << "(There is a bug somewhere)" << std::endl; } } // Find the approximate LCS using the partitioning. timestamp = readTimer(); lcs = 0; size_type losses = 0, processed = 0, percentage = 1; sdsl::util::assign(ref_lcs, sdsl::bit_vector(ref.size(), 0)); sdsl::util::assign(seq_lcs, sdsl::bit_vector(seq.size(), 0)); size_type threads = omp_get_max_threads(); size_type chunk = std::max((size_type)1, results.size() / (threads * threads)); std::vector<std::vector<int>*> buffers(threads, 0); if(parameters.preallocate) { for(size_type i = 0; i < threads; i++) { buffers[i] = new std::vector<int>; buffers[i]->reserve((parameters.max_d + 3) * (parameters.max_d + 1)); } } #pragma omp parallel for schedule(dynamic, chunk) for(size_type i = 0; i < results.size(); i++) { // Ensure that ref_buffer and seq_buffer are aligned in the same way as ref_lcs and seq_lcs. range_type ref_range = results[i].first(), seq_range = results[i].second(); sdsl::bit_vector ref_buffer(Range::length(ref_range) + ref_range.first % 64, 0); sdsl::bit_vector seq_buffer(Range::length(seq_range) + seq_range.first % 64, 0); std::vector<uint8_t> ref_extract; ref.extractBWT(ref_range, ref_extract); std::vector<uint8_t> seq_extract; seq.extractBWT(seq_range, seq_extract); range_type temp = greedyLCS(ref_extract, seq_extract, ref_buffer, seq_buffer, results[i], alphabet, sigma, parameters, buffers[omp_get_thread_num()]); #pragma omp critical (alignbwts) { copyBits(ref_buffer, ref_lcs, ref_range); copyBits(seq_buffer, seq_lcs, seq_range); lcs += temp.first; losses += temp.second; } #pragma omp critical (stderr) { processed++; if(processed >= (percentage / 100.0) * results.size()) { double curr = readTimer(); std::cerr << "Processed " << processed << " / " << results.size() << " ranges in " << (curr - timestamp) << " seconds" << std::endl; percentage++; } } } if(parameters.preallocate) { for(size_type i = 0; i < threads; i++) { delete buffers[i]; buffers[i] = 0; } } if(print) { std::cout << "Found a common subsequence of length " << lcs << " in " << (readTimer() - timestamp) << " seconds" << std::endl; std::cout << "LCS losses: exact " << (intersection - lcs - losses) << ", heuristics " << losses << std::endl; std::cout << std::endl; } } //------------------------------------------------------------------------------ struct range_pair { range_type ref_range, seq_range; // Semiopen ranges [begin, end). range_pair(range_type ref, range_type seq) : ref_range(ref), seq_range(seq) {} }; /* We have implicitly two arrays over the reference, where range ref_range has values seq_range. This function finds the longest increasing subsequence over the reference, where each value can be from either of the two arrays. Return value is subsequence length, the positions of the subsequence are marked in ref_lcs, and the values in the subsequence are marked in seq_lcs. The function clears left_matches and right_matches. */ size_type increasingSubsequence(std::vector<range_pair>& left_matches, std::vector<range_pair>& right_matches, sdsl::bit_vector& ref_lcs, sdsl::bit_vector& seq_lcs, size_type ref_len, size_type seq_len); // Sort the matches and add a guard to the end. void sortMatches(std::vector<range_pair>& matches, size_type ref_len, size_type seq_len); // Determine the number of positions covered by a left/right match. size_type countCoverage(std::vector<range_pair>& left_matches, std::vector<range_pair>& right_matches, size_type ref_len); template<class ReferenceType> struct Match { const ReferenceType& seq; size_type bwt_pos; size_type text_pos; // Ending position of the run in the text. size_type distance; // Distance from SA[bwt_pos] to text_pos. size_type length; // Length of the run. bool following; Match(const ReferenceType& _seq) : seq(_seq) { this->reset(); } void reset() { this->bwt_pos = this->seq.size(); this->text_pos = this->seq.size(); this->distance = 0; this->length = 0; this->following = false; } void follow(size_type new_pos) { this->bwt_pos = new_pos; this->text_pos = this->seq.size(); this->distance = 0; this->length = 1; this->following = true; this->setSample(); } inline void setSample() { if(this->bwt_pos % this->seq.sa_sample_rate == 0) { this->text_pos = this->seq.sa_samples[this->bwt_pos / this->seq.sa_sample_rate] + this->distance; } } // c is the character that should match the one used for LF. void advance(size_type c) { if(this->bwt_pos >= this->seq.size()) { return; } range_type temp = this->seq.LF(this->bwt_pos); if(!hasChar(this->seq.alpha, c) || this->seq.alpha.char2comp[c] != temp.second) { this->following = false; } if(temp.second == 0) { this->text_pos = this->distance; this->following = false; } else { this->bwt_pos = temp.first; this->distance++; this->setSample(); } } void addRun(std::vector<range_pair>& vec, size_type ref_starting_pos) { if(this->length > 1) { range_type ref_run(ref_starting_pos, ref_starting_pos + this->length - 1); this->findSample(); range_type seq_run(this->text_pos + 1 - this->length, this->text_pos); vec.push_back(range_pair(ref_run, seq_run)); } this->reset(); } void findSample() { while(this->text_pos >= this->seq.size()) { this->advance(0); } } }; template<class ReferenceType> void findMatches(const ReferenceType& ref, const ReferenceType& seq, std::vector<range_pair>& left_matches, std::vector<range_pair>& right_matches, const sdsl::bit_vector& merge_vector) { size_type bwt_pos = 0, text_pos = ref.size() - 1; // SA(ref)[bwt_pos] = text_pos Match<ReferenceType> left(seq), right(seq); right.follow(0); // The empty suffix of seq is the right match of the empty suffix of ref. sdsl::bit_vector::select_0_type ref_select(&merge_vector); sdsl::bit_vector::rank_1_type seq_rank(&merge_vector); while(text_pos > 0) { // Advance to the previous position. range_type prev = ref.LF(bwt_pos); bwt_pos = prev.first; text_pos--; prev.second = ref.alpha.comp2char[prev.second]; size_type mutual_pos = ref_select(bwt_pos + 1); // We stop following, if the character is wrong, the match has reached the beginning of // the sequence, there is no longer a match, or the old match is no longer adjacent. if(left.following) { left.advance(prev.second); size_type new_match = seq.size(); if(merge_vector[mutual_pos - 1] == 0) { left.following = false; } else if((new_match = seq_rank(mutual_pos - 1)) != left.bwt_pos) { left.following = false; } if(left.following) { left.length++; } else { left.addRun(left_matches, text_pos + 1); if(new_match < seq.size()) { left.follow(new_match); } } } else if(mutual_pos > 0 && merge_vector[mutual_pos - 1] == 1) { left.follow(seq_rank(mutual_pos - 1)); } if(right.following) { right.advance(prev.second); size_type new_match = seq.size(); if(mutual_pos + 1 < seq.size() && merge_vector[mutual_pos + 1] == 0) { right.following = false; } else if((new_match = seq_rank(mutual_pos + 1)) != right.bwt_pos) { right.following = false; } if(right.following) { right.length++; } else { right.addRun(right_matches, text_pos + 1); if(new_match < seq.size()) { right.follow(new_match); } } } else if(mutual_pos + 1 < seq.size() && merge_vector[mutual_pos + 1] == 1) { right.follow(seq_rank(mutual_pos + 1)); } } left.addRun(left_matches, 0); right.addRun(right_matches, 0); } template<class ReferenceType> void permuteVector(const sdsl::bit_vector& source, sdsl::bit_vector& target, const ReferenceType& index, size_type sa_sample_rate, sdsl::int_vector<0>& sa_samples, size_type isa_sample_rate, sdsl::int_vector<0>& isa_samples) { bool sample_sa = (sa_sample_rate > 0); bool sample_isa = (isa_sample_rate > 0); if(sample_sa) { sdsl::util::assign(sa_samples, sdsl::int_vector<0>((index.size() + sa_sample_rate - 1) / sa_sample_rate, 0, bit_length(index.size() - 1))); } if(sample_isa) { sdsl::util::assign(isa_samples, sdsl::int_vector<0>((index.size() + isa_sample_rate - 1) / isa_sample_rate, 0, bit_length(index.size() - 1))); } sdsl::util::assign(target, sdsl::bit_vector(index.size(), 0)); size_type text_pos = index.size(), bwt_pos = 0; while(text_pos > 1) { text_pos--; // Invariant: SA[bwt_pos] == text_pos target[bwt_pos] = source[text_pos - 1]; if(sample_sa && bwt_pos % sa_sample_rate == 0) { sa_samples[bwt_pos / sa_sample_rate] = text_pos; } if(sample_isa && text_pos % isa_sample_rate == 0) { isa_samples[text_pos / isa_sample_rate] = bwt_pos; } bwt_pos = index.LF(bwt_pos).first; } target[bwt_pos] = source[index.size() - 1]; if(sample_isa) { isa_samples[0] = bwt_pos; } } template<class ReferenceType> void alignBWTs(const ReferenceType& ref, const ReferenceType& seq, sdsl::bit_vector& bwt_ref_lcs, sdsl::bit_vector& bwt_seq_lcs, sdsl::bit_vector& text_ref_lcs, sdsl::bit_vector& text_seq_lcs, size_type& lcs, sdsl::int_vector<0>& sa_samples, sdsl::int_vector<0>& isa_samples, const align_parameters& parameters, bool print) { if(print) { std::cout << "Reference size: " << ref.size() << std::endl; std::cout << "Target size: " << seq.size() << std::endl; } sdsl::util::clear(bwt_ref_lcs); sdsl::util::clear(bwt_seq_lcs); sdsl::util::clear(text_ref_lcs); sdsl::util::clear(text_seq_lcs); // Build a mapping from the comp values of seq to the comp values of ref. sdsl::int_vector<64> comp_mapping(seq.alpha.sigma); sdsl::bit_vector in_ref(seq.alpha.sigma); if(parameters.sorted_alphabet) // Use first ref_c >= seq_c. { size_type ref_comp = 0; for(size_type seq_comp = 0; seq_comp < seq.alpha.sigma; seq_comp++) { size_type seq_c = seq.alpha.comp2char[seq_comp]; while(ref_comp < ref.alpha.sigma && ref.alpha.comp2char[ref_comp] < seq_c) { ref_comp++; } comp_mapping[seq_comp] = ref_comp; in_ref[seq_comp] = (ref_comp < ref.alpha.sigma && ref.alpha.comp2char[ref_comp] == seq_c); } } else // Assume an identical alphabet. { for(size_type i = 0; i < seq.alpha.sigma; i++) { comp_mapping[i] = i; in_ref[i] = true; } } // Build the merging bitvector. double timestamp = readTimer(); sdsl::bit_vector merge_vector(ref.size() + seq.size()); { size_type ref_pos = ref.sequences(), seq_pos = 0; // Number of suffixes smaller than the current one. while(true) { merge_vector[ref_pos + seq_pos] = 1; range_type temp = seq.LF(seq_pos); if(temp.second == 0) { break; } seq_pos = temp.first; if(in_ref[temp.second]) { temp.second = comp_mapping[temp.second]; ref_pos = ref.alpha.C[temp.second] + ref.bwt.rank(ref_pos, temp.second); } else { ref_pos = ref.alpha.C[comp_mapping[temp.second]]; } } } if(print) { std::cout << "Built the merging bitvector in " << (readTimer() - timestamp) << " seconds" << std::endl; } // Build left match and right match arrays. std::vector<range_pair> left_matches, right_matches; timestamp = readTimer(); { findMatches(ref, seq, left_matches, right_matches, merge_vector); sdsl::util::clear(merge_vector); sortMatches(left_matches, ref.size(), seq.size()); sortMatches(right_matches, ref.size(), seq.size()); if(print) { size_type total_matches = countCoverage(left_matches, right_matches, ref.size()); std::cout << "Matched " << total_matches << " positions in " << (readTimer() - timestamp) << " seconds" << std::endl; } } // Find an increasing subsequence in the arrays and mark it in text_lcs bitvectors. timestamp = readTimer(); lcs = increasingSubsequence(left_matches, right_matches, text_ref_lcs, text_seq_lcs, ref.size(), seq.size()); if(print) { std::cout << "Found a common subsequence of length " << lcs << " in " << (readTimer() - timestamp) << " seconds" << std::endl; } // Traverse both CSAs to build the bwt_lcs bitvectors. // Sample SA at the same time if necessary. timestamp = readTimer(); { const ReferenceType* index[2] = { &ref, &seq }; sdsl::bit_vector* text_lcs[2] = { &text_ref_lcs, &text_seq_lcs }; sdsl::bit_vector* bwt_lcs[2] = { &bwt_ref_lcs, &bwt_seq_lcs }; size_type sa_rate[2] = { 0, parameters.sa_sample_rate }; size_type isa_rate[2] = { 0, parameters.isa_sample_rate }; #pragma omp parallel for for(size_type i = 0; i < 2; i++) { permuteVector(*(text_lcs[i]), *(bwt_lcs[i]), *(index[i]), sa_rate[i], sa_samples, isa_rate[i], isa_samples); } } if(print) { std::cout << "Built the bwt_lcs bitvectors "; if(parameters.sa_sample_rate > 0 || parameters.isa_sample_rate > 0) { std::cout << "and samples "; } std::cout << "in " << (readTimer() - timestamp) << " seconds" << std::endl; } } //------------------------------------------------------------------------------ template<class IndexType, class VectorType> void getSortedLCS(const IndexType& index, const VectorType& lcs, sdsl::bit_vector& sorted_lcs, sdsl::int_vector<64>& lcs_C) { sdsl::int_vector<8> buffer; sdsl::bit_vector lcs_buffer; sdsl::int_vector<64> C(index.alpha.sigma, 0); sdsl::util::assign(sorted_lcs, sdsl::bit_vector(index.size(), 0)); sdsl::util::assign(lcs_C, sdsl::int_vector<64>(index.alpha.sigma + 1, 0)); for(size_type i = 0; i < index.size(); i += MEGABYTE) { range_type range(i, std::min(i + MEGABYTE, index.size()) - 1); index.extractBWT(range, buffer); extractBits(lcs, range, lcs_buffer); for(size_type i = 0; i < buffer.size(); i++) { size_type comp = index.alpha.char2comp[buffer[i]]; if(lcs_buffer[i] == 1) { sorted_lcs[index.alpha.C[comp] + C[comp]] = 1; lcs_C[comp + 1]++; } C[comp]++; } } for(size_type i = 2; i <= index.alpha.sigma; i++) { lcs_C[i] += lcs_C[i - 1]; } } //------------------------------------------------------------------------------ } // namespace relative #endif // _RELATIVE_FM_RELATIVE_FM_H
post_utilities.h
#ifndef POST_UTILITIES_H #define POST_UTILITIES_H #include "utilities/timer.h" #include "includes/define.h" #include "includes/variables.h" #include "custom_utilities/create_and_destroy.h" #include "custom_utilities/GeometryFunctions.h" #include "custom_elements/Particle_Contact_Element.h" #ifdef _OPENMP #include <omp.h> #endif #include "utilities/openmp_utils.h" #include <limits> #include <iostream> #include <iomanip> #include <cmath> namespace Kratos { class PostUtilities { public: typedef ModelPart::ElementsContainerType ElementsArrayType; typedef ModelPart::NodesContainerType NodesContainerType; KRATOS_CLASS_POINTER_DEFINITION(PostUtilities); /// Default constructor. PostUtilities() {}; /// Destructor. virtual ~PostUtilities() {}; void AddModelPartToModelPart(ModelPart& rCompleteModelPart, ModelPart& rModelPartToAdd) { ////WATCH OUT! This function respects the existing Id's! KRATOS_TRY; //preallocate the memory needed int tot_nodes = rCompleteModelPart.Nodes().size() + rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().size(); int tot_elements = rCompleteModelPart.Elements().size() + rModelPartToAdd.GetCommunicator().LocalMesh().Elements().size(); rCompleteModelPart.Nodes().reserve(tot_nodes); rCompleteModelPart.Elements().reserve(tot_elements); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { rCompleteModelPart.Nodes().push_back(*node_it); } for (ModelPart::ElementsContainerType::ptr_iterator elem_it = rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_begin(); elem_it != rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_end(); elem_it++) { rCompleteModelPart.Elements().push_back(*elem_it); } KRATOS_CATCH(""); } void AddSpheresNotBelongingToClustersToMixModelPart(ModelPart& rCompleteModelPart, ModelPart& rModelPartToAdd) { ////WATCH OUT! This function respects the existing Id's! KRATOS_TRY; //preallocate the memory needed int tot_size = rCompleteModelPart.Nodes().size(); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { ModelPart::NodeIterator i_iterator = node_it; Node < 3 > & i = *i_iterator; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {tot_size += 1;} } rCompleteModelPart.Nodes().reserve(tot_size); rCompleteModelPart.Elements().reserve(tot_size); for (ModelPart::NodesContainerType::ptr_iterator node_it = rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_begin(); node_it != rModelPartToAdd.GetCommunicator().LocalMesh().Nodes().ptr_end(); node_it++) { ModelPart::NodeIterator i_iterator = node_it; Node < 3 > & i = *i_iterator; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {rCompleteModelPart.Nodes().push_back(*node_it);} } for (ModelPart::ElementsContainerType::ptr_iterator elem_it = rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_begin(); elem_it != rModelPartToAdd.GetCommunicator().LocalMesh().Elements().ptr_end(); elem_it++) { Node < 3 >& i = (*elem_it)->GetGeometry()[0]; if (i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) {rCompleteModelPart.Elements().push_back(*elem_it);} } KRATOS_CATCH(""); } array_1d<double,3> VelocityTrap(ModelPart& rModelPart, const array_1d<double,3>& low_point, const array_1d<double,3>& high_point) { ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(ParallelUtilities::GetNumThreads(), pElements.size(), this->GetElementPartition()); double velocity_X = 0.0, velocity_Y = 0.0, velocity_Z = 0.0; int number_of_elements = 0; #pragma omp parallel for reduction(+: velocity_X, velocity_Y, velocity_Z, number_of_elements) for (int k = 0; k < ParallelUtilities::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it) { array_1d<double,3> coor = (it)->GetGeometry()[0].Coordinates(); if (coor[0] >= low_point[0] && coor[0] <= high_point[0] && coor[1] >= low_point[1] && coor[1] <= high_point[1] && coor[2] >= low_point[2] && coor[2] <= high_point[2]) { velocity_X += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_X); velocity_Y += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_Y); velocity_Z += (it)->GetGeometry()[0].FastGetSolutionStepValue(VELOCITY_Z); number_of_elements++; } } //elements for for (int i = 0; i < 3; ++i) { KRATOS_ERROR_IF(high_point[i] < low_point[i]) << "Check the limits of the Velocity Trap Box. Maximum coordinates smaller than minimum coordinates." << std::endl; } } //parallel for if (number_of_elements) { velocity_X /= number_of_elements; velocity_Y /= number_of_elements; velocity_Z /= number_of_elements; } array_1d<double,3> velocity; velocity[0] = velocity_X; velocity[1] = velocity_Y; velocity[2] = velocity_Z; return velocity; }//VelocityTrap void IntegrationOfForces(ModelPart::NodesContainerType& mesh_nodes , array_1d<double, 3>& total_forces, array_1d<double, 3>& rotation_center, array_1d<double, 3>& total_moment) { for (ModelPart::NodesContainerType::ptr_iterator node_pointer_it = mesh_nodes.ptr_begin(); node_pointer_it != mesh_nodes.ptr_end(); ++node_pointer_it) { const array_1d<double, 3>& contact_forces_summed_at_structure_point = (*node_pointer_it)->FastGetSolutionStepValue(CONTACT_FORCES); noalias(total_forces) += contact_forces_summed_at_structure_point; array_1d<double, 3> vector_from_structure_center_to_structure_point; noalias(vector_from_structure_center_to_structure_point) = (*node_pointer_it)->Coordinates() - rotation_center; array_1d<double, 3> moment_to_add; GeometryFunctions::CrossProduct(vector_from_structure_center_to_structure_point, contact_forces_summed_at_structure_point, moment_to_add); noalias(total_moment) += moment_to_add; } } void IntegrationOfElasticForces(ModelPart::NodesContainerType& mesh_nodes, array_1d<double, 3>& total_forces) { for (ModelPart::NodesContainerType::ptr_iterator node_pointer_it = mesh_nodes.ptr_begin(); node_pointer_it != mesh_nodes.ptr_end(); ++node_pointer_it) { const array_1d<double, 3> elastic_forces_added_up_at_node = (*node_pointer_it)->FastGetSolutionStepValue(ELASTIC_FORCES); noalias(total_forces) += elastic_forces_added_up_at_node; } } array_1d<double, 3> ComputePoisson(ModelPart& rModelPart) { ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); double total_poisson_value = 0.0; unsigned int number_of_spheres_to_evaluate_poisson = 0; array_1d<double, 3> return_data = ZeroVector(3); // TODO: Add OpenMP code for (unsigned int k = 0; k < pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); double& particle_poisson_value = p_sphere->GetGeometry()[0].FastGetSolutionStepValue(POISSON_VALUE); particle_poisson_value = 0.0; double epsilon_XY = 0.0; double epsilon_Z = 0.0; unsigned int number_of_neighbors_per_sphere_to_evaluate_poisson = 0; array_1d<double, 3> other_to_me_vector; array_1d<double, 3> initial_other_to_me_vector; unsigned int number_of_neighbors = p_sphere->mNeighbourElements.size(); for (unsigned int i = 0; i < number_of_neighbors; i++) { if (p_sphere->mNeighbourElements[i] == NULL) continue; noalias(other_to_me_vector) = p_sphere->GetGeometry()[0].Coordinates() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].Coordinates(); noalias(initial_other_to_me_vector) = p_sphere->GetGeometry()[0].GetInitialPosition() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].GetInitialPosition(); double initial_distance_XY = sqrt(initial_other_to_me_vector[0] * initial_other_to_me_vector[0] + initial_other_to_me_vector[1] * initial_other_to_me_vector[1]); double initial_distance_Z = initial_other_to_me_vector[2]; if (initial_distance_XY && initial_distance_Z) { epsilon_XY = -1 + sqrt(other_to_me_vector[0] * other_to_me_vector[0] + other_to_me_vector[1] * other_to_me_vector[1]) / initial_distance_XY; epsilon_Z = -1 + fabs(other_to_me_vector[2] / initial_distance_Z); } else continue; if (epsilon_Z) { // Should it be added here 'if p_sphere->Id() < p_sphere->mNeighbourElements[i]->Id()'? if (((-epsilon_XY / epsilon_Z) > 0.5) || ((-epsilon_XY / epsilon_Z) < 0.0)) continue; // TODO: Check this particle_poisson_value -= epsilon_XY / epsilon_Z; number_of_neighbors_per_sphere_to_evaluate_poisson++; } else continue; } if (number_of_neighbors_per_sphere_to_evaluate_poisson) { particle_poisson_value /= number_of_neighbors_per_sphere_to_evaluate_poisson; number_of_spheres_to_evaluate_poisson++; total_poisson_value += particle_poisson_value; } } if (number_of_spheres_to_evaluate_poisson) total_poisson_value /= number_of_spheres_to_evaluate_poisson; return_data[0] = total_poisson_value; return return_data; } //ComputePoisson array_1d<double, 3> ComputePoisson2D(ModelPart& rModelPart) { // TODO: Adjust this function to the new changes made in the 3D version ElementsArrayType& pElements = rModelPart.GetCommunicator().LocalMesh().Elements(); double total_poisson_value = 0.0; unsigned int number_of_bonds_to_evaluate_poisson = 0; array_1d<double, 3> return_data = ZeroVector(3); double total_epsilon_y_value = 0.0; // TODO: Add OpenMP code for (unsigned int k = 0; k < pElements.size(); k++) { ElementsArrayType::iterator it = pElements.ptr_begin() + k; Element* raw_p_element = &(*it); SphericParticle* p_sphere = dynamic_cast<SphericParticle*>(raw_p_element); double& particle_poisson_value = p_sphere->GetGeometry()[0].FastGetSolutionStepValue(POISSON_VALUE); particle_poisson_value = 0.0; double epsilon_X = 0.0; double epsilon_Y = 0.0; unsigned int number_of_neighbors_to_evaluate_poisson = 0; array_1d<double, 3> other_to_me_vector; array_1d<double, 3> initial_other_to_me_vector; double average_sphere_epsilon_y_value = 0.0; unsigned int number_of_neighbors = p_sphere->mNeighbourElements.size(); for (unsigned int i = 0; i < number_of_neighbors; i++) { if (p_sphere->mNeighbourElements[i] == NULL) continue; noalias(other_to_me_vector) = p_sphere->GetGeometry()[0].Coordinates() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].Coordinates(); noalias(initial_other_to_me_vector) = p_sphere->GetGeometry()[0].GetInitialPosition() - p_sphere->mNeighbourElements[i]->GetGeometry()[0].GetInitialPosition(); double initial_distance_X = initial_other_to_me_vector[0]; double initial_distance_Y = initial_other_to_me_vector[1]; if (initial_distance_X && initial_distance_Y) { epsilon_X = -1 + fabs(other_to_me_vector[0] / initial_distance_X); epsilon_Y = -1 + fabs(other_to_me_vector[1] / initial_distance_Y); } if (epsilon_Y) { particle_poisson_value -= epsilon_X / epsilon_Y; number_of_neighbors_to_evaluate_poisson++; total_poisson_value -= epsilon_X / epsilon_Y; number_of_bonds_to_evaluate_poisson++; } average_sphere_epsilon_y_value += epsilon_Y; } if (number_of_neighbors_to_evaluate_poisson) particle_poisson_value /= number_of_neighbors_to_evaluate_poisson; total_epsilon_y_value += average_sphere_epsilon_y_value / number_of_neighbors; } if (number_of_bonds_to_evaluate_poisson) total_poisson_value /= number_of_bonds_to_evaluate_poisson; total_epsilon_y_value /= pElements.size(); return_data[0] = total_poisson_value; return_data[1] = total_epsilon_y_value; return return_data; } //ComputePoisson2D void ComputeEulerAngles(ModelPart& rSpheresModelPart, ModelPart& rClusterModelPart) { ProcessInfo& r_process_info = rSpheresModelPart.GetProcessInfo(); bool if_trihedron_option = (bool) r_process_info[TRIHEDRON_OPTION]; typedef ModelPart::NodesContainerType NodesArrayType; NodesArrayType& pSpheresNodes = rSpheresModelPart.GetCommunicator().LocalMesh().Nodes(); NodesArrayType& pClusterNodes = rClusterModelPart.GetCommunicator().LocalMesh().Nodes(); #pragma omp parallel for for (int k = 0; k < (int) pSpheresNodes.size(); k++) { ModelPart::NodeIterator i_iterator = pSpheresNodes.ptr_begin() + k; Node < 3 > & i = *i_iterator; array_1d<double, 3 >& rotated_angle = i.FastGetSolutionStepValue(PARTICLE_ROTATION_ANGLE); if (if_trihedron_option && i.IsNot(DEMFlags::BELONGS_TO_A_CLUSTER)) { array_1d<double, 3 >& EulerAngles = i.FastGetSolutionStepValue(EULER_ANGLES); GeometryFunctions::EulerAnglesFromRotationAngle(EulerAngles, rotated_angle); } // if_trihedron_option && Not BELONGS_TO_A_CLUSTER }//for Node #pragma omp parallel for for (int k = 0; k < (int) pClusterNodes.size(); k++) { ModelPart::NodeIterator i_iterator = pClusterNodes.ptr_begin() + k; Node < 3 > & i = *i_iterator; Quaternion<double>& Orientation = i.FastGetSolutionStepValue(ORIENTATION); array_1d<double, 3 >& EulerAngles = i.FastGetSolutionStepValue(EULER_ANGLES); GeometryFunctions::QuaternionToGiDEulerAngles(Orientation, EulerAngles); }//for Node } //ComputeEulerAngles double QuasiStaticAdimensionalNumber(ModelPart& rParticlesModelPart, ModelPart& rContactModelPart, const ProcessInfo& r_process_info) { double adimensional_value = 0.0; ElementsArrayType& pParticleElements = rParticlesModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(ParallelUtilities::GetNumThreads(), pParticleElements.size(), this->GetElementPartition()); array_1d<double,3> particle_forces; const array_1d<double,3>& gravity = r_process_info[GRAVITY]; double total_force = 0.0; //#pragma omp parallel for #pragma omp parallel for reduction(+:total_force) for (int k = 0; k < ParallelUtilities::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pParticleElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pParticleElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it) { Element::GeometryType& geom = it->GetGeometry(); if (geom[0].IsNot(DEMFlags::FIXED_VEL_X) && geom[0].IsNot(DEMFlags::FIXED_VEL_Y) && geom[0].IsNot(DEMFlags::FIXED_VEL_Z)) { particle_forces = geom[0].FastGetSolutionStepValue(TOTAL_FORCES); double mass = geom[0].FastGetSolutionStepValue(NODAL_MASS); particle_forces[0] += mass * gravity[0]; particle_forces[1] += mass * gravity[1]; particle_forces[2] += mass * gravity[2]; double module = 0.0; GeometryFunctions::module(particle_forces, module); total_force += module; } //if }//balls }//paralel ElementsArrayType& pContactElements = rContactModelPart.GetCommunicator().LocalMesh().Elements(); OpenMPUtils::CreatePartition(ParallelUtilities::GetNumThreads(), pContactElements.size(), this->GetElementPartition()); array_1d<double,3> contact_forces; double total_elastic_force = 0.0; #pragma omp parallel for reduction(+:total_elastic_force) for (int k = 0; k < ParallelUtilities::GetNumThreads(); k++) { ElementsArrayType::iterator it_begin = pContactElements.ptr_begin() + this->GetElementPartition()[k]; ElementsArrayType::iterator it_end = pContactElements.ptr_begin() + this->GetElementPartition()[k + 1]; for (ElementsArrayType::iterator it = it_begin; it != it_end; ++it){ Element::GeometryType& geom = it->GetGeometry(); if (geom[0].IsNot(DEMFlags::FIXED_VEL_X) && geom[0].IsNot(DEMFlags::FIXED_VEL_Y) && geom[0].IsNot(DEMFlags::FIXED_VEL_Z) && geom[1].IsNot(DEMFlags::FIXED_VEL_X) && geom[1].IsNot(DEMFlags::FIXED_VEL_Y) && geom[1].IsNot(DEMFlags::FIXED_VEL_Z)) { contact_forces = it->GetValue(LOCAL_CONTACT_FORCE); double module = 0.0; GeometryFunctions::module(contact_forces, module); total_elastic_force += module; } } } if (total_elastic_force != 0.0) { adimensional_value = total_force/total_elastic_force; } else { KRATOS_ERROR << "There are no elastic forces= " << total_elastic_force << std::endl; } return adimensional_value; }//QuasiStaticAdimensionalNumber std::vector<unsigned int>& GetElementPartition() {return (mElementPartition);}; protected: std::vector<unsigned int> mElementPartition; }; // Class PostUtilities } // namespace Kratos. #endif // POST_UTILITIES_H
GB_unaryop__lnot_int32_int8.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__lnot_int32_int8 // op(A') function: GB_tran__lnot_int32_int8 // C type: int32_t // A type: int8_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = !(aij != 0) #define GB_ATYPE \ int8_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ int8_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = !(x != 0) ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_LNOT || GxB_NO_INT32 || GxB_NO_INT8) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__lnot_int32_int8 ( int32_t *Cx, // Cx and Ax may be aliased int8_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__lnot_int32_int8 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
fusedFDM.c
extern "C" void FUNC(fusedFDM)( const dlong& Nelements, pfloat* __restrict__ Su, const pfloat* __restrict__ S_x, const pfloat* __restrict__ S_y, const pfloat* __restrict__ S_z, const pfloat* __restrict__ inv_L, #if p_restrict const dfloat* __restrict__ wts, #endif pfloat* __restrict__ u ) { #define getIdx(k,j,i,e) ((k)*p_Nq_e*p_Nq_e+(j)*p_Nq_e+(i)+(e)*p_Nq_e*p_Nq_e*p_Nq_e) #define work1(k,j,i,e) (u[(getIdx(k,j,i,e))]) pfloat S_x_e[p_Nq_e][p_Nq_e]; pfloat S_y_e[p_Nq_e][p_Nq_e]; pfloat S_z_e[p_Nq_e][p_Nq_e]; pfloat S_x_eT[p_Nq_e][p_Nq_e]; pfloat S_y_eT[p_Nq_e][p_Nq_e]; pfloat S_z_eT[p_Nq_e][p_Nq_e]; pfloat tmp[p_Nq_e][p_Nq_e][p_Nq_e]; pfloat work2[p_Nq_e][p_Nq_e][p_Nq_e]; #ifdef __NEKRS__OMP__ #pragma omp parallel for private(S_x_e, S_y_e, S_z_e, S_x_eT, S_y_eT, S_z_eT, tmp, work2) #endif for (dlong my_elem = 0; my_elem < Nelements; ++my_elem) { const dlong element = my_elem; const dlong elem = element; #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(l1,j,k,elem) = work1(l1,j,k,elem) - work1(l2,j,k,elem); } } #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(p_Nq_e - l1 - 1,j,k,elem) = work1(p_Nq_e - l1 - 1,j,k,elem) - work1(p_Nq_e - l2 - 1,j,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(i,l1,k,elem) = work1(i,l1,k,elem) - work1(i,l2,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 2; work1(i,p_Nq_e - l1 - 1,k,elem) = work1(i,p_Nq_e - l1 - 1,k,elem) - work1(i,p_Nq_e - l2 - 1,k,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; work1(i,j,l1,elem) = work1(i,j,l1,elem) - work1(i,j,l2,elem); } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 2; work1(i,j,p_Nq_e - l1 - 1,elem) = work1(i,j,p_Nq_e - l1 - 1,elem) - work1(i,j,p_Nq_e - l2 - 1,elem); } } #pragma unroll for (int i = 0; i < p_Nq_e; i++){ #pragma unroll for (int j = 0; j < p_Nq_e; j++) { const int ij = j + i * p_Nq_e; S_x_e[i][j] = S_x[ij + element * p_Nq_e * p_Nq_e]; S_y_e[i][j] = S_y[ij + element * p_Nq_e * p_Nq_e]; S_z_e[i][j] = S_z[ij + element * p_Nq_e * p_Nq_e]; S_x_eT[j][i] = S_x_e[i][j]; S_y_eT[j][i] = S_y_e[i][j]; S_z_eT[j][i] = S_z_e[i][j]; } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_x_e[l][j] * work1(k,i,l,elem); work2[k][i][j] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_y_e[l][j] * work2[k][l][i]; //work1(j,i,k,elem) = value; tmp[j][k][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { const int v = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e; pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_z_e[l][k] * tmp[j][l][i]; work2[k][i][j] = value * inv_L[v + element * p_Nq_e * p_Nq_e * p_Nq_e]; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_x_eT[l][i] * work2[k][l][j]; tmp[k][j][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_y_eT[l][j] * tmp[k][l][i]; work2[j][k][i] = value; } } } #pragma unroll for (int k = 0; k < p_Nq_e; k++) { #pragma unroll for (int j = 0; j < p_Nq_e; j++) { #pragma unroll for (int i = 0; i < p_Nq_e; i++) { pfloat value = 0.0; #pragma unroll for (int l = 0; l < p_Nq_e; l++) value += S_z_eT[l][k] * work2[j][l][i]; #if (!p_restrict) const dlong elem_offset = element * p_Nq_e * p_Nq_e * p_Nq_e; const int v = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e + elem_offset; Su[v] = value; #endif tmp[k][j][i] = value; } } } #if (!p_restrict) #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[l1][j][k] = tmp[l2][j][k]; work2[p_Nq_e - l1 - 1][j][k] = tmp[p_Nq_e - l2 - 1][j][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work2[i][l1][k] = tmp[i][l2][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int k = 1; k < p_Nq_e-1; ++k){ const int l1 = 0; const int l2 = 0; work2[i][p_Nq_e - l1 - 1][k] = tmp[i][p_Nq_e - l2 - 1][k]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[i][j][l1] = tmp[i][j][l2]; } } #pragma unroll for(int i = 1; i < p_Nq_e-1; ++i){ #pragma unroll for(int j = 1; j < p_Nq_e-1; ++j){ const int l1 = 0; const int l2 = 0; work2[i][j][p_Nq_e - l1 - 1] = tmp[i][j][p_Nq_e - l2 - 1]; } } #pragma unroll for(int k = 0; k < p_Nq_e; ++k){ #pragma unroll for(int j = 0; j < p_Nq_e; ++j){ #pragma unroll for(int i = 0; i < p_Nq_e; ++i) { const dlong elem_offset = element * p_Nq_e * p_Nq_e * p_Nq_e; const dlong idx = i + j * p_Nq_e + k * p_Nq_e * p_Nq_e + elem_offset; u[idx] = work2[k][j][i]; } } } #else /* if (!p_restrict) */ #pragma unroll for(int k = 0; k < p_Nq; ++k){ #pragma unroll for(int j = 0; j < p_Nq; ++j){ #pragma unroll for(int i = 0; i < p_Nq; ++i){ const dlong elem_offset = element * p_Nq * p_Nq * p_Nq; const dlong idx = i + j * p_Nq + k * p_Nq * p_Nq + elem_offset; Su[idx] = tmp[k + 1][j + 1][i + 1] * wts[idx]; } } } #endif } #undef getIdx #undef work1 }
mxnet_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2017 by Contributors * \file mxnet_op.h * \brief * \author Junyuan Xie */ #ifndef MXNET_OPERATOR_MXNET_OP_H_ #define MXNET_OPERATOR_MXNET_OP_H_ #include <dmlc/omp.h> #include <mxnet/base.h> #include <mxnet/engine.h> #include <mxnet/op_attr_types.h> #include <algorithm> #include "./operator_tune.h" #include "../engine/openmp.h" #ifdef __CUDACC__ #include "../common/cuda_utils.h" #endif // __CUDACC__ namespace mxnet { namespace op { namespace mxnet_op { using namespace mshadow; #ifdef __CUDA_ARCH__ __constant__ const float PI = 3.14159265358979323846; #else const float PI = 3.14159265358979323846; using std::isnan; #endif template<typename xpu> int get_num_threads(const int N); #ifdef __CUDACC__ #define CUDA_KERNEL_LOOP(i, n) \ for (int i = blockIdx.x * blockDim.x + threadIdx.x; \ i < (n); \ i += blockDim.x * gridDim.x) inline cudaDeviceProp cuda_get_device_prop() { int device; CUDA_CALL(cudaGetDevice(&device)); cudaDeviceProp deviceProp; CUDA_CALL(cudaGetDeviceProperties(&deviceProp, device)); return deviceProp; } /*! * \brief Get the number of blocks for cuda kernel given N */ inline int cuda_get_num_blocks(const int N) { using namespace mshadow::cuda; return std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); } template<> inline int get_num_threads<gpu>(const int N) { using namespace mshadow::cuda; return kBaseThreadNum * cuda_get_num_blocks(N); } #endif // __CUDACC__ template<> inline int get_num_threads<cpu>(const int N) { return engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); } /*! \brief operator request type switch */ #define MXNET_ASSIGN_REQ_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } /*! \brief operator request type switch */ #define MXNET_REQ_TYPE_SWITCH(req, ReqType, ...) \ switch (req) { \ case kNullOp: \ { \ const OpReqType ReqType = kNullOp; \ {__VA_ARGS__} \ } \ break; \ case kWriteInplace: \ case kWriteTo: \ { \ const OpReqType ReqType = kWriteTo; \ {__VA_ARGS__} \ } \ break; \ case kAddTo: \ { \ const OpReqType ReqType = kAddTo; \ {__VA_ARGS__} \ } \ break; \ default: \ break; \ } #define MXNET_NDIM_SWITCH(NDim, ndim, ...) \ if (NDim == 0) { \ } else if (NDim == 1) { \ const int ndim = 1; \ {__VA_ARGS__} \ } else if (NDim == 2) { \ const int ndim = 2; \ {__VA_ARGS__} \ } else if (NDim == 3) { \ const int ndim = 3; \ {__VA_ARGS__} \ } else if (NDim == 4) { \ const int ndim = 4; \ {__VA_ARGS__} \ } else if (NDim == 5) { \ const int ndim = 5; \ {__VA_ARGS__} \ } else { \ LOG(FATAL) << "ndim=" << NDim << "too large "; \ } #define MXNET_NO_INT8_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt8: \ LOG(FATAL) << "This operation does not " \ "support int8 or uint8"; \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_NO_FLOAT16_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ LOG(FATAL) << "This operation does not " \ "support float16"; \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_REAL_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not uint8"; \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int8_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types not int8"; \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int32_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int32"; \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ LOG(FATAL) << "This operation only support " \ "floating point types, not int64"; \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_ACC_TYPE_SWITCH(type, DType, AType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ typedef double AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ typedef float AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ typedef uint32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ typedef int32_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ typedef int64_t AType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_INT_TYPE_SWITCH(type, DType, ...)\ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float32"; \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float64"; \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ LOG(FATAL) << "This operation only support " \ "integer types, not float16"; \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt8: \ { \ typedef int8_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt32: \ { \ typedef int32_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kInt64: \ { \ typedef int64_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Unknown type enum " << type; \ } #define MXNET_LOAD_TYPE_SWITCH(type, DType, ...) \ switch (type) { \ case mshadow::kFloat32: \ { \ typedef float DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat64: \ { \ typedef double DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kFloat16: \ { \ typedef mshadow::half::half_t DType; \ {__VA_ARGS__} \ } \ break; \ case mshadow::kUint8: \ { \ typedef uint8_t DType; \ {__VA_ARGS__} \ } \ break; \ default: \ LOG(FATAL) << "Invalid loading enum type " << type; \ } /*! * \brief assign the val to out according * to request in Kernel::Launch * \param out the data to be assigned * \param req the assignment request * \param val the value to be assigned to out * \tparam OType output type * \tparam VType value type */ #define KERNEL_ASSIGN(out, req, val) \ { \ switch (req) { \ case kNullOp: \ break; \ case kWriteTo: \ case kWriteInplace: \ (out) = (val); \ break; \ case kAddTo: \ (out) += (val); \ break; \ default: \ break; \ } \ } #define MXNET_ADD_ALL_TYPES \ .add_enum("float32", mshadow::kFloat32) \ .add_enum("float64", mshadow::kFloat64) \ .add_enum("float16", mshadow::kFloat16) \ .add_enum("uint8", mshadow::kUint8) \ .add_enum("int8", mshadow::kInt8) \ .add_enum("int32", mshadow::kInt32) \ .add_enum("int64", mshadow::kInt64) /* \brief Compute flattened index given coordinates and shape. */ template<int ndim> MSHADOW_XINLINE index_t ravel(const Shape<ndim>& coord, const Shape<ndim>& shape) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret = ret * shape[i] + (shape[i] > coord[i]) * coord[i]; } return ret; } /* Compute coordinates from flattened index given shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> unravel(const index_t idx, const Shape<ndim>& shape) { Shape<ndim> ret; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret[i] = j - tmp*shape[i]; j = tmp; } return ret; } /* Compute dot product of two vector */ template<int ndim> MSHADOW_XINLINE index_t dot(const Shape<ndim>& coord, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (int i = 0; i < ndim; ++i) { ret += coord[i] * stride[i]; } return ret; } /* Combining unravel and dot */ template<int ndim> MSHADOW_XINLINE index_t unravel_dot(const index_t idx, const Shape<ndim>& shape, const Shape<ndim>& stride) { index_t ret = 0; #pragma unroll for (index_t i = ndim-1, j = idx; i >=0; --i) { auto tmp = j / shape[i]; ret += (j - tmp*shape[i])*stride[i]; j = tmp; } return ret; } /* Calculate stride of each dim from shape */ template<int ndim> MSHADOW_XINLINE Shape<ndim> calc_stride(const Shape<ndim>& shape) { Shape<ndim> stride; index_t cumprod = 1; #pragma unroll for (int i = ndim - 1; i >= 0; --i) { stride[i] = (shape[i] > 1) ? cumprod : 0; cumprod *= shape[i]; } return stride; } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx, const Shape<ndim>& stride) { ++(*coord)[ndim-1]; *idx += stride[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx = *idx + stride[i-1] - shape[i] * stride[i]; } } /* Increment coordinates and modify index */ template<int ndim> MSHADOW_XINLINE void inc(Shape<ndim>* coord, const Shape<ndim>& shape, index_t* idx1, const Shape<ndim>& stride1, index_t* idx2, const Shape<ndim>& stride2) { ++(*coord)[ndim-1]; *idx1 += stride1[ndim-1]; *idx2 += stride2[ndim-1]; #pragma unroll for (int i = ndim - 1; i > 0 && (*coord)[i] >= shape[i]; --i) { (*coord)[i] -= shape[i]; ++(*coord)[i-1]; *idx1 = *idx1 + stride1[i-1] - shape[i] * stride1[i]; *idx2 = *idx2 + stride2[i-1] - shape[i] * stride2[i]; } } /*! * \brief Simple copy data from one blob to another * \param to Destination blob * \param from Source blob */ template <typename xpu> MSHADOW_CINLINE void copy(mshadow::Stream<xpu> *s, const TBlob& to, const TBlob& from) { CHECK_EQ(from.Size(), to.Size()); CHECK_EQ(from.dev_mask(), to.dev_mask()); MSHADOW_TYPE_SWITCH(to.type_flag_, DType, { if (to.type_flag_ == from.type_flag_) { mshadow::Copy(to.FlatTo1D<xpu, DType>(s), from.FlatTo1D<xpu, DType>(s), s); } else { MSHADOW_TYPE_SWITCH(from.type_flag_, SrcDType, { to.FlatTo1D<xpu, DType>(s) = mshadow::expr::tcast<DType>(from.FlatTo1D<xpu, SrcDType>(s)); }) } }) } /*! \brief Binary op backward gradient OP wrapper */ template<typename GRAD_OP> struct backward_grad { /* \brief Backward calc with grad * \param a - output grad * \param args... - data to grad calculation op (what this is -- input, output, etc. -- varies) * \return input grad */ template<typename DType, typename ...Args> MSHADOW_XINLINE static DType Map(DType a, Args... args) { return DType(a * GRAD_OP::Map(args...)); } }; /*! \brief Binary op backward gradient OP wrapper (tuned) */ template<typename GRAD_OP> struct backward_grad_tuned : public backward_grad<GRAD_OP>, public tunable { using backward_grad<GRAD_OP>::Map; }; /*! \brief Select assignment operation based upon the req value * Also useful for mapping mshadow Compute (F<OP>) to Kernel<OP>::Launch */ template<typename OP, int req> struct op_with_req { typedef OP Operation; /*! \brief input is one tensor */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i])); } /*! \brief inputs are two tensors */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *lhs, const DType *rhs) { KERNEL_ASSIGN(out[i], req, OP::Map(lhs[i], rhs[i])); } /*! \brief input is tensor and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value)); } /*! \brief input is tensor and two scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *in, const DType value_1, const DType value_2) { KERNEL_ASSIGN(out[i], req, OP::Map(in[i], value_1, value_2)); } /*! \brief No inputs (ie fill to constant value) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { KERNEL_ASSIGN(out[i], req, OP::Map()); } /*! \brief input is single scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(value)); } /*! \brief inputs are two tensors and a scalar value */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType value) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], value)); } /*! \brief inputs are three tensors (ie backward grad with binary grad function) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out, const DType *input_1, const DType *input_2, const DType *input_3) { KERNEL_ASSIGN(out[i], req, OP::Map(input_1[i], input_2[i], input_3[i])); } }; template<typename OP, typename xpu> struct Kernel; /*! * \brief CPU Kernel launcher * \tparam OP Operator to launch */ template<typename OP> struct Kernel<OP, cpu> { /*! * \brief Launch a generic CPU kernel. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool Launch(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch a generic CPU kernel with dynamic schedule. This is recommended * for irregular workloads such as spmv. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function */ template<typename ...Args> inline static bool LaunchDynamic(mshadow::Stream<cpu> *, const int64_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(false); if (omp_threads < 2) { for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) schedule(dynamic) for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } } #else for (int64_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif return true; } /*! * \brief Launch CPU kernel which has OMP tuning data available. * When using this for a new kernel op, add declaration and tuning objects to * operator_tune.cc * \tparam PRIMITIVE_OP The primitive operation to use for tuning * \tparam DType Data type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param dest Destination pointer (used to infer DType) * \param args Varargs to eventually pass to the OP::Map() function */ template<typename PRIMITIVE_OP, typename DType, typename ...Args> static void LaunchTuned(mshadow::Stream<cpu> *, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2 || !tuned_op<PRIMITIVE_OP, DType>::UseOMP( N, static_cast<size_t>(omp_threads))) { for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } } else { #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); ++i) { OP::Map(i, args...); } } #else for (size_t i = 0; i < N; ++i) { OP::Map(i, args...); } #endif } /*! * \brief Launch custom-tuned kernel where each thread is set to * operate on a contiguous partition * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param N Number of iterations * \param args Varargs to eventually pass to the UseOMP() and OP::Map() functions */ template<typename ...Args> inline static void LaunchEx(mshadow::Stream<cpu> *s, const size_t N, Args... args) { #ifdef _OPENMP const int omp_threads = engine::OpenMP::Get()->GetRecommendedOMPThreadCount(); if (omp_threads < 2) { OP::Map(0, N, args...); } else { const auto length = (N + omp_threads - 1) / omp_threads; #pragma omp parallel for num_threads(omp_threads) for (index_t i = 0; i < static_cast<index_t>(N); i += length) { OP::Map(i, i + length > N ? N - i : length, args...); } } #else OP::Map(0, N, args...); #endif } /*! * \brief Launch a tunable OP with implicitly-supplied data type * \tparam DType Data type * \tparam T OP type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, T>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<T, DType>(s, N, dest, args...); return true; } /*! * \brief Launch a tunable OP wrapper with explicitly-supplied data type (ie op_with_req) * \tparam DType Data type * \tparam T Wrapper type * \tparam Args Varargs type to eventually pass to the OP::Map() function * \param s Stream (usually null for CPU) * \param N Number of iterations * \param args Varargs to eventually pass to the OP::Map() function * \return Always true */ template<typename DType, typename T = OP, typename ...Args> static MSHADOW_CINLINE typename std::enable_if<std::is_base_of<tunable, typename T::Operation>::value, bool>::type Launch(mshadow::Stream<cpu> *s, const size_t N, DType *dest, Args... args) { LaunchTuned<typename T::Operation, DType>(s, N, dest, args...); return true; } }; #ifdef __CUDACC__ template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, args...); } } template<typename OP, typename ...Args> __global__ void mxnet_generic_kernel_ex(int N, Args... args) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { OP::Map(i, 1, args...); } } template<typename OP> struct Kernel<OP, gpu> { /*! \brief Launch GPU kernel */ template<typename ...Args> inline static void Launch(mshadow::Stream<gpu> *s, int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel); } template<typename ...Args> inline static void LaunchEx(mshadow::Stream<gpu> *s, const int N, Args... args) { if (0 == N) return; using namespace mshadow::cuda; int ngrid = std::min(kMaxGridNum, (N + kBaseThreadNum - 1) / kBaseThreadNum); mxnet_generic_kernel_ex<OP, Args...> <<<ngrid, kBaseThreadNum, 0, mshadow::Stream<gpu>::GetStream(s)>>>( N, args...); MSHADOW_CUDA_POST_KERNEL_CHECK(mxnet_generic_kernel_ex); } }; #endif // __CUDACC__ /*! * \brief Set to immediate scalar value kernel * \tparam val Scalar immediate */ template<int val> struct set_to_int : public tunable { // mxnet_op version (when used directly with Kernel<>::Launch()) */ template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType *out) { out[i] = DType(val); } // mshadow_op version (when used with op_with_req<>) MSHADOW_XINLINE static int Map() { return val; } }; /*! * \brief Special-case kernel shortcut for setting to zero and one */ using set_zero = set_to_int<0>; using set_one = set_to_int<1>; } // namespace mxnet_op } // namespace op } // namespace mxnet #endif // MXNET_OPERATOR_MXNET_OP_H_
cache.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % CCCC AAA CCCC H H EEEEE % % C A A C H H E % % C AAAAA C HHHHH EEE % % C A A C H H E % % CCCC A A CCCC H H EEEEE % % % % % % MagickCore Pixel Cache Methods % % % % Software Design % % Cristy % % July 1999 % % % % % % Copyright 1999-2021 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/composite-private.h" #include "MagickCore/distribute-cache-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/geometry.h" #include "MagickCore/list.h" #include "MagickCore/log.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/nt-base-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/policy.h" #include "MagickCore/quantum.h" #include "MagickCore/random_.h" #include "MagickCore/registry.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/splay-tree.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/timer-private.h" #include "MagickCore/thread-private.h" #include "MagickCore/utility.h" #include "MagickCore/utility-private.h" #if defined(MAGICKCORE_ZLIB_DELEGATE) #include "zlib.h" #endif /* Define declarations. */ #define CacheTick(offset,extent) QuantumTick((MagickOffsetType) offset,extent) #define IsFileDescriptorLimitExceeded() (GetMagickResource(FileResource) > \ GetMagickResourceLimit(FileResource) ? MagickTrue : MagickFalse) /* Typedef declarations. */ typedef struct _MagickModulo { ssize_t quotient, remainder; } MagickModulo; /* Forward declarations. */ #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif static Cache GetImagePixelCache(Image *,const MagickBooleanType,ExceptionInfo *) magick_hot_spot; static const Quantum *GetVirtualPixelCache(const Image *,const VirtualPixelMethod,const ssize_t, const ssize_t,const size_t,const size_t,ExceptionInfo *), *GetVirtualPixelsCache(const Image *); static const void *GetVirtualMetacontentFromCache(const Image *); static MagickBooleanType GetOneAuthenticPixelFromCache(Image *,const ssize_t,const ssize_t,Quantum *, ExceptionInfo *), GetOneVirtualPixelFromCache(const Image *,const VirtualPixelMethod, const ssize_t,const ssize_t,Quantum *,ExceptionInfo *), OpenPixelCache(Image *,const MapMode,ExceptionInfo *), OpenPixelCacheOnDisk(CacheInfo *,const MapMode), ReadPixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), ReadPixelCacheMetacontent(CacheInfo *magick_restrict, NexusInfo *magick_restrict,ExceptionInfo *), SyncAuthenticPixelsCache(Image *,ExceptionInfo *), WritePixelCachePixels(CacheInfo *magick_restrict,NexusInfo *magick_restrict, ExceptionInfo *), WritePixelCacheMetacontent(CacheInfo *,NexusInfo *magick_restrict, ExceptionInfo *); static Quantum *GetAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *QueueAuthenticPixelsCache(Image *,const ssize_t,const ssize_t,const size_t, const size_t,ExceptionInfo *), *SetPixelCacheNexusPixels(const CacheInfo *magick_restrict,const MapMode, const ssize_t,const ssize_t,const size_t,const size_t, const MagickBooleanType,NexusInfo *magick_restrict,ExceptionInfo *) magick_hot_spot; #if defined(MAGICKCORE_OPENCL_SUPPORT) static void CopyOpenCLBuffer(CacheInfo *magick_restrict); #endif #if defined(__cplusplus) || defined(c_plusplus) } #endif /* Global declarations. */ static SemaphoreInfo *cache_semaphore = (SemaphoreInfo *) NULL; static ssize_t cache_anonymous_memory = (-1); static time_t cache_epoch = 0; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCache() acquires a pixel cache. % % The format of the AcquirePixelCache() method is: % % Cache AcquirePixelCache(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate Cache AcquirePixelCache(const size_t number_threads) { CacheInfo *magick_restrict cache_info; char *value; cache_info=(CacheInfo *) AcquireAlignedMemory(1,sizeof(*cache_info)); if (cache_info == (CacheInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(cache_info,0,sizeof(*cache_info)); cache_info->type=UndefinedCache; cache_info->mode=IOMode; cache_info->disk_mode=IOMode; cache_info->colorspace=sRGBColorspace; cache_info->file=(-1); cache_info->id=GetMagickThreadId(); cache_info->number_threads=number_threads; if (GetOpenMPMaximumThreads() > cache_info->number_threads) cache_info->number_threads=GetOpenMPMaximumThreads(); if (GetMagickResourceLimit(ThreadResource) > cache_info->number_threads) cache_info->number_threads=(size_t) GetMagickResourceLimit(ThreadResource); if (cache_info->number_threads == 0) cache_info->number_threads=1; cache_info->nexus_info=AcquirePixelCacheNexus(cache_info->number_threads); if (cache_info->nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); value=GetEnvironmentValue("MAGICK_SYNCHRONIZE"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } value=GetPolicyValue("cache:synchronize"); if (value != (const char *) NULL) { cache_info->synchronize=IsStringTrue(value); value=DestroyString(value); } cache_info->width_limit=MagickMin(GetMagickResourceLimit(WidthResource), (MagickSizeType) MAGICK_SSIZE_MAX); cache_info->height_limit=MagickMin(GetMagickResourceLimit(HeightResource), (MagickSizeType) MAGICK_SSIZE_MAX); cache_info->semaphore=AcquireSemaphoreInfo(); cache_info->reference_count=1; cache_info->file_semaphore=AcquireSemaphoreInfo(); cache_info->debug=IsEventLogging(); cache_info->signature=MagickCoreSignature; return((Cache ) cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCacheNexus() allocates the NexusInfo structure. % % The format of the AcquirePixelCacheNexus method is: % % NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) % % A description of each parameter follows: % % o number_threads: the number of nexus threads. % */ MagickPrivate NexusInfo **AcquirePixelCacheNexus(const size_t number_threads) { NexusInfo **magick_restrict nexus_info; ssize_t i; nexus_info=(NexusInfo **) MagickAssumeAligned(AcquireAlignedMemory(2* number_threads,sizeof(*nexus_info))); if (nexus_info == (NexusInfo **) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *nexus_info=(NexusInfo *) AcquireQuantumMemory(number_threads, 2*sizeof(**nexus_info)); if (*nexus_info == (NexusInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(*nexus_info,0,2*number_threads*sizeof(**nexus_info)); for (i=0; i < (ssize_t) (2*number_threads); i++) { nexus_info[i]=(*nexus_info+i); if (i < (ssize_t) number_threads) nexus_info[i]->virtual_nexus=(*nexus_info+number_threads+i); nexus_info[i]->signature=MagickCoreSignature; } return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % A c q u i r e P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelCachePixels() returns the pixels associated with the specified % image. % % The format of the AcquirePixelCachePixels() method is: % % void *AcquirePixelCachePixels(const Image *image,size_t *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *AcquirePixelCachePixels(const Image *image,size_t *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); (void) exception; cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=0; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); *length=(size_t) cache_info->length; return(cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t G e n e s i s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentGenesis() instantiates the cache component. % % The format of the CacheComponentGenesis method is: % % MagickBooleanType CacheComponentGenesis(void) % */ MagickPrivate MagickBooleanType CacheComponentGenesis(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) cache_semaphore=AcquireSemaphoreInfo(); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C a c h e C o m p o n e n t T e r m i n u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % CacheComponentTerminus() destroys the cache component. % % The format of the CacheComponentTerminus() method is: % % CacheComponentTerminus(void) % */ MagickPrivate void CacheComponentTerminus(void) { if (cache_semaphore == (SemaphoreInfo *) NULL) ActivateSemaphoreInfo(&cache_semaphore); /* no op-- nothing to destroy */ RelinquishSemaphoreInfo(&cache_semaphore); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l i p P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClipPixelCacheNexus() clips the cache nexus as defined by the image clip % mask. The method returns MagickTrue if the pixel region is clipped, % otherwise MagickFalse. % % The format of the ClipPixelCacheNexus() method is: % % MagickBooleanType ClipPixelCacheNexus(Image *image,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClipPixelCacheNexus(Image *image, NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict p, *magick_restrict q; ssize_t y; /* Apply clip mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & WriteMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; if ((p == (Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (y=0; y < (ssize_t) nexus_info->region.height; y++) { ssize_t x; for (x=0; x < (ssize_t) nexus_info->region.width; x++) { double mask_alpha; ssize_t i; mask_alpha=QuantumScale*GetPixelWriteMask(image,p); if (fabs(mask_alpha) >= MagickEpsilon) { for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ClampToQuantum(MagickOver_((double) p[i],mask_alpha* GetPixelAlpha(image,p),(double) q[i],(double) GetPixelAlpha(image,q))); } SetPixelAlpha(image,GetPixelAlpha(image,p),q); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCache() clones a pixel cache. % % The format of the ClonePixelCache() method is: % % Cache ClonePixelCache(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate Cache ClonePixelCache(const Cache cache) { CacheInfo *magick_restrict clone_info; const CacheInfo *magick_restrict cache_info; assert(cache != NULL); cache_info=(const CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); clone_info=(CacheInfo *) AcquirePixelCache(cache_info->number_threads); clone_info->virtual_pixel_method=cache_info->virtual_pixel_method; return((Cache ) clone_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheMethods() clones the pixel cache methods from one cache to % another. % % The format of the ClonePixelCacheMethods() method is: % % void ClonePixelCacheMethods(Cache clone,const Cache cache) % % A description of each parameter follows: % % o clone: Specifies a pointer to a Cache structure. % % o cache: the pixel cache. % */ MagickPrivate void ClonePixelCacheMethods(Cache clone,const Cache cache) { CacheInfo *magick_restrict cache_info, *magick_restrict source_info; assert(clone != (Cache) NULL); source_info=(CacheInfo *) clone; assert(source_info->signature == MagickCoreSignature); if (source_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", source_info->filename); assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); source_info->methods=cache_info->methods; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C a c h e R e p o s i t o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelCacheRepository() clones the source pixel cache to the destination % cache. % % The format of the ClonePixelCacheRepository() method is: % % MagickBooleanType ClonePixelCacheRepository(CacheInfo *cache_info, % CacheInfo *source_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o source_info: the source pixel cache. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ClonePixelCacheOnDisk( CacheInfo *magick_restrict cache_info,CacheInfo *magick_restrict clone_info) { MagickSizeType extent; size_t quantum; ssize_t count; struct stat file_stats; unsigned char *buffer; /* Clone pixel cache on disk with identical morphology. */ if ((OpenPixelCacheOnDisk(cache_info,ReadMode) == MagickFalse) || (OpenPixelCacheOnDisk(clone_info,IOMode) == MagickFalse)) return(MagickFalse); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); quantum=(size_t) MagickMaxBufferExtent; if ((fstat(cache_info->file,&file_stats) == 0) && (file_stats.st_size > 0)) { #if defined(MAGICKCORE_HAVE_LINUX_SENDFILE) if (cache_info->length < 0x7ffff000) { count=sendfile(clone_info->file,cache_info->file,(off_t *) NULL, (size_t) cache_info->length); if (count == (ssize_t) cache_info->length) return(MagickTrue); if ((lseek(cache_info->file,0,SEEK_SET) < 0) || (lseek(clone_info->file,0,SEEK_SET) < 0)) return(MagickFalse); } #endif quantum=(size_t) MagickMin(file_stats.st_size,MagickMaxBufferExtent); } buffer=(unsigned char *) AcquireQuantumMemory(quantum,sizeof(*buffer)); if (buffer == (unsigned char *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); extent=0; while ((count=read(cache_info->file,buffer,quantum)) > 0) { ssize_t number_bytes; number_bytes=write(clone_info->file,buffer,(size_t) count); if (number_bytes != count) break; extent+=number_bytes; } buffer=(unsigned char *) RelinquishMagickMemory(buffer); if (extent != cache_info->length) return(MagickFalse); return(MagickTrue); } static MagickBooleanType ClonePixelCacheRepository( CacheInfo *magick_restrict clone_info,CacheInfo *magick_restrict cache_info, ExceptionInfo *exception) { #define MaxCacheThreads ((size_t) GetMagickResourceLimit(ThreadResource)) #define cache_number_threads(source,destination,chunk,multithreaded) \ num_threads((multithreaded) == 0 ? 1 : \ (((source)->type != MemoryCache) && ((source)->type != MapCache)) || \ (((destination)->type != MemoryCache) && ((destination)->type != MapCache)) ? \ MagickMax(MagickMin(GetMagickResourceLimit(ThreadResource),2),1) : \ MagickMax(MagickMin((ssize_t) GetMagickResourceLimit(ThreadResource),(ssize_t) (chunk)/256),1)) MagickBooleanType optimize, status; NexusInfo **magick_restrict cache_nexus, **magick_restrict clone_nexus; size_t length; ssize_t y; assert(cache_info != (CacheInfo *) NULL); assert(clone_info != (CacheInfo *) NULL); assert(exception != (ExceptionInfo *) NULL); if (cache_info->type == PingCache) return(MagickTrue); length=cache_info->number_channels*sizeof(*cache_info->channel_map); if ((cache_info->storage_class == clone_info->storage_class) && (cache_info->colorspace == clone_info->colorspace) && (cache_info->alpha_trait == clone_info->alpha_trait) && (cache_info->channels == clone_info->channels) && (cache_info->columns == clone_info->columns) && (cache_info->rows == clone_info->rows) && (cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) && (cache_info->metacontent_extent == clone_info->metacontent_extent)) { /* Identical pixel cache morphology. */ if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && ((clone_info->type == MemoryCache) || (clone_info->type == MapCache))) { (void) memcpy(clone_info->pixels,cache_info->pixels, cache_info->number_channels*cache_info->columns*cache_info->rows* sizeof(*cache_info->pixels)); if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) (void) memcpy(clone_info->metacontent,cache_info->metacontent, cache_info->columns*cache_info->rows* clone_info->metacontent_extent*sizeof(unsigned char)); return(MagickTrue); } if ((cache_info->type == DiskCache) && (clone_info->type == DiskCache)) return(ClonePixelCacheOnDisk(cache_info,clone_info)); } /* Mismatched pixel cache morphology. */ cache_nexus=AcquirePixelCacheNexus(cache_info->number_threads); clone_nexus=AcquirePixelCacheNexus(clone_info->number_threads); length=cache_info->number_channels*sizeof(*cache_info->channel_map); optimize=(cache_info->number_channels == clone_info->number_channels) && (memcmp(cache_info->channel_map,clone_info->channel_map,length) == 0) ? MagickTrue : MagickFalse; length=(size_t) MagickMin(cache_info->number_channels*cache_info->columns, clone_info->number_channels*clone_info->columns); status=MagickTrue; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; ssize_t x; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCachePixels(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; (void) memset(clone_nexus[id]->pixels,0,(size_t) clone_nexus[id]->length); if (optimize != MagickFalse) (void) memcpy(clone_nexus[id]->pixels,cache_nexus[id]->pixels,length* sizeof(Quantum)); else { const Quantum *magick_restrict p; Quantum *magick_restrict q; /* Mismatched pixel channel map. */ p=cache_nexus[id]->pixels; q=clone_nexus[id]->pixels; for (x=0; x < (ssize_t) cache_info->columns; x++) { ssize_t i; if (x == (ssize_t) clone_info->columns) break; for (i=0; i < (ssize_t) clone_info->number_channels; i++) { PixelChannel channel; PixelTrait traits; channel=clone_info->channel_map[i].channel; traits=cache_info->channel_map[channel].traits; if (traits != UndefinedPixelTrait) *q=*(p+cache_info->channel_map[channel].offset); q++; } p+=cache_info->number_channels; } } status=WritePixelCachePixels(clone_info,clone_nexus[id],exception); } if ((cache_info->metacontent_extent != 0) && (clone_info->metacontent_extent != 0)) { /* Clone metacontent. */ length=(size_t) MagickMin(cache_info->metacontent_extent, clone_info->metacontent_extent); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ cache_number_threads(cache_info,clone_info,cache_info->rows,1) #endif for (y=0; y < (ssize_t) cache_info->rows; y++) { const int id = GetOpenMPThreadId(); Quantum *pixels; if (status == MagickFalse) continue; if (y >= (ssize_t) clone_info->rows) continue; pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,0,y, cache_info->columns,1,MagickFalse,cache_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; status=ReadPixelCacheMetacontent(cache_info,cache_nexus[id],exception); if (status == MagickFalse) continue; pixels=SetPixelCacheNexusPixels(clone_info,WriteMode,0,y, clone_info->columns,1,MagickFalse,clone_nexus[id],exception); if (pixels == (Quantum *) NULL) continue; if ((clone_nexus[id]->metacontent != (void *) NULL) && (cache_nexus[id]->metacontent != (void *) NULL)) (void) memcpy(clone_nexus[id]->metacontent, cache_nexus[id]->metacontent,length*sizeof(unsigned char)); status=WritePixelCacheMetacontent(clone_info,clone_nexus[id],exception); } } clone_nexus=DestroyPixelCacheNexus(clone_nexus,clone_info->number_threads); cache_nexus=DestroyPixelCacheNexus(cache_nexus,cache_info->number_threads); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"%s => %s", CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type), CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) clone_info->type)); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixelCache() method is: % % void DestroyImagePixelCache(Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void DestroyImagePixelCache(Image *image) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (image->cache != (void *) NULL) image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyImagePixels() deallocates memory associated with the pixel cache. % % The format of the DestroyImagePixels() method is: % % void DestroyImagePixels(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void DestroyImagePixels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.destroy_pixel_handler != (DestroyPixelHandler) NULL) { cache_info->methods.destroy_pixel_handler(image); return; } image->cache=DestroyPixelCache(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCache() deallocates memory associated with the pixel cache. % % The format of the DestroyPixelCache() method is: % % Cache DestroyPixelCache(Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ static MagickBooleanType ClosePixelCacheOnDisk(CacheInfo *cache_info) { int status; status=(-1); if (cache_info->file != -1) { status=close(cache_info->file); cache_info->file=(-1); RelinquishMagickResource(FileResource,1); } return(status == -1 ? MagickFalse : MagickTrue); } static inline void RelinquishPixelCachePixels(CacheInfo *cache_info) { switch (cache_info->type) { case MemoryCache: { #if defined(MAGICKCORE_OPENCL_SUPPORT) if (cache_info->opencl != (MagickCLCacheInfo) NULL) { cache_info->opencl=RelinquishMagickCLCacheInfo(cache_info->opencl, MagickTrue); cache_info->pixels=(Quantum *) NULL; break; } #endif if (cache_info->mapped == MagickFalse) cache_info->pixels=(Quantum *) RelinquishAlignedMemory( cache_info->pixels); else (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); RelinquishMagickResource(MemoryResource,cache_info->length); break; } case MapCache: { (void) UnmapBlob(cache_info->pixels,(size_t) cache_info->length); cache_info->pixels=(Quantum *) NULL; if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(MapResource,cache_info->length); } case DiskCache: { if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); if ((cache_info->mode != ReadMode) && (cache_info->mode != PersistMode)) (void) RelinquishUniqueFileResource(cache_info->cache_filename); *cache_info->cache_filename='\0'; RelinquishMagickResource(DiskResource,cache_info->length); break; } case DistributedCache: { *cache_info->cache_filename='\0'; (void) RelinquishDistributePixelCache((DistributeCacheInfo *) cache_info->server_info); break; } default: break; } cache_info->type=UndefinedCache; cache_info->mapped=MagickFalse; cache_info->metacontent=(void *) NULL; } MagickPrivate Cache DestroyPixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count--; if (cache_info->reference_count != 0) { UnlockSemaphoreInfo(cache_info->semaphore); return((Cache) NULL); } UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->debug != MagickFalse) { char message[MagickPathExtent]; (void) FormatLocaleString(message,MagickPathExtent,"destroy %s", cache_info->filename); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } RelinquishPixelCachePixels(cache_info); if (cache_info->server_info != (DistributeCacheInfo *) NULL) cache_info->server_info=DestroyDistributeCacheInfo((DistributeCacheInfo *) cache_info->server_info); if (cache_info->nexus_info != (NexusInfo **) NULL) cache_info->nexus_info=DestroyPixelCacheNexus(cache_info->nexus_info, cache_info->number_threads); if (cache_info->random_info != (RandomInfo *) NULL) cache_info->random_info=DestroyRandomInfo(cache_info->random_info); if (cache_info->file_semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->file_semaphore); if (cache_info->semaphore != (SemaphoreInfo *) NULL) RelinquishSemaphoreInfo(&cache_info->semaphore); cache_info->signature=(~MagickCoreSignature); cache_info=(CacheInfo *) RelinquishAlignedMemory(cache_info); cache=(Cache) NULL; return(cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelCacheNexus() destroys a pixel cache nexus. % % The format of the DestroyPixelCacheNexus() method is: % % NexusInfo **DestroyPixelCacheNexus(NexusInfo *nexus_info, % const size_t number_threads) % % A description of each parameter follows: % % o nexus_info: the nexus to destroy. % % o number_threads: the number of nexus threads. % */ static inline void RelinquishCacheNexusPixels(NexusInfo *nexus_info) { if (nexus_info->mapped == MagickFalse) (void) RelinquishAlignedMemory(nexus_info->cache); else (void) UnmapBlob(nexus_info->cache,(size_t) nexus_info->length); nexus_info->cache=(Quantum *) NULL; nexus_info->pixels=(Quantum *) NULL; nexus_info->metacontent=(void *) NULL; nexus_info->length=0; nexus_info->mapped=MagickFalse; } MagickPrivate NexusInfo **DestroyPixelCacheNexus(NexusInfo **nexus_info, const size_t number_threads) { ssize_t i; assert(nexus_info != (NexusInfo **) NULL); for (i=0; i < (ssize_t) (2*number_threads); i++) { if (nexus_info[i]->cache != (Quantum *) NULL) RelinquishCacheNexusPixels(nexus_info[i]); nexus_info[i]->signature=(~MagickCoreSignature); } *nexus_info=(NexusInfo *) RelinquishMagickMemory(*nexus_info); nexus_info=(NexusInfo **) RelinquishAlignedMemory(nexus_info); return(nexus_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontent() returns the authentic metacontent corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the associated pixels are not available. % % The format of the GetAuthenticMetacontent() method is: % % void *GetAuthenticMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void *GetAuthenticMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) { void *metacontent; metacontent=cache_info->methods. get_authentic_metacontent_from_handler(image); return(metacontent); } assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticMetacontentFromCache() returns the meta-content corresponding % with the last call to QueueAuthenticPixelsCache() or % GetAuthenticPixelsCache(). % % The format of the GetAuthenticMetacontentFromCache() method is: % % void *GetAuthenticMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void *GetAuthenticMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->metacontent); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticOpenCLBuffer() returns an OpenCL buffer used to execute OpenCL % operations. % % The format of the GetAuthenticOpenCLBuffer() method is: % % cl_mem GetAuthenticOpenCLBuffer(const Image *image, % MagickCLDevice device,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o device: the device to use. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate cl_mem GetAuthenticOpenCLBuffer(const Image *image, MagickCLDevice device,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(device != (const MagickCLDevice) NULL); cache_info=(CacheInfo *) image->cache; if ((cache_info->type == UndefinedCache) || (cache_info->reference_count > 1)) { SyncImagePixelCache((Image *) image,exception); cache_info=(CacheInfo *) image->cache; } if ((cache_info->type != MemoryCache) || (cache_info->mapped != MagickFalse)) return((cl_mem) NULL); LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->opencl != (MagickCLCacheInfo) NULL) && (cache_info->opencl->device->context != device->context)) cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); if (cache_info->opencl == (MagickCLCacheInfo) NULL) { assert(cache_info->pixels != (Quantum *) NULL); cache_info->opencl=AcquireMagickCLCacheInfo(device,cache_info->pixels, cache_info->length); } if (cache_info->opencl != (MagickCLCacheInfo) NULL) RetainOpenCLMemObject(cache_info->opencl->buffer); UnlockSemaphoreInfo(cache_info->semaphore); if (cache_info->opencl == (MagickCLCacheInfo) NULL) return((cl_mem) NULL); assert(cache_info->opencl->pixels == cache_info->pixels); return(cache_info->opencl->buffer); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelCacheNexus() gets authentic pixels from the in-memory or % disk pixel cache as defined by the geometry parameters. A pointer to the % pixels is returned if the pixels are transferred, otherwise a NULL is % returned. % % The format of the GetAuthenticPixelCacheNexus() method is: % % Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to return. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *GetAuthenticPixelCacheNexus(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict pixels; /* Transfer pixels from the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickTrue, nexus_info,exception); if (pixels == (Quantum *) NULL) return((Quantum *) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (nexus_info->authentic_pixel_cache != MagickFalse) return(pixels); if (ReadPixelCachePixels(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); if (cache_info->metacontent_extent != 0) if (ReadPixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse) return((Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsFromCache() returns the pixels associated with the last % call to the QueueAuthenticPixelsCache() or GetAuthenticPixelsCache() methods. % % The format of the GetAuthenticPixelsFromCache() method is: % % Quantum *GetAuthenticPixelsFromCache(const Image image) % % A description of each parameter follows: % % o image: the image. % */ static Quantum *GetAuthenticPixelsFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelQueue() returns the authentic pixels associated % corresponding with the last call to QueueAuthenticPixels() or % GetAuthenticPixels(). % % The format of the GetAuthenticPixelQueue() method is: % % Quantum *GetAuthenticPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport Quantum *GetAuthenticPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) return(cache_info->methods.get_authentic_pixels_from_handler(image)); assert(id < (int) cache_info->number_threads); return(cache_info->nexus_info[id]->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixels() obtains a pixel region for read/write access. If the % region is successfully accessed, a pointer to a Quantum array % representing the region is returned, otherwise NULL is returned. % % The returned pointer may point to a temporary working copy of the pixels % or it may point to the original pixels in memory. Performance is maximized % if the selected region is part of one row, or one or more full rows, since % then there is opportunity to access the pixels in-place (without a copy) % if the image is in memory, or in a memory-mapped file. The returned pointer % must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image has corresponding metacontent,call % GetAuthenticMetacontent() after invoking GetAuthenticPixels() to obtain the % meta-content corresponding to the region. Once the Quantum array has % been updated, the changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the GetAuthenticPixels() method is: % % Quantum *GetAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *GetAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.get_authentic_pixels_handler(image,x,y,columns, rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetAuthenticPixelsCache() gets pixels from the in-memory or disk pixel cache % as defined by the geometry parameters. A pointer to the pixels is returned % if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetAuthenticPixelsCache() method is: % % Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *GetAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=GetAuthenticPixelCacheNexus(image,x,y,columns,rows, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImageExtent() returns the extent of the pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetAuthenticPixels(). % % The format of the GetImageExtent() method is: % % MagickSizeType GetImageExtent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport MagickSizeType GetImageExtent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetPixelCacheNexusExtent(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCache() ensures that there is only a single reference to the % pixel cache to be modified, updating the provided cache pointer to point to % a clone of the original pixel cache if necessary. % % The format of the GetImagePixelCache method is: % % Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o clone: any value other than MagickFalse clones the cache pixels. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType ValidatePixelCacheMorphology( const Image *magick_restrict image) { const CacheInfo *magick_restrict cache_info; const PixelChannelMap *magick_restrict p, *magick_restrict q; /* Does the image match the pixel cache morphology? */ cache_info=(CacheInfo *) image->cache; p=image->channel_map; q=cache_info->channel_map; if ((image->storage_class != cache_info->storage_class) || (image->colorspace != cache_info->colorspace) || (image->alpha_trait != cache_info->alpha_trait) || (image->channels != cache_info->channels) || (image->columns != cache_info->columns) || (image->rows != cache_info->rows) || (image->number_channels != cache_info->number_channels) || (memcmp(p,q,image->number_channels*sizeof(*p)) != 0) || (image->metacontent_extent != cache_info->metacontent_extent) || (cache_info->nexus_info == (NexusInfo **) NULL)) return(MagickFalse); return(MagickTrue); } static Cache GetImagePixelCache(Image *image,const MagickBooleanType clone, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType destroy, status; static MagickSizeType cache_timelimit = MagickResourceInfinity, cpu_throttle = MagickResourceInfinity, cycles = 0; status=MagickTrue; if (cpu_throttle == MagickResourceInfinity) cpu_throttle=GetMagickResourceLimit(ThrottleResource); if ((cpu_throttle != 0) && ((cycles++ % 32) == 0)) MagickDelay(cpu_throttle); if (cache_epoch == 0) { /* Set the expire time in seconds. */ cache_timelimit=GetMagickResourceLimit(TimeResource); cache_epoch=GetMagickTime(); } if ((cache_timelimit != MagickResourceInfinity) && ((MagickSizeType) (GetMagickTime()-cache_epoch) >= cache_timelimit)) { #if defined(ECANCELED) errno=ECANCELED; #endif cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); ThrowFatalException(ResourceLimitFatalError,"TimeLimitExceeded"); } LockSemaphoreInfo(image->semaphore); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif destroy=MagickFalse; if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { LockSemaphoreInfo(cache_info->semaphore); if ((cache_info->reference_count > 1) || (cache_info->mode == ReadMode)) { CacheInfo *clone_info; Image clone_image; /* Clone pixel cache. */ clone_image=(*image); clone_image.semaphore=AcquireSemaphoreInfo(); clone_image.reference_count=1; clone_image.cache=ClonePixelCache(cache_info); clone_info=(CacheInfo *) clone_image.cache; status=OpenPixelCache(&clone_image,IOMode,exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { if (clone != MagickFalse) status=ClonePixelCacheRepository(clone_info,cache_info, exception); if (status == MagickFalse) clone_info=(CacheInfo *) DestroyPixelCache(clone_info); else { destroy=MagickTrue; image->cache=clone_info; } } RelinquishSemaphoreInfo(&clone_image.semaphore); } UnlockSemaphoreInfo(cache_info->semaphore); } if (destroy != MagickFalse) cache_info=(CacheInfo *) DestroyPixelCache(cache_info); if (status != MagickFalse) { /* Ensure the image matches the pixel cache morphology. */ if (image->type != UndefinedType) image->type=UndefinedType; if (ValidatePixelCacheMorphology(image) == MagickFalse) { status=OpenPixelCache(image,IOMode,exception); cache_info=(CacheInfo *) image->cache; if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); } } UnlockSemaphoreInfo(image->semaphore); if (status == MagickFalse) return((Cache) NULL); return(image->cache); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t I m a g e P i x e l C a c h e T y p e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetImagePixelCacheType() returns the pixel cache type: UndefinedCache, % DiskCache, MemoryCache, MapCache, or PingCache. % % The format of the GetImagePixelCacheType() method is: % % CacheType GetImagePixelCacheType(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport CacheType GetImagePixelCacheType(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->type); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e A u t h e n t i c P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixel() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixel() method is: % % MagickBooleanType GetOneAuthenticPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType CopyPixel(const Image *image, const Quantum *source,Quantum *destination) { ssize_t i; if (source == (const Quantum *) NULL) { destination[RedPixelChannel]=ClampToQuantum(image->background_color.red); destination[GreenPixelChannel]=ClampToQuantum( image->background_color.green); destination[BluePixelChannel]=ClampToQuantum( image->background_color.blue); destination[BlackPixelChannel]=ClampToQuantum( image->background_color.black); destination[AlphaPixelChannel]=ClampToQuantum( image->background_color.alpha); return(MagickFalse); } for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); destination[channel]=source[i]; } return(MagickTrue); } MagickExport MagickBooleanType GetOneAuthenticPixel(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict q; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) return(cache_info->methods.get_one_authentic_pixel_from_handler(image,x,y,pixel,exception)); q=GetAuthenticPixelsCache(image,x,y,1UL,1UL,exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e A u t h e n t i c P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneAuthenticPixelFromCache() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. % % The format of the GetOneAuthenticPixelFromCache() method is: % % MagickBooleanType GetOneAuthenticPixelFromCache(const Image image, % const ssize_t x,const ssize_t y,Quantum *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneAuthenticPixelFromCache(Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict q; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); q=GetAuthenticPixelCacheNexus(image,x,y,1UL,1UL,cache_info->nexus_info[id], exception); return(CopyPixel(image,q,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixel() returns a single virtual pixel at the specified % (x,y) location. The image background color is returned if an error occurs. % If you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixel() method is: % % MagickBooleanType GetOneVirtualPixel(const Image image,const ssize_t x, % const ssize_t y,Quantum *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixel(const Image *image, const ssize_t x,const ssize_t y,Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); if (cache_info->methods.get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) return(cache_info->methods.get_one_virtual_pixel_from_handler(image, GetPixelCacheVirtualMethod(image),x,y,pixel,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, 1UL,1UL,cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t O n e V i r t u a l P i x e l F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelFromCache() returns a single virtual pixel at the % specified (x,y) location. The image background color is returned if an % error occurs. % % The format of the GetOneVirtualPixelFromCache() method is: % % MagickBooleanType GetOneVirtualPixelFromCache(const Image image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: These values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType GetOneVirtualPixelFromCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, Quantum *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); (void) memset(pixel,0,MaxPixelChannels*sizeof(*pixel)); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); return(CopyPixel(image,p,pixel)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t O n e V i r t u a l P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetOneVirtualPixelInfo() returns a single pixel at the specified (x,y) % location. The image background color is returned if an error occurs. If % you plan to modify the pixel, use GetOneAuthenticPixel() instead. % % The format of the GetOneVirtualPixelInfo() method is: % % MagickBooleanType GetOneVirtualPixelInfo(const Image image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,PixelInfo *pixel,ExceptionInfo exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y: these values define the location of the pixel to return. % % o pixel: return a pixel at the specified (x,y) location. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType GetOneVirtualPixelInfo(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, PixelInfo *pixel,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); GetPixelInfo(image,pixel); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,1UL,1UL, cache_info->nexus_info[id],exception); if (p == (const Quantum *) NULL) return(MagickFalse); GetPixelInfoPixel(image,p,pixel); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e C o l o r s p a c e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheColorspace() returns the colorspace of the pixel cache. % % The format of the GetPixelCacheColorspace() method is: % % Colorspace GetPixelCacheColorspace(const Cache cache) % % A description of each parameter follows: % % o cache: the pixel cache. % */ MagickPrivate ColorspaceType GetPixelCacheColorspace(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->colorspace); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e F i l e n a m e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheFilename() returns the filename associated with the pixel % cache. % % The format of the GetPixelCacheFilename() method is: % % const char *GetPixelCacheFilename(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const char *GetPixelCacheFilename(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->cache_filename); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheMethods() initializes the CacheMethods structure. % % The format of the GetPixelCacheMethods() method is: % % void GetPixelCacheMethods(CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void GetPixelCacheMethods(CacheMethods *cache_methods) { assert(cache_methods != (CacheMethods *) NULL); (void) memset(cache_methods,0,sizeof(*cache_methods)); cache_methods->get_virtual_pixel_handler=GetVirtualPixelCache; cache_methods->get_virtual_pixels_handler=GetVirtualPixelsCache; cache_methods->get_virtual_metacontent_from_handler= GetVirtualMetacontentFromCache; cache_methods->get_one_virtual_pixel_from_handler=GetOneVirtualPixelFromCache; cache_methods->get_authentic_pixels_handler=GetAuthenticPixelsCache; cache_methods->get_authentic_metacontent_from_handler= GetAuthenticMetacontentFromCache; cache_methods->get_authentic_pixels_from_handler=GetAuthenticPixelsFromCache; cache_methods->get_one_authentic_pixel_from_handler= GetOneAuthenticPixelFromCache; cache_methods->queue_authentic_pixels_handler=QueueAuthenticPixelsCache; cache_methods->sync_authentic_pixels_handler=SyncAuthenticPixelsCache; cache_methods->destroy_pixel_handler=DestroyImagePixelCache; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e N e x u s E x t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheNexusExtent() returns the extent of the pixels associated % corresponding with the last call to SetPixelCacheNexusPixels() or % GetPixelCacheNexusPixels(). % % The format of the GetPixelCacheNexusExtent() method is: % % MagickSizeType GetPixelCacheNexusExtent(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o nexus_info: the nexus info. % */ MagickPrivate MagickSizeType GetPixelCacheNexusExtent(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; MagickSizeType extent; assert(cache != NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); extent=(MagickSizeType) nexus_info->region.width*nexus_info->region.height; if (extent == 0) return((MagickSizeType) cache_info->columns*cache_info->rows); return(extent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCachePixels() returns the pixels associated with the specified image. % % The format of the GetPixelCachePixels() method is: % % void *GetPixelCachePixels(Image *image,MagickSizeType *length, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o length: the pixel cache length. % % o exception: return any errors or warnings in this structure. % */ MagickExport void *GetPixelCachePixels(Image *image,MagickSizeType *length, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); assert(length != (MagickSizeType *) NULL); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *length=cache_info->length; if ((cache_info->type != MemoryCache) && (cache_info->type != MapCache)) return((void *) NULL); return((void *) cache_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e S t o r a g e C l a s s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheStorageClass() returns the class type of the pixel cache. % % The format of the GetPixelCacheStorageClass() method is: % % ClassType GetPixelCacheStorageClass(Cache cache) % % A description of each parameter follows: % % o type: GetPixelCacheStorageClass returns DirectClass or PseudoClass. % % o cache: the pixel cache. % */ MagickPrivate ClassType GetPixelCacheStorageClass(const Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); return(cache_info->storage_class); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e T i l e S i z e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheTileSize() returns the pixel cache tile size. % % The format of the GetPixelCacheTileSize() method is: % % void GetPixelCacheTileSize(const Image *image,size_t *width, % size_t *height) % % A description of each parameter follows: % % o image: the image. % % o width: the optimized cache tile width in pixels. % % o height: the optimized cache tile height in pixels. % */ MagickPrivate void GetPixelCacheTileSize(const Image *image,size_t *width, size_t *height) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); *width=2048UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); if (GetImagePixelCacheType(image) == DiskCache) *width=8192UL/(MagickMax(cache_info->number_channels,1)*sizeof(Quantum)); *height=(*width); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelCacheVirtualMethod() gets the "virtual pixels" method for the % pixel cache. A virtual pixel is any pixel access that is outside the % boundaries of the image cache. % % The format of the GetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate VirtualPixelMethod GetPixelCacheVirtualMethod(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); return(cache_info->virtual_pixel_method); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromCache() returns the meta-content corresponding with % the last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualMetacontentFromCache() method is: % % void *GetVirtualMetacontentFromCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const void *GetVirtualMetacontentFromCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l M e t a c o n t e n t F r o m N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontentFromNexus() returns the meta-content for the specified % cache nexus. % % The format of the GetVirtualMetacontentFromNexus() method is: % % const void *GetVirtualMetacontentFromNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the meta-content. % */ MagickPrivate const void *GetVirtualMetacontentFromNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((void *) NULL); return(nexus_info->metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualMetacontent() returns the virtual metacontent corresponding with % the last call to QueueAuthenticPixels() or GetVirtualPixels(). NULL is % returned if the meta-content are not available. % % The format of the GetVirtualMetacontent() method is: % % const void *GetVirtualMetacontent(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const void *GetVirtualMetacontent(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const void *magick_restrict metacontent; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); metacontent=cache_info->methods.get_virtual_metacontent_from_handler(image); if (metacontent != (void *) NULL) return(metacontent); assert(id < (int) cache_info->number_threads); metacontent=GetVirtualMetacontentFromNexus(cache_info, cache_info->nexus_info[id]); return(metacontent); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCacheNexus() gets virtual pixels from the in-memory or disk % pixel cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCacheNexus() method is: % % Quantum *GetVirtualPixelCacheNexus(const Image *image, % const VirtualPixelMethod method,const ssize_t x,const ssize_t y, % const size_t columns,const size_t rows,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to acquire. % % o exception: return any errors or warnings in this structure. % */ static ssize_t DitherMatrix[64] = { 0, 48, 12, 60, 3, 51, 15, 63, 32, 16, 44, 28, 35, 19, 47, 31, 8, 56, 4, 52, 11, 59, 7, 55, 40, 24, 36, 20, 43, 27, 39, 23, 2, 50, 14, 62, 1, 49, 13, 61, 34, 18, 46, 30, 33, 17, 45, 29, 10, 58, 6, 54, 9, 57, 5, 53, 42, 26, 38, 22, 41, 25, 37, 21 }; static inline ssize_t DitherX(const ssize_t x,const size_t columns) { ssize_t index; index=x+DitherMatrix[x & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) columns) return((ssize_t) columns-1L); return(index); } static inline ssize_t DitherY(const ssize_t y,const size_t rows) { ssize_t index; index=y+DitherMatrix[y & 0x07]-32L; if (index < 0L) return(0L); if (index >= (ssize_t) rows) return((ssize_t) rows-1L); return(index); } static inline ssize_t EdgeX(const ssize_t x,const size_t columns) { if (x < 0L) return(0L); if (x >= (ssize_t) columns) return((ssize_t) (columns-1)); return(x); } static inline ssize_t EdgeY(const ssize_t y,const size_t rows) { if (y < 0L) return(0L); if (y >= (ssize_t) rows) return((ssize_t) (rows-1)); return(y); } static inline ssize_t RandomX(RandomInfo *random_info,const size_t columns) { return((ssize_t) (columns*GetPseudoRandomValue(random_info))); } static inline ssize_t RandomY(RandomInfo *random_info,const size_t rows) { return((ssize_t) (rows*GetPseudoRandomValue(random_info))); } static inline MagickModulo VirtualPixelModulo(const ssize_t offset, const size_t extent) { MagickModulo modulo; modulo.quotient=offset; if (extent != 0) modulo.quotient=offset/((ssize_t) extent); modulo.remainder=offset % ((ssize_t) extent); if ((modulo.remainder != 0) && ((offset ^ ((ssize_t) extent)) < 0)) { modulo.quotient-=1; modulo.remainder+=((ssize_t) extent); } return(modulo); } MagickPrivate const Quantum *GetVirtualPixelCacheNexus(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType length, number_pixels; NexusInfo *magick_restrict virtual_nexus; Quantum *magick_restrict pixels, virtual_pixel[MaxPixelChannels]; const Quantum *magick_restrict p; const void *magick_restrict r; Quantum *magick_restrict q; ssize_t i, u; unsigned char *magick_restrict s; ssize_t v; void *magick_restrict virtual_metacontent; /* Acquire pixels. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((const Quantum *) NULL); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif pixels=SetPixelCacheNexusPixels(cache_info,ReadMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); if (pixels == (Quantum *) NULL) return((const Quantum *) NULL); q=pixels; offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) (nexus_info->region.height-1L)*cache_info->columns+ nexus_info->region.width-1L; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; if ((offset >= 0) && (((MagickSizeType) offset+length) < number_pixels)) if ((x >= 0) && ((ssize_t) (x+columns-1) < (ssize_t) cache_info->columns) && (y >= 0) && ((ssize_t) (y+rows-1) < (ssize_t) cache_info->rows)) { MagickBooleanType status; /* Pixel request is inside cache extents. */ if (nexus_info->authentic_pixel_cache != MagickFalse) return(q); status=ReadPixelCachePixels(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); if (cache_info->metacontent_extent != 0) { status=ReadPixelCacheMetacontent(cache_info,nexus_info,exception); if (status == MagickFalse) return((const Quantum *) NULL); } return(q); } /* Pixel request is outside cache extents. */ virtual_nexus=nexus_info->virtual_nexus; s=(unsigned char *) nexus_info->metacontent; (void) memset(virtual_pixel,0,cache_info->number_channels* sizeof(*virtual_pixel)); virtual_metacontent=(void *) NULL; switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: case EdgeVirtualPixelMethod: case CheckerTileVirtualPixelMethod: case HorizontalTileVirtualPixelMethod: case VerticalTileVirtualPixelMethod: { if (cache_info->metacontent_extent != 0) { /* Acquire a metacontent buffer. */ virtual_metacontent=(void *) AcquireQuantumMemory(1, cache_info->metacontent_extent); if (virtual_metacontent == (void *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), CacheError,"UnableToGetCacheNexus","`%s'",image->filename); return((const Quantum *) NULL); } (void) memset(virtual_metacontent,0,cache_info->metacontent_extent); } switch (virtual_pixel_method) { case BlackVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case GrayVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange/2, virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } case TransparentVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,(Quantum) 0,virtual_pixel); SetPixelAlpha(image,TransparentAlpha,virtual_pixel); break; } case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { for (i=0; i < (ssize_t) cache_info->number_channels; i++) SetPixelChannel(image,(PixelChannel) i,QuantumRange,virtual_pixel); SetPixelAlpha(image,OpaqueAlpha,virtual_pixel); break; } default: { SetPixelRed(image,ClampToQuantum(image->background_color.red), virtual_pixel); SetPixelGreen(image,ClampToQuantum(image->background_color.green), virtual_pixel); SetPixelBlue(image,ClampToQuantum(image->background_color.blue), virtual_pixel); SetPixelBlack(image,ClampToQuantum(image->background_color.black), virtual_pixel); SetPixelAlpha(image,ClampToQuantum(image->background_color.alpha), virtual_pixel); break; } } break; } default: break; } for (v=0; v < (ssize_t) rows; v++) { ssize_t y_offset; y_offset=y+v; if ((virtual_pixel_method == EdgeVirtualPixelMethod) || (virtual_pixel_method == UndefinedVirtualPixelMethod)) y_offset=EdgeY(y_offset,cache_info->rows); for (u=0; u < (ssize_t) columns; u+=length) { ssize_t x_offset; x_offset=x+u; length=(MagickSizeType) MagickMin(cache_info->columns-x_offset,columns-u); if (((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) || ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) || (length == 0)) { MagickModulo x_modulo, y_modulo; /* Transfer a single pixel. */ length=(MagickSizeType) 1; switch (virtual_pixel_method) { case EdgeVirtualPixelMethod: default: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns), EdgeY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info, nexus_info->virtual_nexus); break; } case RandomVirtualPixelMethod: { if (cache_info->random_info == (RandomInfo *) NULL) cache_info->random_info=AcquireRandomInfo(); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, RandomX(cache_info->random_info,cache_info->columns), RandomY(cache_info->random_info,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case DitherVirtualPixelMethod: { p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, DitherX(x_offset,cache_info->columns), DitherY(y_offset,cache_info->rows),1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case TileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case MirrorVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); if ((x_modulo.quotient & 0x01) == 1L) x_modulo.remainder=(ssize_t) cache_info->columns- x_modulo.remainder-1L; y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if ((y_modulo.quotient & 0x01) == 1L) y_modulo.remainder=(ssize_t) cache_info->rows- y_modulo.remainder-1L; p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileEdgeVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,EdgeY(y_offset,cache_info->rows),1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileEdgeVirtualPixelMethod: { y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, EdgeX(x_offset,cache_info->columns),y_modulo.remainder,1UL,1UL, virtual_nexus,exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case BackgroundVirtualPixelMethod: case BlackVirtualPixelMethod: case GrayVirtualPixelMethod: case TransparentVirtualPixelMethod: case MaskVirtualPixelMethod: case WhiteVirtualPixelMethod: { p=virtual_pixel; r=virtual_metacontent; break; } case CheckerTileVirtualPixelMethod: { x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); if (((x_modulo.quotient ^ y_modulo.quotient) & 0x01) != 0L) { p=virtual_pixel; r=virtual_metacontent; break; } p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case HorizontalTileVirtualPixelMethod: { if ((y_offset < 0) || (y_offset >= (ssize_t) cache_info->rows)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } case VerticalTileVirtualPixelMethod: { if ((x_offset < 0) || (x_offset >= (ssize_t) cache_info->columns)) { p=virtual_pixel; r=virtual_metacontent; break; } x_modulo=VirtualPixelModulo(x_offset,cache_info->columns); y_modulo=VirtualPixelModulo(y_offset,cache_info->rows); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method, x_modulo.remainder,y_modulo.remainder,1UL,1UL,virtual_nexus, exception); r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); break; } } if (p == (const Quantum *) NULL) break; (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels; if ((s != (void *) NULL) && (r != (const void *) NULL)) { (void) memcpy(s,r,(size_t) cache_info->metacontent_extent); s+=cache_info->metacontent_extent; } continue; } /* Transfer a run of pixels. */ p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x_offset,y_offset, (size_t) length,1UL,virtual_nexus,exception); if (p == (const Quantum *) NULL) break; r=GetVirtualMetacontentFromNexus(cache_info,virtual_nexus); (void) memcpy(q,p,(size_t) (cache_info->number_channels*length* sizeof(*p))); q+=cache_info->number_channels*length; if ((r != (void *) NULL) && (s != (const void *) NULL)) { (void) memcpy(s,r,(size_t) length); s+=length*cache_info->metacontent_extent; } } if (u < (ssize_t) columns) break; } /* Free resources. */ if (virtual_metacontent != (void *) NULL) virtual_metacontent=(void *) RelinquishMagickMemory(virtual_metacontent); if (v < (ssize_t) rows) return((const Quantum *) NULL); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelCache() get virtual pixels from the in-memory or disk pixel % cache as defined by the geometry parameters. A pointer to the pixels % is returned if the pixels are transferred, otherwise a NULL is returned. % % The format of the GetVirtualPixelCache() method is: % % const Quantum *GetVirtualPixelCache(const Image *image, % const VirtualPixelMethod virtual_pixel_method,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: the virtual pixel method. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static const Quantum *GetVirtualPixelCache(const Image *image, const VirtualPixelMethod virtual_pixel_method,const ssize_t x,const ssize_t y, const size_t columns,const size_t rows,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,virtual_pixel_method,x,y,columns,rows, cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l Q u e u e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelQueue() returns the virtual pixels associated corresponding % with the last call to QueueAuthenticPixels() or GetVirtualPixels(). % % The format of the GetVirtualPixelQueue() method is: % % const Quantum *GetVirtualPixelQueue(const Image image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport const Quantum *GetVirtualPixelQueue(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixels_handler != (GetVirtualPixelsHandler) NULL) return(cache_info->methods.get_virtual_pixels_handler(image)); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(cache_info,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t V i r t u a l P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixels() returns an immutable pixel region. If the % region is successfully accessed, a pointer to it is returned, otherwise % NULL is returned. The returned pointer may point to a temporary working % copy of the pixels or it may point to the original pixels in memory. % Performance is maximized if the selected region is part of one row, or one % or more full rows, since there is opportunity to access the pixels in-place % (without a copy) if the image is in memory, or in a memory-mapped file. The % returned pointer must *never* be deallocated by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % access the meta-content (of type void) corresponding to the % region. % % If you plan to modify the pixels, use GetAuthenticPixels() instead. % % Note, the GetVirtualPixels() and GetAuthenticPixels() methods are not thread- % safe. In a threaded environment, use GetCacheViewVirtualPixels() or % GetCacheViewAuthenticPixels() instead. % % The format of the GetVirtualPixels() method is: % % const Quantum *GetVirtualPixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport const Quantum *GetVirtualPixels(const Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); const Quantum *magick_restrict p; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) return(cache_info->methods.get_virtual_pixel_handler(image, GetPixelCacheVirtualMethod(image),x,y,columns,rows,exception)); assert(id < (int) cache_info->number_threads); p=GetVirtualPixelCacheNexus(image,GetPixelCacheVirtualMethod(image),x,y, columns,rows,cache_info->nexus_info[id],exception); return(p); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s F r o m C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsCache() returns the pixels associated corresponding with the % last call to QueueAuthenticPixelsCache() or GetVirtualPixelCache(). % % The format of the GetVirtualPixelsCache() method is: % % Quantum *GetVirtualPixelsCache(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static const Quantum *GetVirtualPixelsCache(const Image *image) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); return(GetVirtualPixelsNexus(image->cache,cache_info->nexus_info[id])); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + G e t V i r t u a l P i x e l s N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetVirtualPixelsNexus() returns the pixels associated with the specified % cache nexus. % % The format of the GetVirtualPixelsNexus() method is: % % const Quantum *GetVirtualPixelsNexus(const Cache cache, % NexusInfo *nexus_info) % % A description of each parameter follows: % % o cache: the pixel cache. % % o nexus_info: the cache nexus to return the colormap pixels. % */ MagickPrivate const Quantum *GetVirtualPixelsNexus(const Cache cache, NexusInfo *magick_restrict nexus_info) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->storage_class == UndefinedClass) return((Quantum *) NULL); return((const Quantum *) nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + M a s k P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % MaskPixelCacheNexus() masks the cache nexus as defined by the composite mask. % The method returns MagickTrue if the pixel region is masked, otherwise % MagickFalse. % % The format of the MaskPixelCacheNexus() method is: % % MagickBooleanType MaskPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to clip. % % o exception: return any errors or warnings in this structure. % */ static inline Quantum ApplyPixelCompositeMask(const Quantum p, const MagickRealType alpha,const Quantum q,const MagickRealType beta) { double gamma; if (fabs((double) (alpha-TransparentAlpha)) < MagickEpsilon) return(q); gamma=1.0-QuantumScale*QuantumScale*alpha*beta; gamma=PerceptibleReciprocal(gamma); return(ClampToQuantum(gamma*MagickOver_((double) p,alpha,(double) q,beta))); } static MagickBooleanType MaskPixelCacheNexus(Image *image,NexusInfo *nexus_info, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; Quantum *magick_restrict p, *magick_restrict q; ssize_t y; /* Apply composite mask. */ if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if ((image->channels & CompositeMaskChannel) == 0) return(MagickTrue); if ((nexus_info->region.width == 0) || (nexus_info->region.height == 0)) return(MagickTrue); cache_info=(CacheInfo *) image->cache; if (cache_info == (Cache) NULL) return(MagickFalse); p=GetAuthenticPixelCacheNexus(image,nexus_info->region.x,nexus_info->region.y, nexus_info->region.width,nexus_info->region.height, nexus_info->virtual_nexus,exception); q=nexus_info->pixels; if ((p == (Quantum *) NULL) || (q == (Quantum *) NULL)) return(MagickFalse); for (y=0; y < (ssize_t) nexus_info->region.height; y++) { ssize_t x; for (x=0; x < (ssize_t) nexus_info->region.width; x++) { double alpha; ssize_t i; alpha=(double) GetPixelCompositeMask(image,p); for (i=0; i < (ssize_t) image->number_channels; i++) { PixelChannel channel = GetPixelChannelChannel(image,i); PixelTrait traits = GetPixelChannelTraits(image,channel); if ((traits & UpdatePixelTrait) == 0) continue; q[i]=ApplyPixelCompositeMask(q[i],alpha,p[i],GetPixelAlpha(image,p)); } p+=GetPixelChannels(image); q+=GetPixelChannels(image); } } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + O p e n P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % OpenPixelCache() allocates the pixel cache. This includes defining the cache % dimensions, allocating space for the image pixels and optionally the % metacontent, and memory mapping the cache if it is disk based. The cache % nexus array is initialized as well. % % The format of the OpenPixelCache() method is: % % MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o mode: ReadMode, WriteMode, or IOMode. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType OpenPixelCacheOnDisk(CacheInfo *cache_info, const MapMode mode) { int file; /* Open pixel cache on disk. */ if ((cache_info->file != -1) && (cache_info->disk_mode == mode)) return(MagickTrue); /* cache already open and in the proper mode */ if (*cache_info->cache_filename == '\0') file=AcquireUniqueFileResource(cache_info->cache_filename); else switch (mode) { case ReadMode: { file=open_utf8(cache_info->cache_filename,O_RDONLY | O_BINARY,0); break; } case WriteMode: { file=open_utf8(cache_info->cache_filename,O_WRONLY | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_WRONLY | O_BINARY,S_MODE); break; } case IOMode: default: { file=open_utf8(cache_info->cache_filename,O_RDWR | O_CREAT | O_BINARY | O_EXCL,S_MODE); if (file == -1) file=open_utf8(cache_info->cache_filename,O_RDWR | O_BINARY,S_MODE); break; } } if (file == -1) return(MagickFalse); (void) AcquireMagickResource(FileResource,1); if (cache_info->file != -1) (void) ClosePixelCacheOnDisk(cache_info); cache_info->file=file; cache_info->disk_mode=mode; return(MagickTrue); } static inline MagickOffsetType WritePixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,const unsigned char *magick_restrict buffer) { MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PWRITE) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PWRITE) count=write(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) MAGICK_SSIZE_MAX)); #else count=pwrite(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) MAGICK_SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType SetPixelCacheExtent(Image *image,MagickSizeType length) { CacheInfo *magick_restrict cache_info; MagickOffsetType count, extent, offset; cache_info=(CacheInfo *) image->cache; if (image->debug != MagickFalse) { char format[MagickPathExtent], message[MagickPathExtent]; (void) FormatMagickSize(length,MagickFalse,"B",MagickPathExtent,format); (void) FormatLocaleString(message,MagickPathExtent, "extend %s (%s[%d], disk, %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (length != (MagickSizeType) ((MagickOffsetType) length)) return(MagickFalse); offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_END); if (offset < 0) return(MagickFalse); if ((MagickSizeType) offset >= length) count=(MagickOffsetType) 1; else { extent=(MagickOffsetType) length-1; count=WritePixelCacheRegion(cache_info,extent,1,(const unsigned char *) ""); if (count != 1) return(MagickFalse); #if defined(MAGICKCORE_HAVE_POSIX_FALLOCATE) if (cache_info->synchronize != MagickFalse) if (posix_fallocate(cache_info->file,offset+1,extent-offset) != 0) return(MagickFalse); #endif } offset=(MagickOffsetType) lseek(cache_info->file,0,SEEK_SET); if (offset < 0) return(MagickFalse); return(MagickTrue); } static MagickBooleanType OpenPixelCache(Image *image,const MapMode mode, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, source_info; char format[MagickPathExtent], message[MagickPathExtent]; const char *hosts, *type; MagickBooleanType status; MagickSizeType length, number_pixels; size_t columns, packet_size; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (cache_anonymous_memory < 0) { char *value; /* Does the security policy require anonymous mapping for pixel cache? */ cache_anonymous_memory=0; value=GetPolicyValue("pixel-cache-memory"); if (value == (char *) NULL) value=GetPolicyValue("cache:memory-map"); if (LocaleCompare(value,"anonymous") == 0) { #if defined(MAGICKCORE_HAVE_MMAP) && defined(MAP_ANONYMOUS) cache_anonymous_memory=1; #else (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateError,"DelegateLibrarySupportNotBuiltIn", "'%s' (policy requires anonymous memory mapping)",image->filename); #endif } value=DestroyString(value); } if ((image->columns == 0) || (image->rows == 0)) ThrowBinaryException(CacheError,"NoPixelsDefinedInCache",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (((MagickSizeType) image->columns > cache_info->width_limit) || ((MagickSizeType) image->rows > cache_info->height_limit)) ThrowBinaryException(ImageError,"WidthOrHeightExceedsLimit", image->filename); if (GetMagickResourceLimit(ListLengthResource) != MagickResourceInfinity) { length=GetImageListLength(image); if (AcquireMagickResource(ListLengthResource,length) == MagickFalse) ThrowBinaryException(ResourceLimitError,"ListLengthExceedsLimit", image->filename); } source_info=(*cache_info); source_info.file=(-1); (void) FormatLocaleString(cache_info->filename,MagickPathExtent,"%s[%.20g]", image->filename,(double) image->scene); cache_info->storage_class=image->storage_class; cache_info->colorspace=image->colorspace; cache_info->alpha_trait=image->alpha_trait; cache_info->channels=image->channels; cache_info->rows=image->rows; cache_info->columns=image->columns; InitializePixelChannelMap(image); cache_info->number_channels=GetPixelChannels(image); (void) memcpy(cache_info->channel_map,image->channel_map,MaxPixelChannels* sizeof(*image->channel_map)); cache_info->metacontent_extent=image->metacontent_extent; cache_info->mode=mode; number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; packet_size=MagickMax(cache_info->number_channels,1)*sizeof(Quantum); if (image->metacontent_extent != 0) packet_size+=cache_info->metacontent_extent; length=number_pixels*packet_size; columns=(size_t) (length/cache_info->rows/packet_size); if ((cache_info->columns != columns) || ((ssize_t) cache_info->columns < 0) || ((ssize_t) cache_info->rows < 0)) ThrowBinaryException(ResourceLimitError,"PixelCacheAllocationFailed", image->filename); cache_info->length=length; if (image->ping != MagickFalse) { cache_info->type=PingCache; return(MagickTrue); } status=AcquireMagickResource(AreaResource,(MagickSizeType) cache_info->columns*cache_info->rows); if (cache_info->mode == PersistMode) status=MagickFalse; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if ((status != MagickFalse) && (length == (MagickSizeType) ((size_t) length)) && ((cache_info->type == UndefinedCache) || (cache_info->type == MemoryCache))) { status=AcquireMagickResource(MemoryResource,cache_info->length); if (status != MagickFalse) { status=MagickTrue; if (cache_anonymous_memory <= 0) { cache_info->mapped=MagickFalse; cache_info->pixels=(Quantum *) MagickAssumeAligned( AcquireAlignedMemory(1,(size_t) cache_info->length)); } else { cache_info->mapped=MagickTrue; cache_info->pixels=(Quantum *) MapBlob(-1,IOMode,0,(size_t) cache_info->length); } if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; } else { /* Create memory pixel cache. */ cache_info->type=MemoryCache; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->mapped != MagickFalse ? "Anonymous" : "Heap",type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } cache_info->storage_class=image->storage_class; if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=AcquireMagickResource(DiskResource,cache_info->length); hosts=(const char *) GetImageRegistry(StringRegistryType,"cache:hosts", exception); if ((status == MagickFalse) && (hosts != (const char *) NULL)) { DistributeCacheInfo *server_info; /* Distribute the pixel cache to a remote server. */ server_info=AcquireDistributeCacheInfo(exception); if (server_info != (DistributeCacheInfo *) NULL) { status=OpenDistributePixelCache(server_info,image); if (status == MagickFalse) { ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", GetDistributeCacheHostname(server_info)); server_info=DestroyDistributeCacheInfo(server_info); } else { /* Create a distributed pixel cache. */ status=MagickTrue; cache_info->type=DistributedCache; cache_info->server_info=server_info; (void) FormatLocaleString(cache_info->cache_filename, MagickPathExtent,"%s:%d",GetDistributeCacheHostname( (DistributeCacheInfo *) cache_info->server_info), GetDistributeCachePort((DistributeCacheInfo *) cache_info->server_info)); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, GetDistributeCacheFile((DistributeCacheInfo *) cache_info->server_info),type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } /* Create pixel cache on disk. */ if (status == MagickFalse) { cache_info->type=UndefinedCache; (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode) && (cache_info->mode != PersistMode)) { (void) ClosePixelCacheOnDisk(cache_info); *cache_info->cache_filename='\0'; } if (OpenPixelCacheOnDisk(cache_info,mode) == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToOpenPixelCache", image->filename); return(MagickFalse); } status=SetPixelCacheExtent(image,(MagickSizeType) cache_info->offset+ cache_info->length); if (status == MagickFalse) { cache_info->type=UndefinedCache; ThrowFileException(exception,CacheError,"UnableToExtendCache", image->filename); return(MagickFalse); } cache_info->type=DiskCache; length=number_pixels*(cache_info->number_channels*sizeof(Quantum)+ cache_info->metacontent_extent); if (length == (MagickSizeType) ((size_t) length)) { status=AcquireMagickResource(MapResource,cache_info->length); if (status != MagickFalse) { cache_info->pixels=(Quantum *) MapBlob(cache_info->file,mode, cache_info->offset,(size_t) cache_info->length); if (cache_info->pixels == (Quantum *) NULL) { cache_info->mapped=source_info.mapped; cache_info->pixels=source_info.pixels; RelinquishMagickResource(MapResource,cache_info->length); } else { /* Create file-backed memory-mapped pixel cache. */ (void) ClosePixelCacheOnDisk(cache_info); cache_info->type=MapCache; cache_info->mapped=MagickTrue; cache_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) cache_info->metacontent=(void *) (cache_info->pixels+ cache_info->number_channels*number_pixels); if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info, exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickTrue,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)", cache_info->filename,cache_info->cache_filename, cache_info->file,type,(double) cache_info->columns, (double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s", message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } } } status=MagickTrue; if ((source_info.storage_class != UndefinedClass) && (mode != ReadMode)) { status=ClonePixelCacheRepository(cache_info,&source_info,exception); RelinquishPixelCachePixels(&source_info); } if (image->debug != MagickFalse) { (void) FormatMagickSize(cache_info->length,MagickFalse,"B", MagickPathExtent,format); type=CommandOptionToMnemonic(MagickCacheOptions,(ssize_t) cache_info->type); (void) FormatLocaleString(message,MagickPathExtent, "open %s (%s[%d], %s, %.20gx%.20gx%.20g %s)",cache_info->filename, cache_info->cache_filename,cache_info->file,type,(double) cache_info->columns,(double) cache_info->rows,(double) cache_info->number_channels,format); (void) LogMagickEvent(CacheEvent,GetMagickModule(),"%s",message); } if (status == 0) { cache_info->type=UndefinedCache; return(MagickFalse); } return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + P e r s i s t P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % PersistPixelCache() attaches to or initializes a persistent pixel cache. A % persistent pixel cache is one that resides on disk and is not destroyed % when the program exits. % % The format of the PersistPixelCache() method is: % % MagickBooleanType PersistPixelCache(Image *image,const char *filename, % const MagickBooleanType attach,MagickOffsetType *offset, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o filename: the persistent pixel cache filename. % % o attach: A value other than zero initializes the persistent pixel cache. % % o initialize: A value other than zero initializes the persistent pixel % cache. % % o offset: the offset in the persistent cache to store pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType PersistPixelCache(Image *image, const char *filename,const MagickBooleanType attach,MagickOffsetType *offset, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info, *magick_restrict clone_info; MagickBooleanType status; ssize_t page_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (void *) NULL); assert(filename != (const char *) NULL); assert(offset != (MagickOffsetType *) NULL); page_size=GetMagickPageSize(); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); #if defined(MAGICKCORE_OPENCL_SUPPORT) CopyOpenCLBuffer(cache_info); #endif if (attach != MagickFalse) { /* Attach existing persistent pixel cache. */ if (image->debug != MagickFalse) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "attach persistent cache"); (void) CopyMagickString(cache_info->cache_filename,filename, MagickPathExtent); cache_info->type=MapCache; cache_info->offset=(*offset); if (OpenPixelCache(image,ReadMode,exception) == MagickFalse) return(MagickFalse); *offset+=cache_info->length+page_size-(cache_info->length % page_size); return(MagickTrue); } /* Clone persistent pixel cache. */ status=AcquireMagickResource(DiskResource,cache_info->length); if (status == MagickFalse) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "CacheResourcesExhausted","`%s'",image->filename); return(MagickFalse); } clone_info=(CacheInfo *) ClonePixelCache(cache_info); clone_info->type=DiskCache; (void) CopyMagickString(clone_info->cache_filename,filename,MagickPathExtent); clone_info->file=(-1); clone_info->storage_class=cache_info->storage_class; clone_info->colorspace=cache_info->colorspace; clone_info->alpha_trait=cache_info->alpha_trait; clone_info->channels=cache_info->channels; clone_info->columns=cache_info->columns; clone_info->rows=cache_info->rows; clone_info->number_channels=cache_info->number_channels; clone_info->metacontent_extent=cache_info->metacontent_extent; clone_info->mode=PersistMode; clone_info->length=cache_info->length; (void) memcpy(clone_info->channel_map,cache_info->channel_map, MaxPixelChannels*sizeof(*cache_info->channel_map)); clone_info->offset=(*offset); status=ClonePixelCacheRepository(clone_info,cache_info,exception); *offset+=cache_info->length+page_size-(cache_info->length % page_size); clone_info=(CacheInfo *) DestroyPixelCache(clone_info); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelCacheNexus() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelCacheNexus() method is: % % Quantum *QueueAuthenticPixelCacheNexus(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % const MagickBooleanType clone,NexusInfo *nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o nexus_info: the cache nexus to set. % % o clone: clone the pixel cache. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate Quantum *QueueAuthenticPixelCacheNexus(Image *image, const ssize_t x,const ssize_t y,const size_t columns,const size_t rows, const MagickBooleanType clone,NexusInfo *nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickOffsetType offset; MagickSizeType number_pixels; Quantum *magick_restrict pixels; /* Validate pixel cache geometry. */ assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,clone,exception); if (cache_info == (Cache) NULL) return((Quantum *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->columns == 0) || (cache_info->rows == 0) || (x < 0) || (y < 0) || (x >= (ssize_t) cache_info->columns) || (y >= (ssize_t) cache_info->rows)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "PixelsAreNotAuthentic","`%s'",image->filename); return((Quantum *) NULL); } offset=(MagickOffsetType) y*cache_info->columns+x; if (offset < 0) return((Quantum *) NULL); number_pixels=(MagickSizeType) cache_info->columns*cache_info->rows; offset+=(MagickOffsetType) (rows-1)*cache_info->columns+columns-1; if ((MagickSizeType) offset >= number_pixels) return((Quantum *) NULL); /* Return pixel cache. */ pixels=SetPixelCacheNexusPixels(cache_info,WriteMode,x,y,columns,rows, ((image->channels & WriteMaskChannel) != 0) || ((image->channels & CompositeMaskChannel) != 0) ? MagickTrue : MagickFalse, nexus_info,exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + Q u e u e A u t h e n t i c P i x e l s C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixelsCache() allocates an region to store image pixels as % defined by the region rectangle and returns a pointer to the region. This % region is subsequently transferred from the pixel cache with % SyncAuthenticPixelsCache(). A pointer to the pixels is returned if the % pixels are transferred, otherwise a NULL is returned. % % The format of the QueueAuthenticPixelsCache() method is: % % Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ static Quantum *QueueAuthenticPixelsCache(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % Q u e u e A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % QueueAuthenticPixels() queues a mutable pixel region. If the region is % successfully initialized a pointer to a Quantum array representing the % region is returned, otherwise NULL is returned. The returned pointer may % point to a temporary working buffer for the pixels or it may point to the % final location of the pixels in memory. % % Write-only access means that any existing pixel values corresponding to % the region are ignored. This is useful if the initial image is being % created from scratch, or if the existing pixel values are to be % completely replaced without need to refer to their pre-existing values. % The application is free to read and write the pixel buffer returned by % QueueAuthenticPixels() any way it pleases. QueueAuthenticPixels() does not % initialize the pixel array values. Initializing pixel array values is the % application's responsibility. % % Performance is maximized if the selected region is part of one row, or % one or more full rows, since then there is opportunity to access the % pixels in-place (without a copy) if the image is in memory, or in a % memory-mapped file. The returned pointer must *never* be deallocated % by the user. % % Pixels accessed via the returned pointer represent a simple array of type % Quantum. If the image type is CMYK or the storage class is PseudoClass, % call GetAuthenticMetacontent() after invoking GetAuthenticPixels() to % obtain the meta-content (of type void) corresponding to the region. % Once the Quantum (and/or Quantum) array has been updated, the % changes must be saved back to the underlying image using % SyncAuthenticPixels() or they may be lost. % % The format of the QueueAuthenticPixels() method is: % % Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, % const ssize_t y,const size_t columns,const size_t rows, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,columns,rows: These values define the perimeter of a region of % pixels. % % o exception: return any errors or warnings in this structure. % */ MagickExport Quantum *QueueAuthenticPixels(Image *image,const ssize_t x, const ssize_t y,const size_t columns,const size_t rows, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); Quantum *magick_restrict pixels; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) { pixels=cache_info->methods.queue_authentic_pixels_handler(image,x,y, columns,rows,exception); return(pixels); } assert(id < (int) cache_info->number_threads); pixels=QueueAuthenticPixelCacheNexus(image,x,y,columns,rows,MagickFalse, cache_info->nexus_info[id],exception); return(pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCacheMetacontent() reads metacontent from the specified region of % the pixel cache. % % The format of the ReadPixelCacheMetacontent() method is: % % MagickBooleanType ReadPixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the metacontent. % % o exception: return any errors or warnings in this structure. % */ static inline MagickOffsetType ReadPixelCacheRegion( const CacheInfo *magick_restrict cache_info,const MagickOffsetType offset, const MagickSizeType length,unsigned char *magick_restrict buffer) { MagickOffsetType i; ssize_t count; #if !defined(MAGICKCORE_HAVE_PREAD) if (lseek(cache_info->file,offset,SEEK_SET) < 0) return((MagickOffsetType) -1); #endif count=0; for (i=0; i < (MagickOffsetType) length; i+=count) { #if !defined(MAGICKCORE_HAVE_PREAD) count=read(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) MAGICK_SSIZE_MAX)); #else count=pread(cache_info->file,buffer+i,(size_t) MagickMin(length-i,(size_t) MAGICK_SSIZE_MAX),offset+i); #endif if (count <= 0) { count=0; if (errno != EINTR) break; } } return(i); } static MagickBooleanType ReadPixelCacheMetacontent( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; ssize_t y; unsigned char *magick_restrict q; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; q=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { unsigned char *magick_restrict p; /* Read meta-content from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->metacontent_extent*cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } break; } case DiskCache: { /* Read meta content from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->metacontent_extent*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read metacontent from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d P i x e l C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadPixelCachePixels() reads pixels from the specified region of the pixel % cache. % % The format of the ReadPixelCachePixels() method is: % % MagickBooleanType ReadPixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to read the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ReadPixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; Quantum *magick_restrict q; ssize_t y; size_t number_channels, rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns; if ((ssize_t) (offset/cache_info->columns) != nexus_info->region.y) return(MagickFalse); offset+=nexus_info->region.x; number_channels=cache_info->number_channels; length=(MagickSizeType) number_channels*nexus_info->region.width* sizeof(Quantum); if ((length/number_channels/sizeof(Quantum)) != nexus_info->region.width) return(MagickFalse); rows=nexus_info->region.height; extent=length*rows; if ((extent == 0) || ((extent/length) != rows)) return(MagickFalse); y=0; q=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { Quantum *magick_restrict p; /* Read pixels from memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } p=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } break; } case DiskCache: { /* Read pixels from disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadPixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*q),length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; offset+=cache_info->columns; q+=cache_info->number_channels*nexus_info->region.width; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Read pixels from distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=ReadDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(unsigned char *) q); if (count != (MagickOffsetType) length) break; q+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToReadPixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e f e r e n c e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReferencePixelCache() increments the reference count associated with the % pixel cache returning a pointer to the cache. % % The format of the ReferencePixelCache method is: % % Cache ReferencePixelCache(Cache cache_info) % % A description of each parameter follows: % % o cache_info: the pixel cache. % */ MagickPrivate Cache ReferencePixelCache(Cache cache) { CacheInfo *magick_restrict cache_info; assert(cache != (Cache *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); LockSemaphoreInfo(cache_info->semaphore); cache_info->reference_count++; UnlockSemaphoreInfo(cache_info->semaphore); return(cache_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheChannels() resets the pixel cache channels. % % The format of the ResetPixelCacheChannels method is: % % void ResetPixelCacheChannels(Image *) % % A description of each parameter follows: % % o image: the image. % */ MagickPrivate void ResetPixelCacheChannels(Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); cache_info->number_channels=GetPixelChannels(image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t C a c h e A n o n y m o u s M e m o r y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetCacheAnonymousMemory() resets the anonymous_memory value. % % The format of the ResetCacheAnonymousMemory method is: % % void ResetCacheAnonymousMemory(void) % */ MagickPrivate void ResetCacheAnonymousMemory(void) { cache_anonymous_memory=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e s e t P i x e l C a c h e E p o c h % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ResetPixelCacheEpoch() resets the pixel cache epoch. % % The format of the ResetPixelCacheEpoch method is: % % void ResetPixelCacheEpoch(void) % */ MagickPrivate void ResetPixelCacheEpoch(void) { cache_epoch=0; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e M e t h o d s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheMethods() sets the image pixel methods to the specified ones. % % The format of the SetPixelCacheMethods() method is: % % SetPixelCacheMethods(Cache *,CacheMethods *cache_methods) % % A description of each parameter follows: % % o cache: the pixel cache. % % o cache_methods: Specifies a pointer to a CacheMethods structure. % */ MagickPrivate void SetPixelCacheMethods(Cache cache,CacheMethods *cache_methods) { CacheInfo *magick_restrict cache_info; GetOneAuthenticPixelFromHandler get_one_authentic_pixel_from_handler; GetOneVirtualPixelFromHandler get_one_virtual_pixel_from_handler; /* Set cache pixel methods. */ assert(cache != (Cache) NULL); assert(cache_methods != (CacheMethods *) NULL); cache_info=(CacheInfo *) cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", cache_info->filename); if (cache_methods->get_virtual_pixel_handler != (GetVirtualPixelHandler) NULL) cache_info->methods.get_virtual_pixel_handler= cache_methods->get_virtual_pixel_handler; if (cache_methods->destroy_pixel_handler != (DestroyPixelHandler) NULL) cache_info->methods.destroy_pixel_handler= cache_methods->destroy_pixel_handler; if (cache_methods->get_virtual_metacontent_from_handler != (GetVirtualMetacontentFromHandler) NULL) cache_info->methods.get_virtual_metacontent_from_handler= cache_methods->get_virtual_metacontent_from_handler; if (cache_methods->get_authentic_pixels_handler != (GetAuthenticPixelsHandler) NULL) cache_info->methods.get_authentic_pixels_handler= cache_methods->get_authentic_pixels_handler; if (cache_methods->queue_authentic_pixels_handler != (QueueAuthenticPixelsHandler) NULL) cache_info->methods.queue_authentic_pixels_handler= cache_methods->queue_authentic_pixels_handler; if (cache_methods->sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) cache_info->methods.sync_authentic_pixels_handler= cache_methods->sync_authentic_pixels_handler; if (cache_methods->get_authentic_pixels_from_handler != (GetAuthenticPixelsFromHandler) NULL) cache_info->methods.get_authentic_pixels_from_handler= cache_methods->get_authentic_pixels_from_handler; if (cache_methods->get_authentic_metacontent_from_handler != (GetAuthenticMetacontentFromHandler) NULL) cache_info->methods.get_authentic_metacontent_from_handler= cache_methods->get_authentic_metacontent_from_handler; get_one_virtual_pixel_from_handler= cache_info->methods.get_one_virtual_pixel_from_handler; if (get_one_virtual_pixel_from_handler != (GetOneVirtualPixelFromHandler) NULL) cache_info->methods.get_one_virtual_pixel_from_handler= cache_methods->get_one_virtual_pixel_from_handler; get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; if (get_one_authentic_pixel_from_handler != (GetOneAuthenticPixelFromHandler) NULL) cache_info->methods.get_one_authentic_pixel_from_handler= cache_methods->get_one_authentic_pixel_from_handler; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S e t P i x e l C a c h e N e x u s P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheNexusPixels() defines the region of the cache for the % specified cache nexus. % % The format of the SetPixelCacheNexusPixels() method is: % % Quantum SetPixelCacheNexusPixels( % const CacheInfo *magick_restrict cache_info,const MapMode mode, % const ssize_t x,const ssize_t y,const size_t width,const size_t height, % const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o mode: ReadMode, WriteMode, or IOMode. % % o x,y,width,height: define the region of this particular cache nexus. % % o buffered: if true, nexus pixels are buffered. % % o nexus_info: the cache nexus to set. % % o exception: return any errors or warnings in this structure. % */ static inline MagickBooleanType AcquireCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MagickSizeType length, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { if (length != (MagickSizeType) ((size_t) length)) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=0; nexus_info->mapped=MagickFalse; if (cache_anonymous_memory <= 0) { nexus_info->cache=(Quantum *) MagickAssumeAligned(AcquireAlignedMemory(1, (size_t) length)); if (nexus_info->cache != (Quantum *) NULL) (void) memset(nexus_info->cache,0,(size_t) length); } else { nexus_info->cache=(Quantum *) MapBlob(-1,IOMode,0,(size_t) length); if (nexus_info->cache != (Quantum *) NULL) nexus_info->mapped=MagickTrue; } if (nexus_info->cache == (Quantum *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"PixelCacheAllocationFailed","`%s'", cache_info->filename); return(MagickFalse); } nexus_info->length=length; return(MagickTrue); } static inline void PrefetchPixelCacheNexusPixels(const NexusInfo *nexus_info, const MapMode mode) { if (nexus_info->length < CACHE_LINE_SIZE) return; if (mode == ReadMode) { MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE, 0,1); return; } MagickCachePrefetch((unsigned char *) nexus_info->pixels+CACHE_LINE_SIZE,1,1); } static inline MagickBooleanType ValidatePixelOffset(const ssize_t x, const size_t a) { if ((x >= 0) && (x >= ((ssize_t) MAGICK_SSIZE_MAX-(ssize_t) a))) return(MagickFalse); if (x <= ((ssize_t) MAGICK_SSIZE_MIN+(ssize_t) a)) return(MagickFalse); return(MagickTrue); } static Quantum *SetPixelCacheNexusPixels( const CacheInfo *magick_restrict cache_info,const MapMode mode, const ssize_t x,const ssize_t y,const size_t width,const size_t height, const MagickBooleanType buffered,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickBooleanType status; MagickSizeType length, number_pixels; assert(cache_info != (const CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return((Quantum *) NULL); assert(nexus_info->signature == MagickCoreSignature); (void) memset(&nexus_info->region,0,sizeof(nexus_info->region)); if ((width == 0) || (height == 0)) { (void) ThrowMagickException(exception,GetMagickModule(),CacheError, "NoPixelsDefinedInCache","`%s'",cache_info->filename); return((Quantum *) NULL); } if (((MagickSizeType) width > cache_info->width_limit) || ((MagickSizeType) height > cache_info->height_limit) || (ValidatePixelOffset(x,width) == MagickFalse) || (ValidatePixelOffset(y,height) == MagickFalse)) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "WidthOrHeightExceedsLimit","`%s'",cache_info->filename); return((Quantum *) NULL); } if (((cache_info->type == MemoryCache) || (cache_info->type == MapCache)) && (buffered == MagickFalse)) { if (((x >= 0) && (y >= 0) && (((ssize_t) height+y-1) < (ssize_t) cache_info->rows)) && (((x == 0) && (width == cache_info->columns)) || ((height == 1) && (((ssize_t) width+x-1) < (ssize_t) cache_info->columns)))) { MagickOffsetType offset; /* Pixels are accessed directly from memory. */ offset=(MagickOffsetType) y*cache_info->columns+x; nexus_info->pixels=cache_info->pixels+cache_info->number_channels* offset; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(unsigned char *) cache_info->metacontent+ offset*cache_info->metacontent_extent; nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=MagickTrue; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } } /* Pixels are stored in a staging region until they are synced to the cache. */ number_pixels=(MagickSizeType) width*height; length=MagickMax(number_pixels,MagickMax(cache_info->columns, cache_info->rows))*cache_info->number_channels*sizeof(*nexus_info->pixels); if (cache_info->metacontent_extent != 0) length+=number_pixels*cache_info->metacontent_extent; status=MagickTrue; if (nexus_info->cache == (Quantum *) NULL) status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); else if (nexus_info->length < length) { RelinquishCacheNexusPixels(nexus_info); status=AcquireCacheNexusPixels(cache_info,length,nexus_info,exception); } if (status == MagickFalse) return((Quantum *) NULL); nexus_info->pixels=nexus_info->cache; nexus_info->metacontent=(void *) NULL; if (cache_info->metacontent_extent != 0) nexus_info->metacontent=(void *) (nexus_info->pixels+ cache_info->number_channels*number_pixels); nexus_info->region.width=width; nexus_info->region.height=height; nexus_info->region.x=x; nexus_info->region.y=y; nexus_info->authentic_pixel_cache=cache_info->type == PingCache ? MagickTrue : MagickFalse; PrefetchPixelCacheNexusPixels(nexus_info,mode); return(nexus_info->pixels); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C a c h e V i r t u a l M e t h o d % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelCacheVirtualMethod() sets the "virtual pixels" method for the % pixel cache and returns the previous setting. A virtual pixel is any pixel % access that is outside the boundaries of the image cache. % % The format of the SetPixelCacheVirtualMethod() method is: % % VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, % const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o virtual_pixel_method: choose the type of virtual pixel. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SetCacheAlphaChannel(Image *image,const Quantum alpha, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; CacheView *magick_restrict image_view; MagickBooleanType status; ssize_t y; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); image->alpha_trait=BlendPixelTrait; status=MagickTrue; image_view=AcquireVirtualCacheView(image,exception); /* must be virtual */ #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns; x++) { SetPixelAlpha(image,alpha,q); q+=GetPixelChannels(image); } status=SyncCacheViewAuthenticPixels(image_view,exception); } image_view=DestroyCacheView(image_view); return(status); } MagickPrivate VirtualPixelMethod SetPixelCacheVirtualMethod(Image *image, const VirtualPixelMethod virtual_pixel_method,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; VirtualPixelMethod method; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); method=cache_info->virtual_pixel_method; cache_info->virtual_pixel_method=virtual_pixel_method; if ((image->columns != 0) && (image->rows != 0)) switch (virtual_pixel_method) { case BackgroundVirtualPixelMethod: { if ((image->background_color.alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) SetImageColorspace(image,sRGBColorspace,exception); break; } case TransparentVirtualPixelMethod: { if (image->alpha_trait == UndefinedPixelTrait) (void) SetCacheAlphaChannel(image,OpaqueAlpha,exception); break; } default: break; } return(method); } #if defined(MAGICKCORE_OPENCL_SUPPORT) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c O p e n C L B u f f e r % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticOpenCLBuffer() makes sure that all the OpenCL operations have % been completed and updates the host memory. % % The format of the SyncAuthenticOpenCLBuffer() method is: % % void SyncAuthenticOpenCLBuffer(const Image *image) % % A description of each parameter follows: % % o image: the image. % */ static void CopyOpenCLBuffer(CacheInfo *magick_restrict cache_info) { assert(cache_info != (CacheInfo *) NULL); assert(cache_info->signature == MagickCoreSignature); if ((cache_info->type != MemoryCache) || (cache_info->opencl == (MagickCLCacheInfo) NULL)) return; /* Ensure single threaded access to OpenCL environment. */ LockSemaphoreInfo(cache_info->semaphore); cache_info->opencl=CopyMagickCLCacheInfo(cache_info->opencl); UnlockSemaphoreInfo(cache_info->semaphore); } MagickPrivate void SyncAuthenticOpenCLBuffer(const Image *image) { CacheInfo *magick_restrict cache_info; assert(image != (const Image *) NULL); cache_info=(CacheInfo *) image->cache; CopyOpenCLBuffer(cache_info); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e N e x u s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelCacheNexus() saves the authentic image pixels to the % in-memory or disk cache. The method returns MagickTrue if the pixel region % is synced, otherwise MagickFalse. % % The format of the SyncAuthenticPixelCacheNexus() method is: % % MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o nexus_info: the cache nexus to sync. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncAuthenticPixelCacheNexus(Image *image, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; MagickBooleanType status; /* Transfer pixels to the cache. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->cache == (Cache) NULL) ThrowBinaryException(CacheError,"PixelCacheIsNotOpen",image->filename); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->type == UndefinedCache) return(MagickFalse); if (image->mask_trait != UpdatePixelTrait) { if (((image->channels & WriteMaskChannel) != 0) && (ClipPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); if (((image->channels & CompositeMaskChannel) != 0) && (MaskPixelCacheNexus(image,nexus_info,exception) == MagickFalse)) return(MagickFalse); } if (nexus_info->authentic_pixel_cache != MagickFalse) { if (image->taint == MagickFalse) image->taint=MagickTrue; return(MagickTrue); } assert(cache_info->signature == MagickCoreSignature); status=WritePixelCachePixels(cache_info,nexus_info,exception); if ((cache_info->metacontent_extent != 0) && (WritePixelCacheMetacontent(cache_info,nexus_info,exception) == MagickFalse)) return(MagickFalse); if ((status != MagickFalse) && (image->taint == MagickFalse)) image->taint=MagickTrue; return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c A u t h e n t i c P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixelsCache() saves the authentic image pixels to the in-memory % or disk cache. The method returns MagickTrue if the pixel region is synced, % otherwise MagickFalse. % % The format of the SyncAuthenticPixelsCache() method is: % % MagickBooleanType SyncAuthenticPixelsCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType SyncAuthenticPixelsCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S y n c A u t h e n t i c P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncAuthenticPixels() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncAuthenticPixels() method is: % % MagickBooleanType SyncAuthenticPixels(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SyncAuthenticPixels(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; const int id = GetOpenMPThreadId(); MagickBooleanType status; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image->cache != (Cache) NULL); cache_info=(CacheInfo *) image->cache; assert(cache_info->signature == MagickCoreSignature); if (cache_info->methods.sync_authentic_pixels_handler != (SyncAuthenticPixelsHandler) NULL) { status=cache_info->methods.sync_authentic_pixels_handler(image, exception); return(status); } assert(id < (int) cache_info->number_threads); status=SyncAuthenticPixelCacheNexus(image,cache_info->nexus_info[id], exception); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + S y n c I m a g e P i x e l C a c h e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SyncImagePixelCache() saves the image pixels to the in-memory or disk cache. % The method returns MagickTrue if the pixel region is flushed, otherwise % MagickFalse. % % The format of the SyncImagePixelCache() method is: % % MagickBooleanType SyncImagePixelCache(Image *image, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickPrivate MagickBooleanType SyncImagePixelCache(Image *image, ExceptionInfo *exception) { CacheInfo *magick_restrict cache_info; assert(image != (Image *) NULL); assert(exception != (ExceptionInfo *) NULL); cache_info=(CacheInfo *) GetImagePixelCache(image,MagickTrue,exception); return(cache_info == (CacheInfo *) NULL ? MagickFalse : MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e P i x e l C a c h e M e t a c o n t e n t % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCacheMetacontent() writes the meta-content to the specified region % of the pixel cache. % % The format of the WritePixelCacheMetacontent() method is: % % MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the meta-content. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCacheMetacontent(CacheInfo *cache_info, NexusInfo *magick_restrict nexus_info,ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; const unsigned char *magick_restrict p; ssize_t y; size_t rows; if (cache_info->metacontent_extent == 0) return(MagickFalse); if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) nexus_info->region.width* cache_info->metacontent_extent; extent=(MagickSizeType) length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=(unsigned char *) nexus_info->metacontent; switch (cache_info->type) { case MemoryCache: case MapCache: { unsigned char *magick_restrict q; /* Write associated pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=(unsigned char *) cache_info->metacontent+offset* cache_info->metacontent_extent; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=nexus_info->region.width*cache_info->metacontent_extent; q+=cache_info->columns*cache_info->metacontent_extent; } break; } case DiskCache: { /* Write associated pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } extent=(MagickSizeType) cache_info->columns*cache_info->rows; for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+extent* cache_info->number_channels*sizeof(Quantum)+offset* cache_info->metacontent_extent,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write metacontent to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCacheMetacontent((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->metacontent_extent*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + W r i t e C a c h e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WritePixelCachePixels() writes image pixels to the specified region of the % pixel cache. % % The format of the WritePixelCachePixels() method is: % % MagickBooleanType WritePixelCachePixels(CacheInfo *cache_info, % NexusInfo *nexus_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o cache_info: the pixel cache. % % o nexus_info: the cache nexus to write the pixels. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WritePixelCachePixels( CacheInfo *magick_restrict cache_info,NexusInfo *magick_restrict nexus_info, ExceptionInfo *exception) { MagickOffsetType count, offset; MagickSizeType extent, length; const Quantum *magick_restrict p; ssize_t y; size_t rows; if (nexus_info->authentic_pixel_cache != MagickFalse) return(MagickTrue); offset=(MagickOffsetType) nexus_info->region.y*cache_info->columns+ nexus_info->region.x; length=(MagickSizeType) cache_info->number_channels*nexus_info->region.width* sizeof(Quantum); extent=length*nexus_info->region.height; rows=nexus_info->region.height; y=0; p=nexus_info->pixels; switch (cache_info->type) { case MemoryCache: case MapCache: { Quantum *magick_restrict q; /* Write pixels to memory. */ if ((cache_info->columns == nexus_info->region.width) && (extent == (MagickSizeType) ((size_t) extent))) { length=extent; rows=1UL; } q=cache_info->pixels+cache_info->number_channels*offset; for (y=0; y < (ssize_t) rows; y++) { (void) memcpy(q,p,(size_t) length); p+=cache_info->number_channels*nexus_info->region.width; q+=cache_info->number_channels*cache_info->columns; } break; } case DiskCache: { /* Write pixels to disk. */ LockSemaphoreInfo(cache_info->file_semaphore); if (OpenPixelCacheOnDisk(cache_info,IOMode) == MagickFalse) { ThrowFileException(exception,FileOpenError,"UnableToOpenFile", cache_info->cache_filename); UnlockSemaphoreInfo(cache_info->file_semaphore); return(MagickFalse); } if ((cache_info->columns == nexus_info->region.width) && (extent <= MagickMaxBufferExtent)) { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WritePixelCacheRegion(cache_info,cache_info->offset+offset* cache_info->number_channels*sizeof(*p),length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; offset+=cache_info->columns; } if (IsFileDescriptorLimitExceeded() != MagickFalse) (void) ClosePixelCacheOnDisk(cache_info); UnlockSemaphoreInfo(cache_info->file_semaphore); break; } case DistributedCache: { RectangleInfo region; /* Write pixels to distributed cache. */ LockSemaphoreInfo(cache_info->file_semaphore); region=nexus_info->region; if ((cache_info->columns != nexus_info->region.width) || (extent > MagickMaxBufferExtent)) region.height=1UL; else { length=extent; rows=1UL; } for (y=0; y < (ssize_t) rows; y++) { count=WriteDistributePixelCachePixels((DistributeCacheInfo *) cache_info->server_info,&region,length,(const unsigned char *) p); if (count != (MagickOffsetType) length) break; p+=cache_info->number_channels*nexus_info->region.width; region.y++; } UnlockSemaphoreInfo(cache_info->file_semaphore); break; } default: break; } if (y < (ssize_t) rows) { ThrowFileException(exception,CacheError,"UnableToWritePixelCache", cache_info->cache_filename); return(MagickFalse); } if ((cache_info->debug != MagickFalse) && (CacheTick(nexus_info->region.y,cache_info->rows) != MagickFalse)) (void) LogMagickEvent(CacheEvent,GetMagickModule(), "%s[%.20gx%.20g%+.20g%+.20g]",cache_info->filename,(double) nexus_info->region.width,(double) nexus_info->region.height,(double) nexus_info->region.x,(double) nexus_info->region.y); return(MagickTrue); }
serialized.c
// RUN: %libomp-compile-and-run | FileCheck %s // REQUIRES: ompt #include "callback.h" int main() { #pragma omp parallel num_threads(1) { print_ids(0); print_ids(1); } // Check if libomp supports the callbacks for this test. // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_begin' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_callback_parallel_end' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_event_implicit_task_begin' // CHECK-NOT: {{^}}0: Could not register callback 'ompt_event_implicit_task_end' // CHECK: 0: NULL_POINTER=[[NULL:.*$]] // CHECK: {{^}}[[MASTER_ID:[0-9]+]]: ompt_event_parallel_begin: parent_task_id=[[PARENT_TASK_ID:[0-9]+]], parent_task_frame.exit=[[NULL]], parent_task_frame.reenter={{0x[0-f]+}}, parallel_id=[[PARALLEL_ID:[0-9]+]], requested_team_size=1, parallel_function=0x{{[0-f]+}}, invoker=[[PARALLEL_INVOKER:[0-9]+]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_begin: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID:[0-9]+]] // CHECK: {{^}}[[MASTER_ID]]: task level 0: parallel_id=[[PARALLEL_ID]], task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: task level 1: parallel_id=0, task_id=[[PARENT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_implicit_task_end: parallel_id={{[0-9]+}}, task_id=[[IMPLICIT_TASK_ID]] // CHECK: {{^}}[[MASTER_ID]]: ompt_event_parallel_end: parallel_id=[[PARALLEL_ID]], task_id=[[PARENT_TASK_ID]], invoker=[[PARALLEL_INVOKER]] return 0; }
known_hosts_fmt_plug.c
/* Quick-and-dirty cracker for ~/.ssh/known_hosts hashes (HashKnownHosts yes). * * Based on http://blog.tremily.us/posts/known_hosts/ * * This software is Copyright (c) 2014, Dhiru Kholia <dhiru at openwall.com>, * and it is hereby released to the general public under the following terms: * * Redistribution and use in source and binary forms, with or without modification, * are permitted. * * Significant speedup Dec 2014, JimF. OMPSCALE was way off, and: * NOTE Appears that salt and password are reversed?? With this info, salt was * redone, to compute the first half of the HMAC, and double the speed. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_known_hosts; #elif FMT_REGISTERS_H john_register_one(&fmt_known_hosts); #else #include "sha.h" #include <string.h> #include "arch.h" #include "misc.h" #include "common.h" #include "formats.h" #include "base64.h" #include "params.h" #include "options.h" #ifdef _OPENMP #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include "memdbg.h" #define FORMAT_LABEL "known_hosts" #define FORMAT_TAG "$known_hosts$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #define FORMAT_NAME "HashKnownHosts HMAC-SHA1" #define ALGORITHM_NAME "SHA1 32/" ARCH_BITS_STR #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH 0 #define PLAINTEXT_LENGTH 125 #define BINARY_SIZE 20 #define BINARY_ENCODED_SIZE 28 #define PAD_SIZE 64 #define BINARY_ALIGN 4 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN sizeof(uint64_t) #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 static struct fmt_tests known_hosts_tests[] = { {"$known_hosts$|1|yivSFSAv9mhGu/GPc14KpaPMSjE=|I9L3FH6RGefWIFb0Po74BVN3Fto=", "213.100.98.219"}, {"$known_hosts$|1|pgjIzNM77FYsBHLfKvvG9aWpKAA=|XbHqTCXG1JAV6fb2h2HT8MT7kGU=", "192.30.252.130"}, {"$known_hosts$|1|vAQX51f9EfXY33/j3upxFIlI1ds=|q+CzSLaa1EaSsAQzP/XRM/gaFQ4=", "192.30.252.128"}, {"$known_hosts$|1|F1E1KeoE/eEWhi10WpGv4OdiO6Y=|3988QV0VE8wmZL7suNrYQLITLCg=", "192.168.1.61"}, {NULL} }; static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static uint32_t (*crypt_out)[BINARY_SIZE / sizeof(uint32_t)]; static struct custom_salt { SHA_CTX ipad_ctx; SHA_CTX opad_ctx; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP int 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_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; if (strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) return 0; p = q = ciphertext + TAG_LENGTH; if (p[0] != '|' || p[2] != '|') return 0; p += 3; q = strchr(p, '|'); if (q -p != BINARY_ENCODED_SIZE) return 0; p = strrchr(ciphertext, '|') + 1; if (strlen(p) != BINARY_ENCODED_SIZE) return 0; return 1; } static void *get_salt(char *ciphertext) { char *p, *q; unsigned char ipad[20], opad[20], salt[20 + 4 + 1]; int i; static struct custom_salt cs; memset(&cs, 0, sizeof(cs)); p = ciphertext + TAG_LENGTH + 3; q = strchr(p, '|'); base64_decode(p, q - p, (char*)salt); for (i = 0; i < 20; ++i) { ipad[i] = salt[i] ^ 0x36; opad[i] = salt[i] ^ 0x5C; } SHA1_Init(&cs.ipad_ctx); SHA1_Update(&cs.ipad_ctx, ipad, 20); SHA1_Update(&cs.ipad_ctx, "\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36\x36", 44); SHA1_Init(&cs.opad_ctx); SHA1_Update(&cs.opad_ctx, opad, 20); SHA1_Update(&cs.opad_ctx, "\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C\x5C", 44); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE + 1 + 4]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; p = strrchr(ciphertext, '|') + 1; base64_decode((char*)p, BINARY_ENCODED_SIZE, (char*)out); return out; } static int get_hash_0(int index) { return crypt_out[index][0] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][0] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][0] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][0] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][0] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][0] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][0] & PH_MASK_6; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for #endif for (index = 0; index < count; index++) { SHA_CTX ctx; memcpy(&ctx, &cur_salt->ipad_ctx, sizeof(ctx)); SHA1_Update(&ctx, saved_key[index], strlen(saved_key[index])); SHA1_Final((unsigned char*) crypt_out[index], &ctx); memcpy(&ctx, &cur_salt->opad_ctx, sizeof(ctx)); SHA1_Update(&ctx, crypt_out[index], BINARY_SIZE); SHA1_Final((unsigned char*) crypt_out[index], &ctx); } return count; } static int cmp_all(void *binary, int count) { int index = 0; #ifdef _OPENMP for (; index < count; index++) #endif if (!memcmp(binary, crypt_out[index], ARCH_SIZE)) return 1; return 0; } static int cmp_one(void *binary, int index) { return !memcmp(binary, crypt_out[index], BINARY_SIZE); } static int cmp_exact(char *source, int index) { return 1; } static void known_hosts_set_key(char *key, int index) { int len = strlen(key); memcpy(saved_key[index], key, len); saved_key[index][len] = 0; } static char *get_key(int index) { return saved_key[index]; } struct fmt_main fmt_known_hosts = { { 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 | FMT_OMP_BAD, { NULL }, { FORMAT_TAG }, known_hosts_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 }, fmt_default_salt_hash, NULL, set_salt, known_hosts_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 */
simd-clone-4.h
template <int N> struct S { int s; #pragma omp declare simd notinbranch int f0 (int x); #pragma omp declare simd notinbranch uniform(this) int f1 (int x); #pragma omp declare simd notinbranch linear(this:sizeof(this)/sizeof(this)) int f2 (int x); }; template <int N> struct T { int t[64]; #pragma omp declare simd aligned(this:32) uniform(this) linear(x) int f3 (int x); };
owl_ndarray_maths_map_omp.h
/* * OWL - OCaml Scientific and Engineering Computing * Copyright (c) 2016-2020 Liang Wang <liang.wang@cl.cam.ac.uk> */ #ifdef OWL_ENABLE_TEMPLATE #ifndef INIT // Because some functions do not really utilise this, #define INIT // so define an empty string as default. #endif #include "owl_core_engine.h" #include "owl_omp_parameters.h" // function to perform mapping of elements from x to y #ifdef FUN4 #undef OWL_OMP_THRESHOLD #define OWL_OMP_THRESHOLD OWL_OMP_THRESHOLD_FUN(FUN4) CAMLprim value FUN4(value vN, value vX, value vY) { CAMLparam3(vN, vX, vY); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x, *stop_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { NUMBER x = *(start_x + i); *(start_y + i) = (MAPFN(x)); } } else { while (start_x != stop_x) { NUMBER x = *start_x; *start_y = (MAPFN(x)); start_x += 1; start_y += 1; }; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN4 */ // function to map elements in [x] w.r.t scalar values, linspace and etc. #ifdef FUN12 CAMLprim value FUN12(value vN, value vA, value vB, value vX) { CAMLparam1(vX); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; caml_release_runtime_system(); /* Allow other threads */ if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 1; i <= N; i++) { MAPFN(*(X_data + i - 1)); } } else { for (int i = 1; i <= N; i++) { MAPFN(*X_data); X_data++; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN12 */ // function to calculate logspace_base function #ifdef FUN13 CAMLprim value FUN13(value vN, value vBase, value vA, value vB, value vX) { CAMLparam1(vX); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; caml_release_runtime_system(); /* Allow other threads */ for (int i = 1; i <= N; i++) { MAPFN(X_data); X_data++; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN13 */ // TODO: this needs to be unified with FUN4 in future // similar to FUN4, but mostly for complex numbers #ifdef FUN14 CAMLprim value FUN14(value vN, value vX, value vY) { CAMLparam3(vN, vX, vY); int N = Long_val(vN); struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += 1; start_y += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN14 */ // function to map pairwise elements in x and y then save results to z #ifdef FUN15 CAMLprim value FUN15(value vN, value vX, value vY, value vZ) { CAMLparam4(vN, vX, vY, vZ); int N = Long_val(vN); struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; struct caml_ba_array *Z = Caml_ba_array_val(vZ); NUMBER2 *Z_data = (NUMBER2 *) Z->data; NUMBER *start_x, *stop_x; NUMBER1 *start_y; NUMBER2 *start_z; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; start_y = Y_data; start_z = Z_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i), (start_z + i)); } } else { while (start_x != stop_x) { MAPFN(start_x, start_y, start_z); start_x += 1; start_y += 1; start_z += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN15 */ // function to map all elements in [x] w.r.t to [a] then save results to [y] #ifdef FUN17 CAMLprim value FUN17(value vN, value vX, value vY, value vA) { CAMLparam4(vN, vX, vY, vA); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; start_y = Y_data; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i), (start_y + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += 1; start_y += 1; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN17 */ // function to map elements in [x] w.r.t [a] and [b] then save results to [x] #ifdef FUN18 CAMLprim value FUN18(value vN, value vX, value vA, value vB) { CAMLparam4(vN, vX, vA, vB); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; NUMBER *start_x, *stop_x; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data; stop_x = start_x + N; while (start_x != stop_x) { MAPFN(start_x); start_x += 1; }; caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN18 */ // function to map x to y with explicit offset, step size, number of ops #ifdef FUN19 CAMLprim value FUN19_IMPL( value vN, value vX, value vOFSX, value vINCX, value vY, value vOFSY, value vINCY ) { CAMLparam5(vN, vX, vOFSX, vINCX, vY); CAMLxparam2(vOFSY, vINCY); int N = Long_val(vN); int ofsx = Long_val(vOFSX); int incx = Long_val(vINCX); int ofsy = Long_val(vOFSY); int incy = Long_val(vINCY); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x; NUMBER1 *start_y; caml_release_runtime_system(); /* Allow other threads */ start_x = X_data + ofsx; start_y = Y_data + ofsy; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN((start_x + i * incx), (start_y + i * incy)); } } else { for (int i = 0; i < N; i++) { MAPFN(start_x, start_y); start_x += incx; start_y += incy; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN19(value *argv, int __unused_argn) { return FUN19_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6]); } #endif /* FUN19 */ // function to map x to y with explicit offset, step size, number of ops // more general version of FUN19, so more control over the access pattern to // the data with two embedded loops. #ifdef FUN20 CAMLprim value FUN20_IMPL( value vM, value vN, value vX, value vOFSX, value vINCX_M, value vINCX_N, value vY, value vOFSY, value vINCY_M, value vINCY_N ) { CAMLparam2(vM, vN); CAMLxparam4(vX, vOFSX, vINCX_M, vINCX_N); CAMLxparam4(vY, vOFSY, vINCY_M, vINCY_N); int M = Long_val(vM); int N = Long_val(vN); int ofsx = Long_val(vOFSX); int incx_m = Long_val(vINCX_M); int incx_n = Long_val(vINCX_N); int ofsy = Long_val(vOFSY); int incy_m = Long_val(vINCY_M); int incy_n = Long_val(vINCY_N); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x_m; NUMBER *start_x_n; NUMBER1 *start_y_m; NUMBER1 *start_y_n; caml_release_runtime_system(); /* Allow other threads */ start_x_m = X_data + ofsx; start_y_m = Y_data + ofsy; if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < M; i++) { start_x_n = start_x_m + i * incx_m; start_y_n = start_y_m + i * incy_m; for (int j = 0; j < N; j++) { MAPFN(start_x_n, start_y_n); start_x_n += incx_n; start_y_n += incy_n; } } } else { for (int i = 0; i < M; i++) { start_x_n = start_x_m; start_y_n = start_y_m; for (int j = 0; j < N; j++) { MAPFN(start_x_n, start_y_n); start_x_n += incx_n; start_y_n += incy_n; } start_x_m += incx_m; start_y_m += incy_m; } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN20(value *argv, int __unused_argn) { return FUN20_IMPL( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9] ); } #endif /* FUN20 */ // broadcast function of x and y then save the result to z #ifdef FUN24 static OWL_INLINE void FUN24_CODE ( int d, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_x = X->dim[d] == Z->dim[d] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d] ? stride_y[d] : 0; int inc_z = stride_z[d]; const int n = Z->dim[d]; if (d == X->num_dims - 1) { NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(x, y, z); x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN24_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN24_IMPL( value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y); CAMLxparam2(vZ, vSTRIDE_Z); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ FUN24_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, 0); caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN24(value *argv, int __unused_argn) { return FUN24_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } #endif /* FUN24 */ // broadcast function of x and y then save the result to z. Compared to FUN24, // the difference of FUN25 is z has one extra dimension than max(dim_x, dim_y). // This function is used in owl's distribution module and extra dimension is // used as sample dimension. #ifdef FUN25 static OWL_INLINE void FUN25_CODE ( int d, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0; int inc_z = stride_z[d+1]; const int n = Z->dim[d+1]; if (d == X->num_dims - 1) { NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(x, y, z); x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN25_CODE (d+1, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN25_IMPL( value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vX, vSTRIDE_X, vY, vSTRIDE_Y); CAMLxparam2(vZ, vSTRIDE_Z); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ int ofs_z = 0; for (int i = 0; i < Z->dim[0]; i++) { FUN25_CODE (0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z); ofs_z += stride_z[0]; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN25(value *argv, int __unused_argn) { return FUN25_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5]); } #endif /* FUN25 */ // Similar to FUN25, but broadcast between w, x, y, then save the result to z #ifdef FUN27 static OWL_INLINE void FUN27_CODE ( int d, struct caml_ba_array *W, int64_t *stride_w, int ofs_w, struct caml_ba_array *X, int64_t *stride_x, int ofs_x, struct caml_ba_array *Y, int64_t *stride_y, int ofs_y, struct caml_ba_array *Z, int64_t *stride_z, int ofs_z ) { int inc_w = W->dim[d] == Z->dim[d+1] ? stride_w[d] : 0; int inc_x = X->dim[d] == Z->dim[d+1] ? stride_x[d] : 0; int inc_y = Y->dim[d] == Z->dim[d+1] ? stride_y[d] : 0; int inc_z = stride_z[d+1]; const int n = Z->dim[d+1]; if (d == X->num_dims - 1) { NUMBER *w = (NUMBER *) W->data + ofs_w; NUMBER *x = (NUMBER *) X->data + ofs_x; NUMBER *y = (NUMBER *) Y->data + ofs_y; NUMBER *z = (NUMBER *) Z->data + ofs_z; for (int i = 0; i < n; i++) { MAPFN(w, x, y, z); w += inc_w; x += inc_x; y += inc_y; z += inc_z; } } else { for (int i = 0; i < n; i++) { FUN27_CODE (d+1, W, stride_w, ofs_w, X, stride_x, ofs_x, Y, stride_y, ofs_y, Z, stride_z, ofs_z); ofs_w += inc_w; ofs_x += inc_x; ofs_y += inc_y; ofs_z += inc_z; } } return; } CAMLprim value FUN27_IMPL( value vW, value vSTRIDE_W, value vX, value vSTRIDE_X, value vY, value vSTRIDE_Y, value vZ, value vSTRIDE_Z ) { CAMLparam4(vW, vSTRIDE_W, vX, vSTRIDE_X); CAMLparam4(vY, vSTRIDE_Y, vZ, vSTRIDE_Z); struct caml_ba_array *W = Caml_ba_array_val(vW); struct caml_ba_array *X = Caml_ba_array_val(vX); struct caml_ba_array *Y = Caml_ba_array_val(vY); struct caml_ba_array *Z = Caml_ba_array_val(vZ); struct caml_ba_array *stride_W = Caml_ba_array_val(vSTRIDE_W); int64_t *stride_w = (int64_t *) stride_W->data; struct caml_ba_array *stride_X = Caml_ba_array_val(vSTRIDE_X); int64_t *stride_x = (int64_t *) stride_X->data; struct caml_ba_array *stride_Y = Caml_ba_array_val(vSTRIDE_Y); int64_t *stride_y = (int64_t *) stride_Y->data; struct caml_ba_array *stride_Z = Caml_ba_array_val(vSTRIDE_Z); int64_t *stride_z = (int64_t *) stride_Z->data; caml_release_runtime_system(); /* Allow other threads */ int ofs_z = 0; for (int i = 0; i < Z->dim[0]; i++) { FUN27_CODE (0, W, stride_w, 0, X, stride_x, 0, Y, stride_y, 0, Z, stride_z, ofs_z); ofs_z += stride_z[0]; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN27(value *argv, int __unused_argn) { return FUN27_IMPL(argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7]); } #endif /* FUN27 */ // function to map x to y with explicit offset, step size, number of ops // more general version of FUN20, so more control over the access pattern to // the data with three embedded loops. #ifdef FUN28 CAMLprim value FUN28_IMPL( value vM, value vN, value vO, value vX, value vOFSX, value vINCX_M, value vINCX_N, value vINCX_O, value vY, value vOFSY, value vINCY_M, value vINCY_N, value vINCY_O ) { CAMLparam3(vM, vN, vO); CAMLxparam5(vX, vOFSX, vINCX_M, vINCX_N, vINCX_O); CAMLxparam5(vY, vOFSY, vINCY_M, vINCY_N, vINCY_O); int M = Long_val(vM); int N = Long_val(vN); int O = Long_val(vO); int ofsx = Long_val(vOFSX); int incx_m = Long_val(vINCX_M); int incx_n = Long_val(vINCX_N); int incx_o = Long_val(vINCX_O); int ofsy = Long_val(vOFSY); int incy_m = Long_val(vINCY_M); int incy_n = Long_val(vINCY_N); int incy_o = Long_val(vINCY_O); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER1 *Y_data = (NUMBER1 *) Y->data; NUMBER *start_x_m; NUMBER *start_x_n; NUMBER *start_x_o; NUMBER1 *start_y_m; NUMBER1 *start_y_n; NUMBER1 *start_y_o; caml_release_runtime_system(); /* Allow other threads */ start_x_m = X_data + ofsx; start_y_m = Y_data + ofsy; for (int i = 0; i < M; i++) { start_x_n = start_x_m; start_y_n = start_y_m; for (int j = 0; j < N; j++) { start_x_o = start_x_n; start_y_o = start_y_n; for (int k = 0; k < O; k++) { MAPFN(start_x_o, start_y_o); start_x_o += incx_o; start_y_o += incy_o; } start_x_n += incx_n; start_y_n += incy_n; } start_x_m += incx_m; start_y_m += incy_m; } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } CAMLprim value FUN28(value *argv, int __unused_argn) { return FUN28_IMPL( argv[0], argv[1], argv[2], argv[3], argv[4], argv[5], argv[6], argv[7], argv[8], argv[9], argv[10], argv[11], argv[12] ); } #endif /* FUN28 */ // function to map [x] w.r.t scalar values, similar to FUN12 but saves to Y #ifdef FUN29 CAMLprim value FUN29(value vN, value vA, value vB, value vX, value vY) { CAMLparam5(vN, vA, vB, vX, vY); int N = Long_val(vN); INIT; struct caml_ba_array *X = Caml_ba_array_val(vX); NUMBER *X_data = (NUMBER *) X->data; struct caml_ba_array *Y = Caml_ba_array_val(vY); NUMBER *Y_data = (NUMBER *) Y->data; caml_release_runtime_system(); /* Allow other threads */ if (N >= OWL_OMP_THRESHOLD_DEFAULT) { #pragma omp parallel for schedule(static) for (int i = 0; i < N; i++) { MAPFN(*(X_data + i), *(Y_data + i)); } } else { for (int i = 0; i < N; i++) { MAPFN(*(X_data + i), *(Y_data + i)); } } caml_acquire_runtime_system(); /* Disallow other threads */ CAMLreturn(Val_unit); } #endif /* FUN29 */ #undef NUMBER #undef NUMBER1 #undef NUMBER2 #undef MAPFN #undef MAPFN1 #undef MAPFN2 #undef MAPFN3 #undef INIT #undef FUN4 #undef FUN12 #undef FUN13 #undef FUN14 #undef FUN15 #undef FUN17 #undef FUN18 #undef FUN19 #undef FUN19_IMPL #undef FUN20 #undef FUN20_IMPL #undef FUN24 #undef FUN24_IMPL #undef FUN24_CODE #undef FUN25 #undef FUN25_IMPL #undef FUN25_CODE #undef FUN27 #undef FUN27_IMPL #undef FUN27_CODE #undef FUN28 #undef FUN28_IMPL #undef FUN29 #undef OWL_OMP_THRESHOLD #endif /* OWL_ENABLE_TEMPLATE */
OpenMPClause.h
//===- OpenMPClause.h - Classes for OpenMP clauses --------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // /// \file /// This file defines OpenMP AST classes for clauses. /// There are clauses for executable directives, clauses for declarative /// directives and clauses which can be used in both kinds of directives. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_AST_OPENMPCLAUSE_H #define LLVM_CLANG_AST_OPENMPCLAUSE_H #include "clang/AST/ASTFwd.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclarationName.h" #include "clang/AST/Expr.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtIterator.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/OpenMPKinds.h" #include "clang/Basic/SourceLocation.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/PointerIntPair.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/iterator.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Frontend/OpenMP/OMPAssume.h" #include "llvm/Frontend/OpenMP/OMPConstants.h" #include "llvm/Frontend/OpenMP/OMPContext.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/TrailingObjects.h" #include <cassert> #include <cstddef> #include <iterator> #include <utility> namespace clang { class ASTContext; //===----------------------------------------------------------------------===// // AST classes for clauses. //===----------------------------------------------------------------------===// /// This is a basic class for representing single OpenMP clause. class OMPClause { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Ending location of the clause. SourceLocation EndLoc; /// Kind of the clause. OpenMPClauseKind Kind; protected: OMPClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation EndLoc) : StartLoc(StartLoc), EndLoc(EndLoc), Kind(K) {} public: /// Returns the starting location of the clause. SourceLocation getBeginLoc() const { return StartLoc; } /// Returns the ending location of the clause. SourceLocation getEndLoc() const { return EndLoc; } /// Sets the starting location of the clause. void setLocStart(SourceLocation Loc) { StartLoc = Loc; } /// Sets the ending location of the clause. void setLocEnd(SourceLocation Loc) { EndLoc = Loc; } /// Returns kind of OpenMP clause (private, shared, reduction, etc.). OpenMPClauseKind getClauseKind() const { return Kind; } bool isImplicit() const { return StartLoc.isInvalid(); } using child_iterator = StmtIterator; using const_child_iterator = ConstStmtIterator; using child_range = llvm::iterator_range<child_iterator>; using const_child_range = llvm::iterator_range<const_child_iterator>; child_range children(); const_child_range children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } /// Get the iterator range for the expressions used in the clauses. Used /// expressions include only the children that must be evaluated at the /// runtime before entering the construct. child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *) { return true; } }; /// Class that handles pre-initialization statement for some clauses, like /// 'shedule', 'firstprivate' etc. class OMPClauseWithPreInit { friend class OMPClauseReader; /// Pre-initialization statement for the clause. Stmt *PreInit = nullptr; /// Region that captures the associated stmt. OpenMPDirectiveKind CaptureRegion = llvm::omp::OMPD_unknown; protected: OMPClauseWithPreInit(const OMPClause *This) { assert(get(This) && "get is not tuned for pre-init."); } /// Set pre-initialization statement for the clause. void setPreInitStmt(Stmt *S, OpenMPDirectiveKind ThisRegion = llvm::omp::OMPD_unknown) { PreInit = S; CaptureRegion = ThisRegion; } public: /// Get pre-initialization statement for the clause. const Stmt *getPreInitStmt() const { return PreInit; } /// Get pre-initialization statement for the clause. Stmt *getPreInitStmt() { return PreInit; } /// Get capture region for the stmt in the clause. OpenMPDirectiveKind getCaptureRegion() const { return CaptureRegion; } static OMPClauseWithPreInit *get(OMPClause *C); static const OMPClauseWithPreInit *get(const OMPClause *C); }; /// Class that handles post-update expression for some clauses, like /// 'lastprivate', 'reduction' etc. class OMPClauseWithPostUpdate : public OMPClauseWithPreInit { friend class OMPClauseReader; /// Post-update expression for the clause. Expr *PostUpdate = nullptr; protected: OMPClauseWithPostUpdate(const OMPClause *This) : OMPClauseWithPreInit(This) { assert(get(This) && "get is not tuned for post-update."); } /// Set pre-initialization statement for the clause. void setPostUpdateExpr(Expr *S) { PostUpdate = S; } public: /// Get post-update expression for the clause. const Expr *getPostUpdateExpr() const { return PostUpdate; } /// Get post-update expression for the clause. Expr *getPostUpdateExpr() { return PostUpdate; } static OMPClauseWithPostUpdate *get(OMPClause *C); static const OMPClauseWithPostUpdate *get(const OMPClause *C); }; /// This structure contains most locations needed for by an OMPVarListClause. struct OMPVarListLocTy { /// Starting location of the clause (the clause keyword). SourceLocation StartLoc; /// Location of '('. SourceLocation LParenLoc; /// Ending location of the clause. SourceLocation EndLoc; OMPVarListLocTy() = default; OMPVarListLocTy(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : StartLoc(StartLoc), LParenLoc(LParenLoc), EndLoc(EndLoc) {} }; /// This represents clauses with the list of variables like 'private', /// 'firstprivate', 'copyin', 'shared', or 'reduction' clauses in the /// '#pragma omp ...' directives. template <class T> class OMPVarListClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of variables in the list. unsigned NumVars; protected: /// Build a clause with \a N variables /// /// \param K Kind of the clause. /// \param StartLoc Starting location of the clause (the clause keyword). /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPVarListClause(OpenMPClauseKind K, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(K, StartLoc, EndLoc), LParenLoc(LParenLoc), NumVars(N) {} /// Fetches list of variables associated with this clause. MutableArrayRef<Expr *> getVarRefs() { return MutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } /// Sets the list of variables for this clause. void setVarRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumVars && "Number of variables is not the same as the preallocated buffer"); std::copy(VL.begin(), VL.end(), static_cast<T *>(this)->template getTrailingObjects<Expr *>()); } public: using varlist_iterator = MutableArrayRef<Expr *>::iterator; using varlist_const_iterator = ArrayRef<const Expr *>::iterator; using varlist_range = llvm::iterator_range<varlist_iterator>; using varlist_const_range = llvm::iterator_range<varlist_const_iterator>; 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 getVarRefs().begin(); } varlist_iterator varlist_end() { return getVarRefs().end(); } varlist_const_iterator varlist_begin() const { return getVarRefs().begin(); } varlist_const_iterator varlist_end() const { return getVarRefs().end(); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Fetches list of all variables in the clause. ArrayRef<const Expr *> getVarRefs() const { return llvm::makeArrayRef( static_cast<const T *>(this)->template getTrailingObjects<Expr *>(), NumVars); } }; /// This represents 'allocator' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp allocate(a) allocator(omp_default_mem_alloc) /// \endcode /// In this example directive '#pragma omp allocate' has simple 'allocator' /// clause with the allocator 'omp_default_mem_alloc'. class OMPAllocatorClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression with the allocator. Stmt *Allocator = nullptr; /// Set allocator. void setAllocator(Expr *A) { Allocator = A; } public: /// Build 'allocator' clause with the given allocator. /// /// \param A Allocator. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAllocatorClause(Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_allocator, StartLoc, EndLoc), LParenLoc(LParenLoc), Allocator(A) {} /// Build an empty clause. OMPAllocatorClause() : OMPClause(llvm::omp::OMPC_allocator, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns allocator. Expr *getAllocator() const { return cast_or_null<Expr>(Allocator); } child_range children() { return child_range(&Allocator, &Allocator + 1); } const_child_range children() const { return const_child_range(&Allocator, &Allocator + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocator; } }; /// This represents the 'align' clause in the '#pragma omp allocate' /// directive. /// /// \code /// #pragma omp allocate(a) allocator(omp_default_mem_alloc) align(8) /// \endcode /// In this example directive '#pragma omp allocate' has simple 'allocator' /// clause with the allocator 'omp_default_mem_alloc' and align clause with /// value of 8. class OMPAlignClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Alignment specified with align clause. Stmt *Alignment = nullptr; /// Set alignment value. void setAlignment(Expr *A) { Alignment = A; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Build 'align' clause with the given alignment /// /// \param A Alignment value. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAlignClause(Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_align, StartLoc, EndLoc), LParenLoc(LParenLoc), Alignment(A) {} /// Build an empty clause. OMPAlignClause() : OMPClause(llvm::omp::OMPC_align, SourceLocation(), SourceLocation()) {} public: /// Build 'align' clause with the given alignment /// /// \param A Alignment value. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. static OMPAlignClause *Create(const ASTContext &C, Expr *A, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns alignment Expr *getAlignment() const { return cast_or_null<Expr>(Alignment); } child_range children() { return child_range(&Alignment, &Alignment + 1); } const_child_range children() const { return const_child_range(&Alignment, &Alignment + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_align; } }; /// This represents clause 'allocate' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a) allocate(omp_default_mem_alloc :a) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// and clause 'allocate' for the variable 'a'. class OMPAllocateClause final : public OMPVarListClause<OMPAllocateClause>, private llvm::TrailingObjects<OMPAllocateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Allocator specified in the clause, or 'nullptr' if the default one is /// used. Expr *Allocator = nullptr; /// Position of the ':' delimiter in the clause; SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPAllocateClause(SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, StartLoc, LParenLoc, EndLoc, N), Allocator(Allocator), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPAllocateClause(unsigned N) : OMPVarListClause<OMPAllocateClause>(llvm::omp::OMPC_allocate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } void setAllocator(Expr *A) { Allocator = A; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Allocator Allocator expression. /// \param ColonLoc Location of ':' delimiter. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPAllocateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, Expr *Allocator, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Returns the allocator expression or nullptr, if no allocator is specified. Expr *getAllocator() const { return Allocator; } /// Returns the location of the ':' delimiter. SourceLocation getColonLoc() const { return ColonLoc; } /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPAllocateClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAllocateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_allocate; } }; /// This represents 'if' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel if(parallel:a > 5) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'if' clause with /// condition 'a > 5' and directive name modifier 'parallel'. class OMPIfClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Location of ':' (if any). SourceLocation ColonLoc; /// Directive name modifier for the clause. OpenMPDirectiveKind NameModifier = llvm::omp::OMPD_unknown; /// Name modifier location. SourceLocation NameModifierLoc; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } /// Set directive name modifier for the clause. void setNameModifier(OpenMPDirectiveKind NM) { NameModifier = NM; } /// Set location of directive name modifier for the clause. void setNameModifierLoc(SourceLocation Loc) { NameModifierLoc = Loc; } /// Set location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Build 'if' clause with condition \a Cond. /// /// \param NameModifier [OpenMP 4.1] Directive name modifier of clause. /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param NameModifierLoc Location of directive name modifier. /// \param ColonLoc [OpenMP 4.1] Location of ':'. /// \param EndLoc Ending location of the clause. OMPIfClause(OpenMPDirectiveKind NameModifier, Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation NameModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_if, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond), ColonLoc(ColonLoc), NameModifier(NameModifier), NameModifierLoc(NameModifierLoc) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPIfClause() : OMPClause(llvm::omp::OMPC_if, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } /// Return directive name modifier associated with the clause. OpenMPDirectiveKind getNameModifier() const { return NameModifier; } /// Return the location of directive name modifier. SourceLocation getNameModifierLoc() const { return NameModifierLoc; } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPIfClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_if; } }; /// This represents 'final' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task final(a > 5) /// \endcode /// In this example directive '#pragma omp task' has simple 'final' /// clause with condition 'a > 5'. class OMPFinalClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } public: /// Build 'final' clause with condition \a Cond. /// /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPFinalClause(Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_final, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPFinalClause() : OMPClause(llvm::omp::OMPC_final, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPFinalClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_final; } }; /// This represents 'num_threads' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel num_threads(6) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'num_threads' /// clause with number of threads '6'. class OMPNumThreadsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'num_threads' clause. Stmt *NumThreads = nullptr; /// Set condition. void setNumThreads(Expr *NThreads) { NumThreads = NThreads; } public: /// Build 'num_threads' clause with condition \a NumThreads. /// /// \param NumThreads Number of threads for the construct. /// \param HelperNumThreads Helper Number of threads for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumThreadsClause(Expr *NumThreads, Stmt *HelperNumThreads, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_threads, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumThreads(NumThreads) { setPreInitStmt(HelperNumThreads, CaptureRegion); } /// Build an empty clause. OMPNumThreadsClause() : OMPClause(llvm::omp::OMPC_num_threads, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getNumThreads() const { return cast_or_null<Expr>(NumThreads); } child_range children() { return child_range(&NumThreads, &NumThreads + 1); } const_child_range children() const { return const_child_range(&NumThreads, &NumThreads + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_threads; } }; /// This represents 'safelen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd safelen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'safelen' /// with single expression '4'. /// If the safelen clause is used then no two iterations executed /// concurrently with SIMD instructions can have a greater distance /// in the logical iteration space than its value. The parameter of /// the safelen clause must be a constant positive integer expression. class OMPSafelenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Safelen = nullptr; /// Set safelen. void setSafelen(Expr *Len) { Safelen = Len; } public: /// Build 'safelen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSafelenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_safelen, StartLoc, EndLoc), LParenLoc(LParenLoc), Safelen(Len) {} /// Build an empty clause. explicit OMPSafelenClause() : OMPClause(llvm::omp::OMPC_safelen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSafelen() const { return cast_or_null<Expr>(Safelen); } child_range children() { return child_range(&Safelen, &Safelen + 1); } const_child_range children() const { return const_child_range(&Safelen, &Safelen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_safelen; } }; /// This represents 'simdlen' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd simdlen(4) /// \endcode /// In this example directive '#pragma omp simd' has clause 'simdlen' /// with single expression '4'. /// If the 'simdlen' clause is used then it specifies the preferred number of /// iterations to be executed concurrently. The parameter of the 'simdlen' /// clause must be a constant positive integer expression. class OMPSimdlenClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Simdlen = nullptr; /// Set simdlen. void setSimdlen(Expr *Len) { Simdlen = Len; } public: /// Build 'simdlen' clause. /// /// \param Len Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSimdlenClause(Expr *Len, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simdlen, StartLoc, EndLoc), LParenLoc(LParenLoc), Simdlen(Len) {} /// Build an empty clause. explicit OMPSimdlenClause() : OMPClause(llvm::omp::OMPC_simdlen, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getSimdlen() const { return cast_or_null<Expr>(Simdlen); } child_range children() { return child_range(&Simdlen, &Simdlen + 1); } const_child_range children() const { return const_child_range(&Simdlen, &Simdlen + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simdlen; } }; /// This represents the 'sizes' clause in the '#pragma omp tile' directive. /// /// \code /// #pragma omp tile sizes(5,5) /// for (int i = 0; i < 64; ++i) /// for (int j = 0; j < 64; ++j) /// \endcode class OMPSizesClause final : public OMPClause, private llvm::TrailingObjects<OMPSizesClause, Expr *> { friend class OMPClauseReader; friend class llvm::TrailingObjects<OMPSizesClause, Expr *>; /// Location of '('. SourceLocation LParenLoc; /// Number of tile sizes in the clause. unsigned NumSizes; /// Build an empty clause. explicit OMPSizesClause(int NumSizes) : OMPClause(llvm::omp::OMPC_sizes, SourceLocation(), SourceLocation()), NumSizes(NumSizes) {} public: /// Build a 'sizes' AST node. /// /// \param C Context of the AST. /// \param StartLoc Location of the 'sizes' identifier. /// \param LParenLoc Location of '('. /// \param EndLoc Location of ')'. /// \param Sizes Content of the clause. static OMPSizesClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> Sizes); /// Build an empty 'sizes' AST node for deserialization. /// /// \param C Context of the AST. /// \param NumSizes Number of items in the clause. static OMPSizesClause *CreateEmpty(const ASTContext &C, unsigned NumSizes); /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns the number of list items. unsigned getNumSizes() const { return NumSizes; } /// Returns the tile size expressions. MutableArrayRef<Expr *> getSizesRefs() { return MutableArrayRef<Expr *>(static_cast<OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>(), NumSizes); } ArrayRef<Expr *> getSizesRefs() const { return ArrayRef<Expr *>(static_cast<const OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>(), NumSizes); } /// Sets the tile size expressions. void setSizesRefs(ArrayRef<Expr *> VL) { assert(VL.size() == NumSizes); std::copy(VL.begin(), VL.end(), static_cast<OMPSizesClause *>(this) ->template getTrailingObjects<Expr *>()); } child_range children() { MutableArrayRef<Expr *> Sizes = getSizesRefs(); return child_range(reinterpret_cast<Stmt **>(Sizes.begin()), reinterpret_cast<Stmt **>(Sizes.end())); } const_child_range children() const { ArrayRef<Expr *> Sizes = getSizesRefs(); return const_child_range(reinterpret_cast<Stmt *const *>(Sizes.begin()), reinterpret_cast<Stmt *const *>(Sizes.end())); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_sizes; } }; /// Representation of the 'full' clause of the '#pragma omp unroll' directive. /// /// \code /// #pragma omp unroll full /// for (int i = 0; i < 64; ++i) /// \endcode class OMPFullClause final : public OMPClause { friend class OMPClauseReader; /// Build an empty clause. explicit OMPFullClause() : OMPClause(llvm::omp::OMPC_full, {}, {}) {} public: /// Build an AST node for a 'full' clause. /// /// \param C Context of the AST. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. static OMPFullClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Build an empty 'full' AST node for deserialization. /// /// \param C Context of the AST. static OMPFullClause *CreateEmpty(const ASTContext &C); child_range children() { return {child_iterator(), child_iterator()}; } const_child_range children() const { return {const_child_iterator(), const_child_iterator()}; } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_full; } }; /// Representation of the 'partial' clause of the '#pragma omp unroll' /// directive. /// /// \code /// #pragma omp unroll partial(4) /// for (int i = start; i < end; ++i) /// \endcode class OMPPartialClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Optional argument to the clause (unroll factor). Stmt *Factor; /// Build an empty clause. explicit OMPPartialClause() : OMPClause(llvm::omp::OMPC_partial, {}, {}) {} /// Set the unroll factor. void setFactor(Expr *E) { Factor = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build an AST node for a 'partial' clause. /// /// \param C Context of the AST. /// \param StartLoc Location of the 'partial' identifier. /// \param LParenLoc Location of '('. /// \param EndLoc Location of ')'. /// \param Factor Clause argument. static OMPPartialClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *Factor); /// Build an empty 'partial' AST node for deserialization. /// /// \param C Context of the AST. static OMPPartialClause *CreateEmpty(const ASTContext &C); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns the argument of the clause or nullptr if not set. Expr *getFactor() const { return cast_or_null<Expr>(Factor); } child_range children() { return child_range(&Factor, &Factor + 1); } const_child_range children() const { return const_child_range(&Factor, &Factor + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_partial; } }; /// This represents 'collapse' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp simd collapse(3) /// \endcode /// In this example directive '#pragma omp simd' has clause 'collapse' /// with single expression '3'. /// The parameter must be a constant positive integer expression, it specifies /// the number of nested loops that should be collapsed into a single iteration /// space. class OMPCollapseClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'collapse' clause. /// /// \param Num Expression associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPCollapseClause(Expr *Num, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_collapse, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num) {} /// Build an empty clause. explicit OMPCollapseClause() : OMPClause(llvm::omp::OMPC_collapse, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_collapse; } }; /// This represents 'default' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp parallel default(shared) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'default' /// clause with kind 'shared'. class OMPDefaultClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. llvm::omp::DefaultKind Kind = llvm::omp::OMP_DEFAULT_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clauses. /// /// \param K Argument of clause. void setDefaultKind(llvm::omp::DefaultKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setDefaultKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'default' clause with argument \a A ('none' or 'shared'). /// /// \param A Argument of the clause ('none' or 'shared'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDefaultClause(llvm::omp::DefaultKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_default, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPDefaultClause() : OMPClause(llvm::omp::OMPC_default, SourceLocation(), SourceLocation()) { } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::DefaultKind getDefaultKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getDefaultKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_default; } }; /// This represents 'proc_bind' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp parallel proc_bind(master) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'proc_bind' /// clause with kind 'master'. class OMPProcBindClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'proc_bind' clause. llvm::omp::ProcBindKind Kind = llvm::omp::OMP_PROC_BIND_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setProcBindKind(llvm::omp::ProcBindKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setProcBindKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'proc_bind' clause with argument \a A ('master', 'close' or /// 'spread'). /// /// \param A Argument of the clause ('master', 'close' or 'spread'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPProcBindClause(llvm::omp::ProcBindKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_proc_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPProcBindClause() : OMPClause(llvm::omp::OMPC_proc_bind, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. llvm::omp::ProcBindKind getProcBindKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getProcBindKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_proc_bind; } }; /// This represents 'unified_address' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_address /// \endcode /// In this example directive '#pragma omp requires' has 'unified_address' /// clause. class OMPUnifiedAddressClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_address' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedAddressClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_address, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedAddressClause() : OMPClause(llvm::omp::OMPC_unified_address, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_address; } }; /// This represents 'unified_shared_memory' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires unified_shared_memory /// \endcode /// In this example directive '#pragma omp requires' has 'unified_shared_memory' /// clause. class OMPUnifiedSharedMemoryClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'unified_shared_memory' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUnifiedSharedMemoryClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_unified_shared_memory, StartLoc, EndLoc) {} /// Build an empty clause. OMPUnifiedSharedMemoryClause() : OMPClause(llvm::omp::OMPC_unified_shared_memory, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_unified_shared_memory; } }; /// This represents 'reverse_offload' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires reverse_offload /// \endcode /// In this example directive '#pragma omp requires' has 'reverse_offload' /// clause. class OMPReverseOffloadClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'reverse_offload' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReverseOffloadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_reverse_offload, StartLoc, EndLoc) {} /// Build an empty clause. OMPReverseOffloadClause() : OMPClause(llvm::omp::OMPC_reverse_offload, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reverse_offload; } }; /// This represents 'dynamic_allocators' clause in the '#pragma omp requires' /// directive. /// /// \code /// #pragma omp requires dynamic_allocators /// \endcode /// In this example directive '#pragma omp requires' has 'dynamic_allocators' /// clause. class OMPDynamicAllocatorsClause final : public OMPClause { public: friend class OMPClauseReader; /// Build 'dynamic_allocators' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDynamicAllocatorsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_dynamic_allocators, StartLoc, EndLoc) {} /// Build an empty clause. OMPDynamicAllocatorsClause() : OMPClause(llvm::omp::OMPC_dynamic_allocators, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dynamic_allocators; } }; /// This represents 'atomic_default_mem_order' clause in the '#pragma omp /// requires' directive. /// /// \code /// #pragma omp requires atomic_default_mem_order(seq_cst) /// \endcode /// In this example directive '#pragma omp requires' has simple /// atomic_default_mem_order' clause with kind 'seq_cst'. class OMPAtomicDefaultMemOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '(' SourceLocation LParenLoc; /// A kind of the 'atomic_default_mem_order' clause. OpenMPAtomicDefaultMemOrderClauseKind Kind = OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Kind of clause. void setAtomicDefaultMemOrderKind(OpenMPAtomicDefaultMemOrderClauseKind K) { Kind = K; } /// Set clause kind location. /// /// \param KLoc Kind location. void setAtomicDefaultMemOrderKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'atomic_default_mem_order' clause with argument \a A ('seq_cst', /// 'acq_rel' or 'relaxed'). /// /// \param A Argument of the clause ('seq_cst', 'acq_rel' or 'relaxed'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPAtomicDefaultMemOrderClause(OpenMPAtomicDefaultMemOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPAtomicDefaultMemOrderClause() : OMPClause(llvm::omp::OMPC_atomic_default_mem_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the locaiton of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPAtomicDefaultMemOrderClauseKind getAtomicDefaultMemOrderKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getAtomicDefaultMemOrderKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_atomic_default_mem_order; } }; /// This represents 'schedule' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for schedule(static, 3) /// \endcode /// In this example directive '#pragma omp for' has 'schedule' clause with /// arguments 'static' and '3'. class OMPScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPScheduleClauseKind Kind = OMPC_SCHEDULE_unknown; /// Modifiers for 'schedule' clause. enum {FIRST, SECOND, NUM_MODIFIERS}; OpenMPScheduleClauseModifier Modifiers[NUM_MODIFIERS]; /// Locations of modifiers. SourceLocation ModifiersLoc[NUM_MODIFIERS]; /// Start location of the schedule ind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setScheduleKind(OpenMPScheduleClauseKind K) { Kind = K; } /// Set the first schedule modifier. /// /// \param M Schedule modifier. void setFirstScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[FIRST] = M; } /// Set the second schedule modifier. /// /// \param M Schedule modifier. void setSecondScheduleModifier(OpenMPScheduleClauseModifier M) { Modifiers[SECOND] = M; } /// Set location of the first schedule modifier. void setFirstScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[FIRST] = Loc; } /// Set location of the second schedule modifier. void setSecondScheduleModifierLoc(SourceLocation Loc) { ModifiersLoc[SECOND] = Loc; } /// Set schedule modifier location. /// /// \param M Schedule modifier location. void setScheduleModifer(OpenMPScheduleClauseModifier M) { if (Modifiers[FIRST] == OMPC_SCHEDULE_MODIFIER_unknown) Modifiers[FIRST] = M; else { assert(Modifiers[SECOND] == OMPC_SCHEDULE_MODIFIER_unknown); Modifiers[SECOND] = M; } } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'schedule' clause with schedule kind \a Kind and chunk size /// expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind Schedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. /// \param M1 The first modifier applied to 'schedule' clause. /// \param M1Loc Location of the first modifier /// \param M2 The second modifier applied to 'schedule' clause. /// \param M2Loc Location of the second modifier OMPScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize, OpenMPScheduleClauseModifier M1, SourceLocation M1Loc, OpenMPScheduleClauseModifier M2, SourceLocation M2Loc) : OMPClause(llvm::omp::OMPC_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); Modifiers[FIRST] = M1; Modifiers[SECOND] = M2; ModifiersLoc[FIRST] = M1Loc; ModifiersLoc[SECOND] = M2Loc; } /// Build an empty clause. explicit OMPScheduleClause() : OMPClause(llvm::omp::OMPC_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) { Modifiers[FIRST] = OMPC_SCHEDULE_MODIFIER_unknown; Modifiers[SECOND] = OMPC_SCHEDULE_MODIFIER_unknown; } /// Get kind of the clause. OpenMPScheduleClauseKind getScheduleKind() const { return Kind; } /// Get the first modifier of the clause. OpenMPScheduleClauseModifier getFirstScheduleModifier() const { return Modifiers[FIRST]; } /// Get the second modifier of the clause. OpenMPScheduleClauseModifier getSecondScheduleModifier() const { return Modifiers[SECOND]; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getScheduleKindLoc() { return KindLoc; } /// Get the first modifier location. SourceLocation getFirstScheduleModifierLoc() const { return ModifiersLoc[FIRST]; } /// Get the second modifier location. SourceLocation getSecondScheduleModifierLoc() const { return ModifiersLoc[SECOND]; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_schedule; } }; /// This represents 'ordered' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for ordered (2) /// \endcode /// In this example directive '#pragma omp for' has 'ordered' clause with /// parameter 2. class OMPOrderedClause final : public OMPClause, private llvm::TrailingObjects<OMPOrderedClause, Expr *> { friend class OMPClauseReader; friend TrailingObjects; /// Location of '('. SourceLocation LParenLoc; /// Number of for-loops. Stmt *NumForLoops = nullptr; /// Real number of loops. unsigned NumberOfLoops = 0; /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderedClause(Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_ordered, StartLoc, EndLoc), LParenLoc(LParenLoc), NumForLoops(Num), NumberOfLoops(NumLoops) {} /// Build an empty clause. explicit OMPOrderedClause(unsigned NumLoops) : OMPClause(llvm::omp::OMPC_ordered, SourceLocation(), SourceLocation()), NumberOfLoops(NumLoops) {} /// Set the number of associated for-loops. void setNumForLoops(Expr *Num) { NumForLoops = Num; } public: /// Build 'ordered' clause. /// /// \param Num Expression, possibly associated with this clause. /// \param NumLoops Number of loops, associated with this clause. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. static OMPOrderedClause *Create(const ASTContext &C, Expr *Num, unsigned NumLoops, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Build an empty clause. static OMPOrderedClause* CreateEmpty(const ASTContext &C, unsigned NumLoops); /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return the number of associated for-loops. Expr *getNumForLoops() const { return cast_or_null<Expr>(NumForLoops); } /// Set number of iterations for the specified loop. void setLoopNumIterations(unsigned NumLoop, Expr *NumIterations); /// Get number of iterations for all the loops. ArrayRef<Expr *> getLoopNumIterations() const; /// Set loop counter for the specified loop. void setLoopCounter(unsigned NumLoop, Expr *Counter); /// Get loops counter for the specified loop. Expr *getLoopCounter(unsigned NumLoop); const Expr *getLoopCounter(unsigned NumLoop) const; child_range children() { return child_range(&NumForLoops, &NumForLoops + 1); } const_child_range children() const { return const_child_range(&NumForLoops, &NumForLoops + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_ordered; } }; /// This represents 'nowait' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp for nowait /// \endcode /// In this example directive '#pragma omp for' has 'nowait' clause. class OMPNowaitClause : public OMPClause { public: /// Build 'nowait' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNowaitClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nowait, StartLoc, EndLoc) {} /// Build an empty clause. OMPNowaitClause() : OMPClause(llvm::omp::OMPC_nowait, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nowait; } }; /// This represents 'untied' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp task untied /// \endcode /// In this example directive '#pragma omp task' has 'untied' clause. class OMPUntiedClause : public OMPClause { public: /// Build 'untied' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUntiedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_untied, StartLoc, EndLoc) {} /// Build an empty clause. OMPUntiedClause() : OMPClause(llvm::omp::OMPC_untied, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_untied; } }; /// This represents 'mergeable' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task mergeable /// \endcode /// In this example directive '#pragma omp task' has 'mergeable' clause. class OMPMergeableClause : public OMPClause { public: /// Build 'mergeable' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPMergeableClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_mergeable, StartLoc, EndLoc) {} /// Build an empty clause. OMPMergeableClause() : OMPClause(llvm::omp::OMPC_mergeable, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_mergeable; } }; /// This represents 'read' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic read /// \endcode /// In this example directive '#pragma omp atomic' has 'read' clause. class OMPReadClause : public OMPClause { public: /// Build 'read' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReadClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_read, StartLoc, EndLoc) {} /// Build an empty clause. OMPReadClause() : OMPClause(llvm::omp::OMPC_read, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_read; } }; /// This represents 'write' clause in the '#pragma omp atomic' directive. /// /// \code /// #pragma omp atomic write /// \endcode /// In this example directive '#pragma omp atomic' has 'write' clause. class OMPWriteClause : public OMPClause { public: /// Build 'write' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPWriteClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_write, StartLoc, EndLoc) {} /// Build an empty clause. OMPWriteClause() : OMPClause(llvm::omp::OMPC_write, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_write; } }; /// This represents 'update' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic update /// \endcode /// In this example directive '#pragma omp atomic' has 'update' clause. /// Also, this class represents 'update' clause in '#pragma omp depobj' /// directive. /// /// \code /// #pragma omp depobj(a) update(in) /// \endcode /// In this example directive '#pragma omp depobj' has 'update' clause with 'in' /// dependence kind. class OMPUpdateClause final : public OMPClause, private llvm::TrailingObjects<OMPUpdateClause, SourceLocation, OpenMPDependClauseKind> { friend class OMPClauseReader; friend TrailingObjects; /// true if extended version of the clause for 'depobj' directive. bool IsExtended = false; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<SourceLocation>) const { // 2 locations: for '(' and argument location. return IsExtended ? 2 : 0; } /// Sets the location of '(' in clause for 'depobj' directive. void setLParenLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<SourceLocation>() = Loc; } /// Sets the location of '(' in clause for 'depobj' directive. void setArgumentLoc(SourceLocation Loc) { assert(IsExtended && "Expected extended clause."); *std::next(getTrailingObjects<SourceLocation>(), 1) = Loc; } /// Sets the dependence kind for the clause for 'depobj' directive. void setDependencyKind(OpenMPDependClauseKind DK) { assert(IsExtended && "Expected extended clause."); *getTrailingObjects<OpenMPDependClauseKind>() = DK; } /// Build 'update' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPUpdateClause(SourceLocation StartLoc, SourceLocation EndLoc, bool IsExtended) : OMPClause(llvm::omp::OMPC_update, StartLoc, EndLoc), IsExtended(IsExtended) {} /// Build an empty clause. OMPUpdateClause(bool IsExtended) : OMPClause(llvm::omp::OMPC_update, SourceLocation(), SourceLocation()), IsExtended(IsExtended) {} public: /// Creates clause for 'atomic' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc); /// Creates clause for 'depobj' directive. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ArgumentLoc Location of the argument. /// \param DK Dependence kind. /// \param EndLoc Ending location of the clause. static OMPUpdateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ArgumentLoc, OpenMPDependClauseKind DK, SourceLocation EndLoc); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param IsExtended true if extended clause for 'depobj' directive must be /// created. static OMPUpdateClause *CreateEmpty(const ASTContext &C, bool IsExtended); /// Checks if the clause is the extended clauses for 'depobj' directive. bool isExtended() const { return IsExtended; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } /// Gets the location of '(' in clause for 'depobj' directive. SourceLocation getLParenLoc() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<SourceLocation>(); } /// Gets the location of argument in clause for 'depobj' directive. SourceLocation getArgumentLoc() const { assert(IsExtended && "Expected extended clause."); return *std::next(getTrailingObjects<SourceLocation>(), 1); } /// Gets the dependence kind in clause for 'depobj' directive. OpenMPDependClauseKind getDependencyKind() const { assert(IsExtended && "Expected extended clause."); return *getTrailingObjects<OpenMPDependClauseKind>(); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_update; } }; /// This represents 'capture' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic capture /// \endcode /// In this example directive '#pragma omp atomic' has 'capture' clause. class OMPCaptureClause : public OMPClause { public: /// Build 'capture' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPCaptureClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_capture, StartLoc, EndLoc) {} /// Build an empty clause. OMPCaptureClause() : OMPClause(llvm::omp::OMPC_capture, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_capture; } }; /// This represents 'compare' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic compare /// \endcode /// In this example directive '#pragma omp atomic' has 'compare' clause. class OMPCompareClause final : public OMPClause { public: /// Build 'compare' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPCompareClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_compare, StartLoc, EndLoc) {} /// Build an empty clause. OMPCompareClause() : OMPClause(llvm::omp::OMPC_compare, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_compare; } }; /// This represents 'seq_cst' clause in the '#pragma omp atomic' /// directive. /// /// \code /// #pragma omp atomic seq_cst /// \endcode /// In this example directive '#pragma omp atomic' has 'seq_cst' clause. class OMPSeqCstClause : public OMPClause { public: /// Build 'seq_cst' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSeqCstClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_seq_cst, StartLoc, EndLoc) {} /// Build an empty clause. OMPSeqCstClause() : OMPClause(llvm::omp::OMPC_seq_cst, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_seq_cst; } }; /// This represents 'acq_rel' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acq_rel /// \endcode /// In this example directive '#pragma omp flush' has 'acq_rel' clause. class OMPAcqRelClause final : public OMPClause { public: /// Build 'ack_rel' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcqRelClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acq_rel, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcqRelClause() : OMPClause(llvm::omp::OMPC_acq_rel, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acq_rel; } }; /// This represents 'acquire' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush acquire /// \endcode /// In this example directive '#pragma omp flush' has 'acquire' clause. class OMPAcquireClause final : public OMPClause { public: /// Build 'acquire' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPAcquireClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_acquire, StartLoc, EndLoc) {} /// Build an empty clause. OMPAcquireClause() : OMPClause(llvm::omp::OMPC_acquire, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_acquire; } }; /// This represents 'release' clause in the '#pragma omp atomic|flush' /// directives. /// /// \code /// #pragma omp flush release /// \endcode /// In this example directive '#pragma omp flush' has 'release' clause. class OMPReleaseClause final : public OMPClause { public: /// Build 'release' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPReleaseClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_release, StartLoc, EndLoc) {} /// Build an empty clause. OMPReleaseClause() : OMPClause(llvm::omp::OMPC_release, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_release; } }; /// This represents 'relaxed' clause in the '#pragma omp atomic' /// directives. /// /// \code /// #pragma omp atomic relaxed /// \endcode /// In this example directive '#pragma omp atomic' has 'relaxed' clause. class OMPRelaxedClause final : public OMPClause { public: /// Build 'relaxed' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPRelaxedClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_relaxed, StartLoc, EndLoc) {} /// Build an empty clause. OMPRelaxedClause() : OMPClause(llvm::omp::OMPC_relaxed, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_relaxed; } }; /// This represents clause 'private' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel private(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'private' /// with the variables 'a' and 'b'. class OMPPrivateClause final : public OMPVarListClause<OMPPrivateClause>, private llvm::TrailingObjects<OMPPrivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPPrivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPPrivateClause(unsigned N) : OMPVarListClause<OMPPrivateClause>(llvm::omp::OMPC_private, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PrivateVL List of references to private copies with initializers. static OMPPrivateClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPPrivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPPrivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_private; } }; /// This represents clause 'firstprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel firstprivate(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'firstprivate' /// with the variables 'a' and 'b'. class OMPFirstprivateClause final : public OMPVarListClause<OMPFirstprivateClause>, public OMPClauseWithPreInit, private llvm::TrailingObjects<OMPFirstprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFirstprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFirstprivateClause>(llvm::omp::OMPC_firstprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPreInit(this) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFirstprivateClause(unsigned N) : OMPVarListClause<OMPFirstprivateClause>( llvm::omp::OMPC_firstprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPreInit(this) {} /// Sets the list of references to private copies with initializers for /// new private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for /// new private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new /// private variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new /// private variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. /// \param PrivateVL List of references to private copies with initializers. /// \param InitVL List of references to auto generated variables used for /// initialization of a single array element. Used if firstprivate variable is /// of array type. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. static OMPFirstprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PrivateVL, ArrayRef<Expr *> InitVL, Stmt *PreInit); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFirstprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPFirstprivateClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_firstprivate; } }; /// This represents clause 'lastprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd lastprivate(a,b) /// \endcode /// In this example directive '#pragma omp simd' has clause 'lastprivate' /// with the variables 'a' and 'b'. class OMPLastprivateClause final : public OMPVarListClause<OMPLastprivateClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLastprivateClause, Expr *> { // There are 4 additional tail-allocated arrays at the end of the class: // 1. Contains list of pseudo variables with the default initialization for // each non-firstprivate variables. Used in codegen for initialization of // lastprivate copies. // 2. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents private variables // (for arrays, single array element). // 3. List of helper expressions for proper generation of assignment operation // required for lastprivate clause. This list represents original variables // (for arrays, single array element). // 4. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of final assignment performed by the // lastprivate clause. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Optional lastprivate kind, e.g. 'conditional', if specified by user. OpenMPLastprivateModifier LPKind; /// Optional location of the lasptrivate kind, if specified by user. SourceLocation LPKindLoc; /// Optional colon location, if specified by user. SourceLocation ColonLoc; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPLastprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, unsigned N) : OMPVarListClause<OMPLastprivateClause>(llvm::omp::OMPC_lastprivate, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), LPKind(LPKind), LPKindLoc(LPKindLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPLastprivateClause(unsigned N) : OMPVarListClause<OMPLastprivateClause>( llvm::omp::OMPC_lastprivate, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Get the list of helper expressions for initialization of private /// copies for lastprivate variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent original variables (for arrays, single /// array element) in the final assignment statement performed by the /// lastprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign private copy of the variable to original variable. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } /// Sets lastprivate kind. void setKind(OpenMPLastprivateModifier Kind) { LPKind = Kind; } /// Sets location of the lastprivate kind. void setKindLoc(SourceLocation Loc) { LPKindLoc = Loc; } /// Sets colon symbol location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// private variables (for arrays, single array element). /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for lastprivate clause. This list represents /// original variables (for arrays, single array element). /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// lastprivate clause. /// \param LPKind Lastprivate kind, e.g. 'conditional'. /// \param LPKindLoc Location of the lastprivate kind. /// \param ColonLoc Location of the ':' symbol if lastprivate kind is used. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLastprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps, OpenMPLastprivateModifier LPKind, SourceLocation LPKindLoc, SourceLocation ColonLoc, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPLastprivateClause *CreateEmpty(const ASTContext &C, unsigned N); /// Lastprivate kind. OpenMPLastprivateModifier getKind() const { return LPKind; } /// Returns the location of the lastprivate kind. SourceLocation getKindLoc() const { return LPKindLoc; } /// Returns the location of the ':' symbol, if any. SourceLocation getColonLoc() const { return ColonLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; /// Set list of helper expressions, required for generation of private /// copies of original lastprivate variables. void setPrivateCopies(ArrayRef<Expr *> PrivateCopies); helper_expr_const_range private_copies() const { return helper_expr_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_range private_copies() { return helper_expr_range(getPrivateCopies().begin(), getPrivateCopies().end()); } helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLastprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_lastprivate; } }; /// This represents clause 'shared' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel shared(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'shared' /// with the variables 'a' and 'b'. class OMPSharedClause final : public OMPVarListClause<OMPSharedClause>, private llvm::TrailingObjects<OMPSharedClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPSharedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPSharedClause(unsigned N) : OMPVarListClause<OMPSharedClause>(llvm::omp::OMPC_shared, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPSharedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPSharedClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPSharedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_shared; } }; /// This represents clause 'reduction' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp parallel reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'reduction' /// with operator '+' and the variables 'a' and 'b'. class OMPReductionClause final : public OMPVarListClause<OMPReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Reduction modifier. OpenMPReductionClauseModifier Modifier = OMPC_REDUCTION_unknown; /// Reduction modifier location. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPReductionClause(unsigned N) : OMPVarListClause<OMPReductionClause>(llvm::omp::OMPC_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets reduction modifier. void setModifier(OpenMPReductionClauseModifier M) { Modifier = M; } /// Sets location of the modifier. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent private copy of the reduction /// variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent LHS expression in the final /// reduction expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent RHS expression in the final /// reduction expression performed by the reduction clause. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } /// Set list of helper copy operations for inscan reductions. /// The form is: Temps[i] = LHS[i]; void setInscanCopyOps(ArrayRef<Expr *> Ops); /// Get the list of helper inscan copy operations. MutableArrayRef<Expr *> getInscanCopyOps() { return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyOps() const { return llvm::makeArrayRef(getReductionOps().end(), varlist_size()); } /// Set list of helper temp vars for inscan copy array operations. void setInscanCopyArrayTemps(ArrayRef<Expr *> CopyArrayTemps); /// Get the list of helper inscan copy temps. MutableArrayRef<Expr *> getInscanCopyArrayTemps() { return MutableArrayRef<Expr *>(getInscanCopyOps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyArrayTemps() const { return llvm::makeArrayRef(getInscanCopyOps().end(), varlist_size()); } /// Set list of helper temp elements vars for inscan copy array operations. void setInscanCopyArrayElems(ArrayRef<Expr *> CopyArrayElems); /// Get the list of helper inscan copy temps. MutableArrayRef<Expr *> getInscanCopyArrayElems() { return MutableArrayRef<Expr *>(getInscanCopyArrayTemps().end(), varlist_size()); } ArrayRef<const Expr *> getInscanCopyArrayElems() const { return llvm::makeArrayRef(getInscanCopyArrayTemps().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param CopyOps List of copy operations for inscan reductions: /// \code /// TempExprs = LHSExprs; /// \endcode /// \param CopyArrayTemps Temp arrays for prefix sums. /// \param CopyArrayElems Temp arrays for prefix sums. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, OpenMPReductionClauseModifier Modifier, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> CopyOps, ArrayRef<Expr *> CopyArrayTemps, ArrayRef<Expr *> CopyArrayElems, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// \param Modifier Reduction modifier. static OMPReductionClause * CreateEmpty(const ASTContext &C, unsigned N, OpenMPReductionClauseModifier Modifier); /// Returns modifier. OpenMPReductionClauseModifier getModifier() const { return Modifier; } /// Returns modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_const_range copy_ops() const { return helper_expr_const_range(getInscanCopyOps().begin(), getInscanCopyOps().end()); } helper_expr_range copy_ops() { return helper_expr_range(getInscanCopyOps().begin(), getInscanCopyOps().end()); } helper_expr_const_range copy_array_temps() const { return helper_expr_const_range(getInscanCopyArrayTemps().begin(), getInscanCopyArrayTemps().end()); } helper_expr_range copy_array_temps() { return helper_expr_range(getInscanCopyArrayTemps().begin(), getInscanCopyArrayTemps().end()); } helper_expr_const_range copy_array_elems() const { return helper_expr_const_range(getInscanCopyArrayElems().begin(), getInscanCopyArrayElems().end()); } helper_expr_range copy_array_elems() { return helper_expr_range(getInscanCopyArrayElems().begin(), getInscanCopyArrayElems().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range used_children() const { auto Children = const_cast<OMPReductionClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_reduction; } }; /// This represents clause 'task_reduction' in the '#pragma omp taskgroup' /// directives. /// /// \code /// #pragma omp taskgroup task_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp taskgroup' has clause /// 'task_reduction' with operator '+' and the variables 'a' and 'b'. class OMPTaskReductionClause final : public OMPVarListClause<OMPTaskReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPTaskReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPTaskReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPTaskReductionClause(unsigned N) : OMPVarListClause<OMPTaskReductionClause>( llvm::omp::OMPC_task_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPTaskReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPTaskReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPTaskReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_task_reduction; } }; /// This represents clause 'in_reduction' in the '#pragma omp task' directives. /// /// \code /// #pragma omp task in_reduction(+:a,b) /// \endcode /// In this example directive '#pragma omp task' has clause 'in_reduction' with /// operator '+' and the variables 'a' and 'b'. class OMPInReductionClause final : public OMPVarListClause<OMPInReductionClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPInReductionClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Nested name specifier for C++. NestedNameSpecifierLoc QualifierLoc; /// Name of custom operator. DeclarationNameInfo NameInfo; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param ColonLoc Location of ':'. /// \param N Number of the variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. OMPInReductionClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo) : OMPVarListClause<OMPInReductionClause>(llvm::omp::OMPC_in_reduction, StartLoc, LParenLoc, EndLoc, N), OMPClauseWithPostUpdate(this), ColonLoc(ColonLoc), QualifierLoc(QualifierLoc), NameInfo(NameInfo) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInReductionClause(unsigned N) : OMPVarListClause<OMPInReductionClause>( llvm::omp::OMPC_in_reduction, SourceLocation(), SourceLocation(), SourceLocation(), N), OMPClauseWithPostUpdate(this) {} /// Sets location of ':' symbol in clause. void setColonLoc(SourceLocation CL) { ColonLoc = CL; } /// Sets the name info for specified reduction identifier. void setNameInfo(DeclarationNameInfo DNI) { NameInfo = DNI; } /// Sets the nested name specifier. void setQualifierLoc(NestedNameSpecifierLoc NSL) { QualifierLoc = NSL; } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent private copy of the reduction variable. void setPrivates(ArrayRef<Expr *> Privates); /// Get the list of helper privates. MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent LHS expression in the final reduction /// expression performed by the reduction clause. void setLHSExprs(ArrayRef<Expr *> LHSExprs); /// Get the list of helper LHS expressions. MutableArrayRef<Expr *> getLHSExprs() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getLHSExprs() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the clause. /// These expressions represent RHS expression in the final reduction /// expression performed by the reduction clause. Also, variables in these /// expressions are used for proper initialization of reduction copies. void setRHSExprs(ArrayRef<Expr *> RHSExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getRHSExprs() { return MutableArrayRef<Expr *>(getLHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getRHSExprs() const { return llvm::makeArrayRef(getLHSExprs().end(), varlist_size()); } /// Set list of helper reduction expressions, required for proper /// codegen of the clause. These expressions are binary expressions or /// operator/custom reduction call that calculates new value from source /// helper expressions to destination helper expressions. void setReductionOps(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction expressions. MutableArrayRef<Expr *> getReductionOps() { return MutableArrayRef<Expr *>(getRHSExprs().end(), varlist_size()); } ArrayRef<const Expr *> getReductionOps() const { return llvm::makeArrayRef(getRHSExprs().end(), varlist_size()); } /// Set list of helper reduction taskgroup descriptors. void setTaskgroupDescriptors(ArrayRef<Expr *> ReductionOps); /// Get the list of helper reduction taskgroup descriptors. MutableArrayRef<Expr *> getTaskgroupDescriptors() { return MutableArrayRef<Expr *>(getReductionOps().end(), varlist_size()); } ArrayRef<const Expr *> getTaskgroupDescriptors() const { return llvm::makeArrayRef(getReductionOps().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL The variables in the clause. /// \param QualifierLoc The nested-name qualifier with location information /// \param NameInfo The full name info for reduction identifier. /// \param Privates List of helper expressions for proper generation of /// private copies. /// \param LHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// LHSs of the reduction expressions. /// \param RHSExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// RHSs of the reduction expressions. /// Also, variables in these expressions are used for proper initialization of /// reduction copies. /// \param ReductionOps List of helper expressions that represents reduction /// expressions: /// \code /// LHSExprs binop RHSExprs; /// operator binop(LHSExpr, RHSExpr); /// <CutomReduction>(LHSExpr, RHSExpr); /// \endcode /// Required for proper codegen of final reduction operation performed by the /// reduction clause. /// \param TaskgroupDescriptors List of helper taskgroup descriptors for /// corresponding items in parent taskgroup task_reduction clause. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPInReductionClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, ArrayRef<Expr *> Privates, ArrayRef<Expr *> LHSExprs, ArrayRef<Expr *> RHSExprs, ArrayRef<Expr *> ReductionOps, ArrayRef<Expr *> TaskgroupDescriptors, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInReductionClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets location of ':' symbol in clause. SourceLocation getColonLoc() const { return ColonLoc; } /// Gets the name info for specified reduction identifier. const DeclarationNameInfo &getNameInfo() const { return NameInfo; } /// Gets the nested name specifier. NestedNameSpecifierLoc getQualifierLoc() const { return QualifierLoc; } using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range privates() const { return helper_expr_const_range(getPrivates().begin(), getPrivates().end()); } helper_expr_range privates() { return helper_expr_range(getPrivates().begin(), getPrivates().end()); } helper_expr_const_range lhs_exprs() const { return helper_expr_const_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_range lhs_exprs() { return helper_expr_range(getLHSExprs().begin(), getLHSExprs().end()); } helper_expr_const_range rhs_exprs() const { return helper_expr_const_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_range rhs_exprs() { return helper_expr_range(getRHSExprs().begin(), getRHSExprs().end()); } helper_expr_const_range reduction_ops() const { return helper_expr_const_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_range reduction_ops() { return helper_expr_range(getReductionOps().begin(), getReductionOps().end()); } helper_expr_const_range taskgroup_descriptors() const { return helper_expr_const_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } helper_expr_range taskgroup_descriptors() { return helper_expr_range(getTaskgroupDescriptors().begin(), getTaskgroupDescriptors().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInReductionClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_in_reduction; } }; /// This represents clause 'linear' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd linear(a,b : 2) /// \endcode /// In this example directive '#pragma omp simd' has clause 'linear' /// with variables 'a', 'b' and linear step '2'. class OMPLinearClause final : public OMPVarListClause<OMPLinearClause>, public OMPClauseWithPostUpdate, private llvm::TrailingObjects<OMPLinearClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Modifier of 'linear' clause. OpenMPLinearClauseKind Modifier = OMPC_LINEAR_val; /// Location of linear modifier if any. SourceLocation ModifierLoc; /// Location of ':'. SourceLocation ColonLoc; /// Sets the linear step for clause. void setStep(Expr *Step) { *(getFinals().end()) = Step; } /// Sets the expression to calculate linear step for clause. void setCalcStep(Expr *CalcStep) { *(getFinals().end() + 1) = CalcStep; } /// Build 'linear' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPLinearClause(SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, StartLoc, LParenLoc, EndLoc, NumVars), OMPClauseWithPostUpdate(this), Modifier(Modifier), ModifierLoc(ModifierLoc), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPLinearClause(unsigned NumVars) : OMPVarListClause<OMPLinearClause>(llvm::omp::OMPC_linear, SourceLocation(), SourceLocation(), SourceLocation(), NumVars), OMPClauseWithPostUpdate(this) {} /// Gets the list of initial values for linear variables. /// /// There are NumVars expressions with initial values allocated after the /// varlist, they are followed by NumVars update expressions (used to update /// the linear variable's value on current iteration) and they are followed by /// NumVars final expressions (used to calculate the linear variable's /// value after the loop body). After these lists, there are 2 helper /// expressions - linear step and a helper to calculate it before the /// loop body (used when the linear step is not constant): /// /// { Vars[] /* in OMPVarListClause */; Privates[]; Inits[]; Updates[]; /// Finals[]; Step; CalcStep; } MutableArrayRef<Expr *> getPrivates() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivates() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivates().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivates().end(), varlist_size()); } /// Sets the list of update expressions for linear variables. MutableArrayRef<Expr *> getUpdates() { return MutableArrayRef<Expr *>(getInits().end(), varlist_size()); } ArrayRef<const Expr *> getUpdates() const { return llvm::makeArrayRef(getInits().end(), varlist_size()); } /// Sets the list of final update expressions for linear variables. MutableArrayRef<Expr *> getFinals() { return MutableArrayRef<Expr *>(getUpdates().end(), varlist_size()); } ArrayRef<const Expr *> getFinals() const { return llvm::makeArrayRef(getUpdates().end(), varlist_size()); } /// Gets the list of used expressions for linear variables. MutableArrayRef<Expr *> getUsedExprs() { return MutableArrayRef<Expr *>(getFinals().end() + 2, varlist_size() + 1); } ArrayRef<const Expr *> getUsedExprs() const { return llvm::makeArrayRef(getFinals().end() + 2, varlist_size() + 1); } /// Sets the list of the copies of original linear variables. /// \param PL List of expressions. void setPrivates(ArrayRef<Expr *> PL); /// Sets the list of the initial values for linear variables. /// \param IL List of expressions. void setInits(ArrayRef<Expr *> IL); public: /// Creates clause with a list of variables \a VL and a linear step /// \a Step. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param Modifier Modifier of 'linear' clause. /// \param ModifierLoc Modifier location. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param PL List of private copies of original variables. /// \param IL List of initial values for the variables. /// \param Step Linear step. /// \param CalcStep Calculation of the linear step. /// \param PreInit Statement that must be executed before entering the OpenMP /// region with this clause. /// \param PostUpdate Expression that must be executed after exit from the /// OpenMP region with this clause. static OMPLinearClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, OpenMPLinearClauseKind Modifier, SourceLocation ModifierLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> PL, ArrayRef<Expr *> IL, Expr *Step, Expr *CalcStep, Stmt *PreInit, Expr *PostUpdate); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPLinearClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Set modifier. void setModifier(OpenMPLinearClauseKind Kind) { Modifier = Kind; } /// Return modifier. OpenMPLinearClauseKind getModifier() const { return Modifier; } /// Set modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Return modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns linear step. Expr *getStep() { return *(getFinals().end()); } /// Returns linear step. const Expr *getStep() const { return *(getFinals().end()); } /// Returns expression to calculate linear step. Expr *getCalcStep() { return *(getFinals().end() + 1); } /// Returns expression to calculate linear step. const Expr *getCalcStep() const { return *(getFinals().end() + 1); } /// Sets the list of update expressions for linear variables. /// \param UL List of expressions. void setUpdates(ArrayRef<Expr *> UL); /// Sets the list of final update expressions for linear variables. /// \param FL List of expressions. void setFinals(ArrayRef<Expr *> FL); /// Sets the list of used expressions for the linear clause. void setUsedExprs(ArrayRef<Expr *> UE); using privates_iterator = MutableArrayRef<Expr *>::iterator; using privates_const_iterator = ArrayRef<const Expr *>::iterator; using privates_range = llvm::iterator_range<privates_iterator>; using privates_const_range = llvm::iterator_range<privates_const_iterator>; privates_range privates() { return privates_range(getPrivates().begin(), getPrivates().end()); } privates_const_range privates() const { return privates_const_range(getPrivates().begin(), getPrivates().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } using updates_iterator = MutableArrayRef<Expr *>::iterator; using updates_const_iterator = ArrayRef<const Expr *>::iterator; using updates_range = llvm::iterator_range<updates_iterator>; using updates_const_range = llvm::iterator_range<updates_const_iterator>; updates_range updates() { return updates_range(getUpdates().begin(), getUpdates().end()); } updates_const_range updates() const { return updates_const_range(getUpdates().begin(), getUpdates().end()); } using finals_iterator = MutableArrayRef<Expr *>::iterator; using finals_const_iterator = ArrayRef<const Expr *>::iterator; using finals_range = llvm::iterator_range<finals_iterator>; using finals_const_range = llvm::iterator_range<finals_const_iterator>; finals_range finals() { return finals_range(getFinals().begin(), getFinals().end()); } finals_const_range finals() const { return finals_const_range(getFinals().begin(), getFinals().end()); } using used_expressions_iterator = MutableArrayRef<Expr *>::iterator; using used_expressions_const_iterator = ArrayRef<const Expr *>::iterator; using used_expressions_range = llvm::iterator_range<used_expressions_iterator>; using used_expressions_const_range = llvm::iterator_range<used_expressions_const_iterator>; used_expressions_range used_expressions() { return finals_range(getUsedExprs().begin(), getUsedExprs().end()); } used_expressions_const_range used_expressions() const { return finals_const_range(getUsedExprs().begin(), getUsedExprs().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPLinearClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPLinearClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_linear; } }; /// This represents clause 'aligned' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp simd aligned(a,b : 8) /// \endcode /// In this example directive '#pragma omp simd' has clause 'aligned' /// with variables 'a', 'b' and alignment '8'. class OMPAlignedClause final : public OMPVarListClause<OMPAlignedClause>, private llvm::TrailingObjects<OMPAlignedClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':'. SourceLocation ColonLoc; /// Sets the alignment for clause. void setAlignment(Expr *A) { *varlist_end() = A; } /// Build 'aligned' clause with given number of variables \a NumVars. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param NumVars Number of variables. OMPAlignedClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, StartLoc, LParenLoc, EndLoc, NumVars), ColonLoc(ColonLoc) {} /// Build an empty clause. /// /// \param NumVars Number of variables. explicit OMPAlignedClause(unsigned NumVars) : OMPVarListClause<OMPAlignedClause>(llvm::omp::OMPC_aligned, SourceLocation(), SourceLocation(), SourceLocation(), NumVars) {} public: /// Creates clause with a list of variables \a VL and alignment \a A. /// /// \param C AST Context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param A Alignment. static OMPAlignedClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, Expr *A); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param NumVars Number of variables. static OMPAlignedClause *CreateEmpty(const ASTContext &C, unsigned NumVars); /// Sets the location of ':'. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Returns the location of ':'. SourceLocation getColonLoc() const { return ColonLoc; } /// Returns alignment. Expr *getAlignment() { return *varlist_end(); } /// Returns alignment. const Expr *getAlignment() const { return *varlist_end(); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPAlignedClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_aligned; } }; /// This represents clause 'copyin' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp parallel copyin(a,b) /// \endcode /// In this example directive '#pragma omp parallel' has clause 'copyin' /// with the variables 'a' and 'b'. class OMPCopyinClause final : public OMPVarListClause<OMPCopyinClause>, private llvm::TrailingObjects<OMPCopyinClause, Expr *> { // Class has 3 additional tail allocated arrays: // 1. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents sources. // 2. List of helper expressions for proper generation of assignment operation // required for copyin clause. This list represents destinations. // 3. List of helper expressions that represents assignment operation: // \code // DstExprs = SrcExprs; // \endcode // Required for proper codegen of propagation of master's thread values of // threadprivate variables to local instances of that variables in other // implicit threads. friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyinClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyinClause(unsigned N) : OMPVarListClause<OMPCopyinClause>(llvm::omp::OMPC_copyin, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyin clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyin clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyin clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of propagation of master's thread values of /// threadprivate variables to local instances of that variables in other /// implicit threads. static OMPCopyinClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyinClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyinClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyin; } }; /// This represents clause 'copyprivate' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp single copyprivate(a,b) /// \endcode /// In this example directive '#pragma omp single' has clause 'copyprivate' /// with the variables 'a' and 'b'. class OMPCopyprivateClause final : public OMPVarListClause<OMPCopyprivateClause>, private llvm::TrailingObjects<OMPCopyprivateClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPCopyprivateClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPCopyprivateClause>(llvm::omp::OMPC_copyprivate, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPCopyprivateClause(unsigned N) : OMPVarListClause<OMPCopyprivateClause>( llvm::omp::OMPC_copyprivate, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent source expression in the final /// assignment statement performed by the copyprivate clause. void setSourceExprs(ArrayRef<Expr *> SrcExprs); /// Get the list of helper source expressions. MutableArrayRef<Expr *> getSourceExprs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getSourceExprs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Set list of helper expressions, required for proper codegen of the /// clause. These expressions represent destination expression in the final /// assignment statement performed by the copyprivate clause. void setDestinationExprs(ArrayRef<Expr *> DstExprs); /// Get the list of helper destination expressions. MutableArrayRef<Expr *> getDestinationExprs() { return MutableArrayRef<Expr *>(getSourceExprs().end(), varlist_size()); } ArrayRef<const Expr *> getDestinationExprs() const { return llvm::makeArrayRef(getSourceExprs().end(), varlist_size()); } /// Set list of helper assignment expressions, required for proper /// codegen of the clause. These expressions are assignment expressions that /// assign source helper expressions to destination helper expressions /// correspondingly. void setAssignmentOps(ArrayRef<Expr *> AssignmentOps); /// Get the list of helper assignment expressions. MutableArrayRef<Expr *> getAssignmentOps() { return MutableArrayRef<Expr *>(getDestinationExprs().end(), varlist_size()); } ArrayRef<const Expr *> getAssignmentOps() const { return llvm::makeArrayRef(getDestinationExprs().end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. /// \param SrcExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// sources. /// \param DstExprs List of helper expressions for proper generation of /// assignment operation required for copyprivate clause. This list represents /// destinations. /// \param AssignmentOps List of helper expressions that represents assignment /// operation: /// \code /// DstExprs = SrcExprs; /// \endcode /// Required for proper codegen of final assignment performed by the /// copyprivate clause. static OMPCopyprivateClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL, ArrayRef<Expr *> SrcExprs, ArrayRef<Expr *> DstExprs, ArrayRef<Expr *> AssignmentOps); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPCopyprivateClause *CreateEmpty(const ASTContext &C, unsigned N); using helper_expr_iterator = MutableArrayRef<Expr *>::iterator; using helper_expr_const_iterator = ArrayRef<const Expr *>::iterator; using helper_expr_range = llvm::iterator_range<helper_expr_iterator>; using helper_expr_const_range = llvm::iterator_range<helper_expr_const_iterator>; helper_expr_const_range source_exprs() const { return helper_expr_const_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_range source_exprs() { return helper_expr_range(getSourceExprs().begin(), getSourceExprs().end()); } helper_expr_const_range destination_exprs() const { return helper_expr_const_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_range destination_exprs() { return helper_expr_range(getDestinationExprs().begin(), getDestinationExprs().end()); } helper_expr_const_range assignment_ops() const { return helper_expr_const_range(getAssignmentOps().begin(), getAssignmentOps().end()); } helper_expr_range assignment_ops() { return helper_expr_range(getAssignmentOps().begin(), getAssignmentOps().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPCopyprivateClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_copyprivate; } }; /// This represents implicit clause 'flush' for the '#pragma omp flush' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// flush' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp flush(a,b) /// \endcode /// In this example directive '#pragma omp flush' has implicit clause 'flush' /// with the variables 'a' and 'b'. class OMPFlushClause final : public OMPVarListClause<OMPFlushClause>, private llvm::TrailingObjects<OMPFlushClause, Expr *> { friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPFlushClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPFlushClause(unsigned N) : OMPVarListClause<OMPFlushClause>(llvm::omp::OMPC_flush, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPFlushClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPFlushClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFlushClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_flush; } }; /// This represents implicit clause 'depobj' for the '#pragma omp depobj' /// directive. /// This clause does not exist by itself, it can be only as a part of 'omp /// depobj' directive. This clause is introduced to keep the original structure /// of \a OMPExecutableDirective class and its derivatives and to use the /// existing infrastructure of clauses with the list of variables. /// /// \code /// #pragma omp depobj(a) destroy /// \endcode /// In this example directive '#pragma omp depobj' has implicit clause 'depobj' /// with the depobj 'a'. class OMPDepobjClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Chunk size. Expr *Depobj = nullptr; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDepobjClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_depobj, StartLoc, EndLoc), LParenLoc(LParenLoc) {} /// Build an empty clause. /// explicit OMPDepobjClause() : OMPClause(llvm::omp::OMPC_depobj, SourceLocation(), SourceLocation()) {} void setDepobj(Expr *E) { Depobj = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Creates clause. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Depobj depobj expression associated with the 'depobj' directive. static OMPDepobjClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *Depobj); /// Creates an empty clause. /// /// \param C AST context. static OMPDepobjClause *CreateEmpty(const ASTContext &C); /// Returns depobj expression associated with the clause. Expr *getDepobj() { return Depobj; } const Expr *getDepobj() const { return Depobj; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&Depobj), reinterpret_cast<Stmt **>(&Depobj) + 1); } const_child_range children() const { auto Children = const_cast<OMPDepobjClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depobj; } }; /// This represents implicit clause 'depend' for the '#pragma omp task' /// directive. /// /// \code /// #pragma omp task depend(in:a,b) /// \endcode /// In this example directive '#pragma omp task' with clause 'depend' with the /// variables 'a' and 'b' with dependency 'in'. class OMPDependClause final : public OMPVarListClause<OMPDependClause>, private llvm::TrailingObjects<OMPDependClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Dependency type (one of in, out, inout). OpenMPDependClauseKind DepKind = OMPC_DEPEND_unknown; /// Dependency type location. SourceLocation DepLoc; /// Colon location. SourceLocation ColonLoc; /// Number of loops, associated with the depend clause. unsigned NumLoops = 0; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. /// \param NumLoops Number of loops that is associated with this depend /// clause. OMPDependClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, StartLoc, LParenLoc, EndLoc, N), NumLoops(NumLoops) {} /// Build an empty clause. /// /// \param N Number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. explicit OMPDependClause(unsigned N, unsigned NumLoops) : OMPVarListClause<OMPDependClause>(llvm::omp::OMPC_depend, SourceLocation(), SourceLocation(), SourceLocation(), N), NumLoops(NumLoops) {} /// Set dependency kind. void setDependencyKind(OpenMPDependClauseKind K) { DepKind = K; } /// Set dependency kind and its location. void setDependencyLoc(SourceLocation Loc) { DepLoc = Loc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Sets optional dependency modifier. void setModifier(Expr *DepModifier); public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param DepKind Dependency type. /// \param DepLoc Location of the dependency type. /// \param ColonLoc Colon location. /// \param VL List of references to the variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, Expr *DepModifier, OpenMPDependClauseKind DepKind, SourceLocation DepLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VL, unsigned NumLoops); /// Creates an empty clause with \a N variables. /// /// \param C AST context. /// \param N The number of variables. /// \param NumLoops Number of loops that is associated with this depend /// clause. static OMPDependClause *CreateEmpty(const ASTContext &C, unsigned N, unsigned NumLoops); /// Get dependency type. OpenMPDependClauseKind getDependencyKind() const { return DepKind; } /// Return optional depend modifier. Expr *getModifier(); const Expr *getModifier() const { return const_cast<OMPDependClause *>(this)->getModifier(); } /// Get dependency type location. SourceLocation getDependencyLoc() const { return DepLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } /// Get number of loops associated with the clause. unsigned getNumLoops() const { return NumLoops; } /// Set the loop data for the depend clauses with 'sink|source' kind of /// dependency. void setLoopData(unsigned NumLoop, Expr *Cnt); /// Get the loop data. Expr *getLoopData(unsigned NumLoop); const Expr *getLoopData(unsigned NumLoop) const; child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPDependClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_depend; } }; /// This represents 'device' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp target device(a) /// \endcode /// In this example directive '#pragma omp target' has clause 'device' /// with single expression 'a'. class OMPDeviceClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Device clause modifier. OpenMPDeviceClauseModifier Modifier = OMPC_DEVICE_unknown; /// Location of the modifier. SourceLocation ModifierLoc; /// Device number. Stmt *Device = nullptr; /// Set the device number. /// /// \param E Device number. void setDevice(Expr *E) { Device = E; } /// Sets modifier. void setModifier(OpenMPDeviceClauseModifier M) { Modifier = M; } /// Setst modifier location. void setModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } public: /// Build 'device' clause. /// /// \param Modifier Clause modifier. /// \param E Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param ModifierLoc Modifier location. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDeviceClause(OpenMPDeviceClauseModifier Modifier, Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ModifierLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_device, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Modifier(Modifier), ModifierLoc(ModifierLoc), Device(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPDeviceClause() : OMPClause(llvm::omp::OMPC_device, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return device number. Expr *getDevice() { return cast<Expr>(Device); } /// Return device number. Expr *getDevice() const { return cast<Expr>(Device); } /// Gets modifier. OpenMPDeviceClauseModifier getModifier() const { return Modifier; } /// Gets modifier location. SourceLocation getModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(&Device, &Device + 1); } const_child_range children() const { return const_child_range(&Device, &Device + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_device; } }; /// This represents 'threads' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered threads /// \endcode /// In this example directive '#pragma omp ordered' has simple 'threads' clause. class OMPThreadsClause : public OMPClause { public: /// Build 'threads' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPThreadsClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_threads, StartLoc, EndLoc) {} /// Build an empty clause. OMPThreadsClause() : OMPClause(llvm::omp::OMPC_threads, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_threads; } }; /// This represents 'simd' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp ordered simd /// \endcode /// In this example directive '#pragma omp ordered' has simple 'simd' clause. class OMPSIMDClause : public OMPClause { public: /// Build 'simd' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPSIMDClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_simd, StartLoc, EndLoc) {} /// Build an empty clause. OMPSIMDClause() : OMPClause(llvm::omp::OMPC_simd, SourceLocation(), SourceLocation()) {} child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_simd; } }; /// Struct that defines common infrastructure to handle mappable /// expressions used in OpenMP clauses. class OMPClauseMappableExprCommon { public: /// Class that represents a component of a mappable expression. E.g. /// for an expression S.a, the first component is a declaration reference /// expression associated with 'S' and the second is a member expression /// associated with the field declaration 'a'. If the expression is an array /// subscript it may not have any associated declaration. In that case the /// associated declaration is set to nullptr. class MappableComponent { /// Pair of Expression and Non-contiguous pair associated with the /// component. llvm::PointerIntPair<Expr *, 1, bool> AssociatedExpressionNonContiguousPr; /// Declaration associated with the declaration. If the component does /// not have a declaration (e.g. array subscripts or section), this is set /// to nullptr. ValueDecl *AssociatedDeclaration = nullptr; public: explicit MappableComponent() = default; explicit MappableComponent(Expr *AssociatedExpression, ValueDecl *AssociatedDeclaration, bool IsNonContiguous) : AssociatedExpressionNonContiguousPr(AssociatedExpression, IsNonContiguous), AssociatedDeclaration( AssociatedDeclaration ? cast<ValueDecl>(AssociatedDeclaration->getCanonicalDecl()) : nullptr) {} Expr *getAssociatedExpression() const { return AssociatedExpressionNonContiguousPr.getPointer(); } bool isNonContiguous() const { return AssociatedExpressionNonContiguousPr.getInt(); } ValueDecl *getAssociatedDeclaration() const { return AssociatedDeclaration; } }; // List of components of an expression. This first one is the whole // expression and the last one is the base expression. using MappableExprComponentList = SmallVector<MappableComponent, 8>; using MappableExprComponentListRef = ArrayRef<MappableComponent>; // List of all component lists associated to the same base declaration. // E.g. if both 'S.a' and 'S.b' are a mappable expressions, each will have // their component list but the same base declaration 'S'. using MappableExprComponentLists = SmallVector<MappableExprComponentList, 8>; using MappableExprComponentListsRef = ArrayRef<MappableExprComponentList>; protected: // Return the total number of elements in a list of component lists. static unsigned getComponentsTotalNumber(MappableExprComponentListsRef ComponentLists); // Return the total number of elements in a list of declarations. All // declarations are expected to be canonical. static unsigned getUniqueDeclarationsTotalNumber(ArrayRef<const ValueDecl *> Declarations); }; /// This structure contains all sizes needed for by an /// OMPMappableExprListClause. struct OMPMappableExprListSizeTy { /// Number of expressions listed. unsigned NumVars; /// Number of unique base declarations. unsigned NumUniqueDeclarations; /// Number of component lists. unsigned NumComponentLists; /// Total number of expression components. unsigned NumComponents; OMPMappableExprListSizeTy() = default; OMPMappableExprListSizeTy(unsigned NumVars, unsigned NumUniqueDeclarations, unsigned NumComponentLists, unsigned NumComponents) : NumVars(NumVars), NumUniqueDeclarations(NumUniqueDeclarations), NumComponentLists(NumComponentLists), NumComponents(NumComponents) {} }; /// This represents clauses with a list of expressions that are mappable. /// Examples of these clauses are 'map' in /// '#pragma omp target [enter|exit] [data]...' directives, and 'to' and 'from /// in '#pragma omp target update...' directives. template <class T> class OMPMappableExprListClause : public OMPVarListClause<T>, public OMPClauseMappableExprCommon { friend class OMPClauseReader; /// Number of unique declarations in this clause. unsigned NumUniqueDeclarations; /// Number of component lists in this clause. unsigned NumComponentLists; /// Total number of components in this clause. unsigned NumComponents; /// Whether this clause is possible to have user-defined mappers associated. /// It should be true for map, to, and from clauses, and false for /// use_device_ptr and is_device_ptr. const bool SupportsMapper; /// C++ nested name specifier for the associated user-defined mapper. NestedNameSpecifierLoc MapperQualifierLoc; /// The associated user-defined mapper identifier information. DeclarationNameInfo MapperIdInfo; protected: /// Build a clause for \a NumUniqueDeclarations declarations, \a /// NumComponentLists total component lists, and \a NumComponents total /// components. /// /// \param K Kind of the clause. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. /// \param SupportsMapper Indicates whether this clause is possible to have /// user-defined mappers associated. /// \param MapperQualifierLocPtr C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfoPtr The identifier of associated user-defined mapper. OMPMappableExprListClause( OpenMPClauseKind K, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes, bool SupportsMapper = false, NestedNameSpecifierLoc *MapperQualifierLocPtr = nullptr, DeclarationNameInfo *MapperIdInfoPtr = nullptr) : OMPVarListClause<T>(K, Locs.StartLoc, Locs.LParenLoc, Locs.EndLoc, Sizes.NumVars), NumUniqueDeclarations(Sizes.NumUniqueDeclarations), NumComponentLists(Sizes.NumComponentLists), NumComponents(Sizes.NumComponents), SupportsMapper(SupportsMapper) { if (MapperQualifierLocPtr) MapperQualifierLoc = *MapperQualifierLocPtr; if (MapperIdInfoPtr) MapperIdInfo = *MapperIdInfoPtr; } /// Get the unique declarations that are in the trailing objects of the /// class. MutableArrayRef<ValueDecl *> getUniqueDeclsRef() { return MutableArrayRef<ValueDecl *>( static_cast<T *>(this)->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Get the unique declarations that are in the trailing objects of the /// class. ArrayRef<ValueDecl *> getUniqueDeclsRef() const { return ArrayRef<ValueDecl *>( static_cast<const T *>(this) ->template getTrailingObjects<ValueDecl *>(), NumUniqueDeclarations); } /// Set the unique declarations that are in the trailing objects of the /// class. void setUniqueDecls(ArrayRef<ValueDecl *> UDs) { assert(UDs.size() == NumUniqueDeclarations && "Unexpected amount of unique declarations."); std::copy(UDs.begin(), UDs.end(), getUniqueDeclsRef().begin()); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. MutableArrayRef<unsigned> getDeclNumListsRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Get the number of lists per declaration that are in the trailing /// objects of the class. ArrayRef<unsigned> getDeclNumListsRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>(), NumUniqueDeclarations); } /// Set the number of lists per declaration that are in the trailing /// objects of the class. void setDeclNumLists(ArrayRef<unsigned> DNLs) { assert(DNLs.size() == NumUniqueDeclarations && "Unexpected amount of list numbers."); std::copy(DNLs.begin(), DNLs.end(), getDeclNumListsRef().begin()); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. MutableArrayRef<unsigned> getComponentListSizesRef() { return MutableArrayRef<unsigned>( static_cast<T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Get the cumulative component lists sizes that are in the trailing /// objects of the class. They are appended after the number of lists. ArrayRef<unsigned> getComponentListSizesRef() const { return ArrayRef<unsigned>( static_cast<const T *>(this)->template getTrailingObjects<unsigned>() + NumUniqueDeclarations, NumComponentLists); } /// Set the cumulative component lists sizes that are in the trailing /// objects of the class. void setComponentListSizes(ArrayRef<unsigned> CLSs) { assert(CLSs.size() == NumComponentLists && "Unexpected amount of component lists."); std::copy(CLSs.begin(), CLSs.end(), getComponentListSizesRef().begin()); } /// Get the components that are in the trailing objects of the class. MutableArrayRef<MappableComponent> getComponentsRef() { return MutableArrayRef<MappableComponent>( static_cast<T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Get the components that are in the trailing objects of the class. ArrayRef<MappableComponent> getComponentsRef() const { return ArrayRef<MappableComponent>( static_cast<const T *>(this) ->template getTrailingObjects<MappableComponent>(), NumComponents); } /// Set the components that are in the trailing objects of the class. /// This requires the list sizes so that it can also fill the original /// expressions, which are the first component of each list. void setComponents(ArrayRef<MappableComponent> Components, ArrayRef<unsigned> CLSs) { assert(Components.size() == NumComponents && "Unexpected amount of component lists."); assert(CLSs.size() == NumComponentLists && "Unexpected amount of list sizes."); std::copy(Components.begin(), Components.end(), getComponentsRef().begin()); } /// Fill the clause information from the list of declarations and /// associated component lists. void setClauseInfo(ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists) { // Perform some checks to make sure the data sizes are consistent with the // information available when the clause was created. assert(getUniqueDeclarationsTotalNumber(Declarations) == NumUniqueDeclarations && "Unexpected number of mappable expression info entries!"); assert(getComponentsTotalNumber(ComponentLists) == NumComponents && "Unexpected total number of components!"); assert(Declarations.size() == ComponentLists.size() && "Declaration and component lists size is not consistent!"); assert(Declarations.size() == NumComponentLists && "Unexpected declaration and component lists size!"); // Organize the components by declaration and retrieve the original // expression. Original expressions are always the first component of the // mappable component list. llvm::MapVector<ValueDecl *, SmallVector<MappableExprComponentListRef, 8>> ComponentListMap; { auto CI = ComponentLists.begin(); for (auto DI = Declarations.begin(), DE = Declarations.end(); DI != DE; ++DI, ++CI) { assert(!CI->empty() && "Invalid component list!"); ComponentListMap[*DI].push_back(*CI); } } // Iterators of the target storage. auto UniqueDeclarations = getUniqueDeclsRef(); auto UDI = UniqueDeclarations.begin(); auto DeclNumLists = getDeclNumListsRef(); auto DNLI = DeclNumLists.begin(); auto ComponentListSizes = getComponentListSizesRef(); auto CLSI = ComponentListSizes.begin(); auto Components = getComponentsRef(); auto CI = Components.begin(); // Variable to compute the accumulation of the number of components. unsigned PrevSize = 0u; // Scan all the declarations and associated component lists. for (auto &M : ComponentListMap) { // The declaration. auto *D = M.first; // The component lists. auto CL = M.second; // Initialize the entry. *UDI = D; ++UDI; *DNLI = CL.size(); ++DNLI; // Obtain the cumulative sizes and concatenate all the components in the // reserved storage. for (auto C : CL) { // Accumulate with the previous size. PrevSize += C.size(); // Save the size. *CLSI = PrevSize; ++CLSI; // Append components after the current components iterator. CI = std::copy(C.begin(), C.end(), CI); } } } /// Set the nested name specifier of associated user-defined mapper. void setMapperQualifierLoc(NestedNameSpecifierLoc NNSL) { MapperQualifierLoc = NNSL; } /// Set the name of associated user-defined mapper. void setMapperIdInfo(DeclarationNameInfo MapperId) { MapperIdInfo = MapperId; } /// Get the user-defined mapper references that are in the trailing objects of /// the class. MutableArrayRef<Expr *> getUDMapperRefs() { assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); return llvm::makeMutableArrayRef<Expr *>( static_cast<T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Get the user-defined mappers references that are in the trailing objects /// of the class. ArrayRef<Expr *> getUDMapperRefs() const { assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); return llvm::makeArrayRef<Expr *>( static_cast<const T *>(this)->template getTrailingObjects<Expr *>() + OMPVarListClause<T>::varlist_size(), OMPVarListClause<T>::varlist_size()); } /// Set the user-defined mappers that are in the trailing objects of the /// class. void setUDMapperRefs(ArrayRef<Expr *> DMDs) { assert(DMDs.size() == OMPVarListClause<T>::varlist_size() && "Unexpected number of user-defined mappers."); assert(SupportsMapper && "Must be a clause that is possible to have user-defined mappers"); std::copy(DMDs.begin(), DMDs.end(), getUDMapperRefs().begin()); } public: /// Return the number of unique base declarations in this clause. unsigned getUniqueDeclarationsNum() const { return NumUniqueDeclarations; } /// Return the number of lists derived from the clause expressions. unsigned getTotalComponentListNum() const { return NumComponentLists; } /// Return the total number of components in all lists derived from the /// clause. unsigned getTotalComponentsNum() const { return NumComponents; } /// Gets the nested name specifier for associated user-defined mapper. NestedNameSpecifierLoc getMapperQualifierLoc() const { return MapperQualifierLoc; } /// Gets the name info for associated user-defined mapper. const DeclarationNameInfo &getMapperIdInfo() const { return MapperIdInfo; } /// Iterator that browse the components by lists. It also allows /// browsing components of a single declaration. class const_component_lists_iterator : public llvm::iterator_adaptor_base< const_component_lists_iterator, MappableExprComponentListRef::const_iterator, std::forward_iterator_tag, MappableComponent, ptrdiff_t, MappableComponent, MappableComponent> { // The declaration the iterator currently refers to. ArrayRef<ValueDecl *>::iterator DeclCur; // The list number associated with the current declaration. ArrayRef<unsigned>::iterator NumListsCur; // Whether this clause is possible to have user-defined mappers associated. const bool SupportsMapper; // The user-defined mapper associated with the current declaration. ArrayRef<Expr *>::iterator MapperCur; // Remaining lists for the current declaration. unsigned RemainingLists = 0; // The cumulative size of the previous list, or zero if there is no previous // list. unsigned PrevListSize = 0; // The cumulative sizes of the current list - it will delimit the remaining // range of interest. ArrayRef<unsigned>::const_iterator ListSizeCur; ArrayRef<unsigned>::const_iterator ListSizeEnd; // Iterator to the end of the components storage. MappableExprComponentListRef::const_iterator End; public: /// Construct an iterator that scans all lists. explicit const_component_lists_iterator( ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components, bool SupportsMapper, ArrayRef<Expr *> Mappers) : const_component_lists_iterator::iterator_adaptor_base( Components.begin()), DeclCur(UniqueDecls.begin()), NumListsCur(DeclsListNum.begin()), SupportsMapper(SupportsMapper), ListSizeCur(CumulativeListSizes.begin()), ListSizeEnd(CumulativeListSizes.end()), End(Components.end()) { assert(UniqueDecls.size() == DeclsListNum.size() && "Inconsistent number of declarations and list sizes!"); if (!DeclsListNum.empty()) RemainingLists = *NumListsCur; if (SupportsMapper) MapperCur = Mappers.begin(); } /// Construct an iterator that scan lists for a given declaration \a /// Declaration. explicit const_component_lists_iterator( const ValueDecl *Declaration, ArrayRef<ValueDecl *> UniqueDecls, ArrayRef<unsigned> DeclsListNum, ArrayRef<unsigned> CumulativeListSizes, MappableExprComponentListRef Components, bool SupportsMapper, ArrayRef<Expr *> Mappers) : const_component_lists_iterator(UniqueDecls, DeclsListNum, CumulativeListSizes, Components, SupportsMapper, Mappers) { // Look for the desired declaration. While we are looking for it, we // update the state so that we know the component where a given list // starts. for (; DeclCur != UniqueDecls.end(); ++DeclCur, ++NumListsCur) { if (*DeclCur == Declaration) break; assert(*NumListsCur > 0 && "No lists associated with declaration??"); // Skip the lists associated with the current declaration, but save the // last list size that was skipped. std::advance(ListSizeCur, *NumListsCur - 1); PrevListSize = *ListSizeCur; ++ListSizeCur; if (SupportsMapper) ++MapperCur; } // If we didn't find any declaration, advance the iterator to after the // last component and set remaining lists to zero. if (ListSizeCur == CumulativeListSizes.end()) { this->I = End; RemainingLists = 0u; return; } // Set the remaining lists with the total number of lists of the current // declaration. RemainingLists = *NumListsCur; // Adjust the list size end iterator to the end of the relevant range. ListSizeEnd = ListSizeCur; std::advance(ListSizeEnd, RemainingLists); // Given that the list sizes are cumulative, the index of the component // that start the list is the size of the previous list. std::advance(this->I, PrevListSize); } // Return the array with the current list. The sizes are cumulative, so the // array size is the difference between the current size and previous one. std::tuple<const ValueDecl *, MappableExprComponentListRef, const ValueDecl *> operator*() const { assert(ListSizeCur != ListSizeEnd && "Invalid iterator!"); const ValueDecl *Mapper = nullptr; if (SupportsMapper && *MapperCur) Mapper = cast<ValueDecl>(cast<DeclRefExpr>(*MapperCur)->getDecl()); return std::make_tuple( *DeclCur, MappableExprComponentListRef(&*this->I, *ListSizeCur - PrevListSize), Mapper); } std::tuple<const ValueDecl *, MappableExprComponentListRef, const ValueDecl *> operator->() const { return **this; } // Skip the components of the current list. const_component_lists_iterator &operator++() { assert(ListSizeCur != ListSizeEnd && RemainingLists && "Invalid iterator!"); // If we don't have more lists just skip all the components. Otherwise, // advance the iterator by the number of components in the current list. if (std::next(ListSizeCur) == ListSizeEnd) { this->I = End; RemainingLists = 0; } else { std::advance(this->I, *ListSizeCur - PrevListSize); PrevListSize = *ListSizeCur; // We are done with a declaration, move to the next one. if (!(--RemainingLists)) { ++DeclCur; ++NumListsCur; RemainingLists = *NumListsCur; assert(RemainingLists && "No lists in the following declaration??"); } } ++ListSizeCur; if (SupportsMapper) ++MapperCur; return *this; } }; using const_component_lists_range = llvm::iterator_range<const_component_lists_iterator>; /// Iterators for all component lists. const_component_lists_iterator component_lists_begin() const { return const_component_lists_iterator( getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef(), SupportsMapper, SupportsMapper ? getUDMapperRefs() : llvm::None); } const_component_lists_iterator component_lists_end() const { return const_component_lists_iterator( ArrayRef<ValueDecl *>(), ArrayRef<unsigned>(), ArrayRef<unsigned>(), MappableExprComponentListRef(getComponentsRef().end(), getComponentsRef().end()), SupportsMapper, llvm::None); } const_component_lists_range component_lists() const { return {component_lists_begin(), component_lists_end()}; } /// Iterators for component lists associated with the provided /// declaration. const_component_lists_iterator decl_component_lists_begin(const ValueDecl *VD) const { return const_component_lists_iterator( VD, getUniqueDeclsRef(), getDeclNumListsRef(), getComponentListSizesRef(), getComponentsRef(), SupportsMapper, SupportsMapper ? getUDMapperRefs() : llvm::None); } const_component_lists_iterator decl_component_lists_end() const { return component_lists_end(); } const_component_lists_range decl_component_lists(const ValueDecl *VD) const { return {decl_component_lists_begin(VD), decl_component_lists_end()}; } /// Iterators to access all the declarations, number of lists, list sizes, and /// components. using const_all_decls_iterator = ArrayRef<ValueDecl *>::iterator; using const_all_decls_range = llvm::iterator_range<const_all_decls_iterator>; const_all_decls_range all_decls() const { auto A = getUniqueDeclsRef(); return const_all_decls_range(A.begin(), A.end()); } using const_all_num_lists_iterator = ArrayRef<unsigned>::iterator; using const_all_num_lists_range = llvm::iterator_range<const_all_num_lists_iterator>; const_all_num_lists_range all_num_lists() const { auto A = getDeclNumListsRef(); return const_all_num_lists_range(A.begin(), A.end()); } using const_all_lists_sizes_iterator = ArrayRef<unsigned>::iterator; using const_all_lists_sizes_range = llvm::iterator_range<const_all_lists_sizes_iterator>; const_all_lists_sizes_range all_lists_sizes() const { auto A = getComponentListSizesRef(); return const_all_lists_sizes_range(A.begin(), A.end()); } using const_all_components_iterator = ArrayRef<MappableComponent>::iterator; using const_all_components_range = llvm::iterator_range<const_all_components_iterator>; const_all_components_range all_components() const { auto A = getComponentsRef(); return const_all_components_range(A.begin(), A.end()); } using mapperlist_iterator = MutableArrayRef<Expr *>::iterator; using mapperlist_const_iterator = ArrayRef<const Expr *>::iterator; using mapperlist_range = llvm::iterator_range<mapperlist_iterator>; using mapperlist_const_range = llvm::iterator_range<mapperlist_const_iterator>; mapperlist_iterator mapperlist_begin() { return getUDMapperRefs().begin(); } mapperlist_iterator mapperlist_end() { return getUDMapperRefs().end(); } mapperlist_const_iterator mapperlist_begin() const { return getUDMapperRefs().begin(); } mapperlist_const_iterator mapperlist_end() const { return getUDMapperRefs().end(); } mapperlist_range mapperlists() { return mapperlist_range(mapperlist_begin(), mapperlist_end()); } mapperlist_const_range mapperlists() const { return mapperlist_const_range(mapperlist_begin(), mapperlist_end()); } }; /// This represents clause 'map' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target map(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause 'map' /// with the variables 'a' and 'b'. class OMPMapClause final : public OMPMappableExprListClause<OMPMapClause>, private llvm::TrailingObjects< OMPMapClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } private: /// Map-type-modifiers for the 'map' clause. OpenMPMapModifierKind MapTypeModifiers[NumberOfOMPMapClauseModifiers] = { OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown, OMPC_MAP_MODIFIER_unknown}; /// Location of map-type-modifiers for the 'map' clause. SourceLocation MapTypeModifiersLoc[NumberOfOMPMapClauseModifiers]; /// Map type for the 'map' clause. OpenMPMapClauseKind MapType = OMPC_MAP_unknown; /// Is this an implicit map type or not. bool MapTypeIsImplicit = false; /// Location of the map type. SourceLocation MapLoc; /// Colon location. SourceLocation ColonLoc; /// Build a clause for \a NumVars listed expressions, \a /// NumUniqueDeclarations declarations, \a NumComponentLists total component /// lists, and \a NumComponents total expression components. /// /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Locations of map-type-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param MapType Map type. /// \param MapTypeIsImplicit Map type is inferred implicitly. /// \param MapLoc Location of the map type. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, OpenMPMapClauseKind MapType, bool MapTypeIsImplicit, SourceLocation MapLoc, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo), MapType(MapType), MapTypeIsImplicit(MapTypeIsImplicit), MapLoc(MapLoc) { assert(llvm::array_lengthof(MapTypeModifiers) == MapModifiers.size() && "Unexpected number of map type modifiers."); llvm::copy(MapModifiers, std::begin(MapTypeModifiers)); assert(llvm::array_lengthof(MapTypeModifiersLoc) == MapModifiersLoc.size() && "Unexpected number of map type modifier locations."); llvm::copy(MapModifiersLoc, std::begin(MapTypeModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPMapClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_map, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set map-type-modifier for the clause. /// /// \param I index for map-type-modifier. /// \param T map-type-modifier for the clause. void setMapTypeModifier(unsigned I, OpenMPMapModifierKind T) { assert(I < NumberOfOMPMapClauseModifiers && "Unexpected index to store map type modifier, exceeds array size."); MapTypeModifiers[I] = T; } /// Set location for the map-type-modifier. /// /// \param I index for map-type-modifier location. /// \param TLoc map-type-modifier location. void setMapTypeModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMapClauseModifiers && "Index to store map type modifier location exceeds array size."); MapTypeModifiersLoc[I] = TLoc; } /// Set type for the clause. /// /// \param T Type for the clause. void setMapType(OpenMPMapClauseKind T) { MapType = T; } /// Set type location. /// /// \param TLoc Type location. void setMapLoc(SourceLocation TLoc) { MapLoc = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param MapModifiers Map-type-modifiers. /// \param MapModifiersLoc Location of map-type-modifiers. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. /// \param Type Map type. /// \param TypeIsImplicit Map type is inferred implicitly. /// \param TypeLoc Location of the map type. static OMPMapClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMapModifierKind> MapModifiers, ArrayRef<SourceLocation> MapModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId, OpenMPMapClauseKind Type, bool TypeIsImplicit, SourceLocation TypeLoc); /// Creates an empty clause with the place for \a NumVars original /// expressions, \a NumUniqueDeclarations declarations, \NumComponentLists /// lists, and \a NumComponents expression components. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPMapClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches mapping kind for the clause. OpenMPMapClauseKind getMapType() const LLVM_READONLY { return MapType; } /// Is this an implicit map type? /// We have to capture 'IsMapTypeImplicit' from the parser for more /// informative error messages. It helps distinguish map(r) from /// map(tofrom: r), which is important to print more helpful error /// messages for some target directives. bool isImplicitMapType() const LLVM_READONLY { return MapTypeIsImplicit; } /// Fetches the map-type-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for map-type-modifier. OpenMPMapModifierKind getMapTypeModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier exceeds the total number of modifiers."); return MapTypeModifiers[Cnt]; } /// Fetches the map-type-modifier location at 'Cnt' index of array of /// modifiers' locations. /// /// \param Cnt index for map-type-modifier location. SourceLocation getMapTypeModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMapClauseModifiers && "Requested modifier location exceeds total number of modifiers."); return MapTypeModifiersLoc[Cnt]; } /// Fetches ArrayRef of map-type-modifiers. ArrayRef<OpenMPMapModifierKind> getMapTypeModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiers); } /// Fetches ArrayRef of location of map-type-modifiers. ArrayRef<SourceLocation> getMapTypeModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MapTypeModifiersLoc); } /// Fetches location of clause mapping kind. SourceLocation getMapLoc() const LLVM_READONLY { return MapLoc; } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range( reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPMapClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { if (MapType == OMPC_MAP_to || MapType == OMPC_MAP_tofrom) return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { auto Children = const_cast<OMPMapClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_map; } }; /// This represents 'num_teams' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams num_teams(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'num_teams' /// with single expression 'n'. class OMPNumTeamsClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// NumTeams number. Stmt *NumTeams = nullptr; /// Set the NumTeams number. /// /// \param E NumTeams number. void setNumTeams(Expr *E) { NumTeams = E; } public: /// Build 'num_teams' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNumTeamsClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_teams, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTeams(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPNumTeamsClause() : OMPClause(llvm::omp::OMPC_num_teams, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return NumTeams number. Expr *getNumTeams() { return cast<Expr>(NumTeams); } /// Return NumTeams number. Expr *getNumTeams() const { return cast<Expr>(NumTeams); } child_range children() { return child_range(&NumTeams, &NumTeams + 1); } const_child_range children() const { return const_child_range(&NumTeams, &NumTeams + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_teams; } }; /// This represents 'thread_limit' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp teams thread_limit(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'thread_limit' /// with single expression 'n'. class OMPThreadLimitClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// ThreadLimit number. Stmt *ThreadLimit = nullptr; /// Set the ThreadLimit number. /// /// \param E ThreadLimit number. void setThreadLimit(Expr *E) { ThreadLimit = E; } public: /// Build 'thread_limit' clause. /// /// \param E Expression associated with this clause. /// \param HelperE Helper Expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPThreadLimitClause(Expr *E, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_thread_limit, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadLimit(E) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPThreadLimitClause() : OMPClause(llvm::omp::OMPC_thread_limit, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return ThreadLimit number. Expr *getThreadLimit() { return cast<Expr>(ThreadLimit); } /// Return ThreadLimit number. Expr *getThreadLimit() const { return cast<Expr>(ThreadLimit); } child_range children() { return child_range(&ThreadLimit, &ThreadLimit + 1); } const_child_range children() const { return const_child_range(&ThreadLimit, &ThreadLimit + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_thread_limit; } }; /// This represents 'priority' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp task priority(n) /// \endcode /// In this example directive '#pragma omp teams' has clause 'priority' with /// single expression 'n'. class OMPPriorityClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Priority number. Stmt *Priority = nullptr; /// Set the Priority number. /// /// \param E Priority number. void setPriority(Expr *E) { Priority = E; } public: /// Build 'priority' clause. /// /// \param Priority Expression associated with this clause. /// \param HelperPriority Helper priority for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPPriorityClause(Expr *Priority, Stmt *HelperPriority, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_priority, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Priority(Priority) { setPreInitStmt(HelperPriority, CaptureRegion); } /// Build an empty clause. OMPPriorityClause() : OMPClause(llvm::omp::OMPC_priority, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return Priority number. Expr *getPriority() { return cast<Expr>(Priority); } /// Return Priority number. Expr *getPriority() const { return cast<Expr>(Priority); } child_range children() { return child_range(&Priority, &Priority + 1); } const_child_range children() const { return const_child_range(&Priority, &Priority + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPPriorityClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_priority; } }; /// This represents 'grainsize' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop grainsize(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'grainsize' /// with single expression '4'. class OMPGrainsizeClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *Grainsize = nullptr; /// Set safelen. void setGrainsize(Expr *Size) { Grainsize = Size; } public: /// Build 'grainsize' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPGrainsizeClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_grainsize, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Grainsize(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPGrainsizeClause() : OMPClause(llvm::omp::OMPC_grainsize, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getGrainsize() const { return cast_or_null<Expr>(Grainsize); } child_range children() { return child_range(&Grainsize, &Grainsize + 1); } const_child_range children() const { return const_child_range(&Grainsize, &Grainsize + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPGrainsizeClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_grainsize; } }; /// This represents 'nogroup' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp taskloop nogroup /// \endcode /// In this example directive '#pragma omp taskloop' has 'nogroup' clause. class OMPNogroupClause : public OMPClause { public: /// Build 'nogroup' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNogroupClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nogroup, StartLoc, EndLoc) {} /// Build an empty clause. OMPNogroupClause() : OMPClause(llvm::omp::OMPC_nogroup, SourceLocation(), SourceLocation()) { } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nogroup; } }; /// This represents 'num_tasks' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp taskloop num_tasks(4) /// \endcode /// In this example directive '#pragma omp taskloop' has clause 'num_tasks' /// with single expression '4'. class OMPNumTasksClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Safe iteration space distance. Stmt *NumTasks = nullptr; /// Set safelen. void setNumTasks(Expr *Size) { NumTasks = Size; } public: /// Build 'num_tasks' clause. /// /// \param Size Expression associated with this clause. /// \param HelperSize Helper grainsize for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPNumTasksClause(Expr *Size, Stmt *HelperSize, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_num_tasks, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), NumTasks(Size) { setPreInitStmt(HelperSize, CaptureRegion); } /// Build an empty clause. explicit OMPNumTasksClause() : OMPClause(llvm::omp::OMPC_num_tasks, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return safe iteration space distance. Expr *getNumTasks() const { return cast_or_null<Expr>(NumTasks); } child_range children() { return child_range(&NumTasks, &NumTasks + 1); } const_child_range children() const { return const_child_range(&NumTasks, &NumTasks + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPNumTasksClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_num_tasks; } }; /// This represents 'hint' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp critical (name) hint(6) /// \endcode /// In this example directive '#pragma omp critical' has name 'name' and clause /// 'hint' with argument '6'. class OMPHintClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Hint expression of the 'hint' clause. Stmt *Hint = nullptr; /// Set hint expression. void setHint(Expr *H) { Hint = H; } public: /// Build 'hint' clause with expression \a Hint. /// /// \param Hint Hint expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPHintClause(Expr *Hint, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_hint, StartLoc, EndLoc), LParenLoc(LParenLoc), Hint(Hint) {} /// Build an empty clause. OMPHintClause() : OMPClause(llvm::omp::OMPC_hint, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of threads. Expr *getHint() const { return cast_or_null<Expr>(Hint); } child_range children() { return child_range(&Hint, &Hint + 1); } const_child_range children() const { return const_child_range(&Hint, &Hint + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_hint; } }; /// This represents 'dist_schedule' clause in the '#pragma omp ...' /// directive. /// /// \code /// #pragma omp distribute dist_schedule(static, 3) /// \endcode /// In this example directive '#pragma omp distribute' has 'dist_schedule' /// clause with arguments 'static' and '3'. class OMPDistScheduleClause : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'schedule' clause. OpenMPDistScheduleClauseKind Kind = OMPC_DIST_SCHEDULE_unknown; /// Start location of the schedule kind in source code. SourceLocation KindLoc; /// Location of ',' (if any). SourceLocation CommaLoc; /// Chunk size. Expr *ChunkSize = nullptr; /// Set schedule kind. /// /// \param K Schedule kind. void setDistScheduleKind(OpenMPDistScheduleClauseKind K) { Kind = K; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set schedule kind start location. /// /// \param KLoc Schedule kind location. void setDistScheduleKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Set location of ','. /// /// \param Loc Location of ','. void setCommaLoc(SourceLocation Loc) { CommaLoc = Loc; } /// Set chunk size. /// /// \param E Chunk size. void setChunkSize(Expr *E) { ChunkSize = E; } public: /// Build 'dist_schedule' clause with schedule kind \a Kind and chunk /// size expression \a ChunkSize. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param CommaLoc Location of ','. /// \param EndLoc Ending location of the clause. /// \param Kind DistSchedule kind. /// \param ChunkSize Chunk size. /// \param HelperChunkSize Helper chunk size for combined directives. OMPDistScheduleClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation KLoc, SourceLocation CommaLoc, SourceLocation EndLoc, OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, Stmt *HelperChunkSize) : OMPClause(llvm::omp::OMPC_dist_schedule, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Kind(Kind), KindLoc(KLoc), CommaLoc(CommaLoc), ChunkSize(ChunkSize) { setPreInitStmt(HelperChunkSize); } /// Build an empty clause. explicit OMPDistScheduleClause() : OMPClause(llvm::omp::OMPC_dist_schedule, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Get kind of the clause. OpenMPDistScheduleClauseKind getDistScheduleKind() const { return Kind; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDistScheduleKindLoc() { return KindLoc; } /// Get location of ','. SourceLocation getCommaLoc() { return CommaLoc; } /// Get chunk size. Expr *getChunkSize() { return ChunkSize; } /// Get chunk size. const Expr *getChunkSize() const { return ChunkSize; } child_range children() { return child_range(reinterpret_cast<Stmt **>(&ChunkSize), reinterpret_cast<Stmt **>(&ChunkSize) + 1); } const_child_range children() const { auto Children = const_cast<OMPDistScheduleClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_dist_schedule; } }; /// This represents 'defaultmap' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp target defaultmap(tofrom: scalar) /// \endcode /// In this example directive '#pragma omp target' has 'defaultmap' clause of kind /// 'scalar' with modifier 'tofrom'. class OMPDefaultmapClause : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Modifiers for 'defaultmap' clause. OpenMPDefaultmapClauseModifier Modifier = OMPC_DEFAULTMAP_MODIFIER_unknown; /// Locations of modifiers. SourceLocation ModifierLoc; /// A kind of the 'defaultmap' clause. OpenMPDefaultmapClauseKind Kind = OMPC_DEFAULTMAP_unknown; /// Start location of the defaultmap kind in source code. SourceLocation KindLoc; /// Set defaultmap kind. /// /// \param K Defaultmap kind. void setDefaultmapKind(OpenMPDefaultmapClauseKind K) { Kind = K; } /// Set the defaultmap modifier. /// /// \param M Defaultmap modifier. void setDefaultmapModifier(OpenMPDefaultmapClauseModifier M) { Modifier = M; } /// Set location of the defaultmap modifier. void setDefaultmapModifierLoc(SourceLocation Loc) { ModifierLoc = Loc; } /// Sets the location of '('. /// /// \param Loc Location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set defaultmap kind start location. /// /// \param KLoc Defaultmap kind location. void setDefaultmapKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } public: /// Build 'defaultmap' clause with defaultmap kind \a Kind /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param KLoc Starting location of the argument. /// \param EndLoc Ending location of the clause. /// \param Kind Defaultmap kind. /// \param M The modifier applied to 'defaultmap' clause. /// \param MLoc Location of the modifier OMPDefaultmapClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc, SourceLocation KLoc, SourceLocation EndLoc, OpenMPDefaultmapClauseKind Kind, OpenMPDefaultmapClauseModifier M) : OMPClause(llvm::omp::OMPC_defaultmap, StartLoc, EndLoc), LParenLoc(LParenLoc), Modifier(M), ModifierLoc(MLoc), Kind(Kind), KindLoc(KLoc) {} /// Build an empty clause. explicit OMPDefaultmapClause() : OMPClause(llvm::omp::OMPC_defaultmap, SourceLocation(), SourceLocation()) {} /// Get kind of the clause. OpenMPDefaultmapClauseKind getDefaultmapKind() const { return Kind; } /// Get the modifier of the clause. OpenMPDefaultmapClauseModifier getDefaultmapModifier() const { return Modifier; } /// Get location of '('. SourceLocation getLParenLoc() { return LParenLoc; } /// Get kind location. SourceLocation getDefaultmapKindLoc() { return KindLoc; } /// Get the modifier location. SourceLocation getDefaultmapModifierLoc() const { return ModifierLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_defaultmap; } }; /// This represents clause 'to' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update to(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'to' /// with the variables 'a' and 'b'. class OMPToClause final : public OMPMappableExprListClause<OMPToClause>, private llvm::TrailingObjects< OMPToClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Motion-modifiers for the 'to' clause. OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = { OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown}; /// Location of motion-modifiers for the 'to' clause. SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers]; /// Colon location. SourceLocation ColonLoc; /// Build clause with number of variables \a NumVars. /// /// \param TheMotionModifiers Motion-modifiers. /// \param TheMotionModifiersLoc Locations of motion-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers, ArrayRef<SourceLocation> TheMotionModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo) { assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() && "Unexpected number of motion modifiers."); llvm::copy(TheMotionModifiers, std::begin(MotionModifiers)); assert(llvm::array_lengthof(MotionModifiersLoc) == TheMotionModifiersLoc.size() && "Unexpected number of motion modifier locations."); llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPToClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_to, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set motion-modifier for the clause. /// /// \param I index for motion-modifier. /// \param T motion-modifier for the clause. void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) { assert(I < NumberOfOMPMotionModifiers && "Unexpected index to store motion modifier, exceeds array size."); MotionModifiers[I] = T; } /// Set location for the motion-modifier. /// /// \param I index for motion-modifier location. /// \param TLoc motion-modifier location. void setMotionModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMotionModifiers && "Index to store motion modifier location exceeds array size."); MotionModifiersLoc[I] = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param MotionModifiers Motion-modifiers. /// \param MotionModifiersLoc Location of motion-modifiers. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPToClause *Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPToClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches the motion-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for motion-modifier. OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier exceeds the total number of modifiers."); return MotionModifiers[Cnt]; } /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers' /// locations. /// /// \param Cnt index for motion-modifier location. SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier location exceeds total number of modifiers."); return MotionModifiersLoc[Cnt]; } /// Fetches ArrayRef of motion-modifiers. ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiers); } /// Fetches ArrayRef of location of motion-modifiers. ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiersLoc); } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPToClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_to; } }; /// This represents clause 'from' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target update from(a,b) /// \endcode /// In this example directive '#pragma omp target update' has clause 'from' /// with the variables 'a' and 'b'. class OMPFromClause final : public OMPMappableExprListClause<OMPFromClause>, private llvm::TrailingObjects< OMPFromClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Motion-modifiers for the 'from' clause. OpenMPMotionModifierKind MotionModifiers[NumberOfOMPMotionModifiers] = { OMPC_MOTION_MODIFIER_unknown, OMPC_MOTION_MODIFIER_unknown}; /// Location of motion-modifiers for the 'from' clause. SourceLocation MotionModifiersLoc[NumberOfOMPMotionModifiers]; /// Colon location. SourceLocation ColonLoc; /// Build clause with number of variables \a NumVars. /// /// \param TheMotionModifiers Motion-modifiers. /// \param TheMotionModifiersLoc Locations of motion-modifiers. /// \param MapperQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperIdInfo The identifier of associated user-defined mapper. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(ArrayRef<OpenMPMotionModifierKind> TheMotionModifiers, ArrayRef<SourceLocation> TheMotionModifiersLoc, NestedNameSpecifierLoc MapperQualifierLoc, DeclarationNameInfo MapperIdInfo, const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, Locs, Sizes, /*SupportsMapper=*/true, &MapperQualifierLoc, &MapperIdInfo) { assert(llvm::array_lengthof(MotionModifiers) == TheMotionModifiers.size() && "Unexpected number of motion modifiers."); llvm::copy(TheMotionModifiers, std::begin(MotionModifiers)); assert(llvm::array_lengthof(MotionModifiersLoc) == TheMotionModifiersLoc.size() && "Unexpected number of motion modifier locations."); llvm::copy(TheMotionModifiersLoc, std::begin(MotionModifiersLoc)); } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPFromClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_from, OMPVarListLocTy(), Sizes, /*SupportsMapper=*/true) {} /// Set motion-modifier for the clause. /// /// \param I index for motion-modifier. /// \param T motion-modifier for the clause. void setMotionModifier(unsigned I, OpenMPMotionModifierKind T) { assert(I < NumberOfOMPMotionModifiers && "Unexpected index to store motion modifier, exceeds array size."); MotionModifiers[I] = T; } /// Set location for the motion-modifier. /// /// \param I index for motion-modifier location. /// \param TLoc motion-modifier location. void setMotionModifierLoc(unsigned I, SourceLocation TLoc) { assert(I < NumberOfOMPMotionModifiers && "Index to store motion modifier location exceeds array size."); MotionModifiersLoc[I] = TLoc; } /// Set colon location. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { // There are varlist_size() of expressions, and varlist_size() of // user-defined mappers. return 2 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. /// \param MotionModifiers Motion-modifiers. /// \param MotionModifiersLoc Location of motion-modifiers. /// \param UDMapperRefs References to user-defined mappers associated with /// expressions used in the clause. /// \param UDMQualifierLoc C++ nested name specifier for the associated /// user-defined mapper. /// \param MapperId The identifier of associated user-defined mapper. static OMPFromClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists, ArrayRef<Expr *> UDMapperRefs, ArrayRef<OpenMPMotionModifierKind> MotionModifiers, ArrayRef<SourceLocation> MotionModifiersLoc, NestedNameSpecifierLoc UDMQualifierLoc, DeclarationNameInfo MapperId); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPFromClause *CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); /// Fetches the motion-modifier at 'Cnt' index of array of modifiers. /// /// \param Cnt index for motion-modifier. OpenMPMotionModifierKind getMotionModifier(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier exceeds the total number of modifiers."); return MotionModifiers[Cnt]; } /// Fetches the motion-modifier location at 'Cnt' index of array of modifiers' /// locations. /// /// \param Cnt index for motion-modifier location. SourceLocation getMotionModifierLoc(unsigned Cnt) const LLVM_READONLY { assert(Cnt < NumberOfOMPMotionModifiers && "Requested modifier location exceeds total number of modifiers."); return MotionModifiersLoc[Cnt]; } /// Fetches ArrayRef of motion-modifiers. ArrayRef<OpenMPMotionModifierKind> getMotionModifiers() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiers); } /// Fetches ArrayRef of location of motion-modifiers. ArrayRef<SourceLocation> getMotionModifiersLoc() const LLVM_READONLY { return llvm::makeArrayRef(MotionModifiersLoc); } /// Get colon location. SourceLocation getColonLoc() const { return ColonLoc; } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPFromClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_from; } }; /// This represents clause 'use_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target data use_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target data' has clause /// 'use_device_ptr' with the variables 'a' and 'b'. class OMPUseDevicePtrClause final : public OMPMappableExprListClause<OMPUseDevicePtrClause>, private llvm::TrailingObjects< OMPUseDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, Locs, Sizes) { } /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return 3 * varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } /// Sets the list of references to private copies with initializers for new /// private variables. /// \param VL List of references. void setPrivateCopies(ArrayRef<Expr *> VL); /// Gets the list of references to private copies with initializers for new /// private variables. MutableArrayRef<Expr *> getPrivateCopies() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateCopies() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } /// Sets the list of references to initializer variables for new private /// variables. /// \param VL List of references. void setInits(ArrayRef<Expr *> VL); /// Gets the list of references to initializer variables for new private /// variables. MutableArrayRef<Expr *> getInits() { return MutableArrayRef<Expr *>(getPrivateCopies().end(), varlist_size()); } ArrayRef<const Expr *> getInits() const { return llvm::makeArrayRef(getPrivateCopies().end(), varlist_size()); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param PrivateVars Expressions referring to private copies. /// \param Inits Expressions referring to private copy initializers. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPUseDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<Expr *> PrivateVars, ArrayRef<Expr *> Inits, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPUseDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); using private_copies_iterator = MutableArrayRef<Expr *>::iterator; using private_copies_const_iterator = ArrayRef<const Expr *>::iterator; using private_copies_range = llvm::iterator_range<private_copies_iterator>; using private_copies_const_range = llvm::iterator_range<private_copies_const_iterator>; private_copies_range private_copies() { return private_copies_range(getPrivateCopies().begin(), getPrivateCopies().end()); } private_copies_const_range private_copies() const { return private_copies_const_range(getPrivateCopies().begin(), getPrivateCopies().end()); } using inits_iterator = MutableArrayRef<Expr *>::iterator; using inits_const_iterator = ArrayRef<const Expr *>::iterator; using inits_range = llvm::iterator_range<inits_iterator>; using inits_const_range = llvm::iterator_range<inits_const_iterator>; inits_range inits() { return inits_range(getInits().begin(), getInits().end()); } inits_const_range inits() const { return inits_const_range(getInits().begin(), getInits().end()); } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPUseDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use_device_ptr; } }; /// This represents clause 'use_device_addr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target data use_device_addr(a,b) /// \endcode /// In this example directive '#pragma omp target data' has clause /// 'use_device_addr' with the variables 'a' and 'b'. class OMPUseDeviceAddrClause final : public OMPMappableExprListClause<OMPUseDeviceAddrClause>, private llvm::TrailingObjects< OMPUseDeviceAddrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDeviceAddrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr, Locs, Sizes) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPUseDeviceAddrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_use_device_addr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPUseDeviceAddrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPUseDeviceAddrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPUseDeviceAddrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use_device_addr; } }; /// This represents clause 'is_device_ptr' in the '#pragma omp ...' /// directives. /// /// \code /// #pragma omp target is_device_ptr(a,b) /// \endcode /// In this example directive '#pragma omp target' has clause /// 'is_device_ptr' with the variables 'a' and 'b'. class OMPIsDevicePtrClause final : public OMPMappableExprListClause<OMPIsDevicePtrClause>, private llvm::TrailingObjects< OMPIsDevicePtrClause, Expr *, ValueDecl *, unsigned, OMPClauseMappableExprCommon::MappableComponent> { friend class OMPClauseReader; friend OMPMappableExprListClause; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a NumVars. /// /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPVarListLocTy &Locs, const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, Locs, Sizes) {} /// Build an empty clause. /// /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. explicit OMPIsDevicePtrClause(const OMPMappableExprListSizeTy &Sizes) : OMPMappableExprListClause(llvm::omp::OMPC_is_device_ptr, OMPVarListLocTy(), Sizes) {} /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<Expr *>) const { return varlist_size(); } size_t numTrailingObjects(OverloadToken<ValueDecl *>) const { return getUniqueDeclarationsNum(); } size_t numTrailingObjects(OverloadToken<unsigned>) const { return getUniqueDeclarationsNum() + getTotalComponentListNum(); } public: /// Creates clause with a list of variables \a Vars. /// /// \param C AST context. /// \param Locs Locations needed to build a mappable clause. It includes 1) /// StartLoc: starting location of the clause (the clause keyword); 2) /// LParenLoc: location of '('; 3) EndLoc: ending location of the clause. /// \param Vars The original expression used in the clause. /// \param Declarations Declarations used in the clause. /// \param ComponentLists Component lists used in the clause. static OMPIsDevicePtrClause * Create(const ASTContext &C, const OMPVarListLocTy &Locs, ArrayRef<Expr *> Vars, ArrayRef<ValueDecl *> Declarations, MappableExprComponentListsRef ComponentLists); /// Creates an empty clause with the place for \a NumVars variables. /// /// \param C AST context. /// \param Sizes All required sizes to build a mappable clause. It includes 1) /// NumVars: number of expressions listed in this clause; 2) /// NumUniqueDeclarations: number of unique base declarations in this clause; /// 3) NumComponentLists: number of component lists in this clause; and 4) /// NumComponents: total number of expression components in the clause. static OMPIsDevicePtrClause * CreateEmpty(const ASTContext &C, const OMPMappableExprListSizeTy &Sizes); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPIsDevicePtrClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_is_device_ptr; } }; /// This represents clause 'nontemporal' in the '#pragma omp ...' directives. /// /// \code /// #pragma omp simd nontemporal(a) /// \endcode /// In this example directive '#pragma omp simd' has clause 'nontemporal' for /// the variable 'a'. class OMPNontemporalClause final : public OMPVarListClause<OMPNontemporalClause>, private llvm::TrailingObjects<OMPNontemporalClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPNontemporalClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPNontemporalClause>(llvm::omp::OMPC_nontemporal, StartLoc, LParenLoc, EndLoc, N) { } /// Build an empty clause. /// /// \param N Number of variables. explicit OMPNontemporalClause(unsigned N) : OMPVarListClause<OMPNontemporalClause>( llvm::omp::OMPC_nontemporal, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Get the list of privatied copies if the member expression was captured by /// one of the privatization clauses. MutableArrayRef<Expr *> getPrivateRefs() { return MutableArrayRef<Expr *>(varlist_end(), varlist_size()); } ArrayRef<const Expr *> getPrivateRefs() const { return llvm::makeArrayRef(varlist_end(), varlist_size()); } public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the variables. static OMPNontemporalClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPNontemporalClause *CreateEmpty(const ASTContext &C, unsigned N); /// Sets the list of references to private copies created in private clauses. /// \param VL List of references. void setPrivateRefs(ArrayRef<Expr *> VL); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPNontemporalClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range private_refs() { return child_range(reinterpret_cast<Stmt **>(getPrivateRefs().begin()), reinterpret_cast<Stmt **>(getPrivateRefs().end())); } const_child_range private_refs() const { auto Children = const_cast<OMPNontemporalClause *>(this)->private_refs(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nontemporal; } }; /// This represents 'order' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp simd order(concurrent) /// \endcode /// In this example directive '#pragma omp parallel' has simple 'order' /// clause with kind 'concurrent'. class OMPOrderClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// A kind of the 'default' clause. OpenMPOrderClauseKind Kind = OMPC_ORDER_unknown; /// Start location of the kind in source code. SourceLocation KindKwLoc; /// Set kind of the clause. /// /// \param K Argument of clause. void setKind(OpenMPOrderClauseKind K) { Kind = K; } /// Set argument location. /// /// \param KLoc Argument location. void setKindKwLoc(SourceLocation KLoc) { KindKwLoc = KLoc; } public: /// Build 'order' clause with argument \p A ('concurrent'). /// /// \param A Argument of the clause ('concurrent'). /// \param ALoc Starting location of the argument. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPOrderClause(OpenMPOrderClauseKind A, SourceLocation ALoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_order, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(A), KindKwLoc(ALoc) {} /// Build an empty clause. OMPOrderClause() : OMPClause(llvm::omp::OMPC_order, SourceLocation(), SourceLocation()) {} /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPOrderClauseKind getKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getKindKwLoc() const { return KindKwLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_order; } }; /// This represents the 'init' clause in '#pragma omp ...' directives. /// /// \code /// #pragma omp interop init(target:obj) /// \endcode class OMPInitClause final : public OMPVarListClause<OMPInitClause>, private llvm::TrailingObjects<OMPInitClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of interop variable. SourceLocation VarLoc; bool IsTarget = false; bool IsTargetSync = false; void setInteropVar(Expr *E) { varlist_begin()[0] = E; } void setIsTarget(bool V) { IsTarget = V; } void setIsTargetSync(bool V) { IsTargetSync = V; } /// Sets the location of the interop variable. void setVarLoc(SourceLocation Loc) { VarLoc = Loc; } /// Build 'init' clause. /// /// \param IsTarget Uses the 'target' interop-type. /// \param IsTargetSync Uses the 'targetsync' interop-type. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param VarLoc Location of the interop variable. /// \param EndLoc Ending location of the clause. /// \param N Number of expressions. OMPInitClause(bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPInitClause>(llvm::omp::OMPC_init, StartLoc, LParenLoc, EndLoc, N), VarLoc(VarLoc), IsTarget(IsTarget), IsTargetSync(IsTargetSync) {} /// Build an empty clause. OMPInitClause(unsigned N) : OMPVarListClause<OMPInitClause>(llvm::omp::OMPC_init, SourceLocation(), SourceLocation(), SourceLocation(), N) { } public: /// Creates a fully specified clause. /// /// \param C AST context. /// \param InteropVar The interop variable. /// \param PrefExprs The list of preference expressions. /// \param IsTarget Uses the 'target' interop-type. /// \param IsTargetSync Uses the 'targetsync' interop-type. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param VarLoc Location of the interop variable. /// \param EndLoc Ending location of the clause. static OMPInitClause *Create(const ASTContext &C, Expr *InteropVar, ArrayRef<Expr *> PrefExprs, bool IsTarget, bool IsTargetSync, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc); /// Creates an empty clause with \a N expressions. /// /// \param C AST context. /// \param N Number of expression items. static OMPInitClause *CreateEmpty(const ASTContext &C, unsigned N); /// Returns the location of the interop variable. SourceLocation getVarLoc() const { return VarLoc; } /// Returns the interop variable. Expr *getInteropVar() { return varlist_begin()[0]; } const Expr *getInteropVar() const { return varlist_begin()[0]; } /// Returns true is interop-type 'target' is used. bool getIsTarget() const { return IsTarget; } /// Returns true is interop-type 'targetsync' is used. bool getIsTargetSync() const { return IsTargetSync; } child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInitClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } using prefs_iterator = MutableArrayRef<Expr *>::iterator; using const_prefs_iterator = ArrayRef<const Expr *>::iterator; using prefs_range = llvm::iterator_range<prefs_iterator>; using const_prefs_range = llvm::iterator_range<const_prefs_iterator>; prefs_range prefs() { return prefs_range(reinterpret_cast<Expr **>(std::next(varlist_begin())), reinterpret_cast<Expr **>(varlist_end())); } const_prefs_range prefs() const { auto Prefs = const_cast<OMPInitClause *>(this)->prefs(); return const_prefs_range(Prefs.begin(), Prefs.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_init; } }; /// This represents the 'use' clause in '#pragma omp ...' directives. /// /// \code /// #pragma omp interop use(obj) /// \endcode class OMPUseClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Location of interop variable. SourceLocation VarLoc; /// The interop variable. Stmt *InteropVar = nullptr; /// Set the interop variable. void setInteropVar(Expr *E) { InteropVar = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Sets the location of the interop variable. void setVarLoc(SourceLocation Loc) { VarLoc = Loc; } public: /// Build 'use' clause with and interop variable expression \a InteropVar. /// /// \param InteropVar The interop variable. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param VarLoc Location of the interop variable. /// \param EndLoc Ending location of the clause. OMPUseClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_use, StartLoc, EndLoc), LParenLoc(LParenLoc), VarLoc(VarLoc), InteropVar(InteropVar) {} /// Build an empty clause. OMPUseClause() : OMPClause(llvm::omp::OMPC_use, SourceLocation(), SourceLocation()) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns the location of the interop variable. SourceLocation getVarLoc() const { return VarLoc; } /// Returns the interop variable. Expr *getInteropVar() const { return cast<Expr>(InteropVar); } child_range children() { return child_range(&InteropVar, &InteropVar + 1); } const_child_range children() const { return const_child_range(&InteropVar, &InteropVar + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_use; } }; /// This represents 'destroy' clause in the '#pragma omp depobj' /// directive or the '#pragma omp interop' directive.. /// /// \code /// #pragma omp depobj(a) destroy /// #pragma omp interop destroy(obj) /// \endcode /// In these examples directive '#pragma omp depobj' and '#pragma omp interop' /// have a 'destroy' clause. The 'interop' directive includes an object. class OMPDestroyClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Location of interop variable. SourceLocation VarLoc; /// The interop variable. Stmt *InteropVar = nullptr; /// Set the interop variable. void setInteropVar(Expr *E) { InteropVar = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Sets the location of the interop variable. void setVarLoc(SourceLocation Loc) { VarLoc = Loc; } public: /// Build 'destroy' clause with an interop variable expression \a InteropVar. /// /// \param InteropVar The interop variable. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param VarLoc Location of the interop variable. /// \param EndLoc Ending location of the clause. OMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation VarLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_destroy, StartLoc, EndLoc), LParenLoc(LParenLoc), VarLoc(VarLoc), InteropVar(InteropVar) {} /// Build 'destroy' clause. /// /// \param StartLoc Starting location of the clause. /// \param EndLoc Ending location of the clause. OMPDestroyClause(SourceLocation StartLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_destroy, StartLoc, EndLoc) {} /// Build an empty clause. OMPDestroyClause() : OMPClause(llvm::omp::OMPC_destroy, SourceLocation(), SourceLocation()) { } /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns the location of the interop variable. SourceLocation getVarLoc() const { return VarLoc; } /// Returns the interop variable. Expr *getInteropVar() const { return cast_or_null<Expr>(InteropVar); } child_range children() { if (InteropVar) return child_range(&InteropVar, &InteropVar + 1); return child_range(child_iterator(), child_iterator()); } const_child_range children() const { if (InteropVar) return const_child_range(&InteropVar, &InteropVar + 1); return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_destroy; } }; /// This represents 'novariants' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp dispatch novariants(a > 5) /// \endcode /// In this example directive '#pragma omp dispatch' has simple 'novariants' /// clause with condition 'a > 5'. class OMPNovariantsClause final : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'novariants' clause with condition \a Cond. /// /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNovariantsClause(Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_novariants, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPNovariantsClause() : OMPClause(llvm::omp::OMPC_novariants, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPNovariantsClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_novariants; } }; /// This represents 'nocontext' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp dispatch nocontext(a > 5) /// \endcode /// In this example directive '#pragma omp dispatch' has simple 'nocontext' /// clause with condition 'a > 5'. class OMPNocontextClause final : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Condition of the 'if' clause. Stmt *Condition = nullptr; /// Set condition. void setCondition(Expr *Cond) { Condition = Cond; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'nocontext' clause with condition \a Cond. /// /// \param Cond Condition of the clause. /// \param HelperCond Helper condition for the construct. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPNocontextClause(Expr *Cond, Stmt *HelperCond, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_nocontext, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), Condition(Cond) { setPreInitStmt(HelperCond, CaptureRegion); } /// Build an empty clause. OMPNocontextClause() : OMPClause(llvm::omp::OMPC_nocontext, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns condition. Expr *getCondition() const { return cast_or_null<Expr>(Condition); } child_range children() { return child_range(&Condition, &Condition + 1); } const_child_range children() const { return const_child_range(&Condition, &Condition + 1); } child_range used_children(); const_child_range used_children() const { auto Children = const_cast<OMPNocontextClause *>(this)->used_children(); return const_child_range(Children.begin(), Children.end()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_nocontext; } }; /// This represents 'detach' clause in the '#pragma omp task' directive. /// /// \code /// #pragma omp task detach(evt) /// \endcode /// In this example directive '#pragma omp detach' has simple 'detach' clause /// with the variable 'evt'. class OMPDetachClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Expression of the 'detach' clause. Stmt *Evt = nullptr; /// Set condition. void setEventHandler(Expr *E) { Evt = E; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'detach' clause with event-handler \a Evt. /// /// \param Evt Event handler expression. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPDetachClause(Expr *Evt, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_detach, StartLoc, EndLoc), LParenLoc(LParenLoc), Evt(Evt) {} /// Build an empty clause. OMPDetachClause() : OMPClause(llvm::omp::OMPC_detach, SourceLocation(), SourceLocation()) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns event-handler expression. Expr *getEventHandler() const { return cast_or_null<Expr>(Evt); } child_range children() { return child_range(&Evt, &Evt + 1); } const_child_range children() const { return const_child_range(&Evt, &Evt + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_detach; } }; /// This represents clause 'inclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan inclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'inclusive' /// with the variables 'a' and 'b'. class OMPInclusiveClause final : public OMPVarListClause<OMPInclusiveClause>, private llvm::TrailingObjects<OMPInclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPInclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPInclusiveClause(unsigned N) : OMPVarListClause<OMPInclusiveClause>(llvm::omp::OMPC_inclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPInclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPInclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPInclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_inclusive; } }; /// This represents clause 'exclusive' in the '#pragma omp scan' directive. /// /// \code /// #pragma omp scan exclusive(a,b) /// \endcode /// In this example directive '#pragma omp scan' has clause 'exclusive' /// with the variables 'a' and 'b'. class OMPExclusiveClause final : public OMPVarListClause<OMPExclusiveClause>, private llvm::TrailingObjects<OMPExclusiveClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Build clause with number of variables \a N. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of the variables in the clause. OMPExclusiveClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// /// \param N Number of variables. explicit OMPExclusiveClause(unsigned N) : OMPVarListClause<OMPExclusiveClause>(llvm::omp::OMPC_exclusive, SourceLocation(), SourceLocation(), SourceLocation(), N) {} public: /// Creates clause with a list of variables \a VL. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param VL List of references to the original variables. static OMPExclusiveClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<Expr *> VL); /// Creates an empty clause with the place for \a N variables. /// /// \param C AST context. /// \param N The number of variables. static OMPExclusiveClause *CreateEmpty(const ASTContext &C, unsigned N); child_range children() { return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end())); } const_child_range children() const { auto Children = const_cast<OMPExclusiveClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_exclusive; } }; /// This represents clause 'uses_allocators' in the '#pragma omp target'-based /// directives. /// /// \code /// #pragma omp target uses_allocators(default_allocator, my_allocator(traits)) /// \endcode /// In this example directive '#pragma omp target' has clause 'uses_allocators' /// with the allocators 'default_allocator' and user-defined 'my_allocator'. class OMPUsesAllocatorsClause final : public OMPClause, private llvm::TrailingObjects<OMPUsesAllocatorsClause, Expr *, SourceLocation> { public: /// Data for list of allocators. struct Data { /// Allocator. Expr *Allocator = nullptr; /// Allocator traits. Expr *AllocatorTraits = nullptr; /// Locations of '(' and ')' symbols. SourceLocation LParenLoc, RParenLoc; }; private: friend class OMPClauseReader; friend TrailingObjects; enum class ExprOffsets { Allocator, AllocatorTraits, Total, }; enum class ParenLocsOffsets { LParen, RParen, Total, }; /// Location of '('. SourceLocation LParenLoc; /// Total number of allocators in the clause. unsigned NumOfAllocators = 0; /// Build clause. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param N Number of allocators asssociated with the clause. OMPUsesAllocatorsClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, StartLoc, EndLoc), LParenLoc(LParenLoc), NumOfAllocators(N) {} /// Build an empty clause. /// \param N Number of allocators asssociated with the clause. /// explicit OMPUsesAllocatorsClause(unsigned N) : OMPClause(llvm::omp::OMPC_uses_allocators, SourceLocation(), SourceLocation()), NumOfAllocators(N) {} unsigned numTrailingObjects(OverloadToken<Expr *>) const { return NumOfAllocators * static_cast<int>(ExprOffsets::Total); } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Sets the allocators data for the clause. void setAllocatorsData(ArrayRef<OMPUsesAllocatorsClause::Data> Data); public: /// Creates clause with a list of allocators \p Data. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. /// \param Data List of allocators. static OMPUsesAllocatorsClause * Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc, ArrayRef<OMPUsesAllocatorsClause::Data> Data); /// Creates an empty clause with the place for \p N allocators. /// /// \param C AST context. /// \param N The number of allocators. static OMPUsesAllocatorsClause *CreateEmpty(const ASTContext &C, unsigned N); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns number of allocators associated with the clause. unsigned getNumberOfAllocators() const { return NumOfAllocators; } /// Returns data for the specified allocator. OMPUsesAllocatorsClause::Data getAllocatorData(unsigned I) const; // Iterators child_range children() { Stmt **Begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>()); return child_range(Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } const_child_range children() const { Stmt *const *Begin = reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>()); return const_child_range( Begin, Begin + NumOfAllocators * static_cast<int>(ExprOffsets::Total)); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_uses_allocators; } }; /// This represents clause 'affinity' in the '#pragma omp task'-based /// directives. /// /// \code /// #pragma omp task affinity(iterator(i = 0:n) : ([3][n])a, b[:n], c[i]) /// \endcode /// In this example directive '#pragma omp task' has clause 'affinity' with the /// affinity modifer 'iterator(i = 0:n)' and locator items '([3][n])a', 'b[:n]' /// and 'c[i]'. class OMPAffinityClause final : public OMPVarListClause<OMPAffinityClause>, private llvm::TrailingObjects<OMPAffinityClause, Expr *> { friend class OMPClauseReader; friend OMPVarListClause; friend TrailingObjects; /// Location of ':' symbol. SourceLocation ColonLoc; /// Build clause. /// /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param N Number of locators asssociated with the clause. OMPAffinityClause(SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, unsigned N) : OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity, StartLoc, LParenLoc, EndLoc, N) {} /// Build an empty clause. /// \param N Number of locators asssociated with the clause. /// explicit OMPAffinityClause(unsigned N) : OMPVarListClause<OMPAffinityClause>(llvm::omp::OMPC_affinity, SourceLocation(), SourceLocation(), SourceLocation(), N) {} /// Sets the affinity modifier for the clause, if any. void setModifier(Expr *E) { getTrailingObjects<Expr *>()[varlist_size()] = E; } /// Sets the location of ':' symbol. void setColonLoc(SourceLocation Loc) { ColonLoc = Loc; } public: /// Creates clause with a modifier a list of locator items. /// /// \param C AST context. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param ColonLoc Location of ':'. /// \param EndLoc Ending location of the clause. /// \param Locators List of locator items. static OMPAffinityClause *Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc, Expr *Modifier, ArrayRef<Expr *> Locators); /// Creates an empty clause with the place for \p N locator items. /// /// \param C AST context. /// \param N The number of locator items. static OMPAffinityClause *CreateEmpty(const ASTContext &C, unsigned N); /// Gets affinity modifier. Expr *getModifier() { return getTrailingObjects<Expr *>()[varlist_size()]; } Expr *getModifier() const { return getTrailingObjects<Expr *>()[varlist_size()]; } /// Gets the location of ':' symbol. SourceLocation getColonLoc() const { return ColonLoc; } // Iterators child_range children() { int Offset = getModifier() ? 1 : 0; return child_range(reinterpret_cast<Stmt **>(varlist_begin()), reinterpret_cast<Stmt **>(varlist_end() + Offset)); } const_child_range children() const { auto Children = const_cast<OMPAffinityClause *>(this)->children(); return const_child_range(Children.begin(), Children.end()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_affinity; } }; /// This represents 'filter' clause in the '#pragma omp ...' directive. /// /// \code /// #pragma omp masked filter(tid) /// \endcode /// In this example directive '#pragma omp masked' has 'filter' clause with /// thread id. class OMPFilterClause final : public OMPClause, public OMPClauseWithPreInit { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// Express of the 'filter' clause. Stmt *ThreadID = nullptr; /// Sets the thread identifier. void setThreadID(Expr *TID) { ThreadID = TID; } /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } public: /// Build 'filter' clause with thread-id \a ThreadID. /// /// \param ThreadID Thread identifier. /// \param HelperE Helper expression associated with this clause. /// \param CaptureRegion Innermost OpenMP region where expressions in this /// clause must be captured. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPFilterClause(Expr *ThreadID, Stmt *HelperE, OpenMPDirectiveKind CaptureRegion, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_filter, StartLoc, EndLoc), OMPClauseWithPreInit(this), LParenLoc(LParenLoc), ThreadID(ThreadID) { setPreInitStmt(HelperE, CaptureRegion); } /// Build an empty clause. OMPFilterClause() : OMPClause(llvm::omp::OMPC_filter, SourceLocation(), SourceLocation()), OMPClauseWithPreInit(this) {} /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Return thread identifier. Expr *getThreadID() { return cast<Expr>(ThreadID); } /// Return thread identifier. Expr *getThreadID() const { return cast<Expr>(ThreadID); } child_range children() { return child_range(&ThreadID, &ThreadID + 1); } const_child_range children() const { return const_child_range(&ThreadID, &ThreadID + 1); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_filter; } }; /// This represents 'bind' clause in the '#pragma omp ...' directives. /// /// \code /// #pragma omp loop bind(parallel) /// \endcode class OMPBindClause final : public OMPClause { friend class OMPClauseReader; /// Location of '('. SourceLocation LParenLoc; /// The binding kind of 'bind' clause. OpenMPBindClauseKind Kind = OMPC_BIND_unknown; /// Start location of the kind in source code. SourceLocation KindLoc; /// Sets the location of '('. void setLParenLoc(SourceLocation Loc) { LParenLoc = Loc; } /// Set the binding kind. void setBindKind(OpenMPBindClauseKind K) { Kind = K; } /// Set the binding kind location. void setBindKindLoc(SourceLocation KLoc) { KindLoc = KLoc; } /// Build 'bind' clause with kind \a K ('teams', 'parallel', or 'thread'). /// /// \param K Binding kind of the clause ('teams', 'parallel' or 'thread'). /// \param KLoc Starting location of the binding kind. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. OMPBindClause(OpenMPBindClauseKind K, SourceLocation KLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) : OMPClause(llvm::omp::OMPC_bind, StartLoc, EndLoc), LParenLoc(LParenLoc), Kind(K), KindLoc(KLoc) {} /// Build an empty clause. OMPBindClause() : OMPClause(llvm::omp::OMPC_bind, SourceLocation(), SourceLocation()) {} public: /// Build 'bind' clause with kind \a K ('teams', 'parallel', or 'thread'). /// /// \param C AST context /// \param K Binding kind of the clause ('teams', 'parallel' or 'thread'). /// \param KLoc Starting location of the binding kind. /// \param StartLoc Starting location of the clause. /// \param LParenLoc Location of '('. /// \param EndLoc Ending location of the clause. static OMPBindClause *Create(const ASTContext &C, OpenMPBindClauseKind K, SourceLocation KLoc, SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc); /// Build an empty 'bind' clause. /// /// \param C AST context static OMPBindClause *CreateEmpty(const ASTContext &C); /// Returns the location of '('. SourceLocation getLParenLoc() const { return LParenLoc; } /// Returns kind of the clause. OpenMPBindClauseKind getBindKind() const { return Kind; } /// Returns location of clause kind. SourceLocation getBindKindLoc() const { return KindLoc; } child_range children() { return child_range(child_iterator(), child_iterator()); } const_child_range children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } child_range used_children() { return child_range(child_iterator(), child_iterator()); } const_child_range used_children() const { return const_child_range(const_child_iterator(), const_child_iterator()); } static bool classof(const OMPClause *T) { return T->getClauseKind() == llvm::omp::OMPC_bind; } }; /// This class implements a simple visitor for OMPClause /// subclasses. template<class ImplClass, template <typename> class Ptr, typename RetTy> class OMPClauseVisitorBase { public: #define PTR(CLASS) Ptr<CLASS> #define DISPATCH(CLASS) \ return static_cast<ImplClass*>(this)->Visit##CLASS(static_cast<PTR(CLASS)>(S)) #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) \ RetTy Visit##Class(PTR(Class) S) { DISPATCH(Class); } #include "llvm/Frontend/OpenMP/OMP.inc" RetTy Visit(PTR(OMPClause) S) { // Top switch clause: visit each OMPClause. switch (S->getClauseKind()) { #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) \ case llvm::omp::Clause::Enum: \ return Visit##Class(static_cast<PTR(Class)>(S)); #define CLAUSE_NO_CLASS(Enum, Str) \ case llvm::omp::Clause::Enum: \ break; #include "llvm/Frontend/OpenMP/OMP.inc" } } // Base case, ignore it. :) RetTy VisitOMPClause(PTR(OMPClause) Node) { return RetTy(); } #undef PTR #undef DISPATCH }; template <typename T> using const_ptr = std::add_pointer_t<std::add_const_t<T>>; template <class ImplClass, typename RetTy = void> class OMPClauseVisitor : public OMPClauseVisitorBase<ImplClass, std::add_pointer_t, RetTy> {}; template<class ImplClass, typename RetTy = void> class ConstOMPClauseVisitor : public OMPClauseVisitorBase <ImplClass, const_ptr, RetTy> {}; class OMPClausePrinter final : public OMPClauseVisitor<OMPClausePrinter> { raw_ostream &OS; const PrintingPolicy &Policy; /// Process clauses with list of variables. template <typename T> void VisitOMPClauseList(T *Node, char StartSym); /// Process motion clauses. template <typename T> void VisitOMPMotionClause(T *Node); public: OMPClausePrinter(raw_ostream &OS, const PrintingPolicy &Policy) : OS(OS), Policy(Policy) {} #define GEN_CLANG_CLAUSE_CLASS #define CLAUSE_CLASS(Enum, Str, Class) void Visit##Class(Class *S); #include "llvm/Frontend/OpenMP/OMP.inc" }; struct OMPTraitProperty { llvm::omp::TraitProperty Kind = llvm::omp::TraitProperty::invalid; /// The raw string as we parsed it. This is needed for the `isa` trait set /// (which accepts anything) and (later) extensions. StringRef RawString; }; struct OMPTraitSelector { Expr *ScoreOrCondition = nullptr; llvm::omp::TraitSelector Kind = llvm::omp::TraitSelector::invalid; llvm::SmallVector<OMPTraitProperty, 1> Properties; }; struct OMPTraitSet { llvm::omp::TraitSet Kind = llvm::omp::TraitSet::invalid; llvm::SmallVector<OMPTraitSelector, 2> Selectors; }; /// Helper data structure representing the traits in a match clause of an /// `declare variant` or `metadirective`. The outer level is an ordered /// collection of selector sets, each with an associated kind and an ordered /// collection of selectors. A selector has a kind, an optional score/condition, /// and an ordered collection of properties. class OMPTraitInfo { /// Private constructor accesible only by ASTContext. OMPTraitInfo() {} friend class ASTContext; public: /// Reconstruct a (partial) OMPTraitInfo object from a mangled name. OMPTraitInfo(StringRef MangledName); /// The outermost level of selector sets. llvm::SmallVector<OMPTraitSet, 2> Sets; bool anyScoreOrCondition( llvm::function_ref<bool(Expr *&, bool /* IsScore */)> Cond) { return llvm::any_of(Sets, [&](OMPTraitSet &Set) { return llvm::any_of( Set.Selectors, [&](OMPTraitSelector &Selector) { return Cond(Selector.ScoreOrCondition, /* IsScore */ Selector.Kind != llvm::omp::TraitSelector::user_condition); }); }); } /// Create a variant match info object from this trait info object. While the /// former is a flat representation the actual main difference is that the /// latter uses clang::Expr to store the score/condition while the former is /// independent of clang. Thus, expressions and conditions are evaluated in /// this method. void getAsVariantMatchInfo(ASTContext &ASTCtx, llvm::omp::VariantMatchInfo &VMI) const; /// Return a string representation identifying this context selector. std::string getMangledName() const; /// Check the extension trait \p TP is active. bool isExtensionActive(llvm::omp::TraitProperty TP) { for (const OMPTraitSet &Set : Sets) { if (Set.Kind != llvm::omp::TraitSet::implementation) continue; for (const OMPTraitSelector &Selector : Set.Selectors) { if (Selector.Kind != llvm::omp::TraitSelector::implementation_extension) continue; for (const OMPTraitProperty &Property : Selector.Properties) { if (Property.Kind == TP) return true; } } } return false; } /// Print a human readable representation into \p OS. void print(llvm::raw_ostream &OS, const PrintingPolicy &Policy) const; }; llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo &TI); llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, const OMPTraitInfo *TI); /// Clang specific specialization of the OMPContext to lookup target features. struct TargetOMPContext final : public llvm::omp::OMPContext { TargetOMPContext(ASTContext &ASTCtx, std::function<void(StringRef)> &&DiagUnknownTrait, const FunctionDecl *CurrentFunctionDecl, ArrayRef<llvm::omp::TraitProperty> ConstructTraits); virtual ~TargetOMPContext() = default; /// See llvm::omp::OMPContext::matchesISATrait bool matchesISATrait(StringRef RawString) const override; private: std::function<bool(StringRef)> FeatureValidityCheck; std::function<void(StringRef)> DiagUnknownTrait; llvm::StringMap<bool> FeatureMap; }; /// Contains data for OpenMP directives: clauses, children /// expressions/statements (helpers for codegen) and associated statement, if /// any. class OMPChildren final : private llvm::TrailingObjects<OMPChildren, OMPClause *, Stmt *> { friend TrailingObjects; friend class OMPClauseReader; friend class OMPExecutableDirective; template <typename T> friend class OMPDeclarativeDirective; /// Numbers of clauses. unsigned NumClauses = 0; /// Number of child expressions/stmts. unsigned NumChildren = 0; /// true if the directive has associated statement. bool HasAssociatedStmt = false; /// Define the sizes of each trailing object array except the last one. This /// is required for TrailingObjects to work properly. size_t numTrailingObjects(OverloadToken<OMPClause *>) const { return NumClauses; } OMPChildren() = delete; OMPChildren(unsigned NumClauses, unsigned NumChildren, bool HasAssociatedStmt) : NumClauses(NumClauses), NumChildren(NumChildren), HasAssociatedStmt(HasAssociatedStmt) {} static size_t size(unsigned NumClauses, bool HasAssociatedStmt, unsigned NumChildren); static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses); static OMPChildren *Create(void *Mem, ArrayRef<OMPClause *> Clauses, Stmt *S, unsigned NumChildren = 0); static OMPChildren *CreateEmpty(void *Mem, unsigned NumClauses, bool HasAssociatedStmt = false, unsigned NumChildren = 0); public: unsigned getNumClauses() const { return NumClauses; } unsigned getNumChildren() const { return NumChildren; } bool hasAssociatedStmt() const { return HasAssociatedStmt; } /// Set associated statement. void setAssociatedStmt(Stmt *S) { getTrailingObjects<Stmt *>()[NumChildren] = S; } void setChildren(ArrayRef<Stmt *> Children); /// Sets the list of variables for this clause. /// /// \param Clauses The list of clauses for the directive. /// void setClauses(ArrayRef<OMPClause *> Clauses); /// Returns statement associated with the directive. const Stmt *getAssociatedStmt() const { return const_cast<OMPChildren *>(this)->getAssociatedStmt(); } Stmt *getAssociatedStmt() { assert(HasAssociatedStmt && "Expected directive with the associated statement."); return getTrailingObjects<Stmt *>()[NumChildren]; } /// Get the clauses storage. MutableArrayRef<OMPClause *> getClauses() { return llvm::makeMutableArrayRef(getTrailingObjects<OMPClause *>(), NumClauses); } ArrayRef<OMPClause *> getClauses() const { return const_cast<OMPChildren *>(this)->getClauses(); } /// Returns the captured statement associated with the /// component region within the (combined) directive. /// /// \param RegionKind Component region kind. const CapturedStmt * getCapturedStmt(OpenMPDirectiveKind RegionKind, ArrayRef<OpenMPDirectiveKind> CaptureRegions) const { assert(llvm::any_of( CaptureRegions, [=](const OpenMPDirectiveKind K) { return K == RegionKind; }) && "RegionKind not found in OpenMP CaptureRegions."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (auto ThisCaptureRegion : CaptureRegions) { if (ThisCaptureRegion == RegionKind) return CS; CS = cast<CapturedStmt>(CS->getCapturedStmt()); } llvm_unreachable("Incorrect RegionKind specified for directive."); } /// Get innermost captured statement for the construct. CapturedStmt * getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) { assert(hasAssociatedStmt() && "Must have associated captured statement."); assert(!CaptureRegions.empty() && "At least one captured statement must be provided."); auto *CS = cast<CapturedStmt>(getAssociatedStmt()); for (unsigned Level = CaptureRegions.size(); Level > 1; --Level) CS = cast<CapturedStmt>(CS->getCapturedStmt()); return CS; } const CapturedStmt * getInnermostCapturedStmt(ArrayRef<OpenMPDirectiveKind> CaptureRegions) const { return const_cast<OMPChildren *>(this)->getInnermostCapturedStmt( CaptureRegions); } MutableArrayRef<Stmt *> getChildren(); ArrayRef<Stmt *> getChildren() const { return const_cast<OMPChildren *>(this)->getChildren(); } Stmt *getRawStmt() { assert(HasAssociatedStmt && "Expected directive with the associated statement."); if (auto *CS = dyn_cast<CapturedStmt>(getAssociatedStmt())) { Stmt *S = nullptr; do { S = CS->getCapturedStmt(); CS = dyn_cast<CapturedStmt>(S); } while (CS); return S; } return getAssociatedStmt(); } const Stmt *getRawStmt() const { return const_cast<OMPChildren *>(this)->getRawStmt(); } Stmt::child_range getAssociatedStmtAsRange() { if (!HasAssociatedStmt) return Stmt::child_range(Stmt::child_iterator(), Stmt::child_iterator()); return Stmt::child_range(&getTrailingObjects<Stmt *>()[NumChildren], &getTrailingObjects<Stmt *>()[NumChildren + 1]); } }; } // namespace clang #endif // LLVM_CLANG_AST_OPENMPCLAUSE_H
omp_pi_num_integration2.c
/* vim: set ts=4 sw=4: */ /* Filename : omp_pi_num_integration2.c * Description : calculate pi * Author : SunYoung Kim <sunyzero@gmail.com> * Notes : numerical integration method */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> const int num_steps=800000000; /* integration 횟수: 8억번 (너무 많으면 줄이자.) */ int main() { double step, sum = 0.0; step = 1.0/(double) num_steps; printf("%d, %d\n", num_steps<<1, num_steps>>1); #pragma omp parallel sections reduction(+:sum) { #pragma omp section { double x1; int num_steps1=num_steps>>1; for (int i=0; i<num_steps1; i++) { x1 = (i+0.5) * step; sum += 4.0/(1.0 + x1*x1); } } #pragma omp section { double x2; for (int i = num_steps>>1; i<num_steps; i++) { x2 = (i+0.5) * step; sum += 4.0/(1.0 + x2*x2); } } } printf("pi = %.8f (sum = %.8f), 4*atan(1) = %.8f\n", step*sum, sum, atan(1)*4); return EXIT_SUCCESS; }
GB_binop__isge_int64.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__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_08__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_02__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_04__isge_int64) // A.*B function (eWiseMult): GB (_AemultB_bitmap__isge_int64) // A*D function (colscale): GB (_AxD__isge_int64) // D*A function (rowscale): GB (_DxB__isge_int64) // C+=B function (dense accum): GB (_Cdense_accumB__isge_int64) // C+=b function (dense accum): GB (_Cdense_accumb__isge_int64) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__isge_int64) // C=scalar+B GB (_bind1st__isge_int64) // C=scalar+B' GB (_bind1st_tran__isge_int64) // C=A+scalar GB (_bind2nd__isge_int64) // C=A'+scalar GB (_bind2nd_tran__isge_int64) // C type: int64_t // 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 \ int64_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) \ int64_t aij = GBX (Ax, pA, A_iso) // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int64_t bij = GBX (Bx, pB, B_iso) // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = (x >= y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ISGE || GxB_NO_INT64 || GxB_NO_ISGE_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 //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__isge_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__isge_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 { #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_int64) ( 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 int64_t int64_t bwork = (*((int64_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_int64) ( 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 int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__isge_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 int64_t *restrict Cx = (int64_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__isge_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 Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__isge_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__isge_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__isge_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__isge_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__isge_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 int64_t *Cx = (int64_t *) 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__isge_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 ; int64_t *Cx = (int64_t *) 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__isge_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__isge_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
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: HMPR pr; ///< Pointer to associated MGL parser mglGraph(int kind=0, int width=600, int height=400) { pr = NULL; 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) { pr = NULL; 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 enable) { mgl_set_rotated_text(gr, enable); } /// Set to scale text in relative subplots too inline void SetScaleText(bool enable) { mgl_set_scale_text(gr, enable); } /// 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); } /// Add user-defined glyph for symbol and set its optional id inline void DefineSymbol(char id, const mglDataA &x, const mglDataA &y) { mgl_define_symbol(gr, id, &x, &y); } /// 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); } /// Display progress of something. inline void Progress(int value, int maximal) { mgl_progress(value, maximal, gr); } /// 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); } /// Set bit-value flag of HMGL state (for advanced users only) inline void SetFlagAdv(int val, uint32_t flag) { mgl_set_flag(gr, val, flag); } /// 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 and shift it by distance {sx,sy}. /** 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="<>_^", double sx=0, double sy=0) { mgl_multiplot_d(gr, nx, ny, m, dx, dy, style, sx, sy); } /// 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); } /// Set boundary box for export graphics into 2D file formats. /** If x2<0 (y2<0) then full width (height) will be used. * If x1<0 or y1<0 or x1>=x2|Width or y1>=y2|Height then cropping will be disabled. */ inline void SetBBox(int x1=0, int y1=0, int x2=-1, int y2=-1) { mgl_set_bbox(gr,x1,y1,x2,y2); } /// 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 Iris plots for determining cross-dependences of data arrays /** NOTE: using the same ranges and empty ids will not draw axis. This will add data to existing Iris plot. * Option value set the size of data labels ids, separated by ';'.*/ inline void Iris(mglDataA &dats, const char *ids, const char *stl="", const char *opt="") { mgl_iris_1(gr,&dats,ids,stl,opt); } inline void Iris(mglDataA &dats, const wchar_t *ids, const char *stl="", const char *opt="") { mgl_irisw_1(gr,&dats,ids,stl,opt); } inline void Iris(mglDataA &dats, mglDataA &ranges, const char *ids, const char *stl="", const char *opt="") { mgl_iris(gr,&dats,&ranges,ids,stl,opt); } inline void Iris(mglDataA &dats, mglDataA &ranges, const wchar_t *ids, const char *stl="", const char *opt="") { mgl_irisw(gr,&dats,&ranges,ids,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 pa, mglPoint p1, double a, const char *stl="r") { mgl_arc_ext(gr, p0.x,p0.y,p0.z, pa.x,pa.y,pa.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); } /// Draw user-defined symbol in position p inline void Symbol(mglPoint p, char id, const char *how="", double size=-1) { mgl_symbol(gr, p.x, p.y, p.z, id, how, size); } /// Draw user-defined symbol in position p along direction d inline void Symbol(mglPoint p, mglPoint d, char id, const char *how="", double size=-1) { mgl_symbol_dir(gr, p.x, p.y, p.z, d.x, d.y, d.z, id, how, size); } /// 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 belts for 2d data specified parametrically with color proportional to c /** Style 'x' draw belts in x-direction. */ inline void BeltC(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_beltc_xy(gr, &x, &y, &z, &c, stl, opt); } /// Draw belts for 2d data with color proportional to c /** Style 'x' draw belts in x-direction. */ inline void BeltC(const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_beltc(gr, &z, &c, 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 with manual colors c for 2d data specified parametrically inline void Tile(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &c, const char *stl="", const char *opt="") { mgl_tile_xyc(gr, &x, &y, &z, &c, 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 on parametric surface at manual levels for 2d data specified parametrically /** Style ‘f’ to draw solid contours. * Style 't'/'T' draw contour labels below/above contours.*/ inline void ContP(const mglDataA &v, const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_contp_val(gr, &v, &x, &y, &z, &a, sch, opt); } /// Draw contour lines on parametric surface at manual levels for 2d data specified parametrically /** Style ‘f’ to draw solid contours. * Style ‘t’/‘T’ draw contour labels below/above contours. * Option "value" set the number of contour levels (default is 7). */ inline void ContP(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &a, const char *sch="", const char *opt="") { mgl_contp(gr, &x, &y, &z, &a, 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.*/ 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 and manual colors c for 2d data specified parametrically inline void TileS(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &r, const mglDataA &c, const char *stl="", const char *opt="") { mgl_tiles_xyc(gr, &x, &y, &z, &r, &c, stl, opt); } /// 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 from given plain 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); * 'v' for drawing arrows on the threads; * 't' for drawing tapes of normals in x-y and y-z planes. * Option "value" sets the number of threads (default is 5). */ inline void Flow3(const mglDataA &x, const mglDataA &y, const mglDataA &z, const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double sVal=-1, const char *opt="") { mgl_flow3_xyz(gr, &x, &y, &z, &ax, &ay, &az, sch, sVal, opt); } /// Plot flows from given plain 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); * 'v' for drawing arrows on the threads; * 't' for drawing tapes of normals in x-y and y-z planes. * Option "value" sets the number of threads (default is 5). */ inline void Flow3(const mglDataA &ax, const mglDataA &ay, const mglDataA &az, const char *sch="", double sVal=-1, const char *opt="") { mgl_flow3(gr, &ax, &ay, &az, sch, sVal, 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; mglParse &operator=(mglParse &p) { pr = p.pr; mgl_use_parser(pr,1); return p; } 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 number 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); } // Open all data arrays from HDF file and assign it as variables of parser p inline void OpenHDF(const char *fname) { mgl_parser_openhdf(pr, fname); } /// 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); } /// Set starting object ID inline void StartID(int id=0) { mgl_parser_start_id(pr, id); } /// 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); } /// Get constant with given id. Can be NULL if not found. /// NOTE !!! You must not delete obtained data arrays !!! inline mglNum *GetConst(unsigned long id) { return mgl_parser_get_const(pr,id); } /// Get number of constants inline long GetNumConst() { return mgl_parser_num_const(pr); } }; //----------------------------------------------------------------------------- #endif #endif
GB_binop__isne_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB_AaddB__isne_uint32 // A.*B function (eWiseMult): GB_AemultB__isne_uint32 // A*D function (colscale): GB_AxD__isne_uint32 // D*A function (rowscale): GB_DxB__isne_uint32 // C+=B function (dense accum): GB_Cdense_accumB__isne_uint32 // C+=b function (dense accum): GB_Cdense_accumb__isne_uint32 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__isne_uint32 // C=scalar+B GB_bind1st__isne_uint32 // C=scalar+B' GB_bind1st_tran__isne_uint32 // C=A+scalar GB_bind2nd__isne_uint32 // C=A'+scalar GB_bind2nd_tran__isne_uint32 // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = (aij != bij) #define GB_ATYPE \ uint32_t #define GB_BTYPE \ uint32_t #define GB_CTYPE \ 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) \ uint32_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ uint32_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ uint32_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) ; // 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_ISNE || GxB_NO_UINT32 || GxB_NO_ISNE_UINT32) //------------------------------------------------------------------------------ // 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__isne_uint32 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__isne_uint32 ( 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__isne_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__isne_uint32 ( 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 uint32_t *GB_RESTRICT Cx = (uint32_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__isne_uint32 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *GB_RESTRICT Cx = (uint32_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__isne_uint32 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__isne_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 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__isne_uint32 ( 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 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; uint32_t bij = Bx [p] ; Cx [p] = (x != bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__isne_uint32 ( 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 ; 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 = Ax [p] ; Cx [p] = (aij != y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = (x != aij) ; \ } GrB_Info GB_bind1st_tran__isne_uint32 ( 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 \ uint32_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t x = (*((const uint32_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ uint32_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint32_t aij = Ax [pA] ; \ Cx [pC] = (aij != y) ; \ } GrB_Info GB_bind2nd_tran__isne_uint32 ( 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 uint32_t y = (*((const uint32_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
acado_integrator.c
/* * This file was auto-generated using the ACADO Toolkit. * * While ACADO Toolkit is free software released under the terms of * the GNU Lesser General Public License (LGPL), the generated code * as such remains the property of the user who used ACADO Toolkit * to generate this code. In particular, user dependent data of the code * do not inherit the GNU LGPL license. On the other hand, parts of the * generated code that are a direct copy of source code from the * ACADO Toolkit or the software tools it is based on, remain, as derived * work, automatically covered by the LGPL license. * * ACADO Toolkit 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. * */ #include "acado_common.h" real_t rk_dim20_swap; /** Column vector of size: 20 */ real_t rk_dim20_bPerm[ 20 ]; real_t rk_ttt; /** Row vector of size: 24 */ real_t rk_xxx[ 24 ]; /** Matrix of size: 10 x 2 (row major format) */ real_t rk_kkk[ 20 ]; /** Matrix of size: 20 x 20 (row major format) */ real_t rk_A[ 400 ]; /** Column vector of size: 20 */ real_t rk_b[ 20 ]; /** Row vector of size: 20 */ int rk_dim20_perm[ 20 ]; /** Column vector of size: 10 */ real_t rk_rhsTemp[ 10 ]; /** Matrix of size: 2 x 140 (row major format) */ real_t rk_diffsTemp2[ 280 ]; /** Matrix of size: 10 x 2 (row major format) */ real_t rk_diffK[ 20 ]; /** Matrix of size: 10 x 14 (row major format) */ real_t rk_diffsNew2[ 140 ]; #pragma omp threadprivate( auxVar, rk_ttt, rk_xxx, rk_kkk, rk_diffK, rk_rhsTemp, rk_dim20_perm, rk_A, rk_b, rk_diffsNew2, rk_diffsTemp2, rk_dim20_swap, rk_dim20_bPerm ) void acado_rhs(const real_t* in, real_t* out) { const real_t* xd = in; const real_t* u = in + 10; /* Compute outputs: */ out[0] = xd[7]; out[1] = xd[8]; out[2] = xd[9]; out[3] = ((real_t)(5.0000000000000000e-01)*(((((real_t)(0.0000000000000000e+00)-u[1])*xd[4])-(u[2]*xd[5]))-(u[3]*xd[6]))); out[4] = ((real_t)(5.0000000000000000e-01)*(((u[1]*xd[3])+(u[3]*xd[5]))-(u[2]*xd[6]))); out[5] = ((real_t)(5.0000000000000000e-01)*(((u[2]*xd[3])-(u[3]*xd[4]))+(u[1]*xd[6]))); out[6] = ((real_t)(5.0000000000000000e-01)*(((u[3]*xd[3])+(u[2]*xd[4]))-(u[1]*xd[5]))); out[7] = (((real_t)(2.0000000000000000e+00)*((xd[3]*xd[5])+(xd[4]*xd[6])))*u[0]); out[8] = (((real_t)(2.0000000000000000e+00)*((xd[5]*xd[6])-(xd[3]*xd[4])))*u[0]); out[9] = (((((real_t)(1.0000000000000000e+00)-(((real_t)(2.0000000000000000e+00)*xd[4])*xd[4]))-(((real_t)(2.0000000000000000e+00)*xd[5])*xd[5]))*u[0])-(real_t)(9.8065999999999995e+00)); } void acado_diffs(const real_t* in, real_t* out) { const real_t* xd = in; const real_t* u = in + 10; /* Compute outputs: */ out[0] = (real_t)(0.0000000000000000e+00); out[1] = (real_t)(0.0000000000000000e+00); out[2] = (real_t)(0.0000000000000000e+00); out[3] = (real_t)(0.0000000000000000e+00); out[4] = (real_t)(0.0000000000000000e+00); out[5] = (real_t)(0.0000000000000000e+00); out[6] = (real_t)(0.0000000000000000e+00); out[7] = (real_t)(1.0000000000000000e+00); out[8] = (real_t)(0.0000000000000000e+00); out[9] = (real_t)(0.0000000000000000e+00); out[10] = (real_t)(0.0000000000000000e+00); out[11] = (real_t)(0.0000000000000000e+00); out[12] = (real_t)(0.0000000000000000e+00); out[13] = (real_t)(0.0000000000000000e+00); out[14] = (real_t)(0.0000000000000000e+00); out[15] = (real_t)(0.0000000000000000e+00); out[16] = (real_t)(0.0000000000000000e+00); out[17] = (real_t)(0.0000000000000000e+00); out[18] = (real_t)(0.0000000000000000e+00); out[19] = (real_t)(0.0000000000000000e+00); out[20] = (real_t)(0.0000000000000000e+00); out[21] = (real_t)(0.0000000000000000e+00); out[22] = (real_t)(1.0000000000000000e+00); out[23] = (real_t)(0.0000000000000000e+00); out[24] = (real_t)(0.0000000000000000e+00); out[25] = (real_t)(0.0000000000000000e+00); out[26] = (real_t)(0.0000000000000000e+00); out[27] = (real_t)(0.0000000000000000e+00); out[28] = (real_t)(0.0000000000000000e+00); out[29] = (real_t)(0.0000000000000000e+00); out[30] = (real_t)(0.0000000000000000e+00); out[31] = (real_t)(0.0000000000000000e+00); out[32] = (real_t)(0.0000000000000000e+00); out[33] = (real_t)(0.0000000000000000e+00); out[34] = (real_t)(0.0000000000000000e+00); out[35] = (real_t)(0.0000000000000000e+00); out[36] = (real_t)(0.0000000000000000e+00); out[37] = (real_t)(1.0000000000000000e+00); out[38] = (real_t)(0.0000000000000000e+00); out[39] = (real_t)(0.0000000000000000e+00); out[40] = (real_t)(0.0000000000000000e+00); out[41] = (real_t)(0.0000000000000000e+00); out[42] = (real_t)(0.0000000000000000e+00); out[43] = (real_t)(0.0000000000000000e+00); out[44] = (real_t)(0.0000000000000000e+00); out[45] = (real_t)(0.0000000000000000e+00); out[46] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[1])); out[47] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[2])); out[48] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[3])); out[49] = (real_t)(0.0000000000000000e+00); out[50] = (real_t)(0.0000000000000000e+00); out[51] = (real_t)(0.0000000000000000e+00); out[52] = (real_t)(0.0000000000000000e+00); out[53] = ((real_t)(5.0000000000000000e-01)*(((real_t)(0.0000000000000000e+00)-(real_t)(1.0000000000000000e+00))*xd[4])); out[54] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-xd[5])); out[55] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-xd[6])); out[56] = (real_t)(0.0000000000000000e+00); out[57] = (real_t)(0.0000000000000000e+00); out[58] = (real_t)(0.0000000000000000e+00); out[59] = ((real_t)(5.0000000000000000e-01)*u[1]); out[60] = (real_t)(0.0000000000000000e+00); out[61] = ((real_t)(5.0000000000000000e-01)*u[3]); out[62] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[2])); out[63] = (real_t)(0.0000000000000000e+00); out[64] = (real_t)(0.0000000000000000e+00); out[65] = (real_t)(0.0000000000000000e+00); out[66] = (real_t)(0.0000000000000000e+00); out[67] = ((real_t)(5.0000000000000000e-01)*xd[3]); out[68] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-xd[6])); out[69] = ((real_t)(5.0000000000000000e-01)*xd[5]); out[70] = (real_t)(0.0000000000000000e+00); out[71] = (real_t)(0.0000000000000000e+00); out[72] = (real_t)(0.0000000000000000e+00); out[73] = ((real_t)(5.0000000000000000e-01)*u[2]); out[74] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[3])); out[75] = (real_t)(0.0000000000000000e+00); out[76] = ((real_t)(5.0000000000000000e-01)*u[1]); out[77] = (real_t)(0.0000000000000000e+00); out[78] = (real_t)(0.0000000000000000e+00); out[79] = (real_t)(0.0000000000000000e+00); out[80] = (real_t)(0.0000000000000000e+00); out[81] = ((real_t)(5.0000000000000000e-01)*xd[6]); out[82] = ((real_t)(5.0000000000000000e-01)*xd[3]); out[83] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-xd[4])); out[84] = (real_t)(0.0000000000000000e+00); out[85] = (real_t)(0.0000000000000000e+00); out[86] = (real_t)(0.0000000000000000e+00); out[87] = ((real_t)(5.0000000000000000e-01)*u[3]); out[88] = ((real_t)(5.0000000000000000e-01)*u[2]); out[89] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-u[1])); out[90] = (real_t)(0.0000000000000000e+00); out[91] = (real_t)(0.0000000000000000e+00); out[92] = (real_t)(0.0000000000000000e+00); out[93] = (real_t)(0.0000000000000000e+00); out[94] = (real_t)(0.0000000000000000e+00); out[95] = ((real_t)(5.0000000000000000e-01)*((real_t)(0.0000000000000000e+00)-xd[5])); out[96] = ((real_t)(5.0000000000000000e-01)*xd[4]); out[97] = ((real_t)(5.0000000000000000e-01)*xd[3]); out[98] = (real_t)(0.0000000000000000e+00); out[99] = (real_t)(0.0000000000000000e+00); out[100] = (real_t)(0.0000000000000000e+00); out[101] = (((real_t)(2.0000000000000000e+00)*xd[5])*u[0]); out[102] = (((real_t)(2.0000000000000000e+00)*xd[6])*u[0]); out[103] = (((real_t)(2.0000000000000000e+00)*xd[3])*u[0]); out[104] = (((real_t)(2.0000000000000000e+00)*xd[4])*u[0]); out[105] = (real_t)(0.0000000000000000e+00); out[106] = (real_t)(0.0000000000000000e+00); out[107] = (real_t)(0.0000000000000000e+00); out[108] = ((real_t)(2.0000000000000000e+00)*((xd[3]*xd[5])+(xd[4]*xd[6]))); out[109] = (real_t)(0.0000000000000000e+00); out[110] = (real_t)(0.0000000000000000e+00); out[111] = (real_t)(0.0000000000000000e+00); out[112] = (real_t)(0.0000000000000000e+00); out[113] = (real_t)(0.0000000000000000e+00); out[114] = (real_t)(0.0000000000000000e+00); out[115] = (((real_t)(2.0000000000000000e+00)*((real_t)(0.0000000000000000e+00)-xd[4]))*u[0]); out[116] = (((real_t)(2.0000000000000000e+00)*((real_t)(0.0000000000000000e+00)-xd[3]))*u[0]); out[117] = (((real_t)(2.0000000000000000e+00)*xd[6])*u[0]); out[118] = (((real_t)(2.0000000000000000e+00)*xd[5])*u[0]); out[119] = (real_t)(0.0000000000000000e+00); out[120] = (real_t)(0.0000000000000000e+00); out[121] = (real_t)(0.0000000000000000e+00); out[122] = ((real_t)(2.0000000000000000e+00)*((xd[5]*xd[6])-(xd[3]*xd[4]))); out[123] = (real_t)(0.0000000000000000e+00); out[124] = (real_t)(0.0000000000000000e+00); out[125] = (real_t)(0.0000000000000000e+00); out[126] = (real_t)(0.0000000000000000e+00); out[127] = (real_t)(0.0000000000000000e+00); out[128] = (real_t)(0.0000000000000000e+00); out[129] = (real_t)(0.0000000000000000e+00); out[130] = (((real_t)(0.0000000000000000e+00)-(((real_t)(2.0000000000000000e+00)*xd[4])+((real_t)(2.0000000000000000e+00)*xd[4])))*u[0]); out[131] = (((real_t)(0.0000000000000000e+00)-(((real_t)(2.0000000000000000e+00)*xd[5])+((real_t)(2.0000000000000000e+00)*xd[5])))*u[0]); out[132] = (real_t)(0.0000000000000000e+00); out[133] = (real_t)(0.0000000000000000e+00); out[134] = (real_t)(0.0000000000000000e+00); out[135] = (real_t)(0.0000000000000000e+00); out[136] = (((real_t)(1.0000000000000000e+00)-(((real_t)(2.0000000000000000e+00)*xd[4])*xd[4]))-(((real_t)(2.0000000000000000e+00)*xd[5])*xd[5])); out[137] = (real_t)(0.0000000000000000e+00); out[138] = (real_t)(0.0000000000000000e+00); out[139] = (real_t)(0.0000000000000000e+00); } void acado_solve_dim20_triangular( real_t* const A, real_t* const b ) { b[19] = b[19]/A[399]; b[18] -= + A[379]*b[19]; b[18] = b[18]/A[378]; b[17] -= + A[359]*b[19]; b[17] -= + A[358]*b[18]; b[17] = b[17]/A[357]; b[16] -= + A[339]*b[19]; b[16] -= + A[338]*b[18]; b[16] -= + A[337]*b[17]; b[16] = b[16]/A[336]; b[15] -= + A[319]*b[19]; b[15] -= + A[318]*b[18]; b[15] -= + A[317]*b[17]; b[15] -= + A[316]*b[16]; b[15] = b[15]/A[315]; b[14] -= + A[299]*b[19]; b[14] -= + A[298]*b[18]; b[14] -= + A[297]*b[17]; b[14] -= + A[296]*b[16]; b[14] -= + A[295]*b[15]; b[14] = b[14]/A[294]; b[13] -= + A[279]*b[19]; b[13] -= + A[278]*b[18]; b[13] -= + A[277]*b[17]; b[13] -= + A[276]*b[16]; b[13] -= + A[275]*b[15]; b[13] -= + A[274]*b[14]; b[13] = b[13]/A[273]; b[12] -= + A[259]*b[19]; b[12] -= + A[258]*b[18]; b[12] -= + A[257]*b[17]; b[12] -= + A[256]*b[16]; b[12] -= + A[255]*b[15]; b[12] -= + A[254]*b[14]; b[12] -= + A[253]*b[13]; b[12] = b[12]/A[252]; b[11] -= + A[239]*b[19]; b[11] -= + A[238]*b[18]; b[11] -= + A[237]*b[17]; b[11] -= + A[236]*b[16]; b[11] -= + A[235]*b[15]; b[11] -= + A[234]*b[14]; b[11] -= + A[233]*b[13]; b[11] -= + A[232]*b[12]; b[11] = b[11]/A[231]; b[10] -= + A[219]*b[19]; b[10] -= + A[218]*b[18]; b[10] -= + A[217]*b[17]; b[10] -= + A[216]*b[16]; b[10] -= + A[215]*b[15]; b[10] -= + A[214]*b[14]; b[10] -= + A[213]*b[13]; b[10] -= + A[212]*b[12]; b[10] -= + A[211]*b[11]; b[10] = b[10]/A[210]; b[9] -= + A[199]*b[19]; b[9] -= + A[198]*b[18]; b[9] -= + A[197]*b[17]; b[9] -= + A[196]*b[16]; b[9] -= + A[195]*b[15]; b[9] -= + A[194]*b[14]; b[9] -= + A[193]*b[13]; b[9] -= + A[192]*b[12]; b[9] -= + A[191]*b[11]; b[9] -= + A[190]*b[10]; b[9] = b[9]/A[189]; b[8] -= + A[179]*b[19]; b[8] -= + A[178]*b[18]; b[8] -= + A[177]*b[17]; b[8] -= + A[176]*b[16]; b[8] -= + A[175]*b[15]; b[8] -= + A[174]*b[14]; b[8] -= + A[173]*b[13]; b[8] -= + A[172]*b[12]; b[8] -= + A[171]*b[11]; b[8] -= + A[170]*b[10]; b[8] -= + A[169]*b[9]; b[8] = b[8]/A[168]; b[7] -= + A[159]*b[19]; b[7] -= + A[158]*b[18]; b[7] -= + A[157]*b[17]; b[7] -= + A[156]*b[16]; b[7] -= + A[155]*b[15]; b[7] -= + A[154]*b[14]; b[7] -= + A[153]*b[13]; b[7] -= + A[152]*b[12]; b[7] -= + A[151]*b[11]; b[7] -= + A[150]*b[10]; b[7] -= + A[149]*b[9]; b[7] -= + A[148]*b[8]; b[7] = b[7]/A[147]; b[6] -= + A[139]*b[19]; b[6] -= + A[138]*b[18]; b[6] -= + A[137]*b[17]; b[6] -= + A[136]*b[16]; b[6] -= + A[135]*b[15]; b[6] -= + A[134]*b[14]; b[6] -= + A[133]*b[13]; b[6] -= + A[132]*b[12]; b[6] -= + A[131]*b[11]; b[6] -= + A[130]*b[10]; b[6] -= + A[129]*b[9]; b[6] -= + A[128]*b[8]; b[6] -= + A[127]*b[7]; b[6] = b[6]/A[126]; b[5] -= + A[119]*b[19]; b[5] -= + A[118]*b[18]; b[5] -= + A[117]*b[17]; b[5] -= + A[116]*b[16]; b[5] -= + A[115]*b[15]; b[5] -= + A[114]*b[14]; b[5] -= + A[113]*b[13]; b[5] -= + A[112]*b[12]; b[5] -= + A[111]*b[11]; b[5] -= + A[110]*b[10]; b[5] -= + A[109]*b[9]; b[5] -= + A[108]*b[8]; b[5] -= + A[107]*b[7]; b[5] -= + A[106]*b[6]; b[5] = b[5]/A[105]; b[4] -= + A[99]*b[19]; b[4] -= + A[98]*b[18]; b[4] -= + A[97]*b[17]; b[4] -= + A[96]*b[16]; b[4] -= + A[95]*b[15]; b[4] -= + A[94]*b[14]; b[4] -= + A[93]*b[13]; b[4] -= + A[92]*b[12]; b[4] -= + A[91]*b[11]; b[4] -= + A[90]*b[10]; b[4] -= + A[89]*b[9]; b[4] -= + A[88]*b[8]; b[4] -= + A[87]*b[7]; b[4] -= + A[86]*b[6]; b[4] -= + A[85]*b[5]; b[4] = b[4]/A[84]; b[3] -= + A[79]*b[19]; b[3] -= + A[78]*b[18]; b[3] -= + A[77]*b[17]; b[3] -= + A[76]*b[16]; b[3] -= + A[75]*b[15]; b[3] -= + A[74]*b[14]; b[3] -= + A[73]*b[13]; b[3] -= + A[72]*b[12]; b[3] -= + A[71]*b[11]; b[3] -= + A[70]*b[10]; b[3] -= + A[69]*b[9]; b[3] -= + A[68]*b[8]; b[3] -= + A[67]*b[7]; b[3] -= + A[66]*b[6]; b[3] -= + A[65]*b[5]; b[3] -= + A[64]*b[4]; b[3] = b[3]/A[63]; b[2] -= + A[59]*b[19]; b[2] -= + A[58]*b[18]; b[2] -= + A[57]*b[17]; b[2] -= + A[56]*b[16]; b[2] -= + A[55]*b[15]; b[2] -= + A[54]*b[14]; b[2] -= + A[53]*b[13]; b[2] -= + A[52]*b[12]; b[2] -= + A[51]*b[11]; b[2] -= + A[50]*b[10]; b[2] -= + A[49]*b[9]; b[2] -= + A[48]*b[8]; b[2] -= + A[47]*b[7]; b[2] -= + A[46]*b[6]; b[2] -= + A[45]*b[5]; b[2] -= + A[44]*b[4]; b[2] -= + A[43]*b[3]; b[2] = b[2]/A[42]; b[1] -= + A[39]*b[19]; b[1] -= + A[38]*b[18]; b[1] -= + A[37]*b[17]; b[1] -= + A[36]*b[16]; b[1] -= + A[35]*b[15]; b[1] -= + A[34]*b[14]; b[1] -= + A[33]*b[13]; b[1] -= + A[32]*b[12]; b[1] -= + A[31]*b[11]; b[1] -= + A[30]*b[10]; b[1] -= + A[29]*b[9]; b[1] -= + A[28]*b[8]; b[1] -= + A[27]*b[7]; b[1] -= + A[26]*b[6]; b[1] -= + A[25]*b[5]; b[1] -= + A[24]*b[4]; b[1] -= + A[23]*b[3]; b[1] -= + A[22]*b[2]; b[1] = b[1]/A[21]; b[0] -= + A[19]*b[19]; b[0] -= + A[18]*b[18]; b[0] -= + A[17]*b[17]; b[0] -= + A[16]*b[16]; b[0] -= + A[15]*b[15]; b[0] -= + A[14]*b[14]; b[0] -= + A[13]*b[13]; b[0] -= + A[12]*b[12]; b[0] -= + A[11]*b[11]; b[0] -= + A[10]*b[10]; b[0] -= + A[9]*b[9]; b[0] -= + A[8]*b[8]; b[0] -= + A[7]*b[7]; b[0] -= + A[6]*b[6]; b[0] -= + A[5]*b[5]; b[0] -= + A[4]*b[4]; b[0] -= + A[3]*b[3]; b[0] -= + A[2]*b[2]; b[0] -= + A[1]*b[1]; b[0] = b[0]/A[0]; } real_t acado_solve_dim20_system( real_t* const A, real_t* const b, int* const rk_perm ) { real_t det; int i; int j; int k; int indexMax; int intSwap; real_t valueMax; real_t temp; for (i = 0; i < 20; ++i) { rk_perm[i] = i; } det = 1.0000000000000000e+00; for( i=0; i < (19); i++ ) { indexMax = i; valueMax = fabs(A[i*20+i]); for( j=(i+1); j < 20; j++ ) { temp = fabs(A[j*20+i]); if( temp > valueMax ) { indexMax = j; valueMax = temp; } } if( indexMax > i ) { for (k = 0; k < 20; ++k) { rk_dim20_swap = A[i*20+k]; A[i*20+k] = A[indexMax*20+k]; A[indexMax*20+k] = rk_dim20_swap; } rk_dim20_swap = b[i]; b[i] = b[indexMax]; b[indexMax] = rk_dim20_swap; intSwap = rk_perm[i]; rk_perm[i] = rk_perm[indexMax]; rk_perm[indexMax] = intSwap; } det *= A[i*20+i]; for( j=i+1; j < 20; j++ ) { A[j*20+i] = -A[j*20+i]/A[i*20+i]; for( k=i+1; k < 20; k++ ) { A[j*20+k] += A[j*20+i] * A[i*20+k]; } b[j] += A[j*20+i] * b[i]; } } det *= A[399]; det = fabs(det); acado_solve_dim20_triangular( A, b ); return det; } void acado_solve_dim20_system_reuse( real_t* const A, real_t* const b, int* const rk_perm ) { rk_dim20_bPerm[0] = b[rk_perm[0]]; rk_dim20_bPerm[1] = b[rk_perm[1]]; rk_dim20_bPerm[2] = b[rk_perm[2]]; rk_dim20_bPerm[3] = b[rk_perm[3]]; rk_dim20_bPerm[4] = b[rk_perm[4]]; rk_dim20_bPerm[5] = b[rk_perm[5]]; rk_dim20_bPerm[6] = b[rk_perm[6]]; rk_dim20_bPerm[7] = b[rk_perm[7]]; rk_dim20_bPerm[8] = b[rk_perm[8]]; rk_dim20_bPerm[9] = b[rk_perm[9]]; rk_dim20_bPerm[10] = b[rk_perm[10]]; rk_dim20_bPerm[11] = b[rk_perm[11]]; rk_dim20_bPerm[12] = b[rk_perm[12]]; rk_dim20_bPerm[13] = b[rk_perm[13]]; rk_dim20_bPerm[14] = b[rk_perm[14]]; rk_dim20_bPerm[15] = b[rk_perm[15]]; rk_dim20_bPerm[16] = b[rk_perm[16]]; rk_dim20_bPerm[17] = b[rk_perm[17]]; rk_dim20_bPerm[18] = b[rk_perm[18]]; rk_dim20_bPerm[19] = b[rk_perm[19]]; rk_dim20_bPerm[1] += A[20]*rk_dim20_bPerm[0]; rk_dim20_bPerm[2] += A[40]*rk_dim20_bPerm[0]; rk_dim20_bPerm[2] += A[41]*rk_dim20_bPerm[1]; rk_dim20_bPerm[3] += A[60]*rk_dim20_bPerm[0]; rk_dim20_bPerm[3] += A[61]*rk_dim20_bPerm[1]; rk_dim20_bPerm[3] += A[62]*rk_dim20_bPerm[2]; rk_dim20_bPerm[4] += A[80]*rk_dim20_bPerm[0]; rk_dim20_bPerm[4] += A[81]*rk_dim20_bPerm[1]; rk_dim20_bPerm[4] += A[82]*rk_dim20_bPerm[2]; rk_dim20_bPerm[4] += A[83]*rk_dim20_bPerm[3]; rk_dim20_bPerm[5] += A[100]*rk_dim20_bPerm[0]; rk_dim20_bPerm[5] += A[101]*rk_dim20_bPerm[1]; rk_dim20_bPerm[5] += A[102]*rk_dim20_bPerm[2]; rk_dim20_bPerm[5] += A[103]*rk_dim20_bPerm[3]; rk_dim20_bPerm[5] += A[104]*rk_dim20_bPerm[4]; rk_dim20_bPerm[6] += A[120]*rk_dim20_bPerm[0]; rk_dim20_bPerm[6] += A[121]*rk_dim20_bPerm[1]; rk_dim20_bPerm[6] += A[122]*rk_dim20_bPerm[2]; rk_dim20_bPerm[6] += A[123]*rk_dim20_bPerm[3]; rk_dim20_bPerm[6] += A[124]*rk_dim20_bPerm[4]; rk_dim20_bPerm[6] += A[125]*rk_dim20_bPerm[5]; rk_dim20_bPerm[7] += A[140]*rk_dim20_bPerm[0]; rk_dim20_bPerm[7] += A[141]*rk_dim20_bPerm[1]; rk_dim20_bPerm[7] += A[142]*rk_dim20_bPerm[2]; rk_dim20_bPerm[7] += A[143]*rk_dim20_bPerm[3]; rk_dim20_bPerm[7] += A[144]*rk_dim20_bPerm[4]; rk_dim20_bPerm[7] += A[145]*rk_dim20_bPerm[5]; rk_dim20_bPerm[7] += A[146]*rk_dim20_bPerm[6]; rk_dim20_bPerm[8] += A[160]*rk_dim20_bPerm[0]; rk_dim20_bPerm[8] += A[161]*rk_dim20_bPerm[1]; rk_dim20_bPerm[8] += A[162]*rk_dim20_bPerm[2]; rk_dim20_bPerm[8] += A[163]*rk_dim20_bPerm[3]; rk_dim20_bPerm[8] += A[164]*rk_dim20_bPerm[4]; rk_dim20_bPerm[8] += A[165]*rk_dim20_bPerm[5]; rk_dim20_bPerm[8] += A[166]*rk_dim20_bPerm[6]; rk_dim20_bPerm[8] += A[167]*rk_dim20_bPerm[7]; rk_dim20_bPerm[9] += A[180]*rk_dim20_bPerm[0]; rk_dim20_bPerm[9] += A[181]*rk_dim20_bPerm[1]; rk_dim20_bPerm[9] += A[182]*rk_dim20_bPerm[2]; rk_dim20_bPerm[9] += A[183]*rk_dim20_bPerm[3]; rk_dim20_bPerm[9] += A[184]*rk_dim20_bPerm[4]; rk_dim20_bPerm[9] += A[185]*rk_dim20_bPerm[5]; rk_dim20_bPerm[9] += A[186]*rk_dim20_bPerm[6]; rk_dim20_bPerm[9] += A[187]*rk_dim20_bPerm[7]; rk_dim20_bPerm[9] += A[188]*rk_dim20_bPerm[8]; rk_dim20_bPerm[10] += A[200]*rk_dim20_bPerm[0]; rk_dim20_bPerm[10] += A[201]*rk_dim20_bPerm[1]; rk_dim20_bPerm[10] += A[202]*rk_dim20_bPerm[2]; rk_dim20_bPerm[10] += A[203]*rk_dim20_bPerm[3]; rk_dim20_bPerm[10] += A[204]*rk_dim20_bPerm[4]; rk_dim20_bPerm[10] += A[205]*rk_dim20_bPerm[5]; rk_dim20_bPerm[10] += A[206]*rk_dim20_bPerm[6]; rk_dim20_bPerm[10] += A[207]*rk_dim20_bPerm[7]; rk_dim20_bPerm[10] += A[208]*rk_dim20_bPerm[8]; rk_dim20_bPerm[10] += A[209]*rk_dim20_bPerm[9]; rk_dim20_bPerm[11] += A[220]*rk_dim20_bPerm[0]; rk_dim20_bPerm[11] += A[221]*rk_dim20_bPerm[1]; rk_dim20_bPerm[11] += A[222]*rk_dim20_bPerm[2]; rk_dim20_bPerm[11] += A[223]*rk_dim20_bPerm[3]; rk_dim20_bPerm[11] += A[224]*rk_dim20_bPerm[4]; rk_dim20_bPerm[11] += A[225]*rk_dim20_bPerm[5]; rk_dim20_bPerm[11] += A[226]*rk_dim20_bPerm[6]; rk_dim20_bPerm[11] += A[227]*rk_dim20_bPerm[7]; rk_dim20_bPerm[11] += A[228]*rk_dim20_bPerm[8]; rk_dim20_bPerm[11] += A[229]*rk_dim20_bPerm[9]; rk_dim20_bPerm[11] += A[230]*rk_dim20_bPerm[10]; rk_dim20_bPerm[12] += A[240]*rk_dim20_bPerm[0]; rk_dim20_bPerm[12] += A[241]*rk_dim20_bPerm[1]; rk_dim20_bPerm[12] += A[242]*rk_dim20_bPerm[2]; rk_dim20_bPerm[12] += A[243]*rk_dim20_bPerm[3]; rk_dim20_bPerm[12] += A[244]*rk_dim20_bPerm[4]; rk_dim20_bPerm[12] += A[245]*rk_dim20_bPerm[5]; rk_dim20_bPerm[12] += A[246]*rk_dim20_bPerm[6]; rk_dim20_bPerm[12] += A[247]*rk_dim20_bPerm[7]; rk_dim20_bPerm[12] += A[248]*rk_dim20_bPerm[8]; rk_dim20_bPerm[12] += A[249]*rk_dim20_bPerm[9]; rk_dim20_bPerm[12] += A[250]*rk_dim20_bPerm[10]; rk_dim20_bPerm[12] += A[251]*rk_dim20_bPerm[11]; rk_dim20_bPerm[13] += A[260]*rk_dim20_bPerm[0]; rk_dim20_bPerm[13] += A[261]*rk_dim20_bPerm[1]; rk_dim20_bPerm[13] += A[262]*rk_dim20_bPerm[2]; rk_dim20_bPerm[13] += A[263]*rk_dim20_bPerm[3]; rk_dim20_bPerm[13] += A[264]*rk_dim20_bPerm[4]; rk_dim20_bPerm[13] += A[265]*rk_dim20_bPerm[5]; rk_dim20_bPerm[13] += A[266]*rk_dim20_bPerm[6]; rk_dim20_bPerm[13] += A[267]*rk_dim20_bPerm[7]; rk_dim20_bPerm[13] += A[268]*rk_dim20_bPerm[8]; rk_dim20_bPerm[13] += A[269]*rk_dim20_bPerm[9]; rk_dim20_bPerm[13] += A[270]*rk_dim20_bPerm[10]; rk_dim20_bPerm[13] += A[271]*rk_dim20_bPerm[11]; rk_dim20_bPerm[13] += A[272]*rk_dim20_bPerm[12]; rk_dim20_bPerm[14] += A[280]*rk_dim20_bPerm[0]; rk_dim20_bPerm[14] += A[281]*rk_dim20_bPerm[1]; rk_dim20_bPerm[14] += A[282]*rk_dim20_bPerm[2]; rk_dim20_bPerm[14] += A[283]*rk_dim20_bPerm[3]; rk_dim20_bPerm[14] += A[284]*rk_dim20_bPerm[4]; rk_dim20_bPerm[14] += A[285]*rk_dim20_bPerm[5]; rk_dim20_bPerm[14] += A[286]*rk_dim20_bPerm[6]; rk_dim20_bPerm[14] += A[287]*rk_dim20_bPerm[7]; rk_dim20_bPerm[14] += A[288]*rk_dim20_bPerm[8]; rk_dim20_bPerm[14] += A[289]*rk_dim20_bPerm[9]; rk_dim20_bPerm[14] += A[290]*rk_dim20_bPerm[10]; rk_dim20_bPerm[14] += A[291]*rk_dim20_bPerm[11]; rk_dim20_bPerm[14] += A[292]*rk_dim20_bPerm[12]; rk_dim20_bPerm[14] += A[293]*rk_dim20_bPerm[13]; rk_dim20_bPerm[15] += A[300]*rk_dim20_bPerm[0]; rk_dim20_bPerm[15] += A[301]*rk_dim20_bPerm[1]; rk_dim20_bPerm[15] += A[302]*rk_dim20_bPerm[2]; rk_dim20_bPerm[15] += A[303]*rk_dim20_bPerm[3]; rk_dim20_bPerm[15] += A[304]*rk_dim20_bPerm[4]; rk_dim20_bPerm[15] += A[305]*rk_dim20_bPerm[5]; rk_dim20_bPerm[15] += A[306]*rk_dim20_bPerm[6]; rk_dim20_bPerm[15] += A[307]*rk_dim20_bPerm[7]; rk_dim20_bPerm[15] += A[308]*rk_dim20_bPerm[8]; rk_dim20_bPerm[15] += A[309]*rk_dim20_bPerm[9]; rk_dim20_bPerm[15] += A[310]*rk_dim20_bPerm[10]; rk_dim20_bPerm[15] += A[311]*rk_dim20_bPerm[11]; rk_dim20_bPerm[15] += A[312]*rk_dim20_bPerm[12]; rk_dim20_bPerm[15] += A[313]*rk_dim20_bPerm[13]; rk_dim20_bPerm[15] += A[314]*rk_dim20_bPerm[14]; rk_dim20_bPerm[16] += A[320]*rk_dim20_bPerm[0]; rk_dim20_bPerm[16] += A[321]*rk_dim20_bPerm[1]; rk_dim20_bPerm[16] += A[322]*rk_dim20_bPerm[2]; rk_dim20_bPerm[16] += A[323]*rk_dim20_bPerm[3]; rk_dim20_bPerm[16] += A[324]*rk_dim20_bPerm[4]; rk_dim20_bPerm[16] += A[325]*rk_dim20_bPerm[5]; rk_dim20_bPerm[16] += A[326]*rk_dim20_bPerm[6]; rk_dim20_bPerm[16] += A[327]*rk_dim20_bPerm[7]; rk_dim20_bPerm[16] += A[328]*rk_dim20_bPerm[8]; rk_dim20_bPerm[16] += A[329]*rk_dim20_bPerm[9]; rk_dim20_bPerm[16] += A[330]*rk_dim20_bPerm[10]; rk_dim20_bPerm[16] += A[331]*rk_dim20_bPerm[11]; rk_dim20_bPerm[16] += A[332]*rk_dim20_bPerm[12]; rk_dim20_bPerm[16] += A[333]*rk_dim20_bPerm[13]; rk_dim20_bPerm[16] += A[334]*rk_dim20_bPerm[14]; rk_dim20_bPerm[16] += A[335]*rk_dim20_bPerm[15]; rk_dim20_bPerm[17] += A[340]*rk_dim20_bPerm[0]; rk_dim20_bPerm[17] += A[341]*rk_dim20_bPerm[1]; rk_dim20_bPerm[17] += A[342]*rk_dim20_bPerm[2]; rk_dim20_bPerm[17] += A[343]*rk_dim20_bPerm[3]; rk_dim20_bPerm[17] += A[344]*rk_dim20_bPerm[4]; rk_dim20_bPerm[17] += A[345]*rk_dim20_bPerm[5]; rk_dim20_bPerm[17] += A[346]*rk_dim20_bPerm[6]; rk_dim20_bPerm[17] += A[347]*rk_dim20_bPerm[7]; rk_dim20_bPerm[17] += A[348]*rk_dim20_bPerm[8]; rk_dim20_bPerm[17] += A[349]*rk_dim20_bPerm[9]; rk_dim20_bPerm[17] += A[350]*rk_dim20_bPerm[10]; rk_dim20_bPerm[17] += A[351]*rk_dim20_bPerm[11]; rk_dim20_bPerm[17] += A[352]*rk_dim20_bPerm[12]; rk_dim20_bPerm[17] += A[353]*rk_dim20_bPerm[13]; rk_dim20_bPerm[17] += A[354]*rk_dim20_bPerm[14]; rk_dim20_bPerm[17] += A[355]*rk_dim20_bPerm[15]; rk_dim20_bPerm[17] += A[356]*rk_dim20_bPerm[16]; rk_dim20_bPerm[18] += A[360]*rk_dim20_bPerm[0]; rk_dim20_bPerm[18] += A[361]*rk_dim20_bPerm[1]; rk_dim20_bPerm[18] += A[362]*rk_dim20_bPerm[2]; rk_dim20_bPerm[18] += A[363]*rk_dim20_bPerm[3]; rk_dim20_bPerm[18] += A[364]*rk_dim20_bPerm[4]; rk_dim20_bPerm[18] += A[365]*rk_dim20_bPerm[5]; rk_dim20_bPerm[18] += A[366]*rk_dim20_bPerm[6]; rk_dim20_bPerm[18] += A[367]*rk_dim20_bPerm[7]; rk_dim20_bPerm[18] += A[368]*rk_dim20_bPerm[8]; rk_dim20_bPerm[18] += A[369]*rk_dim20_bPerm[9]; rk_dim20_bPerm[18] += A[370]*rk_dim20_bPerm[10]; rk_dim20_bPerm[18] += A[371]*rk_dim20_bPerm[11]; rk_dim20_bPerm[18] += A[372]*rk_dim20_bPerm[12]; rk_dim20_bPerm[18] += A[373]*rk_dim20_bPerm[13]; rk_dim20_bPerm[18] += A[374]*rk_dim20_bPerm[14]; rk_dim20_bPerm[18] += A[375]*rk_dim20_bPerm[15]; rk_dim20_bPerm[18] += A[376]*rk_dim20_bPerm[16]; rk_dim20_bPerm[18] += A[377]*rk_dim20_bPerm[17]; rk_dim20_bPerm[19] += A[380]*rk_dim20_bPerm[0]; rk_dim20_bPerm[19] += A[381]*rk_dim20_bPerm[1]; rk_dim20_bPerm[19] += A[382]*rk_dim20_bPerm[2]; rk_dim20_bPerm[19] += A[383]*rk_dim20_bPerm[3]; rk_dim20_bPerm[19] += A[384]*rk_dim20_bPerm[4]; rk_dim20_bPerm[19] += A[385]*rk_dim20_bPerm[5]; rk_dim20_bPerm[19] += A[386]*rk_dim20_bPerm[6]; rk_dim20_bPerm[19] += A[387]*rk_dim20_bPerm[7]; rk_dim20_bPerm[19] += A[388]*rk_dim20_bPerm[8]; rk_dim20_bPerm[19] += A[389]*rk_dim20_bPerm[9]; rk_dim20_bPerm[19] += A[390]*rk_dim20_bPerm[10]; rk_dim20_bPerm[19] += A[391]*rk_dim20_bPerm[11]; rk_dim20_bPerm[19] += A[392]*rk_dim20_bPerm[12]; rk_dim20_bPerm[19] += A[393]*rk_dim20_bPerm[13]; rk_dim20_bPerm[19] += A[394]*rk_dim20_bPerm[14]; rk_dim20_bPerm[19] += A[395]*rk_dim20_bPerm[15]; rk_dim20_bPerm[19] += A[396]*rk_dim20_bPerm[16]; rk_dim20_bPerm[19] += A[397]*rk_dim20_bPerm[17]; rk_dim20_bPerm[19] += A[398]*rk_dim20_bPerm[18]; acado_solve_dim20_triangular( A, rk_dim20_bPerm ); b[0] = rk_dim20_bPerm[0]; b[1] = rk_dim20_bPerm[1]; b[2] = rk_dim20_bPerm[2]; b[3] = rk_dim20_bPerm[3]; b[4] = rk_dim20_bPerm[4]; b[5] = rk_dim20_bPerm[5]; b[6] = rk_dim20_bPerm[6]; b[7] = rk_dim20_bPerm[7]; b[8] = rk_dim20_bPerm[8]; b[9] = rk_dim20_bPerm[9]; b[10] = rk_dim20_bPerm[10]; b[11] = rk_dim20_bPerm[11]; b[12] = rk_dim20_bPerm[12]; b[13] = rk_dim20_bPerm[13]; b[14] = rk_dim20_bPerm[14]; b[15] = rk_dim20_bPerm[15]; b[16] = rk_dim20_bPerm[16]; b[17] = rk_dim20_bPerm[17]; b[18] = rk_dim20_bPerm[18]; b[19] = rk_dim20_bPerm[19]; } /** Matrix of size: 2 x 2 (row major format) */ static const real_t acado_Ah_mat[ 4 ] = { 2.5000000000000001e-02, 5.3867513459481292e-02, -3.8675134594812867e-03, 2.5000000000000001e-02 }; /* Fixed step size:0.1 */ int acado_integrate( real_t* const rk_eta, int resetIntegrator ) { int error; int i; int j; int k; int run; int run1; int tmp_index1; int tmp_index2; real_t det; rk_ttt = 0.0000000000000000e+00; rk_xxx[10] = rk_eta[150]; rk_xxx[11] = rk_eta[151]; rk_xxx[12] = rk_eta[152]; rk_xxx[13] = rk_eta[153]; rk_xxx[14] = rk_eta[154]; rk_xxx[15] = rk_eta[155]; rk_xxx[16] = rk_eta[156]; rk_xxx[17] = rk_eta[157]; rk_xxx[18] = rk_eta[158]; rk_xxx[19] = rk_eta[159]; rk_xxx[20] = rk_eta[160]; rk_xxx[21] = rk_eta[161]; rk_xxx[22] = rk_eta[162]; rk_xxx[23] = rk_eta[163]; for (run = 0; run < 1; ++run) { if( resetIntegrator ) { for (i = 0; i < 1; ++i) { for (run1 = 0; run1 < 2; ++run1) { for (j = 0; j < 10; ++j) { rk_xxx[j] = rk_eta[j]; tmp_index1 = j; rk_xxx[j] += + acado_Ah_mat[run1 * 2]*rk_kkk[tmp_index1 * 2]; rk_xxx[j] += + acado_Ah_mat[run1 * 2 + 1]*rk_kkk[tmp_index1 * 2 + 1]; } acado_diffs( rk_xxx, &(rk_diffsTemp2[ run1 * 140 ]) ); for (j = 0; j < 10; ++j) { tmp_index1 = (run1 * 10) + (j); rk_A[tmp_index1 * 20] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14)]; rk_A[tmp_index1 * 20 + 1] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 1)]; rk_A[tmp_index1 * 20 + 2] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 2)]; rk_A[tmp_index1 * 20 + 3] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 3)]; rk_A[tmp_index1 * 20 + 4] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 4)]; rk_A[tmp_index1 * 20 + 5] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 5)]; rk_A[tmp_index1 * 20 + 6] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 6)]; rk_A[tmp_index1 * 20 + 7] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 7)]; rk_A[tmp_index1 * 20 + 8] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 8)]; rk_A[tmp_index1 * 20 + 9] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 9)]; if( 0 == run1 ) rk_A[(tmp_index1 * 20) + (j)] -= 1.0000000000000000e+00; rk_A[tmp_index1 * 20 + 10] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14)]; rk_A[tmp_index1 * 20 + 11] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 1)]; rk_A[tmp_index1 * 20 + 12] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 2)]; rk_A[tmp_index1 * 20 + 13] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 3)]; rk_A[tmp_index1 * 20 + 14] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 4)]; rk_A[tmp_index1 * 20 + 15] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 5)]; rk_A[tmp_index1 * 20 + 16] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 6)]; rk_A[tmp_index1 * 20 + 17] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 7)]; rk_A[tmp_index1 * 20 + 18] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 8)]; rk_A[tmp_index1 * 20 + 19] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 9)]; if( 1 == run1 ) rk_A[(tmp_index1 * 20) + (j + 10)] -= 1.0000000000000000e+00; } acado_rhs( rk_xxx, rk_rhsTemp ); rk_b[run1 * 10] = rk_kkk[run1] - rk_rhsTemp[0]; rk_b[run1 * 10 + 1] = rk_kkk[run1 + 2] - rk_rhsTemp[1]; rk_b[run1 * 10 + 2] = rk_kkk[run1 + 4] - rk_rhsTemp[2]; rk_b[run1 * 10 + 3] = rk_kkk[run1 + 6] - rk_rhsTemp[3]; rk_b[run1 * 10 + 4] = rk_kkk[run1 + 8] - rk_rhsTemp[4]; rk_b[run1 * 10 + 5] = rk_kkk[run1 + 10] - rk_rhsTemp[5]; rk_b[run1 * 10 + 6] = rk_kkk[run1 + 12] - rk_rhsTemp[6]; rk_b[run1 * 10 + 7] = rk_kkk[run1 + 14] - rk_rhsTemp[7]; rk_b[run1 * 10 + 8] = rk_kkk[run1 + 16] - rk_rhsTemp[8]; rk_b[run1 * 10 + 9] = rk_kkk[run1 + 18] - rk_rhsTemp[9]; } det = acado_solve_dim20_system( rk_A, rk_b, rk_dim20_perm ); for (j = 0; j < 2; ++j) { rk_kkk[j] += rk_b[j * 10]; rk_kkk[j + 2] += rk_b[j * 10 + 1]; rk_kkk[j + 4] += rk_b[j * 10 + 2]; rk_kkk[j + 6] += rk_b[j * 10 + 3]; rk_kkk[j + 8] += rk_b[j * 10 + 4]; rk_kkk[j + 10] += rk_b[j * 10 + 5]; rk_kkk[j + 12] += rk_b[j * 10 + 6]; rk_kkk[j + 14] += rk_b[j * 10 + 7]; rk_kkk[j + 16] += rk_b[j * 10 + 8]; rk_kkk[j + 18] += rk_b[j * 10 + 9]; } } } for (i = 0; i < 5; ++i) { for (run1 = 0; run1 < 2; ++run1) { for (j = 0; j < 10; ++j) { rk_xxx[j] = rk_eta[j]; tmp_index1 = j; rk_xxx[j] += + acado_Ah_mat[run1 * 2]*rk_kkk[tmp_index1 * 2]; rk_xxx[j] += + acado_Ah_mat[run1 * 2 + 1]*rk_kkk[tmp_index1 * 2 + 1]; } acado_rhs( rk_xxx, rk_rhsTemp ); rk_b[run1 * 10] = rk_kkk[run1] - rk_rhsTemp[0]; rk_b[run1 * 10 + 1] = rk_kkk[run1 + 2] - rk_rhsTemp[1]; rk_b[run1 * 10 + 2] = rk_kkk[run1 + 4] - rk_rhsTemp[2]; rk_b[run1 * 10 + 3] = rk_kkk[run1 + 6] - rk_rhsTemp[3]; rk_b[run1 * 10 + 4] = rk_kkk[run1 + 8] - rk_rhsTemp[4]; rk_b[run1 * 10 + 5] = rk_kkk[run1 + 10] - rk_rhsTemp[5]; rk_b[run1 * 10 + 6] = rk_kkk[run1 + 12] - rk_rhsTemp[6]; rk_b[run1 * 10 + 7] = rk_kkk[run1 + 14] - rk_rhsTemp[7]; rk_b[run1 * 10 + 8] = rk_kkk[run1 + 16] - rk_rhsTemp[8]; rk_b[run1 * 10 + 9] = rk_kkk[run1 + 18] - rk_rhsTemp[9]; } acado_solve_dim20_system_reuse( rk_A, rk_b, rk_dim20_perm ); for (j = 0; j < 2; ++j) { rk_kkk[j] += rk_b[j * 10]; rk_kkk[j + 2] += rk_b[j * 10 + 1]; rk_kkk[j + 4] += rk_b[j * 10 + 2]; rk_kkk[j + 6] += rk_b[j * 10 + 3]; rk_kkk[j + 8] += rk_b[j * 10 + 4]; rk_kkk[j + 10] += rk_b[j * 10 + 5]; rk_kkk[j + 12] += rk_b[j * 10 + 6]; rk_kkk[j + 14] += rk_b[j * 10 + 7]; rk_kkk[j + 16] += rk_b[j * 10 + 8]; rk_kkk[j + 18] += rk_b[j * 10 + 9]; } } for (run1 = 0; run1 < 2; ++run1) { for (j = 0; j < 10; ++j) { rk_xxx[j] = rk_eta[j]; tmp_index1 = j; rk_xxx[j] += + acado_Ah_mat[run1 * 2]*rk_kkk[tmp_index1 * 2]; rk_xxx[j] += + acado_Ah_mat[run1 * 2 + 1]*rk_kkk[tmp_index1 * 2 + 1]; } acado_diffs( rk_xxx, &(rk_diffsTemp2[ run1 * 140 ]) ); for (j = 0; j < 10; ++j) { tmp_index1 = (run1 * 10) + (j); rk_A[tmp_index1 * 20] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14)]; rk_A[tmp_index1 * 20 + 1] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 1)]; rk_A[tmp_index1 * 20 + 2] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 2)]; rk_A[tmp_index1 * 20 + 3] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 3)]; rk_A[tmp_index1 * 20 + 4] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 4)]; rk_A[tmp_index1 * 20 + 5] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 5)]; rk_A[tmp_index1 * 20 + 6] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 6)]; rk_A[tmp_index1 * 20 + 7] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 7)]; rk_A[tmp_index1 * 20 + 8] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 8)]; rk_A[tmp_index1 * 20 + 9] = + acado_Ah_mat[run1 * 2]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 9)]; if( 0 == run1 ) rk_A[(tmp_index1 * 20) + (j)] -= 1.0000000000000000e+00; rk_A[tmp_index1 * 20 + 10] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14)]; rk_A[tmp_index1 * 20 + 11] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 1)]; rk_A[tmp_index1 * 20 + 12] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 2)]; rk_A[tmp_index1 * 20 + 13] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 3)]; rk_A[tmp_index1 * 20 + 14] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 4)]; rk_A[tmp_index1 * 20 + 15] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 5)]; rk_A[tmp_index1 * 20 + 16] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 6)]; rk_A[tmp_index1 * 20 + 17] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 7)]; rk_A[tmp_index1 * 20 + 18] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 8)]; rk_A[tmp_index1 * 20 + 19] = + acado_Ah_mat[run1 * 2 + 1]*rk_diffsTemp2[(run1 * 140) + (j * 14 + 9)]; if( 1 == run1 ) rk_A[(tmp_index1 * 20) + (j + 10)] -= 1.0000000000000000e+00; } } for (run1 = 0; run1 < 10; ++run1) { for (i = 0; i < 2; ++i) { rk_b[i * 10] = - rk_diffsTemp2[(i * 140) + (run1)]; rk_b[i * 10 + 1] = - rk_diffsTemp2[(i * 140) + (run1 + 14)]; rk_b[i * 10 + 2] = - rk_diffsTemp2[(i * 140) + (run1 + 28)]; rk_b[i * 10 + 3] = - rk_diffsTemp2[(i * 140) + (run1 + 42)]; rk_b[i * 10 + 4] = - rk_diffsTemp2[(i * 140) + (run1 + 56)]; rk_b[i * 10 + 5] = - rk_diffsTemp2[(i * 140) + (run1 + 70)]; rk_b[i * 10 + 6] = - rk_diffsTemp2[(i * 140) + (run1 + 84)]; rk_b[i * 10 + 7] = - rk_diffsTemp2[(i * 140) + (run1 + 98)]; rk_b[i * 10 + 8] = - rk_diffsTemp2[(i * 140) + (run1 + 112)]; rk_b[i * 10 + 9] = - rk_diffsTemp2[(i * 140) + (run1 + 126)]; } if( 0 == run1 ) { det = acado_solve_dim20_system( rk_A, rk_b, rk_dim20_perm ); } else { acado_solve_dim20_system_reuse( rk_A, rk_b, rk_dim20_perm ); } for (i = 0; i < 2; ++i) { rk_diffK[i] = rk_b[i * 10]; rk_diffK[i + 2] = rk_b[i * 10 + 1]; rk_diffK[i + 4] = rk_b[i * 10 + 2]; rk_diffK[i + 6] = rk_b[i * 10 + 3]; rk_diffK[i + 8] = rk_b[i * 10 + 4]; rk_diffK[i + 10] = rk_b[i * 10 + 5]; rk_diffK[i + 12] = rk_b[i * 10 + 6]; rk_diffK[i + 14] = rk_b[i * 10 + 7]; rk_diffK[i + 16] = rk_b[i * 10 + 8]; rk_diffK[i + 18] = rk_b[i * 10 + 9]; } for (i = 0; i < 10; ++i) { rk_diffsNew2[(i * 14) + (run1)] = (i == run1-0); rk_diffsNew2[(i * 14) + (run1)] += + rk_diffK[i * 2]*(real_t)5.0000000000000003e-02 + rk_diffK[i * 2 + 1]*(real_t)5.0000000000000003e-02; } } for (run1 = 0; run1 < 4; ++run1) { for (i = 0; i < 2; ++i) { for (j = 0; j < 10; ++j) { tmp_index1 = (i * 10) + (j); tmp_index2 = (run1) + (j * 14); rk_b[tmp_index1] = - rk_diffsTemp2[(i * 140) + (tmp_index2 + 10)]; } } acado_solve_dim20_system_reuse( rk_A, rk_b, rk_dim20_perm ); for (i = 0; i < 2; ++i) { rk_diffK[i] = rk_b[i * 10]; rk_diffK[i + 2] = rk_b[i * 10 + 1]; rk_diffK[i + 4] = rk_b[i * 10 + 2]; rk_diffK[i + 6] = rk_b[i * 10 + 3]; rk_diffK[i + 8] = rk_b[i * 10 + 4]; rk_diffK[i + 10] = rk_b[i * 10 + 5]; rk_diffK[i + 12] = rk_b[i * 10 + 6]; rk_diffK[i + 14] = rk_b[i * 10 + 7]; rk_diffK[i + 16] = rk_b[i * 10 + 8]; rk_diffK[i + 18] = rk_b[i * 10 + 9]; } for (i = 0; i < 10; ++i) { rk_diffsNew2[(i * 14) + (run1 + 10)] = + rk_diffK[i * 2]*(real_t)5.0000000000000003e-02 + rk_diffK[i * 2 + 1]*(real_t)5.0000000000000003e-02; } } rk_eta[0] += + rk_kkk[0]*(real_t)5.0000000000000003e-02 + rk_kkk[1]*(real_t)5.0000000000000003e-02; rk_eta[1] += + rk_kkk[2]*(real_t)5.0000000000000003e-02 + rk_kkk[3]*(real_t)5.0000000000000003e-02; rk_eta[2] += + rk_kkk[4]*(real_t)5.0000000000000003e-02 + rk_kkk[5]*(real_t)5.0000000000000003e-02; rk_eta[3] += + rk_kkk[6]*(real_t)5.0000000000000003e-02 + rk_kkk[7]*(real_t)5.0000000000000003e-02; rk_eta[4] += + rk_kkk[8]*(real_t)5.0000000000000003e-02 + rk_kkk[9]*(real_t)5.0000000000000003e-02; rk_eta[5] += + rk_kkk[10]*(real_t)5.0000000000000003e-02 + rk_kkk[11]*(real_t)5.0000000000000003e-02; rk_eta[6] += + rk_kkk[12]*(real_t)5.0000000000000003e-02 + rk_kkk[13]*(real_t)5.0000000000000003e-02; rk_eta[7] += + rk_kkk[14]*(real_t)5.0000000000000003e-02 + rk_kkk[15]*(real_t)5.0000000000000003e-02; rk_eta[8] += + rk_kkk[16]*(real_t)5.0000000000000003e-02 + rk_kkk[17]*(real_t)5.0000000000000003e-02; rk_eta[9] += + rk_kkk[18]*(real_t)5.0000000000000003e-02 + rk_kkk[19]*(real_t)5.0000000000000003e-02; for (i = 0; i < 10; ++i) { for (j = 0; j < 10; ++j) { tmp_index2 = (j) + (i * 10); rk_eta[tmp_index2 + 10] = rk_diffsNew2[(i * 14) + (j)]; } for (j = 0; j < 4; ++j) { tmp_index2 = (j) + (i * 4); rk_eta[tmp_index2 + 110] = rk_diffsNew2[(i * 14) + (j + 10)]; } } resetIntegrator = 0; rk_ttt += 1.0000000000000000e+00; } for (i = 0; i < 10; ++i) { } if( det < 1e-12 ) { error = 2; } else if( det < 1e-6 ) { error = 1; } else { error = 0; } return error; }
GB_calloc_memory.c
//------------------------------------------------------------------------------ // GB_calloc_memory: wrapper for calloc //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2018, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // A wrapper for CALLOC. Space is set to zero. // Parameters are the same as the POSIX calloc, except that asking to allocate // a block of zero size causes a block of size 1 to be allocated instead. This // allows the return pointer p to be checked for the out-of-memory condition, // even when allocating an object of size zero. // By default, CALLOC is defined in GB.h as calloc. For a MATLAB mexFunction, // it is mxCalloc. It can also be defined at compile time with // -DCALLOC=mycallocfunc. #include "GB.h" void *GB_calloc_memory // pointer to allocated block of memory ( size_t nitems, // number of items to allocate size_t size_of_item // sizeof each item ) { void *p ; size_t size ; int nmalloc ; // make sure at least one item is allocated nitems = IMAX (1, nitems) ; // make sure at least one byte is allocated size_of_item = IMAX (1, size_of_item) ; bool ok = GB_size_t_multiply (&size, nitems, size_of_item) ; if (!ok || nitems > GB_INDEX_MAX || size_of_item > GB_INDEX_MAX) { // overflow p = NULL ; } else { // check the malloc debug status. This debug flag is set outside // of GraphBLAS and not modified, so it is safe to check it outside // a critical section. bool pretend_to_fail = false ; if (GB_Global.malloc_debug) { // brutal malloc debug; pretend to fail if the count <= 0 #pragma omp critical (GB_memory) { pretend_to_fail = (GB_Global.malloc_debug_count-- <= 0) ; } } if (pretend_to_fail) { p = NULL ; } else { p = (void *) CALLOC (nitems, size_of_item) ; } if (p != NULL) { #pragma omp critical (GB_memory) { nmalloc = ++GB_Global.nmalloc ; GB_Global.inuse += nitems * size_of_item ; GB_Global.maxused = IMAX (GB_Global.maxused, GB_Global.inuse) ; } #ifdef PRINT_MALLOC printf ("calloc: %14p %3d %1d n "GBd" size "GBd"\n", p, nmalloc, GB_Global.malloc_debug, (int64_t) nitems, (int64_t) size_of_item) ; #endif } } return (p) ; }
ASTMatchers.h
//===- ASTMatchers.h - Structural query framework ---------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements matchers to be used together with the MatchFinder to // match AST nodes. // // Matchers are created by generator functions, which can be combined in // a functional in-language DSL to express queries over the C++ AST. // // For example, to match a class with a certain name, one would call: // cxxRecordDecl(hasName("MyClass")) // which returns a matcher that can be used to find all AST nodes that declare // a class named 'MyClass'. // // For more complicated match expressions we're often interested in accessing // multiple parts of the matched AST nodes once a match is found. In that case, // call `.bind("name")` on match expressions that match the nodes you want to // access. // // For example, when we're interested in child classes of a certain class, we // would write: // cxxRecordDecl(hasName("MyClass"), has(recordDecl().bind("child"))) // When the match is found via the MatchFinder, a user provided callback will // be called with a BoundNodes instance that contains a mapping from the // strings that we provided for the `.bind()` calls to the nodes that were // matched. // In the given example, each time our matcher finds a match we get a callback // where "child" is bound to the RecordDecl node of the matching child // class declaration. // // See ASTMatchersInternal.h for a more in-depth explanation of the // implementation details of the matcher framework. // // See ASTMatchFinder.h for how to use the generated matchers to run over // an AST. // //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #define LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H #include "clang/AST/ASTContext.h" #include "clang/AST/ASTTypeTraits.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/Decl.h" #include "clang/AST/DeclCXX.h" #include "clang/AST/DeclFriend.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Expr.h" #include "clang/AST/ExprCXX.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/LambdaCapture.h" #include "clang/AST/NestedNameSpecifier.h" #include "clang/AST/OpenMPClause.h" #include "clang/AST/OperationKinds.h" #include "clang/AST/ParentMapContext.h" #include "clang/AST/Stmt.h" #include "clang/AST/StmtCXX.h" #include "clang/AST/StmtObjC.h" #include "clang/AST/StmtOpenMP.h" #include "clang/AST/TemplateBase.h" #include "clang/AST/TemplateName.h" #include "clang/AST/Type.h" #include "clang/AST/TypeLoc.h" #include "clang/ASTMatchers/ASTMatchersInternal.h" #include "clang/ASTMatchers/ASTMatchersMacros.h" #include "clang/Basic/AttrKinds.h" #include "clang/Basic/ExceptionSpecificationType.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/LLVM.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/Specifiers.h" #include "clang/Basic/TypeTraits.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Regex.h" #include <cassert> #include <cstddef> #include <iterator> #include <limits> #include <string> #include <utility> #include <vector> namespace clang { namespace ast_matchers { /// Maps string IDs to AST nodes matched by parts of a matcher. /// /// The bound nodes are generated by calling \c bind("id") on the node matchers /// of the nodes we want to access later. /// /// The instances of BoundNodes are created by \c MatchFinder when the user's /// callbacks are executed every time a match is found. class BoundNodes { public: /// Returns the AST node bound to \c ID. /// /// Returns NULL if there was no node bound to \c ID or if there is a node but /// it cannot be converted to the specified type. template <typename T> const T *getNodeAs(StringRef ID) const { return MyBoundNodes.getNodeAs<T>(ID); } /// Type of mapping from binding identifiers to bound nodes. This type /// is an associative container with a key type of \c std::string and a value /// type of \c clang::DynTypedNode using IDToNodeMap = internal::BoundNodesMap::IDToNodeMap; /// Retrieve mapping from binding identifiers to bound nodes. const IDToNodeMap &getMap() const { return MyBoundNodes.getMap(); } private: friend class internal::BoundNodesTreeBuilder; /// Create BoundNodes from a pre-filled map of bindings. BoundNodes(internal::BoundNodesMap &MyBoundNodes) : MyBoundNodes(MyBoundNodes) {} internal::BoundNodesMap MyBoundNodes; }; /// Types of matchers for the top-level classes in the AST class /// hierarchy. /// @{ using DeclarationMatcher = internal::Matcher<Decl>; using StatementMatcher = internal::Matcher<Stmt>; using TypeMatcher = internal::Matcher<QualType>; using TypeLocMatcher = internal::Matcher<TypeLoc>; using NestedNameSpecifierMatcher = internal::Matcher<NestedNameSpecifier>; using NestedNameSpecifierLocMatcher = internal::Matcher<NestedNameSpecifierLoc>; using CXXCtorInitializerMatcher = internal::Matcher<CXXCtorInitializer>; using TemplateArgumentMatcher = internal::Matcher<TemplateArgument>; using TemplateArgumentLocMatcher = internal::Matcher<TemplateArgumentLoc>; /// @} /// Matches any node. /// /// Useful when another matcher requires a child matcher, but there's no /// additional constraint. This will often be used with an explicit conversion /// to an \c internal::Matcher<> type such as \c TypeMatcher. /// /// Example: \c DeclarationMatcher(anything()) matches all declarations, e.g., /// \code /// "int* p" and "void f()" in /// int* p; /// void f(); /// \endcode /// /// Usable as: Any Matcher inline internal::TrueMatcher anything() { return internal::TrueMatcher(); } /// Matches the top declaration context. /// /// Given /// \code /// int X; /// namespace NS { /// int Y; /// } // namespace NS /// \endcode /// decl(hasDeclContext(translationUnitDecl())) /// matches "int X", but not "int Y". extern const internal::VariadicDynCastAllOfMatcher<Decl, TranslationUnitDecl> translationUnitDecl; /// Matches typedef declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typedefDecl() /// matches "typedef int X", but not "using Y = int" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefDecl> typedefDecl; /// Matches typedef name declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typedefNameDecl() /// matches "typedef int X" and "using Y = int" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypedefNameDecl> typedefNameDecl; /// Matches type alias declarations. /// /// Given /// \code /// typedef int X; /// using Y = int; /// \endcode /// typeAliasDecl() /// matches "using Y = int", but not "typedef int X" extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasDecl> typeAliasDecl; /// Matches type alias template declarations. /// /// typeAliasTemplateDecl() matches /// \code /// template <typename T> /// using Y = X<T>; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, TypeAliasTemplateDecl> typeAliasTemplateDecl; /// Matches AST nodes that were expanded within the main-file. /// /// Example matches X but not Y /// (matcher = cxxRecordDecl(isExpansionInMainFile()) /// \code /// #include <Y.h> /// class X {}; /// \endcode /// Y.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInMainFile, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); return SourceManager.isInMainFile( SourceManager.getExpansionLoc(Node.getBeginLoc())); } /// Matches AST nodes that were expanded within system-header-files. /// /// Example matches Y but not X /// (matcher = cxxRecordDecl(isExpansionInSystemHeader()) /// \code /// #include <SystemHeader.h> /// class X {}; /// \endcode /// SystemHeader.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER(isExpansionInSystemHeader, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc)) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc()); if (ExpansionLoc.isInvalid()) { return false; } return SourceManager.isInSystemHeader(ExpansionLoc); } /// Matches AST nodes that were expanded within files whose name is /// partially matching a given regex. /// /// Example matches Y but not X /// (matcher = cxxRecordDecl(isExpansionInFileMatching("AST.*")) /// \code /// #include "ASTMatcher.h" /// class X {}; /// \endcode /// ASTMatcher.h: /// \code /// class Y {}; /// \endcode /// /// Usable as: Matcher<Decl>, Matcher<Stmt>, Matcher<TypeLoc> AST_POLYMORPHIC_MATCHER_REGEX(isExpansionInFileMatching, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), RegExp) { auto &SourceManager = Finder->getASTContext().getSourceManager(); auto ExpansionLoc = SourceManager.getExpansionLoc(Node.getBeginLoc()); if (ExpansionLoc.isInvalid()) { return false; } auto FileEntry = SourceManager.getFileEntryForID(SourceManager.getFileID(ExpansionLoc)); if (!FileEntry) { return false; } auto Filename = FileEntry->getName(); return RegExp->match(Filename); } /// Matches statements that are (transitively) expanded from the named macro. /// Does not match if only part of the statement is expanded from that macro or /// if different parts of the the statement are expanded from different /// appearances of the macro. AST_POLYMORPHIC_MATCHER_P(isExpandedFromMacro, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, Stmt, TypeLoc), std::string, MacroName) { // Verifies that the statement' beginning and ending are both expanded from // the same instance of the given macro. auto& Context = Finder->getASTContext(); llvm::Optional<SourceLocation> B = internal::getExpansionLocOfMacro(MacroName, Node.getBeginLoc(), Context); if (!B) return false; llvm::Optional<SourceLocation> E = internal::getExpansionLocOfMacro(MacroName, Node.getEndLoc(), Context); if (!E) return false; return *B == *E; } /// Matches declarations. /// /// Examples matches \c X, \c C, and the friend declaration inside \c C; /// \code /// void X(); /// class C { /// friend X; /// }; /// \endcode extern const internal::VariadicAllOfMatcher<Decl> decl; /// Matches decomposition-declarations. /// /// Examples matches the declaration node with \c foo and \c bar, but not /// \c number. /// (matcher = declStmt(has(decompositionDecl()))) /// /// \code /// int number = 42; /// auto [foo, bar] = std::make_pair{42, 42}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, DecompositionDecl> decompositionDecl; /// Matches binding declarations /// Example matches \c foo and \c bar /// (matcher = bindingDecl() /// /// \code /// auto [foo, bar] = std::make_pair{42, 42}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, BindingDecl> bindingDecl; /// Matches a declaration of a linkage specification. /// /// Given /// \code /// extern "C" {} /// \endcode /// linkageSpecDecl() /// matches "extern "C" {}" extern const internal::VariadicDynCastAllOfMatcher<Decl, LinkageSpecDecl> linkageSpecDecl; /// Matches a declaration of anything that could have a name. /// /// Example matches \c X, \c S, the anonymous union type, \c i, and \c U; /// \code /// typedef int X; /// struct S { /// union { /// int i; /// } U; /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, NamedDecl> namedDecl; /// Matches a declaration of label. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// labelDecl() /// matches 'FOO:' extern const internal::VariadicDynCastAllOfMatcher<Decl, LabelDecl> labelDecl; /// Matches a declaration of a namespace. /// /// Given /// \code /// namespace {} /// namespace test {} /// \endcode /// namespaceDecl() /// matches "namespace {}" and "namespace test {}" extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceDecl> namespaceDecl; /// Matches a declaration of a namespace alias. /// /// Given /// \code /// namespace test {} /// namespace alias = ::test; /// \endcode /// namespaceAliasDecl() /// matches "namespace alias" but not "namespace test" extern const internal::VariadicDynCastAllOfMatcher<Decl, NamespaceAliasDecl> namespaceAliasDecl; /// Matches class, struct, and union declarations. /// /// Example matches \c X, \c Z, \c U, and \c S /// \code /// class X; /// template<class T> class Z {}; /// struct S {}; /// union U {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, RecordDecl> recordDecl; /// Matches C++ class declarations. /// /// Example matches \c X, \c Z /// \code /// class X; /// template<class T> class Z {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXRecordDecl> cxxRecordDecl; /// Matches C++ class template declarations. /// /// Example matches \c Z /// \code /// template<class T> class Z {}; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ClassTemplateDecl> classTemplateDecl; /// Matches C++ class template specializations. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// \endcode /// classTemplateSpecializationDecl() /// matches the specializations \c A<int> and \c A<double> extern const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplateSpecializationDecl> classTemplateSpecializationDecl; /// Matches C++ class template partial specializations. /// /// Given /// \code /// template<class T1, class T2, int I> /// class A {}; /// /// template<class T, int I> /// class A<T, T*, I> {}; /// /// template<> /// class A<int, int, 1> {}; /// \endcode /// classTemplatePartialSpecializationDecl() /// matches the specialization \c A<T,T*,I> but not \c A<int,int,1> extern const internal::VariadicDynCastAllOfMatcher< Decl, ClassTemplatePartialSpecializationDecl> classTemplatePartialSpecializationDecl; /// Matches declarator declarations (field, variable, function /// and non-type template parameter declarations). /// /// Given /// \code /// class X { int y; }; /// \endcode /// declaratorDecl() /// matches \c int y. extern const internal::VariadicDynCastAllOfMatcher<Decl, DeclaratorDecl> declaratorDecl; /// Matches parameter variable declarations. /// /// Given /// \code /// void f(int x); /// \endcode /// parmVarDecl() /// matches \c int x. extern const internal::VariadicDynCastAllOfMatcher<Decl, ParmVarDecl> parmVarDecl; /// Matches C++ access specifier declarations. /// /// Given /// \code /// class C { /// public: /// int a; /// }; /// \endcode /// accessSpecDecl() /// matches 'public:' extern const internal::VariadicDynCastAllOfMatcher<Decl, AccessSpecDecl> accessSpecDecl; /// Matches constructor initializers. /// /// Examples matches \c i(42). /// \code /// class C { /// C() : i(42) {} /// int i; /// }; /// \endcode extern const internal::VariadicAllOfMatcher<CXXCtorInitializer> cxxCtorInitializer; /// Matches template arguments. /// /// Given /// \code /// template <typename T> struct C {}; /// C<int> c; /// \endcode /// templateArgument() /// matches 'int' in C<int>. extern const internal::VariadicAllOfMatcher<TemplateArgument> templateArgument; /// Matches template arguments (with location info). /// /// Given /// \code /// template <typename T> struct C {}; /// C<int> c; /// \endcode /// templateArgumentLoc() /// matches 'int' in C<int>. extern const internal::VariadicAllOfMatcher<TemplateArgumentLoc> templateArgumentLoc; /// Matches template name. /// /// Given /// \code /// template <typename T> class X { }; /// X<int> xi; /// \endcode /// templateName() /// matches 'X' in X<int>. extern const internal::VariadicAllOfMatcher<TemplateName> templateName; /// Matches non-type template parameter declarations. /// /// Given /// \code /// template <typename T, int N> struct C {}; /// \endcode /// nonTypeTemplateParmDecl() /// matches 'N', but not 'T'. extern const internal::VariadicDynCastAllOfMatcher<Decl, NonTypeTemplateParmDecl> nonTypeTemplateParmDecl; /// Matches template type parameter declarations. /// /// Given /// \code /// template <typename T, int N> struct C {}; /// \endcode /// templateTypeParmDecl() /// matches 'T', but not 'N'. extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTypeParmDecl> templateTypeParmDecl; /// Matches template template parameter declarations. /// /// Given /// \code /// template <template <typename> class Z, int N> struct C {}; /// \endcode /// templateTypeParmDecl() /// matches 'Z', but not 'N'. extern const internal::VariadicDynCastAllOfMatcher<Decl, TemplateTemplateParmDecl> templateTemplateParmDecl; /// Matches public C++ declarations and C++ base specifers that specify public /// inheritance. /// /// Examples: /// \code /// class C { /// public: int a; // fieldDecl(isPublic()) matches 'a' /// protected: int b; /// private: int c; /// }; /// \endcode /// /// \code /// class Base {}; /// class Derived1 : public Base {}; // matches 'Base' /// struct Derived2 : Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isPublic, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_public; } /// Matches protected C++ declarations and C++ base specifers that specify /// protected inheritance. /// /// Examples: /// \code /// class C { /// public: int a; /// protected: int b; // fieldDecl(isProtected()) matches 'b' /// private: int c; /// }; /// \endcode /// /// \code /// class Base {}; /// class Derived : protected Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isProtected, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_protected; } /// Matches private C++ declarations and C++ base specifers that specify private /// inheritance. /// /// Examples: /// \code /// class C { /// public: int a; /// protected: int b; /// private: int c; // fieldDecl(isPrivate()) matches 'c' /// }; /// \endcode /// /// \code /// struct Base {}; /// struct Derived1 : private Base {}; // matches 'Base' /// class Derived2 : Base {}; // matches 'Base' /// \endcode AST_POLYMORPHIC_MATCHER(isPrivate, AST_POLYMORPHIC_SUPPORTED_TYPES(Decl, CXXBaseSpecifier)) { return getAccessSpecifier(Node) == AS_private; } /// Matches non-static data members that are bit-fields. /// /// Given /// \code /// class C { /// int a : 2; /// int b; /// }; /// \endcode /// fieldDecl(isBitField()) /// matches 'int a;' but not 'int b;'. AST_MATCHER(FieldDecl, isBitField) { return Node.isBitField(); } /// Matches non-static data members that are bit-fields of the specified /// bit width. /// /// Given /// \code /// class C { /// int a : 2; /// int b : 4; /// int c : 2; /// }; /// \endcode /// fieldDecl(hasBitWidth(2)) /// matches 'int a;' and 'int c;' but not 'int b;'. AST_MATCHER_P(FieldDecl, hasBitWidth, unsigned, Width) { return Node.isBitField() && Node.getBitWidthValue(Finder->getASTContext()) == Width; } /// Matches non-static data members that have an in-class initializer. /// /// Given /// \code /// class C { /// int a = 2; /// int b = 3; /// int c; /// }; /// \endcode /// fieldDecl(hasInClassInitializer(integerLiteral(equals(2)))) /// matches 'int a;' but not 'int b;'. /// fieldDecl(hasInClassInitializer(anything())) /// matches 'int a;' and 'int b;' but not 'int c;'. AST_MATCHER_P(FieldDecl, hasInClassInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr *Initializer = Node.getInClassInitializer(); return (Initializer != nullptr && InnerMatcher.matches(*Initializer, Finder, Builder)); } /// Determines whether the function is "main", which is the entry point /// into an executable program. AST_MATCHER(FunctionDecl, isMain) { return Node.isMain(); } /// Matches the specialized template of a specialization declaration. /// /// Given /// \code /// template<typename T> class A {}; #1 /// template<> class A<int> {}; #2 /// \endcode /// classTemplateSpecializationDecl(hasSpecializedTemplate(classTemplateDecl())) /// matches '#2' with classTemplateDecl() matching the class template /// declaration of 'A' at #1. AST_MATCHER_P(ClassTemplateSpecializationDecl, hasSpecializedTemplate, internal::Matcher<ClassTemplateDecl>, InnerMatcher) { const ClassTemplateDecl* Decl = Node.getSpecializedTemplate(); return (Decl != nullptr && InnerMatcher.matches(*Decl, Finder, Builder)); } /// Matches a declaration that has been implicitly added /// by the compiler (eg. implicit default/copy constructors). AST_MATCHER(Decl, isImplicit) { return Node.isImplicit(); } /// Matches classTemplateSpecializations, templateSpecializationType and /// functionDecl that have at least one TemplateArgument matching the given /// InnerMatcher. /// /// Given /// \code /// template<typename T> class A {}; /// template<> class A<double> {}; /// A<int> a; /// /// template<typename T> f() {}; /// void func() { f<int>(); }; /// \endcode /// /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(asString("int")))) /// matches the specialization \c A<int> /// /// functionDecl(hasAnyTemplateArgument(refersToType(asString("int")))) /// matches the specialization \c f<int> AST_POLYMORPHIC_MATCHER_P( hasAnyTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); return matchesFirstInRange(InnerMatcher, List.begin(), List.end(), Finder, Builder) != List.end(); } /// Causes all nested matchers to be matched with the specified traversal kind. /// /// Given /// \code /// void foo() /// { /// int i = 3.0; /// } /// \endcode /// The matcher /// \code /// traverse(TK_IgnoreUnlessSpelledInSource, /// varDecl(hasInitializer(floatLiteral().bind("init"))) /// ) /// \endcode /// matches the variable declaration with "init" bound to the "3.0". template <typename T> internal::Matcher<T> traverse(TraversalKind TK, const internal::Matcher<T> &InnerMatcher) { return internal::DynTypedMatcher::constructRestrictedWrapper( new internal::TraversalMatcher<T>(TK, InnerMatcher), InnerMatcher.getID().first) .template unconditionalConvertTo<T>(); } template <typename T> internal::BindableMatcher<T> traverse(TraversalKind TK, const internal::BindableMatcher<T> &InnerMatcher) { return internal::BindableMatcher<T>( internal::DynTypedMatcher::constructRestrictedWrapper( new internal::TraversalMatcher<T>(TK, InnerMatcher), InnerMatcher.getID().first) .template unconditionalConvertTo<T>()); } template <typename... T> internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>> traverse(TraversalKind TK, const internal::VariadicOperatorMatcher<T...> &InnerMatcher) { return internal::TraversalWrapper<internal::VariadicOperatorMatcher<T...>>( TK, InnerMatcher); } template <template <typename ToArg, typename FromArg> class ArgumentAdapterT, typename T, typename ToTypes> internal::TraversalWrapper< internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>> traverse(TraversalKind TK, const internal::ArgumentAdaptingMatcherFuncAdaptor< ArgumentAdapterT, T, ToTypes> &InnerMatcher) { return internal::TraversalWrapper< internal::ArgumentAdaptingMatcherFuncAdaptor<ArgumentAdapterT, T, ToTypes>>(TK, InnerMatcher); } template <template <typename T, typename... P> class MatcherT, typename... P, typename ReturnTypesF> internal::TraversalWrapper< internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>> traverse(TraversalKind TK, const internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...> &InnerMatcher) { return internal::TraversalWrapper< internal::PolymorphicMatcher<MatcherT, ReturnTypesF, P...>>(TK, InnerMatcher); } template <typename... T> internal::Matcher<typename internal::GetClade<T...>::Type> traverse(TraversalKind TK, const internal::MapAnyOfHelper<T...> &InnerMatcher) { return traverse(TK, InnerMatcher.with()); } /// Matches expressions that match InnerMatcher after any implicit AST /// nodes are stripped off. /// /// Parentheses and explicit casts are not discarded. /// Given /// \code /// class C {}; /// C a = C(); /// C b; /// C c = b; /// \endcode /// The matchers /// \code /// varDecl(hasInitializer(ignoringImplicit(cxxConstructExpr()))) /// \endcode /// would match the declarations for a, b, and c. /// While /// \code /// varDecl(hasInitializer(cxxConstructExpr())) /// \endcode /// only match the declarations for b and c. AST_MATCHER_P(Expr, ignoringImplicit, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreImplicit(), Finder, Builder); } /// Matches expressions that match InnerMatcher after any implicit casts /// are stripped off. /// /// Parentheses and explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = 0; /// const int c = a; /// int *d = arr; /// long e = (long) 0l; /// \endcode /// The matchers /// \code /// varDecl(hasInitializer(ignoringImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringImpCasts(declRefExpr()))) /// \endcode /// would match the declarations for a, b, c, and d, but not e. /// While /// \code /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// \endcode /// only match the declarations for b, c, and d. AST_MATCHER_P(Expr, ignoringImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreImpCasts(), Finder, Builder); } /// Matches expressions that match InnerMatcher after parentheses and /// casts are stripped off. /// /// Implicit and non-C Style casts are also discarded. /// Given /// \code /// int a = 0; /// char b = (0); /// void* c = reinterpret_cast<char*>(0); /// char d = char(0); /// \endcode /// The matcher /// varDecl(hasInitializer(ignoringParenCasts(integerLiteral()))) /// would match the declarations for a, b, c, and d. /// while /// varDecl(hasInitializer(integerLiteral())) /// only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenCasts(), Finder, Builder); } /// Matches expressions that match InnerMatcher after implicit casts and /// parentheses are stripped off. /// /// Explicit casts are not discarded. /// Given /// \code /// int arr[5]; /// int a = 0; /// char b = (0); /// const int c = a; /// int *d = (arr); /// long e = ((long) 0l); /// \endcode /// The matchers /// varDecl(hasInitializer(ignoringParenImpCasts(integerLiteral()))) /// varDecl(hasInitializer(ignoringParenImpCasts(declRefExpr()))) /// would match the declarations for a, b, c, and d, but not e. /// while /// varDecl(hasInitializer(integerLiteral())) /// varDecl(hasInitializer(declRefExpr())) /// would only match the declaration for a. AST_MATCHER_P(Expr, ignoringParenImpCasts, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.IgnoreParenImpCasts(), Finder, Builder); } /// Matches types that match InnerMatcher after any parens are stripped. /// /// Given /// \code /// void (*fp)(void); /// \endcode /// The matcher /// \code /// varDecl(hasType(pointerType(pointee(ignoringParens(functionType()))))) /// \endcode /// would match the declaration for fp. AST_MATCHER_P_OVERLOAD(QualType, ignoringParens, internal::Matcher<QualType>, InnerMatcher, 0) { return InnerMatcher.matches(Node.IgnoreParens(), Finder, Builder); } /// Overload \c ignoringParens for \c Expr. /// /// Given /// \code /// const char* str = ("my-string"); /// \endcode /// The matcher /// \code /// implicitCastExpr(hasSourceExpression(ignoringParens(stringLiteral()))) /// \endcode /// would match the implicit cast resulting from the assignment. AST_MATCHER_P_OVERLOAD(Expr, ignoringParens, internal::Matcher<Expr>, InnerMatcher, 1) { const Expr *E = Node.IgnoreParens(); return InnerMatcher.matches(*E, Finder, Builder); } /// Matches expressions that are instantiation-dependent even if it is /// neither type- nor value-dependent. /// /// In the following example, the expression sizeof(sizeof(T() + T())) /// is instantiation-dependent (since it involves a template parameter T), /// but is neither type- nor value-dependent, since the type of the inner /// sizeof is known (std::size_t) and therefore the size of the outer /// sizeof is known. /// \code /// template<typename T> /// void f(T x, T y) { sizeof(sizeof(T() + T()); } /// \endcode /// expr(isInstantiationDependent()) matches sizeof(sizeof(T() + T()) AST_MATCHER(Expr, isInstantiationDependent) { return Node.isInstantiationDependent(); } /// Matches expressions that are type-dependent because the template type /// is not yet instantiated. /// /// For example, the expressions "x" and "x + y" are type-dependent in /// the following code, but "y" is not type-dependent: /// \code /// template<typename T> /// void add(T x, int y) { /// x + y; /// } /// \endcode /// expr(isTypeDependent()) matches x + y AST_MATCHER(Expr, isTypeDependent) { return Node.isTypeDependent(); } /// Matches expression that are value-dependent because they contain a /// non-type template parameter. /// /// For example, the array bound of "Chars" in the following example is /// value-dependent. /// \code /// template<int Size> int f() { return Size; } /// \endcode /// expr(isValueDependent()) matches return Size AST_MATCHER(Expr, isValueDependent) { return Node.isValueDependent(); } /// Matches classTemplateSpecializations, templateSpecializationType and /// functionDecl where the n'th TemplateArgument matches the given InnerMatcher. /// /// Given /// \code /// template<typename T, typename U> class A {}; /// A<bool, int> b; /// A<int, bool> c; /// /// template<typename T> void f() {} /// void func() { f<int>(); }; /// \endcode /// classTemplateSpecializationDecl(hasTemplateArgument( /// 1, refersToType(asString("int")))) /// matches the specialization \c A<bool, int> /// /// functionDecl(hasTemplateArgument(0, refersToType(asString("int")))) /// matches the specialization \c f<int> AST_POLYMORPHIC_MATCHER_P2( hasTemplateArgument, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType, FunctionDecl), unsigned, N, internal::Matcher<TemplateArgument>, InnerMatcher) { ArrayRef<TemplateArgument> List = internal::getTemplateSpecializationArgs(Node); if (List.size() <= N) return false; return InnerMatcher.matches(List[N], Finder, Builder); } /// Matches if the number of template arguments equals \p N. /// /// Given /// \code /// template<typename T> struct C {}; /// C<int> c; /// \endcode /// classTemplateSpecializationDecl(templateArgumentCountIs(1)) /// matches C<int>. AST_POLYMORPHIC_MATCHER_P( templateArgumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(ClassTemplateSpecializationDecl, TemplateSpecializationType), unsigned, N) { return internal::getTemplateSpecializationArgs(Node).size() == N; } /// Matches a TemplateArgument that refers to a certain type. /// /// Given /// \code /// struct X {}; /// template<typename T> struct A {}; /// A<X> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToType(class(hasName("X"))))) /// matches the specialization \c A<X> AST_MATCHER_P(TemplateArgument, refersToType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Type) return false; return InnerMatcher.matches(Node.getAsType(), Finder, Builder); } /// Matches a TemplateArgument that refers to a certain template. /// /// Given /// \code /// template<template <typename> class S> class X {}; /// template<typename T> class Y {}; /// X<Y> xi; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToTemplate(templateName()))) /// matches the specialization \c X<Y> AST_MATCHER_P(TemplateArgument, refersToTemplate, internal::Matcher<TemplateName>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Template) return false; return InnerMatcher.matches(Node.getAsTemplate(), Finder, Builder); } /// Matches a canonical TemplateArgument that refers to a certain /// declaration. /// /// Given /// \code /// struct B { int next; }; /// template<int(B::*next_ptr)> struct A {}; /// A<&B::next> a; /// \endcode /// classTemplateSpecializationDecl(hasAnyTemplateArgument( /// refersToDeclaration(fieldDecl(hasName("next"))))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, refersToDeclaration, internal::Matcher<Decl>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Declaration) return InnerMatcher.matches(*Node.getAsDecl(), Finder, Builder); return false; } /// Matches a sugar TemplateArgument that refers to a certain expression. /// /// Given /// \code /// struct B { int next; }; /// template<int(B::*next_ptr)> struct A {}; /// A<&B::next> a; /// \endcode /// templateSpecializationType(hasAnyTemplateArgument( /// isExpr(hasDescendant(declRefExpr(to(fieldDecl(hasName("next")))))))) /// matches the specialization \c A<&B::next> with \c fieldDecl(...) matching /// \c B::next AST_MATCHER_P(TemplateArgument, isExpr, internal::Matcher<Expr>, InnerMatcher) { if (Node.getKind() == TemplateArgument::Expression) return InnerMatcher.matches(*Node.getAsExpr(), Finder, Builder); return false; } /// Matches a TemplateArgument that is an integral value. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(isIntegral())) /// matches the implicit instantiation of C in C<42> /// with isIntegral() matching 42. AST_MATCHER(TemplateArgument, isIntegral) { return Node.getKind() == TemplateArgument::Integral; } /// Matches a TemplateArgument that refers to an integral type. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(refersToIntegralType(asString("int")))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, refersToIntegralType, internal::Matcher<QualType>, InnerMatcher) { if (Node.getKind() != TemplateArgument::Integral) return false; return InnerMatcher.matches(Node.getIntegralType(), Finder, Builder); } /// Matches a TemplateArgument of integral type with a given value. /// /// Note that 'Value' is a string as the template argument's value is /// an arbitrary precision integer. 'Value' must be euqal to the canonical /// representation of that integral value in base 10. /// /// Given /// \code /// template<int T> struct C {}; /// C<42> c; /// \endcode /// classTemplateSpecializationDecl( /// hasAnyTemplateArgument(equalsIntegralValue("42"))) /// matches the implicit instantiation of C in C<42>. AST_MATCHER_P(TemplateArgument, equalsIntegralValue, std::string, Value) { if (Node.getKind() != TemplateArgument::Integral) return false; return Node.getAsIntegral().toString(10) == Value; } /// Matches an Objective-C autorelease pool statement. /// /// Given /// \code /// @autoreleasepool { /// int x = 0; /// } /// \endcode /// autoreleasePoolStmt(stmt()) matches the declaration of "x" /// inside the autorelease pool. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAutoreleasePoolStmt> autoreleasePoolStmt; /// Matches any value declaration. /// /// Example matches A, B, C and F /// \code /// enum X { A, B, C }; /// void F(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ValueDecl> valueDecl; /// Matches C++ constructor declarations. /// /// Example matches Foo::Foo() and Foo::Foo(int) /// \code /// class Foo { /// public: /// Foo(); /// Foo(int); /// int DoSomething(); /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConstructorDecl> cxxConstructorDecl; /// Matches explicit C++ destructor declarations. /// /// Example matches Foo::~Foo() /// \code /// class Foo { /// public: /// virtual ~Foo(); /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDestructorDecl> cxxDestructorDecl; /// Matches enum declarations. /// /// Example matches X /// \code /// enum X { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumDecl> enumDecl; /// Matches enum constants. /// /// Example matches A, B, C /// \code /// enum X { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, EnumConstantDecl> enumConstantDecl; /// Matches tag declarations. /// /// Example matches X, Z, U, S, E /// \code /// class X; /// template<class T> class Z {}; /// struct S {}; /// union U {}; /// enum E { /// A, B, C /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, TagDecl> tagDecl; /// Matches method declarations. /// /// Example matches y /// \code /// class X { void y(); }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXMethodDecl> cxxMethodDecl; /// Matches conversion operator declarations. /// /// Example matches the operator. /// \code /// class X { operator int() const; }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXConversionDecl> cxxConversionDecl; /// Matches user-defined and implicitly generated deduction guide. /// /// Example matches the deduction guide. /// \code /// template<typename T> /// class X { X(int) }; /// X(int) -> X<int>; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, CXXDeductionGuideDecl> cxxDeductionGuideDecl; /// Matches variable declarations. /// /// Note: this does not match declarations of member variables, which are /// "field" declarations in Clang parlance. /// /// Example matches a /// \code /// int a; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, VarDecl> varDecl; /// Matches field declarations. /// /// Given /// \code /// class X { int m; }; /// \endcode /// fieldDecl() /// matches 'm'. extern const internal::VariadicDynCastAllOfMatcher<Decl, FieldDecl> fieldDecl; /// Matches indirect field declarations. /// /// Given /// \code /// struct X { struct { int a; }; }; /// \endcode /// indirectFieldDecl() /// matches 'a'. extern const internal::VariadicDynCastAllOfMatcher<Decl, IndirectFieldDecl> indirectFieldDecl; /// Matches function declarations. /// /// Example matches f /// \code /// void f(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionDecl> functionDecl; /// Matches C++ function template declarations. /// /// Example matches f /// \code /// template<class T> void f(T t) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, FunctionTemplateDecl> functionTemplateDecl; /// Matches friend declarations. /// /// Given /// \code /// class X { friend void foo(); }; /// \endcode /// friendDecl() /// matches 'friend void foo()'. extern const internal::VariadicDynCastAllOfMatcher<Decl, FriendDecl> friendDecl; /// Matches statements. /// /// Given /// \code /// { ++a; } /// \endcode /// stmt() /// matches both the compound statement '{ ++a; }' and '++a'. extern const internal::VariadicAllOfMatcher<Stmt> stmt; /// Matches declaration statements. /// /// Given /// \code /// int a; /// \endcode /// declStmt() /// matches 'int a'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclStmt> declStmt; /// Matches member expressions. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// int a; static int b; /// }; /// \endcode /// memberExpr() /// matches this->x, x, y.x, a, this->b extern const internal::VariadicDynCastAllOfMatcher<Stmt, MemberExpr> memberExpr; /// Matches unresolved member expressions. /// /// Given /// \code /// struct X { /// template <class T> void f(); /// void g(); /// }; /// template <class T> void h() { X x; x.f<T>(); x.g(); } /// \endcode /// unresolvedMemberExpr() /// matches x.f<T> extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedMemberExpr> unresolvedMemberExpr; /// Matches member expressions where the actual member referenced could not be /// resolved because the base expression or the member name was dependent. /// /// Given /// \code /// template <class T> void f() { T t; t.g(); } /// \endcode /// cxxDependentScopeMemberExpr() /// matches t.g extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDependentScopeMemberExpr> cxxDependentScopeMemberExpr; /// Matches call expressions. /// /// Example matches x.y() and y() /// \code /// X x; /// x.y(); /// y(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CallExpr> callExpr; /// Matches call expressions which were resolved using ADL. /// /// Example matches y(x) but not y(42) or NS::y(x). /// \code /// namespace NS { /// struct X {}; /// void y(X); /// } /// /// void y(...); /// /// void test() { /// NS::X x; /// y(x); // Matches /// NS::y(x); // Doesn't match /// y(42); // Doesn't match /// using NS::y; /// y(x); // Found by both unqualified lookup and ADL, doesn't match // } /// \endcode AST_MATCHER(CallExpr, usesADL) { return Node.usesADL(); } /// Matches lambda expressions. /// /// Example matches [&](){return 5;} /// \code /// [&](){return 5;} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, LambdaExpr> lambdaExpr; /// Matches member call expressions. /// /// Example matches x.y() /// \code /// X x; /// x.y(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXMemberCallExpr> cxxMemberCallExpr; /// Matches ObjectiveC Message invocation expressions. /// /// The innermost message send invokes the "alloc" class method on the /// NSString class, while the outermost message send invokes the /// "initWithString" instance method on the object returned from /// NSString's "alloc". This matcher should match both message sends. /// \code /// [[NSString alloc] initWithString:@"Hello"] /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCMessageExpr> objcMessageExpr; /// Matches Objective-C interface declarations. /// /// Example matches Foo /// \code /// @interface Foo /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCInterfaceDecl> objcInterfaceDecl; /// Matches Objective-C implementation declarations. /// /// Example matches Foo /// \code /// @implementation Foo /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCImplementationDecl> objcImplementationDecl; /// Matches Objective-C protocol declarations. /// /// Example matches FooDelegate /// \code /// @protocol FooDelegate /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCProtocolDecl> objcProtocolDecl; /// Matches Objective-C category declarations. /// /// Example matches Foo (Additions) /// \code /// @interface Foo (Additions) /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryDecl> objcCategoryDecl; /// Matches Objective-C category definitions. /// /// Example matches Foo (Additions) /// \code /// @implementation Foo (Additions) /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCCategoryImplDecl> objcCategoryImplDecl; /// Matches Objective-C method declarations. /// /// Example matches both declaration and definition of -[Foo method] /// \code /// @interface Foo /// - (void)method; /// @end /// /// @implementation Foo /// - (void)method {} /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCMethodDecl> objcMethodDecl; /// Matches block declarations. /// /// Example matches the declaration of the nameless block printing an input /// integer. /// /// \code /// myFunc(^(int p) { /// printf("%d", p); /// }) /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, BlockDecl> blockDecl; /// Matches Objective-C instance variable declarations. /// /// Example matches _enabled /// \code /// @implementation Foo { /// BOOL _enabled; /// } /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCIvarDecl> objcIvarDecl; /// Matches Objective-C property declarations. /// /// Example matches enabled /// \code /// @interface Foo /// @property BOOL enabled; /// @end /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, ObjCPropertyDecl> objcPropertyDecl; /// Matches Objective-C \@throw statements. /// /// Example matches \@throw /// \code /// @throw obj; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtThrowStmt> objcThrowStmt; /// Matches Objective-C @try statements. /// /// Example matches @try /// \code /// @try {} /// @catch (...) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtTryStmt> objcTryStmt; /// Matches Objective-C @catch statements. /// /// Example matches @catch /// \code /// @try {} /// @catch (...) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtCatchStmt> objcCatchStmt; /// Matches Objective-C @finally statements. /// /// Example matches @finally /// \code /// @try {} /// @finally {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCAtFinallyStmt> objcFinallyStmt; /// Matches expressions that introduce cleanups to be run at the end /// of the sub-expression's evaluation. /// /// Example matches std::string() /// \code /// const std::string str = std::string(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExprWithCleanups> exprWithCleanups; /// Matches init list expressions. /// /// Given /// \code /// int a[] = { 1, 2 }; /// struct B { int x, y; }; /// B b = { 5, 6 }; /// \endcode /// initListExpr() /// matches "{ 1, 2 }" and "{ 5, 6 }" extern const internal::VariadicDynCastAllOfMatcher<Stmt, InitListExpr> initListExpr; /// Matches the syntactic form of init list expressions /// (if expression have it). AST_MATCHER_P(InitListExpr, hasSyntacticForm, internal::Matcher<Expr>, InnerMatcher) { const Expr *SyntForm = Node.getSyntacticForm(); return (SyntForm != nullptr && InnerMatcher.matches(*SyntForm, Finder, Builder)); } /// Matches C++ initializer list expressions. /// /// Given /// \code /// std::vector<int> a({ 1, 2, 3 }); /// std::vector<int> b = { 4, 5 }; /// int c[] = { 6, 7 }; /// std::pair<int, int> d = { 8, 9 }; /// \endcode /// cxxStdInitializerListExpr() /// matches "{ 1, 2, 3 }" and "{ 4, 5 }" extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStdInitializerListExpr> cxxStdInitializerListExpr; /// Matches implicit initializers of init list expressions. /// /// Given /// \code /// point ptarray[10] = { [2].y = 1.0, [2].x = 2.0, [0].x = 1.0 }; /// \endcode /// implicitValueInitExpr() /// matches "[0].y" (implicitly) extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitValueInitExpr> implicitValueInitExpr; /// Matches paren list expressions. /// ParenListExprs don't have a predefined type and are used for late parsing. /// In the final AST, they can be met in template declarations. /// /// Given /// \code /// template<typename T> class X { /// void f() { /// X x(*this); /// int a = 0, b = 1; int i = (a, b); /// } /// }; /// \endcode /// parenListExpr() matches "*this" but NOT matches (a, b) because (a, b) /// has a predefined type and is a ParenExpr, not a ParenListExpr. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenListExpr> parenListExpr; /// Matches substitutions of non-type template parameters. /// /// Given /// \code /// template <int N> /// struct A { static const int n = N; }; /// struct B : public A<42> {}; /// \endcode /// substNonTypeTemplateParmExpr() /// matches "N" in the right-hand side of "static const int n = N;" extern const internal::VariadicDynCastAllOfMatcher<Stmt, SubstNonTypeTemplateParmExpr> substNonTypeTemplateParmExpr; /// Matches using declarations. /// /// Given /// \code /// namespace X { int x; } /// using X::x; /// \endcode /// usingDecl() /// matches \code using X::x \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDecl> usingDecl; /// Matches using namespace declarations. /// /// Given /// \code /// namespace X { int x; } /// using namespace X; /// \endcode /// usingDirectiveDecl() /// matches \code using namespace X \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UsingDirectiveDecl> usingDirectiveDecl; /// Matches reference to a name that can be looked up during parsing /// but could not be resolved to a specific declaration. /// /// Given /// \code /// template<typename T> /// T foo() { T a; return a; } /// template<typename T> /// void bar() { /// foo<T>(); /// } /// \endcode /// unresolvedLookupExpr() /// matches \code foo<T>() \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnresolvedLookupExpr> unresolvedLookupExpr; /// Matches unresolved using value declarations. /// /// Given /// \code /// template<typename X> /// class C : private X { /// using X::x; /// }; /// \endcode /// unresolvedUsingValueDecl() /// matches \code using X::x \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingValueDecl> unresolvedUsingValueDecl; /// Matches unresolved using value declarations that involve the /// typename. /// /// Given /// \code /// template <typename T> /// struct Base { typedef T Foo; }; /// /// template<typename T> /// struct S : private Base<T> { /// using typename Base<T>::Foo; /// }; /// \endcode /// unresolvedUsingTypenameDecl() /// matches \code using Base<T>::Foo \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, UnresolvedUsingTypenameDecl> unresolvedUsingTypenameDecl; /// Matches a constant expression wrapper. /// /// Example matches the constant in the case statement: /// (matcher = constantExpr()) /// \code /// switch (a) { /// case 37: break; /// } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConstantExpr> constantExpr; /// Matches parentheses used in expressions. /// /// Example matches (foo() + 1) /// \code /// int foo() { return 1; } /// int a = (foo() + 1); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ParenExpr> parenExpr; /// Matches constructor call expressions (including implicit ones). /// /// Example matches string(ptr, n) and ptr within arguments of f /// (matcher = cxxConstructExpr()) /// \code /// void f(const string &a, const string &b); /// char *ptr; /// int n; /// f(string(ptr, n), ptr); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstructExpr> cxxConstructExpr; /// Matches unresolved constructor call expressions. /// /// Example matches T(t) in return statement of f /// (matcher = cxxUnresolvedConstructExpr()) /// \code /// template <typename T> /// void f(const T& t) { return T(t); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXUnresolvedConstructExpr> cxxUnresolvedConstructExpr; /// Matches implicit and explicit this expressions. /// /// Example matches the implicit this expression in "return i". /// (matcher = cxxThisExpr()) /// \code /// struct foo { /// int i; /// int f() { return i; } /// }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThisExpr> cxxThisExpr; /// Matches nodes where temporaries are created. /// /// Example matches FunctionTakesString(GetStringByValue()) /// (matcher = cxxBindTemporaryExpr()) /// \code /// FunctionTakesString(GetStringByValue()); /// FunctionTakesStringByPointer(GetStringPointer()); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBindTemporaryExpr> cxxBindTemporaryExpr; /// Matches nodes where temporaries are materialized. /// /// Example: Given /// \code /// struct T {void func();}; /// T f(); /// void g(T); /// \endcode /// materializeTemporaryExpr() matches 'f()' in these statements /// \code /// T u(f()); /// g(f()); /// f().func(); /// \endcode /// but does not match /// \code /// f(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, MaterializeTemporaryExpr> materializeTemporaryExpr; /// Matches new expressions. /// /// Given /// \code /// new X; /// \endcode /// cxxNewExpr() /// matches 'new X'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNewExpr> cxxNewExpr; /// Matches delete expressions. /// /// Given /// \code /// delete X; /// \endcode /// cxxDeleteExpr() /// matches 'delete X'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDeleteExpr> cxxDeleteExpr; /// Matches noexcept expressions. /// /// Given /// \code /// bool a() noexcept; /// bool b() noexcept(true); /// bool c() noexcept(false); /// bool d() noexcept(noexcept(a())); /// bool e = noexcept(b()) || noexcept(c()); /// \endcode /// cxxNoexceptExpr() /// matches `noexcept(a())`, `noexcept(b())` and `noexcept(c())`. /// doesn't match the noexcept specifier in the declarations a, b, c or d. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNoexceptExpr> cxxNoexceptExpr; /// Matches array subscript expressions. /// /// Given /// \code /// int i = a[1]; /// \endcode /// arraySubscriptExpr() /// matches "a[1]" extern const internal::VariadicDynCastAllOfMatcher<Stmt, ArraySubscriptExpr> arraySubscriptExpr; /// Matches the value of a default argument at the call site. /// /// Example matches the CXXDefaultArgExpr placeholder inserted for the /// default value of the second parameter in the call expression f(42) /// (matcher = cxxDefaultArgExpr()) /// \code /// void f(int x, int y = 0); /// f(42); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDefaultArgExpr> cxxDefaultArgExpr; /// Matches overloaded operator calls. /// /// Note that if an operator isn't overloaded, it won't match. Instead, use /// binaryOperator matcher. /// Currently it does not match operators such as new delete. /// FIXME: figure out why these do not match? /// /// Example matches both operator<<((o << b), c) and operator<<(o, b) /// (matcher = cxxOperatorCallExpr()) /// \code /// ostream &operator<< (ostream &out, int i) { }; /// ostream &o; int b = 1, c = 1; /// o << b << c; /// \endcode /// See also the binaryOperation() matcher for more-general matching of binary /// uses of this AST node. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXOperatorCallExpr> cxxOperatorCallExpr; /// Matches rewritten binary operators /// /// Example matches use of "<": /// \code /// #include <compare> /// struct HasSpaceshipMem { /// int a; /// constexpr auto operator<=>(const HasSpaceshipMem&) const = default; /// }; /// void compare() { /// HasSpaceshipMem hs1, hs2; /// if (hs1 < hs2) /// return; /// } /// \endcode /// See also the binaryOperation() matcher for more-general matching /// of this AST node. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXRewrittenBinaryOperator> cxxRewrittenBinaryOperator; /// Matches expressions. /// /// Example matches x() /// \code /// void f() { x(); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, Expr> expr; /// Matches expressions that refer to declarations. /// /// Example matches x in if (x) /// \code /// bool x; /// if (x) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, DeclRefExpr> declRefExpr; /// Matches a reference to an ObjCIvar. /// /// Example: matches "a" in "init" method: /// \code /// @implementation A { /// NSString *a; /// } /// - (void) init { /// a = @"hello"; /// } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ObjCIvarRefExpr> objcIvarRefExpr; /// Matches a reference to a block. /// /// Example: matches "^{}": /// \code /// void f() { ^{}(); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, BlockExpr> blockExpr; /// Matches if statements. /// /// Example matches 'if (x) {}' /// \code /// if (x) {} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, IfStmt> ifStmt; /// Matches for statements. /// /// Example matches 'for (;;) {}' /// \code /// for (;;) {} /// int i[] = {1, 2, 3}; for (auto a : i); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ForStmt> forStmt; /// Matches the increment statement of a for loop. /// /// Example: /// forStmt(hasIncrement(unaryOperator(hasOperatorName("++")))) /// matches '++x' in /// \code /// for (x; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasIncrement, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Increment = Node.getInc(); return (Increment != nullptr && InnerMatcher.matches(*Increment, Finder, Builder)); } /// Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopInit(declStmt())) /// matches 'int x = 0' in /// \code /// for (int x = 0; x < N; ++x) { } /// \endcode AST_MATCHER_P(ForStmt, hasLoopInit, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Init = Node.getInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// Matches range-based for statements. /// /// cxxForRangeStmt() matches 'for (auto a : i)' /// \code /// int i[] = {1, 2, 3}; for (auto a : i); /// for(int j = 0; j < 5; ++j); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXForRangeStmt> cxxForRangeStmt; /// Matches the initialization statement of a for loop. /// /// Example: /// forStmt(hasLoopVariable(anything())) /// matches 'int x' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasLoopVariable, internal::Matcher<VarDecl>, InnerMatcher) { const VarDecl *const Var = Node.getLoopVariable(); return (Var != nullptr && InnerMatcher.matches(*Var, Finder, Builder)); } /// Matches the range initialization statement of a for loop. /// /// Example: /// forStmt(hasRangeInit(anything())) /// matches 'a' in /// \code /// for (int x : a) { } /// \endcode AST_MATCHER_P(CXXForRangeStmt, hasRangeInit, internal::Matcher<Expr>, InnerMatcher) { const Expr *const Init = Node.getRangeInit(); return (Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder)); } /// Matches while statements. /// /// Given /// \code /// while (true) {} /// \endcode /// whileStmt() /// matches 'while (true) {}'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, WhileStmt> whileStmt; /// Matches do statements. /// /// Given /// \code /// do {} while (true); /// \endcode /// doStmt() /// matches 'do {} while(true)' extern const internal::VariadicDynCastAllOfMatcher<Stmt, DoStmt> doStmt; /// Matches break statements. /// /// Given /// \code /// while (true) { break; } /// \endcode /// breakStmt() /// matches 'break' extern const internal::VariadicDynCastAllOfMatcher<Stmt, BreakStmt> breakStmt; /// Matches continue statements. /// /// Given /// \code /// while (true) { continue; } /// \endcode /// continueStmt() /// matches 'continue' extern const internal::VariadicDynCastAllOfMatcher<Stmt, ContinueStmt> continueStmt; /// Matches return statements. /// /// Given /// \code /// return 1; /// \endcode /// returnStmt() /// matches 'return 1' extern const internal::VariadicDynCastAllOfMatcher<Stmt, ReturnStmt> returnStmt; /// Matches goto statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// gotoStmt() /// matches 'goto FOO' extern const internal::VariadicDynCastAllOfMatcher<Stmt, GotoStmt> gotoStmt; /// Matches label statements. /// /// Given /// \code /// goto FOO; /// FOO: bar(); /// \endcode /// labelStmt() /// matches 'FOO:' extern const internal::VariadicDynCastAllOfMatcher<Stmt, LabelStmt> labelStmt; /// Matches address of label statements (GNU extension). /// /// Given /// \code /// FOO: bar(); /// void *ptr = &&FOO; /// goto *bar; /// \endcode /// addrLabelExpr() /// matches '&&FOO' extern const internal::VariadicDynCastAllOfMatcher<Stmt, AddrLabelExpr> addrLabelExpr; /// Matches switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchStmt() /// matches 'switch(a)'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchStmt> switchStmt; /// Matches case and default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// switchCase() /// matches 'case 42:' and 'default:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, SwitchCase> switchCase; /// Matches case statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// caseStmt() /// matches 'case 42:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CaseStmt> caseStmt; /// Matches default statements inside switch statements. /// /// Given /// \code /// switch(a) { case 42: break; default: break; } /// \endcode /// defaultStmt() /// matches 'default:'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, DefaultStmt> defaultStmt; /// Matches compound statements. /// /// Example matches '{}' and '{{}}' in 'for (;;) {{}}' /// \code /// for (;;) {{}} /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundStmt> compoundStmt; /// Matches catch statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// cxxCatchStmt() /// matches 'catch(int i)' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXCatchStmt> cxxCatchStmt; /// Matches try statements. /// /// \code /// try {} catch(int i) {} /// \endcode /// cxxTryStmt() /// matches 'try {}' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTryStmt> cxxTryStmt; /// Matches throw expressions. /// /// \code /// try { throw 5; } catch(int i) {} /// \endcode /// cxxThrowExpr() /// matches 'throw 5' extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXThrowExpr> cxxThrowExpr; /// Matches null statements. /// /// \code /// foo();; /// \endcode /// nullStmt() /// matches the second ';' extern const internal::VariadicDynCastAllOfMatcher<Stmt, NullStmt> nullStmt; /// Matches asm statements. /// /// \code /// int i = 100; /// __asm("mov al, 2"); /// \endcode /// asmStmt() /// matches '__asm("mov al, 2")' extern const internal::VariadicDynCastAllOfMatcher<Stmt, AsmStmt> asmStmt; /// Matches bool literals. /// /// Example matches true /// \code /// true /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXBoolLiteralExpr> cxxBoolLiteral; /// Matches string literals (also matches wide string literals). /// /// Example matches "abcd", L"abcd" /// \code /// char *s = "abcd"; /// wchar_t *ws = L"abcd"; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, StringLiteral> stringLiteral; /// Matches character literals (also matches wchar_t). /// /// Not matching Hex-encoded chars (e.g. 0x1234, which is a IntegerLiteral), /// though. /// /// Example matches 'a', L'a' /// \code /// char ch = 'a'; /// wchar_t chw = L'a'; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CharacterLiteral> characterLiteral; /// Matches integer literals of all sizes / encodings, e.g. /// 1, 1L, 0x1 and 1U. /// /// Does not match character-encoded integers such as L'a'. extern const internal::VariadicDynCastAllOfMatcher<Stmt, IntegerLiteral> integerLiteral; /// Matches float literals of all sizes / encodings, e.g. /// 1.0, 1.0f, 1.0L and 1e10. /// /// Does not match implicit conversions such as /// \code /// float a = 10; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, FloatingLiteral> floatLiteral; /// Matches imaginary literals, which are based on integer and floating /// point literals e.g.: 1i, 1.0i extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImaginaryLiteral> imaginaryLiteral; /// Matches fixed point literals extern const internal::VariadicDynCastAllOfMatcher<Stmt, FixedPointLiteral> fixedPointLiteral; /// Matches user defined literal operator call. /// /// Example match: "foo"_suffix extern const internal::VariadicDynCastAllOfMatcher<Stmt, UserDefinedLiteral> userDefinedLiteral; /// Matches compound (i.e. non-scalar) literals /// /// Example match: {1}, (1, 2) /// \code /// int array[4] = {1}; /// vector int myvec = (vector int)(1, 2); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CompoundLiteralExpr> compoundLiteralExpr; /// Matches nullptr literal. extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXNullPtrLiteralExpr> cxxNullPtrLiteralExpr; /// Matches GNU __builtin_choose_expr. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ChooseExpr> chooseExpr; /// Matches GNU __null expression. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GNUNullExpr> gnuNullExpr; /// Matches C11 _Generic expression. extern const internal::VariadicDynCastAllOfMatcher<Stmt, GenericSelectionExpr> genericSelectionExpr; /// Matches atomic builtins. /// Example matches __atomic_load_n(ptr, 1) /// \code /// void foo() { int *ptr; __atomic_load_n(ptr, 1); } /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, AtomicExpr> atomicExpr; /// Matches statement expression (GNU extension). /// /// Example match: ({ int X = 4; X; }) /// \code /// int C = ({ int X = 4; X; }); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, StmtExpr> stmtExpr; /// Matches binary operator expressions. /// /// Example matches a || b /// \code /// !(a || b) /// \endcode /// See also the binaryOperation() matcher for more-general matching. extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryOperator> binaryOperator; /// Matches unary operator expressions. /// /// Example matches !a /// \code /// !a || b /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryOperator> unaryOperator; /// Matches conditional operator expressions. /// /// Example matches a ? b : c /// \code /// (a ? b : c) + 42 /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ConditionalOperator> conditionalOperator; /// Matches binary conditional operator expressions (GNU extension). /// /// Example matches a ?: b /// \code /// (a ?: b) + 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, BinaryConditionalOperator> binaryConditionalOperator; /// Matches opaque value expressions. They are used as helpers /// to reference another expressions and can be met /// in BinaryConditionalOperators, for example. /// /// Example matches 'a' /// \code /// (a ?: c) + 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, OpaqueValueExpr> opaqueValueExpr; /// Matches a C++ static_assert declaration. /// /// Example: /// staticAssertExpr() /// matches /// static_assert(sizeof(S) == sizeof(int)) /// in /// \code /// struct S { /// int x; /// }; /// static_assert(sizeof(S) == sizeof(int)); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Decl, StaticAssertDecl> staticAssertDecl; /// Matches a reinterpret_cast expression. /// /// Either the source expression or the destination type can be matched /// using has(), but hasDestinationType() is more specific and can be /// more readable. /// /// Example matches reinterpret_cast<char*>(&p) in /// \code /// void* p = reinterpret_cast<char*>(&p); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXReinterpretCastExpr> cxxReinterpretCastExpr; /// Matches a C++ static_cast expression. /// /// \see hasDestinationType /// \see reinterpretCast /// /// Example: /// cxxStaticCastExpr() /// matches /// static_cast<long>(8) /// in /// \code /// long eight(static_cast<long>(8)); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXStaticCastExpr> cxxStaticCastExpr; /// Matches a dynamic_cast expression. /// /// Example: /// cxxDynamicCastExpr() /// matches /// dynamic_cast<D*>(&b); /// in /// \code /// struct B { virtual ~B() {} }; struct D : B {}; /// B b; /// D* p = dynamic_cast<D*>(&b); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXDynamicCastExpr> cxxDynamicCastExpr; /// Matches a const_cast expression. /// /// Example: Matches const_cast<int*>(&r) in /// \code /// int n = 42; /// const int &r(n); /// int* p = const_cast<int*>(&r); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXConstCastExpr> cxxConstCastExpr; /// Matches a C-style cast expression. /// /// Example: Matches (int) 2.2f in /// \code /// int i = (int) 2.2f; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CStyleCastExpr> cStyleCastExpr; /// Matches explicit cast expressions. /// /// Matches any cast expression written in user code, whether it be a /// C-style cast, a functional-style cast, or a keyword cast. /// /// Does not match implicit conversions. /// /// Note: the name "explicitCast" is chosen to match Clang's terminology, as /// Clang uses the term "cast" to apply to implicit conversions as well as to /// actual cast expressions. /// /// \see hasDestinationType. /// /// Example: matches all five of the casts in /// \code /// int((int)(reinterpret_cast<int>(static_cast<int>(const_cast<int>(42))))) /// \endcode /// but does not match the implicit conversion in /// \code /// long ell = 42; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, ExplicitCastExpr> explicitCastExpr; /// Matches the implicit cast nodes of Clang's AST. /// /// This matches many different places, including function call return value /// eliding, as well as any type conversions. extern const internal::VariadicDynCastAllOfMatcher<Stmt, ImplicitCastExpr> implicitCastExpr; /// Matches any cast nodes of Clang's AST. /// /// Example: castExpr() matches each of the following: /// \code /// (int) 3; /// const_cast<Expr *>(SubExpr); /// char c = 0; /// \endcode /// but does not match /// \code /// int i = (0); /// int k = 0; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CastExpr> castExpr; /// Matches functional cast expressions /// /// Example: Matches Foo(bar); /// \code /// Foo f = bar; /// Foo g = (Foo) bar; /// Foo h = Foo(bar); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXFunctionalCastExpr> cxxFunctionalCastExpr; /// Matches functional cast expressions having N != 1 arguments /// /// Example: Matches Foo(bar, bar) /// \code /// Foo h = Foo(bar, bar); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CXXTemporaryObjectExpr> cxxTemporaryObjectExpr; /// Matches predefined identifier expressions [C99 6.4.2.2]. /// /// Example: Matches __func__ /// \code /// printf("%s", __func__); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, PredefinedExpr> predefinedExpr; /// Matches C99 designated initializer expressions [C99 6.7.8]. /// /// Example: Matches { [2].y = 1.0, [0].x = 1.0 } /// \code /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, DesignatedInitExpr> designatedInitExpr; /// Matches designated initializer expressions that contain /// a specific number of designators. /// /// Example: Given /// \code /// point ptarray[10] = { [2].y = 1.0, [0].x = 1.0 }; /// point ptarray2[10] = { [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }; /// \endcode /// designatorCountIs(2) /// matches '{ [2].y = 1.0, [0].x = 1.0 }', /// but not '{ [2].y = 1.0, [2].x = 0.0, [0].x = 1.0 }'. AST_MATCHER_P(DesignatedInitExpr, designatorCountIs, unsigned, N) { return Node.size() == N; } /// Matches \c QualTypes in the clang AST. extern const internal::VariadicAllOfMatcher<QualType> qualType; /// Matches \c Types in the clang AST. extern const internal::VariadicAllOfMatcher<Type> type; /// Matches \c TypeLocs in the clang AST. extern const internal::VariadicAllOfMatcher<TypeLoc> typeLoc; /// Matches if any of the given matchers matches. /// /// Unlike \c anyOf, \c eachOf will generate a match result for each /// matching submatcher. /// /// For example, in: /// \code /// class A { int a; int b; }; /// \endcode /// The matcher: /// \code /// cxxRecordDecl(eachOf(has(fieldDecl(hasName("a")).bind("v")), /// has(fieldDecl(hasName("b")).bind("v")))) /// \endcode /// will generate two results binding "v", the first of which binds /// the field declaration of \c a, the second the field declaration of /// \c b. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> eachOf; /// Matches if any of the given matchers matches. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> anyOf; /// Matches if all given matchers match. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc< 2, std::numeric_limits<unsigned>::max()> allOf; /// Matches any node regardless of the submatcher. /// /// However, \c optionally will retain any bindings generated by the submatcher. /// Useful when additional information which may or may not present about a main /// matching node is desired. /// /// For example, in: /// \code /// class Foo { /// int bar; /// } /// \endcode /// The matcher: /// \code /// cxxRecordDecl( /// optionally(has( /// fieldDecl(hasName("bar")).bind("var") /// ))).bind("record") /// \endcode /// will produce a result binding for both "record" and "var". /// The matcher will produce a "record" binding for even if there is no data /// member named "bar" in that class. /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc<1, 1> optionally; /// Matches sizeof (C99), alignof (C++11) and vec_step (OpenCL) /// /// Given /// \code /// Foo x = bar; /// int y = sizeof(x) + alignof(x); /// \endcode /// unaryExprOrTypeTraitExpr() /// matches \c sizeof(x) and \c alignof(x) extern const internal::VariadicDynCastAllOfMatcher<Stmt, UnaryExprOrTypeTraitExpr> unaryExprOrTypeTraitExpr; /// Matches any of the \p NodeMatchers with InnerMatchers nested within /// /// Given /// \code /// if (true); /// for (; true; ); /// \endcode /// with the matcher /// \code /// mapAnyOf(ifStmt, forStmt).with( /// hasCondition(cxxBoolLiteralExpr(equals(true))) /// ).bind("trueCond") /// \endcode /// matches the \c if and the \c for. It is equivalent to: /// \code /// auto trueCond = hasCondition(cxxBoolLiteralExpr(equals(true))); /// anyOf( /// ifStmt(trueCond).bind("trueCond"), /// forStmt(trueCond).bind("trueCond") /// ); /// \endcode /// /// The with() chain-call accepts zero or more matchers which are combined /// as-if with allOf() in each of the node matchers. /// Usable as: Any Matcher template <typename T, typename... U> auto mapAnyOf(internal::VariadicDynCastAllOfMatcher<T, U> const &...) { return internal::MapAnyOfHelper<U...>(); } /// Matches nodes which can be used with binary operators. /// /// The code /// \code /// var1 != var2; /// \endcode /// might be represented in the clang AST as a binaryOperator, a /// cxxOperatorCallExpr or a cxxRewrittenBinaryOperator, depending on /// /// * whether the types of var1 and var2 are fundamental (binaryOperator) or at /// least one is a class type (cxxOperatorCallExpr) /// * whether the code appears in a template declaration, if at least one of the /// vars is a dependent-type (binaryOperator) /// * whether the code relies on a rewritten binary operator, such as a /// spaceship operator or an inverted equality operator /// (cxxRewrittenBinaryOperator) /// /// This matcher elides details in places where the matchers for the nodes are /// compatible. /// /// Given /// \code /// binaryOperation( /// hasOperatorName("!="), /// hasLHS(expr().bind("lhs")), /// hasRHS(expr().bind("rhs")) /// ) /// \endcode /// matches each use of "!=" in: /// \code /// struct S{ /// bool operator!=(const S&) const; /// }; /// /// void foo() /// { /// 1 != 2; /// S() != S(); /// } /// /// template<typename T> /// void templ() /// { /// 1 != 2; /// T() != S(); /// } /// struct HasOpEq /// { /// bool operator==(const HasOpEq &) const; /// }; /// /// void inverse() /// { /// HasOpEq s1; /// HasOpEq s2; /// if (s1 != s2) /// return; /// } /// /// struct HasSpaceship /// { /// bool operator<=>(const HasOpEq &) const; /// }; /// /// void use_spaceship() /// { /// HasSpaceship s1; /// HasSpaceship s2; /// if (s1 != s2) /// return; /// } /// \endcode extern const internal::MapAnyOfMatcher<BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator> binaryOperation; /// Matches function calls and constructor calls /// /// Because CallExpr and CXXConstructExpr do not share a common /// base class with API accessing arguments etc, AST Matchers for code /// which should match both are typically duplicated. This matcher /// removes the need for duplication. /// /// Given code /// \code /// struct ConstructorTakesInt /// { /// ConstructorTakesInt(int i) {} /// }; /// /// void callTakesInt(int i) /// { /// } /// /// void doCall() /// { /// callTakesInt(42); /// } /// /// void doConstruct() /// { /// ConstructorTakesInt cti(42); /// } /// \endcode /// /// The matcher /// \code /// invocation(hasArgument(0, integerLiteral(equals(42)))) /// \endcode /// matches the expression in both doCall and doConstruct extern const internal::MapAnyOfMatcher<CallExpr, CXXConstructExpr> invocation; /// Matches unary expressions that have a specific type of argument. /// /// Given /// \code /// int a, c; float b; int s = sizeof(a) + sizeof(b) + alignof(c); /// \endcode /// unaryExprOrTypeTraitExpr(hasArgumentOfType(asString("int")) /// matches \c sizeof(a) and \c alignof(c) AST_MATCHER_P(UnaryExprOrTypeTraitExpr, hasArgumentOfType, internal::Matcher<QualType>, InnerMatcher) { const QualType ArgumentType = Node.getTypeOfArgument(); return InnerMatcher.matches(ArgumentType, Finder, Builder); } /// Matches unary expressions of a certain kind. /// /// Given /// \code /// int x; /// int s = sizeof(x) + alignof(x) /// \endcode /// unaryExprOrTypeTraitExpr(ofKind(UETT_SizeOf)) /// matches \c sizeof(x) /// /// If the matcher is use from clang-query, UnaryExprOrTypeTrait parameter /// should be passed as a quoted string. e.g., ofKind("UETT_SizeOf"). AST_MATCHER_P(UnaryExprOrTypeTraitExpr, ofKind, UnaryExprOrTypeTrait, Kind) { return Node.getKind() == Kind; } /// Same as unaryExprOrTypeTraitExpr, but only matching /// alignof. inline internal::BindableMatcher<Stmt> alignOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr( allOf(anyOf(ofKind(UETT_AlignOf), ofKind(UETT_PreferredAlignOf)), InnerMatcher))); } /// Same as unaryExprOrTypeTraitExpr, but only matching /// sizeof. inline internal::BindableMatcher<Stmt> sizeOfExpr( const internal::Matcher<UnaryExprOrTypeTraitExpr> &InnerMatcher) { return stmt(unaryExprOrTypeTraitExpr( allOf(ofKind(UETT_SizeOf), InnerMatcher))); } /// Matches NamedDecl nodes that have the specified name. /// /// Supports specifying enclosing namespaces or classes by prefixing the name /// with '<enclosing>::'. /// Does not match typedefs of an underlying type with the given name. /// /// Example matches X (Name == "X") /// \code /// class X; /// \endcode /// /// Example matches X (Name is one of "::a::b::X", "a::b::X", "b::X", "X") /// \code /// namespace a { namespace b { class X; } } /// \endcode inline internal::Matcher<NamedDecl> hasName(StringRef Name) { return internal::Matcher<NamedDecl>( new internal::HasNameMatcher({std::string(Name)})); } /// Matches NamedDecl nodes that have any of the specified names. /// /// This matcher is only provided as a performance optimization of hasName. /// \code /// hasAnyName(a, b, c) /// \endcode /// is equivalent to, but faster than /// \code /// anyOf(hasName(a), hasName(b), hasName(c)) /// \endcode extern const internal::VariadicFunction<internal::Matcher<NamedDecl>, StringRef, internal::hasAnyNameFunc> hasAnyName; /// Matches NamedDecl nodes whose fully qualified names contain /// a substring matched by the given RegExp. /// /// Supports specifying enclosing namespaces or classes by /// prefixing the name with '<enclosing>::'. Does not match typedefs /// of an underlying type with the given name. /// /// Example matches X (regexp == "::X") /// \code /// class X; /// \endcode /// /// Example matches X (regexp is one of "::X", "^foo::.*X", among others) /// \code /// namespace foo { namespace bar { class X; } } /// \endcode AST_MATCHER_REGEX(NamedDecl, matchesName, RegExp) { std::string FullNameString = "::" + Node.getQualifiedNameAsString(); return RegExp->match(FullNameString); } /// Matches overloaded operator names. /// /// Matches overloaded operator names specified in strings without the /// "operator" prefix: e.g. "<<". /// /// Given: /// \code /// class A { int operator*(); }; /// const A &operator<<(const A &a, const A &b); /// A a; /// a << a; // <-- This matches /// \endcode /// /// \c cxxOperatorCallExpr(hasOverloadedOperatorName("<<"))) matches the /// specified line and /// \c cxxRecordDecl(hasMethod(hasOverloadedOperatorName("*"))) /// matches the declaration of \c A. /// /// Usable as: Matcher<CXXOperatorCallExpr>, Matcher<FunctionDecl> inline internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>> hasOverloadedOperatorName(StringRef Name) { return internal::PolymorphicMatcher< internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>>({std::string(Name)}); } /// Matches overloaded operator names. /// /// Matches overloaded operator names specified in strings without the /// "operator" prefix: e.g. "<<". /// /// hasAnyOverloadedOperatorName("+", "-") /// Is equivalent to /// anyOf(hasOverloadedOperatorName("+"), hasOverloadedOperatorName("-")) extern const internal::VariadicFunction< internal::PolymorphicMatcher<internal::HasOverloadedOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES( CXXOperatorCallExpr, FunctionDecl), std::vector<std::string>>, StringRef, internal::hasAnyOverloadedOperatorNameFunc> hasAnyOverloadedOperatorName; /// Matches template-dependent, but known, member names. /// /// In template declarations, dependent members are not resolved and so can /// not be matched to particular named declarations. /// /// This matcher allows to match on the known name of members. /// /// Given /// \code /// template <typename T> /// struct S { /// void mem(); /// }; /// template <typename T> /// void x() { /// S<T> s; /// s.mem(); /// } /// \endcode /// \c cxxDependentScopeMemberExpr(hasMemberName("mem")) matches `s.mem()` AST_MATCHER_P(CXXDependentScopeMemberExpr, hasMemberName, std::string, N) { return Node.getMember().getAsString() == N; } /// Matches template-dependent, but known, member names against an already-bound /// node /// /// In template declarations, dependent members are not resolved and so can /// not be matched to particular named declarations. /// /// This matcher allows to match on the name of already-bound VarDecl, FieldDecl /// and CXXMethodDecl nodes. /// /// Given /// \code /// template <typename T> /// struct S { /// void mem(); /// }; /// template <typename T> /// void x() { /// S<T> s; /// s.mem(); /// } /// \endcode /// The matcher /// @code /// \c cxxDependentScopeMemberExpr( /// hasObjectExpression(declRefExpr(hasType(templateSpecializationType( /// hasDeclaration(classTemplateDecl(has(cxxRecordDecl(has( /// cxxMethodDecl(hasName("mem")).bind("templMem") /// ))))) /// )))), /// memberHasSameNameAsBoundNode("templMem") /// ) /// @endcode /// first matches and binds the @c mem member of the @c S template, then /// compares its name to the usage in @c s.mem() in the @c x function template AST_MATCHER_P(CXXDependentScopeMemberExpr, memberHasSameNameAsBoundNode, std::string, BindingID) { auto MemberName = Node.getMember().getAsString(); return Builder->removeBindings( [this, MemberName](const BoundNodesMap &Nodes) { const auto &BN = Nodes.getNode(this->BindingID); if (const auto *ND = BN.get<NamedDecl>()) { if (!isa<FieldDecl, CXXMethodDecl, VarDecl>(ND)) return true; return ND->getName() != MemberName; } return true; }); } /// Matches C++ classes that are directly or indirectly derived from a class /// matching \c Base, or Objective-C classes that directly or indirectly /// subclass a class matching \c Base. /// /// Note that a class is not considered to be derived from itself. /// /// Example matches Y, Z, C (Base == hasName("X")) /// \code /// class X; /// class Y : public X {}; // directly derived /// class Z : public Y {}; // indirectly derived /// typedef X A; /// typedef A B; /// class C : public B {}; // derived from a typedef of X /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("X")): /// \code /// class Foo; /// typedef Foo X; /// class Bar : public Foo {}; // derived from a type that X is a typedef of /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("NSObject")) /// \code /// @interface NSObject @end /// @interface Bar : NSObject @end /// \endcode /// /// Usable as: Matcher<CXXRecordDecl>, Matcher<ObjCInterfaceDecl> AST_POLYMORPHIC_MATCHER_P( isDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base) { // Check if the node is a C++ struct/union/class. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/false); // The node must be an Objective-C class. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder, /*Directly=*/false); } /// Overloaded method as shortcut for \c isDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches C++ classes that have a direct or indirect base matching \p /// BaseSpecMatcher. /// /// Example: /// matcher hasAnyBase(hasType(cxxRecordDecl(hasName("SpecialBase")))) /// \code /// class Foo; /// class Bar : Foo {}; /// class Baz : Bar {}; /// class SpecialBase; /// class Proxy : SpecialBase {}; // matches Proxy /// class IndirectlyDerived : Proxy {}; //matches IndirectlyDerived /// \endcode /// // FIXME: Refactor this and isDerivedFrom to reuse implementation. AST_MATCHER_P(CXXRecordDecl, hasAnyBase, internal::Matcher<CXXBaseSpecifier>, BaseSpecMatcher) { return internal::matchesAnyBase(Node, BaseSpecMatcher, Finder, Builder); } /// Matches C++ classes that have a direct base matching \p BaseSpecMatcher. /// /// Example: /// matcher hasDirectBase(hasType(cxxRecordDecl(hasName("SpecialBase")))) /// \code /// class Foo; /// class Bar : Foo {}; /// class Baz : Bar {}; /// class SpecialBase; /// class Proxy : SpecialBase {}; // matches Proxy /// class IndirectlyDerived : Proxy {}; // doesn't match /// \endcode AST_MATCHER_P(CXXRecordDecl, hasDirectBase, internal::Matcher<CXXBaseSpecifier>, BaseSpecMatcher) { return Node.hasDefinition() && llvm::any_of(Node.bases(), [&](const CXXBaseSpecifier &Base) { return BaseSpecMatcher.matches(Base, Finder, Builder); }); } /// Similar to \c isDerivedFrom(), but also matches classes that directly /// match \c Base. AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isSameOrDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base, 0) { const auto M = anyOf(Base, isDerivedFrom(Base)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Overloaded method as shortcut for /// \c isSameOrDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isSameOrDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isSameOrDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches C++ or Objective-C classes that are directly derived from a class /// matching \c Base. /// /// Note that a class is not considered to be derived from itself. /// /// Example matches Y, C (Base == hasName("X")) /// \code /// class X; /// class Y : public X {}; // directly derived /// class Z : public Y {}; // indirectly derived /// typedef X A; /// typedef A B; /// class C : public B {}; // derived from a typedef of X /// \endcode /// /// In the following example, Bar matches isDerivedFrom(hasName("X")): /// \code /// class Foo; /// typedef Foo X; /// class Bar : public Foo {}; // derived from a type that X is a typedef of /// \endcode AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDirectlyDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), internal::Matcher<NamedDecl>, Base, 0) { // Check if the node is a C++ struct/union/class. if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Finder->classIsDerivedFrom(RD, Base, Builder, /*Directly=*/true); // The node must be an Objective-C class. const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Finder->objcClassIsDerivedFrom(InterfaceDecl, Base, Builder, /*Directly=*/true); } /// Overloaded method as shortcut for \c isDirectlyDerivedFrom(hasName(...)). AST_POLYMORPHIC_MATCHER_P_OVERLOAD( isDirectlyDerivedFrom, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, ObjCInterfaceDecl), std::string, BaseName, 1) { if (BaseName.empty()) return false; const auto M = isDirectlyDerivedFrom(hasName(BaseName)); if (const auto *RD = dyn_cast<CXXRecordDecl>(&Node)) return Matcher<CXXRecordDecl>(M).matches(*RD, Finder, Builder); const auto *InterfaceDecl = cast<ObjCInterfaceDecl>(&Node); return Matcher<ObjCInterfaceDecl>(M).matches(*InterfaceDecl, Finder, Builder); } /// Matches the first method of a class or struct that satisfies \c /// InnerMatcher. /// /// Given: /// \code /// class A { void func(); }; /// class B { void member(); }; /// \endcode /// /// \c cxxRecordDecl(hasMethod(hasName("func"))) matches the declaration of /// \c A but not \c B. AST_MATCHER_P(CXXRecordDecl, hasMethod, internal::Matcher<CXXMethodDecl>, InnerMatcher) { BoundNodesTreeBuilder Result(*Builder); auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.method_begin(), Node.method_end(), Finder, &Result); if (MatchIt == Node.method_end()) return false; if (Finder->isTraversalIgnoringImplicitNodes() && (*MatchIt)->isImplicit()) return false; *Builder = std::move(Result); return true; } /// Matches the generated class of lambda expressions. /// /// Given: /// \code /// auto x = []{}; /// \endcode /// /// \c cxxRecordDecl(isLambda()) matches the implicit class declaration of /// \c decltype(x) AST_MATCHER(CXXRecordDecl, isLambda) { return Node.isLambda(); } /// Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y /// (matcher = cxxRecordDecl(has(cxxRecordDecl(hasName("X"))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// Usable as: Any Matcher /// Note that has is direct matcher, so it also matches things like implicit /// casts and paren casts. If you are matching with expr then you should /// probably consider using ignoringParenImpCasts like: /// has(ignoringParenImpCasts(expr())). extern const internal::ArgumentAdaptingMatcherFunc<internal::HasMatcher> has; /// Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, Y, Z /// (matcher = cxxRecordDecl(hasDescendant(cxxRecordDecl(hasName("X"))))) /// \code /// class X {}; // Matches X, because X::X is a class of name X inside X. /// class Y { class X {}; }; /// class Z { class Y { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasDescendantMatcher> hasDescendant; /// Matches AST nodes that have child AST nodes that match the /// provided matcher. /// /// Example matches X, Y, Y::X, Z::Y, Z::Y::X /// (matcher = cxxRecordDecl(forEach(cxxRecordDecl(hasName("X"))) /// \code /// class X {}; /// class Y { class X {}; }; // Matches Y, because Y::X is a class of name X /// // inside Y. /// class Z { class Y { class X {}; }; }; // Does not match Z. /// \endcode /// /// ChildT must be an AST base type. /// /// As opposed to 'has', 'forEach' will cause a match for each result that /// matches instead of only on the first one. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc<internal::ForEachMatcher> forEach; /// Matches AST nodes that have descendant AST nodes that match the /// provided matcher. /// /// Example matches X, A, A::X, B, B::C, B::C::X /// (matcher = cxxRecordDecl(forEachDescendant(cxxRecordDecl(hasName("X"))))) /// \code /// class X {}; /// class A { class X {}; }; // Matches A, because A::X is a class of name /// // X inside A. /// class B { class C { class X {}; }; }; /// \endcode /// /// DescendantT must be an AST base type. /// /// As opposed to 'hasDescendant', 'forEachDescendant' will cause a match for /// each result that matches instead of only on the first one. /// /// Note: Recursively combined ForEachDescendant can cause many matches: /// cxxRecordDecl(forEachDescendant(cxxRecordDecl( /// forEachDescendant(cxxRecordDecl()) /// ))) /// will match 10 times (plus injected class name matches) on: /// \code /// class A { class B { class C { class D { class E {}; }; }; }; }; /// \endcode /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::ForEachDescendantMatcher> forEachDescendant; /// Matches if the node or any descendant matches. /// /// Generates results for each match. /// /// For example, in: /// \code /// class A { class B {}; class C {}; }; /// \endcode /// The matcher: /// \code /// cxxRecordDecl(hasName("::A"), /// findAll(cxxRecordDecl(isDefinition()).bind("m"))) /// \endcode /// will generate results for \c A, \c B and \c C. /// /// Usable as: Any Matcher template <typename T> internal::Matcher<T> findAll(const internal::Matcher<T> &Matcher) { return eachOf(Matcher, forEachDescendant(Matcher)); } /// Matches AST nodes that have a parent that matches the provided /// matcher. /// /// Given /// \code /// void f() { for (;;) { int x = 42; if (true) { int x = 43; } } } /// \endcode /// \c compoundStmt(hasParent(ifStmt())) matches "{ int x = 43; }". /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasParentMatcher, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>> hasParent; /// Matches AST nodes that have an ancestor that matches the provided /// matcher. /// /// Given /// \code /// void f() { if (true) { int x = 42; } } /// void g() { for (;;) { int x = 43; } } /// \endcode /// \c expr(integerLiteral(hasAncestor(ifStmt()))) matches \c 42, but not 43. /// /// Usable as: Any Matcher extern const internal::ArgumentAdaptingMatcherFunc< internal::HasAncestorMatcher, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>, internal::TypeList<Decl, NestedNameSpecifierLoc, Stmt, TypeLoc>> hasAncestor; /// Matches if the provided matcher does not match. /// /// Example matches Y (matcher = cxxRecordDecl(unless(hasName("X")))) /// \code /// class X {}; /// class Y {}; /// \endcode /// /// Usable as: Any Matcher extern const internal::VariadicOperatorMatcherFunc<1, 1> unless; /// Matches a node if the declaration associated with that node /// matches the given matcher. /// /// The associated declaration is: /// - for type nodes, the declaration of the underlying type /// - for CallExpr, the declaration of the callee /// - for MemberExpr, the declaration of the referenced member /// - for CXXConstructExpr, the declaration of the constructor /// - for CXXNewExpr, the declaration of the operator new /// - for ObjCIvarExpr, the declaration of the ivar /// /// For type nodes, hasDeclaration will generally match the declaration of the /// sugared type. Given /// \code /// class X {}; /// typedef X Y; /// Y y; /// \endcode /// in varDecl(hasType(hasDeclaration(decl()))) the decl will match the /// typedefDecl. A common use case is to match the underlying, desugared type. /// This can be achieved by using the hasUnqualifiedDesugaredType matcher: /// \code /// varDecl(hasType(hasUnqualifiedDesugaredType( /// recordType(hasDeclaration(decl()))))) /// \endcode /// In this matcher, the decl will match the CXXRecordDecl of class X. /// /// Usable as: Matcher<AddrLabelExpr>, Matcher<CallExpr>, /// Matcher<CXXConstructExpr>, Matcher<CXXNewExpr>, Matcher<DeclRefExpr>, /// Matcher<EnumType>, Matcher<InjectedClassNameType>, Matcher<LabelStmt>, /// Matcher<MemberExpr>, Matcher<QualType>, Matcher<RecordType>, /// Matcher<TagType>, Matcher<TemplateSpecializationType>, /// Matcher<TemplateTypeParmType>, Matcher<TypedefType>, /// Matcher<UnresolvedUsingType> inline internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>> hasDeclaration(const internal::Matcher<Decl> &InnerMatcher) { return internal::PolymorphicMatcher< internal::HasDeclarationMatcher, void(internal::HasDeclarationSupportedTypes), internal::Matcher<Decl>>( InnerMatcher); } /// Matches a \c NamedDecl whose underlying declaration matches the given /// matcher. /// /// Given /// \code /// namespace N { template<class T> void f(T t); } /// template <class T> void g() { using N::f; f(T()); } /// \endcode /// \c unresolvedLookupExpr(hasAnyDeclaration( /// namedDecl(hasUnderlyingDecl(hasName("::N::f"))))) /// matches the use of \c f in \c g() . AST_MATCHER_P(NamedDecl, hasUnderlyingDecl, internal::Matcher<NamedDecl>, InnerMatcher) { const NamedDecl *UnderlyingDecl = Node.getUnderlyingDecl(); return UnderlyingDecl != nullptr && InnerMatcher.matches(*UnderlyingDecl, Finder, Builder); } /// Matches on the implicit object argument of a member call expression, after /// stripping off any parentheses or implicit casts. /// /// Given /// \code /// class Y { public: void m(); }; /// Y g(); /// class X : public Y {}; /// void z(Y y, X x) { y.m(); (g()).m(); x.m(); } /// \endcode /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("Y"))))) /// matches `y.m()` and `(g()).m()`. /// cxxMemberCallExpr(on(hasType(cxxRecordDecl(hasName("X"))))) /// matches `x.m()`. /// cxxMemberCallExpr(on(callExpr())) /// matches `(g()).m()`. /// /// FIXME: Overload to allow directly matching types? AST_MATCHER_P(CXXMemberCallExpr, on, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument() ->IgnoreParenImpCasts(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches on the receiver of an ObjectiveC Message expression. /// /// Example /// matcher = objCMessageExpr(hasReceiverType(asString("UIWebView *"))); /// matches the [webView ...] message invocation. /// \code /// NSString *webViewJavaScript = ... /// UIWebView *webView = ... /// [webView stringByEvaluatingJavaScriptFromString:webViewJavascript]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasReceiverType, internal::Matcher<QualType>, InnerMatcher) { const QualType TypeDecl = Node.getReceiverType(); return InnerMatcher.matches(TypeDecl, Finder, Builder); } /// Returns true when the Objective-C method declaration is a class method. /// /// Example /// matcher = objcMethodDecl(isClassMethod()) /// matches /// \code /// @interface I + (void)foo; @end /// \endcode /// but not /// \code /// @interface I - (void)bar; @end /// \endcode AST_MATCHER(ObjCMethodDecl, isClassMethod) { return Node.isClassMethod(); } /// Returns true when the Objective-C method declaration is an instance method. /// /// Example /// matcher = objcMethodDecl(isInstanceMethod()) /// matches /// \code /// @interface I - (void)bar; @end /// \endcode /// but not /// \code /// @interface I + (void)foo; @end /// \endcode AST_MATCHER(ObjCMethodDecl, isInstanceMethod) { return Node.isInstanceMethod(); } /// Returns true when the Objective-C message is sent to a class. /// /// Example /// matcher = objcMessageExpr(isClassMessage()) /// matches /// \code /// [NSString stringWithFormat:@"format"]; /// \endcode /// but not /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode AST_MATCHER(ObjCMessageExpr, isClassMessage) { return Node.isClassMessage(); } /// Returns true when the Objective-C message is sent to an instance. /// /// Example /// matcher = objcMessageExpr(isInstanceMessage()) /// matches /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode /// but not /// \code /// [NSString stringWithFormat:@"format"]; /// \endcode AST_MATCHER(ObjCMessageExpr, isInstanceMessage) { return Node.isInstanceMessage(); } /// Matches if the Objective-C message is sent to an instance, /// and the inner matcher matches on that instance. /// /// For example the method call in /// \code /// NSString *x = @"hello"; /// [x containsString:@"h"]; /// \endcode /// is matched by /// objcMessageExpr(hasReceiver(declRefExpr(to(varDecl(hasName("x")))))) AST_MATCHER_P(ObjCMessageExpr, hasReceiver, internal::Matcher<Expr>, InnerMatcher) { const Expr *ReceiverNode = Node.getInstanceReceiver(); return (ReceiverNode != nullptr && InnerMatcher.matches(*ReceiverNode->IgnoreParenImpCasts(), Finder, Builder)); } /// Matches when BaseName == Selector.getAsString() /// /// matcher = objCMessageExpr(hasSelector("loadHTMLString:baseURL:")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, hasSelector, std::string, BaseName) { Selector Sel = Node.getSelector(); return BaseName.compare(Sel.getAsString()) == 0; } /// Matches when at least one of the supplied string equals to the /// Selector.getAsString() /// /// matcher = objCMessageExpr(hasSelector("methodA:", "methodB:")); /// matches both of the expressions below: /// \code /// [myObj methodA:argA]; /// [myObj methodB:argB]; /// \endcode extern const internal::VariadicFunction<internal::Matcher<ObjCMessageExpr>, StringRef, internal::hasAnySelectorFunc> hasAnySelector; /// Matches ObjC selectors whose name contains /// a substring matched by the given RegExp. /// matcher = objCMessageExpr(matchesSelector("loadHTMLString\:baseURL?")); /// matches the outer message expr in the code below, but NOT the message /// invocation for self.bodyView. /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_REGEX(ObjCMessageExpr, matchesSelector, RegExp) { std::string SelectorString = Node.getSelector().getAsString(); return RegExp->match(SelectorString); } /// Matches when the selector is the empty selector /// /// Matches only when the selector of the objCMessageExpr is NULL. This may /// represent an error condition in the tree! AST_MATCHER(ObjCMessageExpr, hasNullSelector) { return Node.getSelector().isNull(); } /// Matches when the selector is a Unary Selector /// /// matcher = objCMessageExpr(matchesSelector(hasUnarySelector()); /// matches self.bodyView in the code below, but NOT the outer message /// invocation of "loadHTMLString:baseURL:". /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER(ObjCMessageExpr, hasUnarySelector) { return Node.getSelector().isUnarySelector(); } /// Matches when the selector is a keyword selector /// /// objCMessageExpr(hasKeywordSelector()) matches the generated setFrame /// message expression in /// /// \code /// UIWebView *webView = ...; /// CGRect bodyFrame = webView.frame; /// bodyFrame.size.height = self.bodyContentHeight; /// webView.frame = bodyFrame; /// // ^---- matches here /// \endcode AST_MATCHER(ObjCMessageExpr, hasKeywordSelector) { return Node.getSelector().isKeywordSelector(); } /// Matches when the selector has the specified number of arguments /// /// matcher = objCMessageExpr(numSelectorArgs(0)); /// matches self.bodyView in the code below /// /// matcher = objCMessageExpr(numSelectorArgs(2)); /// matches the invocation of "loadHTMLString:baseURL:" but not that /// of self.bodyView /// \code /// [self.bodyView loadHTMLString:html baseURL:NULL]; /// \endcode AST_MATCHER_P(ObjCMessageExpr, numSelectorArgs, unsigned, N) { return Node.getSelector().getNumArgs() == N; } /// Matches if the call expression's callee expression matches. /// /// Given /// \code /// class Y { void x() { this->x(); x(); Y y; y.x(); } }; /// void f() { f(); } /// \endcode /// callExpr(callee(expr())) /// matches this->x(), x(), y.x(), f() /// with callee(...) /// matching this->x, x, y.x, f respectively /// /// Note: Callee cannot take the more general internal::Matcher<Expr> /// because this introduces ambiguous overloads with calls to Callee taking a /// internal::Matcher<Decl>, as the matcher hierarchy is purely /// implemented in terms of implicit casts. AST_MATCHER_P(CallExpr, callee, internal::Matcher<Stmt>, InnerMatcher) { const Expr *ExprNode = Node.getCallee(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches if the call expression's callee's declaration matches the /// given matcher. /// /// Example matches y.x() (matcher = callExpr(callee( /// cxxMethodDecl(hasName("x"))))) /// \code /// class Y { public: void x(); }; /// void z() { Y y; y.x(); } /// \endcode AST_MATCHER_P_OVERLOAD(CallExpr, callee, internal::Matcher<Decl>, InnerMatcher, 1) { return callExpr(hasDeclaration(InnerMatcher)).matches(Node, Finder, Builder); } /// Matches if the expression's or declaration's type matches a type /// matcher. /// /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) /// and U (matcher = typedefDecl(hasType(asString("int"))) /// and friend class X (matcher = friendDecl(hasType("X")) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// typedef int U; /// class Y { friend class X; }; /// \endcode AST_POLYMORPHIC_MATCHER_P_OVERLOAD( hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, TypedefNameDecl, ValueDecl), internal::Matcher<QualType>, InnerMatcher, 0) { QualType QT = internal::getUnderlyingType(Node); if (!QT.isNull()) return InnerMatcher.matches(QT, Finder, Builder); return false; } /// Overloaded to match the declaration of the expression's or value /// declaration's type. /// /// In case of a value declaration (for example a variable declaration), /// this resolves one layer of indirection. For example, in the value /// declaration "X x;", cxxRecordDecl(hasName("X")) matches the declaration of /// X, while varDecl(hasType(cxxRecordDecl(hasName("X")))) matches the /// declaration of x. /// /// Example matches x (matcher = expr(hasType(cxxRecordDecl(hasName("X"))))) /// and z (matcher = varDecl(hasType(cxxRecordDecl(hasName("X"))))) /// and friend class X (matcher = friendDecl(hasType("X")) /// \code /// class X {}; /// void y(X &x) { x; X z; } /// class Y { friend class X; }; /// \endcode /// /// Example matches class Derived /// (matcher = cxxRecordDecl(hasAnyBase(hasType(cxxRecordDecl(hasName("Base")))))) /// \code /// class Base {}; /// class Derived : Base {}; /// \endcode /// /// Usable as: Matcher<Expr>, Matcher<FriendDecl>, Matcher<ValueDecl>, /// Matcher<CXXBaseSpecifier> AST_POLYMORPHIC_MATCHER_P_OVERLOAD( hasType, AST_POLYMORPHIC_SUPPORTED_TYPES(Expr, FriendDecl, ValueDecl, CXXBaseSpecifier), internal::Matcher<Decl>, InnerMatcher, 1) { QualType QT = internal::getUnderlyingType(Node); if (!QT.isNull()) return qualType(hasDeclaration(InnerMatcher)).matches(QT, Finder, Builder); return false; } /// Matches if the type location of the declarator decl's type matches /// the inner matcher. /// /// Given /// \code /// int x; /// \endcode /// declaratorDecl(hasTypeLoc(loc(asString("int")))) /// matches int x AST_MATCHER_P(DeclaratorDecl, hasTypeLoc, internal::Matcher<TypeLoc>, Inner) { if (!Node.getTypeSourceInfo()) // This happens for example for implicit destructors. return false; return Inner.matches(Node.getTypeSourceInfo()->getTypeLoc(), Finder, Builder); } /// Matches if the matched type is represented by the given string. /// /// Given /// \code /// class Y { public: void x(); }; /// void z() { Y* y; y->x(); } /// \endcode /// cxxMemberCallExpr(on(hasType(asString("class Y *")))) /// matches y->x() AST_MATCHER_P(QualType, asString, std::string, Name) { return Name == Node.getAsString(); } /// Matches if the matched type is a pointer type and the pointee type /// matches the specified matcher. /// /// Example matches y->x() /// (matcher = cxxMemberCallExpr(on(hasType(pointsTo /// cxxRecordDecl(hasName("Y"))))))) /// \code /// class Y { public: void x(); }; /// void z() { Y *y; y->x(); } /// \endcode AST_MATCHER_P( QualType, pointsTo, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isAnyPointerType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// Overloaded to match the pointee type's declaration. AST_MATCHER_P_OVERLOAD(QualType, pointsTo, internal::Matcher<Decl>, InnerMatcher, 1) { return pointsTo(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches if the matched type matches the unqualified desugared /// type of the matched node. /// /// For example, in: /// \code /// class A {}; /// using B = A; /// \endcode /// The matcher type(hasUnqualifiedDesugaredType(recordType())) matches /// both B and A. AST_MATCHER_P(Type, hasUnqualifiedDesugaredType, internal::Matcher<Type>, InnerMatcher) { return InnerMatcher.matches(*Node.getUnqualifiedDesugaredType(), Finder, Builder); } /// Matches if the matched type is a reference type and the referenced /// type matches the specified matcher. /// /// Example matches X &x and const X &y /// (matcher = varDecl(hasType(references(cxxRecordDecl(hasName("X")))))) /// \code /// class X { /// void a(X b) { /// X &x = b; /// const X &y = b; /// } /// }; /// \endcode AST_MATCHER_P(QualType, references, internal::Matcher<QualType>, InnerMatcher) { return (!Node.isNull() && Node->isReferenceType() && InnerMatcher.matches(Node->getPointeeType(), Finder, Builder)); } /// Matches QualTypes whose canonical type matches InnerMatcher. /// /// Given: /// \code /// typedef int &int_ref; /// int a; /// int_ref b = a; /// \endcode /// /// \c varDecl(hasType(qualType(referenceType()))))) will not match the /// declaration of b but \c /// varDecl(hasType(qualType(hasCanonicalType(referenceType())))))) does. AST_MATCHER_P(QualType, hasCanonicalType, internal::Matcher<QualType>, InnerMatcher) { if (Node.isNull()) return false; return InnerMatcher.matches(Node.getCanonicalType(), Finder, Builder); } /// Overloaded to match the referenced type's declaration. AST_MATCHER_P_OVERLOAD(QualType, references, internal::Matcher<Decl>, InnerMatcher, 1) { return references(qualType(hasDeclaration(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches on the implicit object argument of a member call expression. Unlike /// `on`, matches the argument directly without stripping away anything. /// /// Given /// \code /// class Y { public: void m(); }; /// Y g(); /// class X : public Y { void g(); }; /// void z(Y y, X x) { y.m(); x.m(); x.g(); (g()).m(); } /// \endcode /// cxxMemberCallExpr(onImplicitObjectArgument(hasType( /// cxxRecordDecl(hasName("Y"))))) /// matches `y.m()`, `x.m()` and (g()).m(), but not `x.g()`. /// cxxMemberCallExpr(on(callExpr())) /// does not match `(g()).m()`, because the parens are not ignored. /// /// FIXME: Overload to allow directly matching types? AST_MATCHER_P(CXXMemberCallExpr, onImplicitObjectArgument, internal::Matcher<Expr>, InnerMatcher) { const Expr *ExprNode = Node.getImplicitObjectArgument(); return (ExprNode != nullptr && InnerMatcher.matches(*ExprNode, Finder, Builder)); } /// Matches if the type of the expression's implicit object argument either /// matches the InnerMatcher, or is a pointer to a type that matches the /// InnerMatcher. /// /// Given /// \code /// class Y { public: void m(); }; /// class X : public Y { void g(); }; /// void z() { Y y; y.m(); Y *p; p->m(); X x; x.m(); x.g(); } /// \endcode /// cxxMemberCallExpr(thisPointerType(hasDeclaration( /// cxxRecordDecl(hasName("Y"))))) /// matches `y.m()`, `p->m()` and `x.m()`. /// cxxMemberCallExpr(thisPointerType(hasDeclaration( /// cxxRecordDecl(hasName("X"))))) /// matches `x.g()`. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<QualType>, InnerMatcher, 0) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// Overloaded to match the type's declaration. AST_MATCHER_P_OVERLOAD(CXXMemberCallExpr, thisPointerType, internal::Matcher<Decl>, InnerMatcher, 1) { return onImplicitObjectArgument( anyOf(hasType(InnerMatcher), hasType(pointsTo(InnerMatcher)))) .matches(Node, Finder, Builder); } /// Matches a DeclRefExpr that refers to a declaration that matches the /// specified matcher. /// /// Example matches x in if(x) /// (matcher = declRefExpr(to(varDecl(hasName("x"))))) /// \code /// bool x; /// if (x) {} /// \endcode AST_MATCHER_P(DeclRefExpr, to, internal::Matcher<Decl>, InnerMatcher) { const Decl *DeclNode = Node.getDecl(); return (DeclNode != nullptr && InnerMatcher.matches(*DeclNode, Finder, Builder)); } /// Matches a \c DeclRefExpr that refers to a declaration through a /// specific using shadow declaration. /// /// Given /// \code /// namespace a { void f() {} } /// using a::f; /// void g() { /// f(); // Matches this .. /// a::f(); // .. but not this. /// } /// \endcode /// declRefExpr(throughUsingDecl(anything())) /// matches \c f() AST_MATCHER_P(DeclRefExpr, throughUsingDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { const NamedDecl *FoundDecl = Node.getFoundDecl(); if (const UsingShadowDecl *UsingDecl = dyn_cast<UsingShadowDecl>(FoundDecl)) return InnerMatcher.matches(*UsingDecl, Finder, Builder); return false; } /// Matches an \c OverloadExpr if any of the declarations in the set of /// overloads matches the given matcher. /// /// Given /// \code /// template <typename T> void foo(T); /// template <typename T> void bar(T); /// template <typename T> void baz(T t) { /// foo(t); /// bar(t); /// } /// \endcode /// unresolvedLookupExpr(hasAnyDeclaration( /// functionTemplateDecl(hasName("foo")))) /// matches \c foo in \c foo(t); but not \c bar in \c bar(t); AST_MATCHER_P(OverloadExpr, hasAnyDeclaration, internal::Matcher<Decl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.decls_begin(), Node.decls_end(), Finder, Builder) != Node.decls_end(); } /// Matches the Decl of a DeclStmt which has a single declaration. /// /// Given /// \code /// int a, b; /// int c; /// \endcode /// declStmt(hasSingleDecl(anything())) /// matches 'int c;' but not 'int a, b;'. AST_MATCHER_P(DeclStmt, hasSingleDecl, internal::Matcher<Decl>, InnerMatcher) { if (Node.isSingleDecl()) { const Decl *FoundDecl = Node.getSingleDecl(); return InnerMatcher.matches(*FoundDecl, Finder, Builder); } return false; } /// Matches a variable declaration that has an initializer expression /// that matches the given matcher. /// /// Example matches x (matcher = varDecl(hasInitializer(callExpr()))) /// \code /// bool y() { return true; } /// bool x = y(); /// \endcode AST_MATCHER_P( VarDecl, hasInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr *Initializer = Node.getAnyInitializer(); return (Initializer != nullptr && InnerMatcher.matches(*Initializer, Finder, Builder)); } /// \brief Matches a static variable with local scope. /// /// Example matches y (matcher = varDecl(isStaticLocal())) /// \code /// void f() { /// int x; /// static int y; /// } /// static int z; /// \endcode AST_MATCHER(VarDecl, isStaticLocal) { return Node.isStaticLocal(); } /// Matches a variable declaration that has function scope and is a /// non-static local variable. /// /// Example matches x (matcher = varDecl(hasLocalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasLocalStorage) { return Node.hasLocalStorage(); } /// Matches a variable declaration that does not have local storage. /// /// Example matches y and z (matcher = varDecl(hasGlobalStorage()) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode AST_MATCHER(VarDecl, hasGlobalStorage) { return Node.hasGlobalStorage(); } /// Matches a variable declaration that has automatic storage duration. /// /// Example matches x, but not y, z, or a. /// (matcher = varDecl(hasAutomaticStorageDuration()) /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// \endcode AST_MATCHER(VarDecl, hasAutomaticStorageDuration) { return Node.getStorageDuration() == SD_Automatic; } /// Matches a variable declaration that has static storage duration. /// It includes the variable declared at namespace scope and those declared /// with "static" and "extern" storage class specifiers. /// /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// static int b; /// extern int c; /// varDecl(hasStaticStorageDuration()) /// matches the function declaration y, a, b and c. /// \endcode AST_MATCHER(VarDecl, hasStaticStorageDuration) { return Node.getStorageDuration() == SD_Static; } /// Matches a variable declaration that has thread storage duration. /// /// Example matches z, but not x, z, or a. /// (matcher = varDecl(hasThreadStorageDuration()) /// \code /// void f() { /// int x; /// static int y; /// thread_local int z; /// } /// int a; /// \endcode AST_MATCHER(VarDecl, hasThreadStorageDuration) { return Node.getStorageDuration() == SD_Thread; } /// Matches a variable declaration that is an exception variable from /// a C++ catch block, or an Objective-C \@catch statement. /// /// Example matches x (matcher = varDecl(isExceptionVariable()) /// \code /// void f(int y) { /// try { /// } catch (int x) { /// } /// } /// \endcode AST_MATCHER(VarDecl, isExceptionVariable) { return Node.isExceptionVariable(); } /// Checks that a call expression or a constructor call expression has /// a specific number of arguments (including absent default arguments). /// /// Example matches f(0, 0) (matcher = callExpr(argumentCountIs(2))) /// \code /// void f(int x, int y); /// f(0, 0); /// \endcode AST_POLYMORPHIC_MATCHER_P(argumentCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), unsigned, N) { unsigned NumArgs = Node.getNumArgs(); if (!Finder->isTraversalIgnoringImplicitNodes()) return NumArgs == N; while (NumArgs) { if (!isa<CXXDefaultArgExpr>(Node.getArg(NumArgs - 1))) break; --NumArgs; } return NumArgs == N; } /// Matches the n'th argument of a call expression or a constructor /// call expression. /// /// Example matches y in x(y) /// (matcher = callExpr(hasArgument(0, declRefExpr()))) /// \code /// void x(int) { int y; x(y); } /// \endcode AST_POLYMORPHIC_MATCHER_P2(hasArgument, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), unsigned, N, internal::Matcher<Expr>, InnerMatcher) { if (N >= Node.getNumArgs()) return false; const Expr *Arg = Node.getArg(N); if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg)) return false; return InnerMatcher.matches(*Arg->IgnoreParenImpCasts(), Finder, Builder); } /// Matches the n'th item of an initializer list expression. /// /// Example matches y. /// (matcher = initListExpr(hasInit(0, expr()))) /// \code /// int x{y}. /// \endcode AST_MATCHER_P2(InitListExpr, hasInit, unsigned, N, ast_matchers::internal::Matcher<Expr>, InnerMatcher) { return N < Node.getNumInits() && InnerMatcher.matches(*Node.getInit(N), Finder, Builder); } /// Matches declaration statements that contain a specific number of /// declarations. /// /// Example: Given /// \code /// int a, b; /// int c; /// int d = 2, e; /// \endcode /// declCountIs(2) /// matches 'int a, b;' and 'int d = 2, e;', but not 'int c;'. AST_MATCHER_P(DeclStmt, declCountIs, unsigned, N) { return std::distance(Node.decl_begin(), Node.decl_end()) == (ptrdiff_t)N; } /// Matches the n'th declaration of a declaration statement. /// /// Note that this does not work for global declarations because the AST /// breaks up multiple-declaration DeclStmt's into multiple single-declaration /// DeclStmt's. /// Example: Given non-global declarations /// \code /// int a, b = 0; /// int c; /// int d = 2, e; /// \endcode /// declStmt(containsDeclaration( /// 0, varDecl(hasInitializer(anything())))) /// matches only 'int d = 2, e;', and /// declStmt(containsDeclaration(1, varDecl())) /// \code /// matches 'int a, b = 0' as well as 'int d = 2, e;' /// but 'int c;' is not matched. /// \endcode AST_MATCHER_P2(DeclStmt, containsDeclaration, unsigned, N, internal::Matcher<Decl>, InnerMatcher) { const unsigned NumDecls = std::distance(Node.decl_begin(), Node.decl_end()); if (N >= NumDecls) return false; DeclStmt::const_decl_iterator Iterator = Node.decl_begin(); std::advance(Iterator, N); return InnerMatcher.matches(**Iterator, Finder, Builder); } /// Matches a C++ catch statement that has a catch-all handler. /// /// Given /// \code /// try { /// // ... /// } catch (int) { /// // ... /// } catch (...) { /// // ... /// } /// \endcode /// cxxCatchStmt(isCatchAll()) matches catch(...) but not catch(int). AST_MATCHER(CXXCatchStmt, isCatchAll) { return Node.getExceptionDecl() == nullptr; } /// Matches a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl( /// hasAnyConstructorInitializer(anything()) /// ))) /// record matches Foo, hasAnyConstructorInitializer matches foo_(1) AST_MATCHER_P(CXXConstructorDecl, hasAnyConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { auto MatchIt = matchesFirstInPointerRange(InnerMatcher, Node.init_begin(), Node.init_end(), Finder, Builder); if (MatchIt == Node.init_end()) return false; return (*MatchIt)->isWritten() || !Finder->isTraversalIgnoringImplicitNodes(); } /// Matches the field declaration of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( /// forField(hasName("foo_")))))) /// matches Foo /// with forField matching foo_ AST_MATCHER_P(CXXCtorInitializer, forField, internal::Matcher<FieldDecl>, InnerMatcher) { const FieldDecl *NodeAsDecl = Node.getAnyMember(); return (NodeAsDecl != nullptr && InnerMatcher.matches(*NodeAsDecl, Finder, Builder)); } /// Matches the initializer expression of a constructor initializer. /// /// Given /// \code /// struct Foo { /// Foo() : foo_(1) { } /// int foo_; /// }; /// \endcode /// cxxRecordDecl(has(cxxConstructorDecl(hasAnyConstructorInitializer( /// withInitializer(integerLiteral(equals(1))))))) /// matches Foo /// with withInitializer matching (1) AST_MATCHER_P(CXXCtorInitializer, withInitializer, internal::Matcher<Expr>, InnerMatcher) { const Expr* NodeAsExpr = Node.getInit(); return (NodeAsExpr != nullptr && InnerMatcher.matches(*NodeAsExpr, Finder, Builder)); } /// Matches a constructor initializer if it is explicitly written in /// code (as opposed to implicitly added by the compiler). /// /// Given /// \code /// struct Foo { /// Foo() { } /// Foo(int) : foo_("A") { } /// string foo_; /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isWritten())) /// will match Foo(int), but not Foo() AST_MATCHER(CXXCtorInitializer, isWritten) { return Node.isWritten(); } /// Matches a constructor initializer if it is initializing a base, as /// opposed to a member. /// /// Given /// \code /// struct B {}; /// struct D : B { /// int I; /// D(int i) : I(i) {} /// }; /// struct E : B { /// E() : B() {} /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isBaseInitializer())) /// will match E(), but not match D(int). AST_MATCHER(CXXCtorInitializer, isBaseInitializer) { return Node.isBaseInitializer(); } /// Matches a constructor initializer if it is initializing a member, as /// opposed to a base. /// /// Given /// \code /// struct B {}; /// struct D : B { /// int I; /// D(int i) : I(i) {} /// }; /// struct E : B { /// E() : B() {} /// }; /// \endcode /// cxxConstructorDecl(hasAnyConstructorInitializer(isMemberInitializer())) /// will match D(int), but not match E(). AST_MATCHER(CXXCtorInitializer, isMemberInitializer) { return Node.isMemberInitializer(); } /// Matches any argument of a call expression or a constructor call /// expression, or an ObjC-message-send expression. /// /// Given /// \code /// void x(int, int, int) { int y; x(1, y, 42); } /// \endcode /// callExpr(hasAnyArgument(declRefExpr())) /// matches x(1, y, 42) /// with hasAnyArgument(...) /// matching y /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// void foo(I *i) { [i f:12]; } /// \endcode /// objcMessageExpr(hasAnyArgument(integerLiteral(equals(12)))) /// matches [i f:12] AST_POLYMORPHIC_MATCHER_P(hasAnyArgument, AST_POLYMORPHIC_SUPPORTED_TYPES( CallExpr, CXXConstructExpr, CXXUnresolvedConstructExpr, ObjCMessageExpr), internal::Matcher<Expr>, InnerMatcher) { for (const Expr *Arg : Node.arguments()) { if (Finder->isTraversalIgnoringImplicitNodes() && isa<CXXDefaultArgExpr>(Arg)) break; BoundNodesTreeBuilder Result(*Builder); if (InnerMatcher.matches(*Arg, Finder, &Result)) { *Builder = std::move(Result); return true; } } return false; } /// Matches any capture of a lambda expression. /// /// Given /// \code /// void foo() { /// int x; /// auto f = [x](){}; /// } /// \endcode /// lambdaExpr(hasAnyCapture(anything())) /// matches [x](){}; AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<VarDecl>, InnerMatcher, 0) { for (const LambdaCapture &Capture : Node.captures()) { if (Capture.capturesVariable()) { BoundNodesTreeBuilder Result(*Builder); if (InnerMatcher.matches(*Capture.getCapturedVar(), Finder, &Result)) { *Builder = std::move(Result); return true; } } } return false; } /// Matches any capture of 'this' in a lambda expression. /// /// Given /// \code /// struct foo { /// void bar() { /// auto f = [this](){}; /// } /// } /// \endcode /// lambdaExpr(hasAnyCapture(cxxThisExpr())) /// matches [this](){}; AST_MATCHER_P_OVERLOAD(LambdaExpr, hasAnyCapture, internal::Matcher<CXXThisExpr>, InnerMatcher, 1) { return llvm::any_of(Node.captures(), [](const LambdaCapture &LC) { return LC.capturesThis(); }); } /// Matches a constructor call expression which uses list initialization. AST_MATCHER(CXXConstructExpr, isListInitialization) { return Node.isListInitialization(); } /// Matches a constructor call expression which requires /// zero initialization. /// /// Given /// \code /// void foo() { /// struct point { double x; double y; }; /// point pt[2] = { { 1.0, 2.0 } }; /// } /// \endcode /// initListExpr(has(cxxConstructExpr(requiresZeroInitialization())) /// will match the implicit array filler for pt[1]. AST_MATCHER(CXXConstructExpr, requiresZeroInitialization) { return Node.requiresZeroInitialization(); } /// Matches the n'th parameter of a function or an ObjC method /// declaration or a block. /// /// Given /// \code /// class X { void f(int x) {} }; /// \endcode /// cxxMethodDecl(hasParameter(0, hasType(varDecl()))) /// matches f(int x) {} /// with hasParameter(...) /// matching int x /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// \endcode // /// the matcher objcMethodDecl(hasParameter(0, hasName("y"))) /// matches the declaration of method f with hasParameter /// matching y. AST_POLYMORPHIC_MATCHER_P2(hasParameter, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, ObjCMethodDecl, BlockDecl), unsigned, N, internal::Matcher<ParmVarDecl>, InnerMatcher) { return (N < Node.parameters().size() && InnerMatcher.matches(*Node.parameters()[N], Finder, Builder)); } /// Matches all arguments and their respective ParmVarDecl. /// /// Given /// \code /// void f(int i); /// int y; /// f(y); /// \endcode /// callExpr( /// forEachArgumentWithParam( /// declRefExpr(to(varDecl(hasName("y")))), /// parmVarDecl(hasType(isInteger())) /// )) /// matches f(y); /// with declRefExpr(...) /// matching int y /// and parmVarDecl(...) /// matching int i AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParam, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), internal::Matcher<Expr>, ArgMatcher, internal::Matcher<ParmVarDecl>, ParamMatcher) { BoundNodesTreeBuilder Result; // The first argument of an overloaded member operator is the implicit object // argument of the method which should not be matched against a parameter, so // we skip over it here. BoundNodesTreeBuilder Matches; unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) .matches(Node, Finder, &Matches) ? 1 : 0; int ParamIndex = 0; bool Matched = false; for (; ArgIndex < Node.getNumArgs(); ++ArgIndex) { BoundNodesTreeBuilder ArgMatches(*Builder); if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, &ArgMatches)) { BoundNodesTreeBuilder ParamMatches(ArgMatches); if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( hasParameter(ParamIndex, ParamMatcher)))), callExpr(callee(functionDecl( hasParameter(ParamIndex, ParamMatcher)))))) .matches(Node, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; } } ++ParamIndex; } *Builder = std::move(Result); return Matched; } /// Matches all arguments and their respective types for a \c CallExpr or /// \c CXXConstructExpr. It is very similar to \c forEachArgumentWithParam but /// it works on calls through function pointers as well. /// /// The difference is, that function pointers do not provide access to a /// \c ParmVarDecl, but only the \c QualType for each argument. /// /// Given /// \code /// void f(int i); /// int y; /// f(y); /// void (*f_ptr)(int) = f; /// f_ptr(y); /// \endcode /// callExpr( /// forEachArgumentWithParamType( /// declRefExpr(to(varDecl(hasName("y")))), /// qualType(isInteger()).bind("type) /// )) /// matches f(y) and f_ptr(y) /// with declRefExpr(...) /// matching int y /// and qualType(...) /// matching int AST_POLYMORPHIC_MATCHER_P2(forEachArgumentWithParamType, AST_POLYMORPHIC_SUPPORTED_TYPES(CallExpr, CXXConstructExpr), internal::Matcher<Expr>, ArgMatcher, internal::Matcher<QualType>, ParamMatcher) { BoundNodesTreeBuilder Result; // The first argument of an overloaded member operator is the implicit object // argument of the method which should not be matched against a parameter, so // we skip over it here. BoundNodesTreeBuilder Matches; unsigned ArgIndex = cxxOperatorCallExpr(callee(cxxMethodDecl())) .matches(Node, Finder, &Matches) ? 1 : 0; const FunctionProtoType *FProto = nullptr; if (const auto *Call = dyn_cast<CallExpr>(&Node)) { if (const auto *Value = dyn_cast_or_null<ValueDecl>(Call->getCalleeDecl())) { QualType QT = Value->getType().getCanonicalType(); // This does not necessarily lead to a `FunctionProtoType`, // e.g. K&R functions do not have a function prototype. if (QT->isFunctionPointerType()) FProto = QT->getPointeeType()->getAs<FunctionProtoType>(); if (QT->isMemberFunctionPointerType()) { const auto *MP = QT->getAs<MemberPointerType>(); assert(MP && "Must be member-pointer if its a memberfunctionpointer"); FProto = MP->getPointeeType()->getAs<FunctionProtoType>(); assert(FProto && "The call must have happened through a member function " "pointer"); } } } int ParamIndex = 0; bool Matched = false; for (; ArgIndex < Node.getNumArgs(); ++ArgIndex, ++ParamIndex) { BoundNodesTreeBuilder ArgMatches(*Builder); if (ArgMatcher.matches(*(Node.getArg(ArgIndex)->IgnoreParenCasts()), Finder, &ArgMatches)) { BoundNodesTreeBuilder ParamMatches(ArgMatches); // This test is cheaper compared to the big matcher in the next if. // Therefore, please keep this order. if (FProto) { QualType ParamType = FProto->getParamType(ParamIndex); if (ParamMatcher.matches(ParamType, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; continue; } } if (expr(anyOf(cxxConstructExpr(hasDeclaration(cxxConstructorDecl( hasParameter(ParamIndex, hasType(ParamMatcher))))), callExpr(callee(functionDecl( hasParameter(ParamIndex, hasType(ParamMatcher))))))) .matches(Node, Finder, &ParamMatches)) { Result.addMatch(ParamMatches); Matched = true; continue; } } } *Builder = std::move(Result); return Matched; } /// Matches the ParmVarDecl nodes that are at the N'th position in the parameter /// list. The parameter list could be that of either a block, function, or /// objc-method. /// /// /// Given /// /// \code /// void f(int a, int b, int c) { /// } /// \endcode /// /// ``parmVarDecl(isAtPosition(0))`` matches ``int a``. /// /// ``parmVarDecl(isAtPosition(1))`` matches ``int b``. AST_MATCHER_P(ParmVarDecl, isAtPosition, unsigned, N) { const clang::DeclContext *Context = Node.getParentFunctionOrMethod(); if (const auto *Decl = dyn_cast_or_null<FunctionDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; if (const auto *Decl = dyn_cast_or_null<BlockDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; if (const auto *Decl = dyn_cast_or_null<ObjCMethodDecl>(Context)) return N < Decl->param_size() && Decl->getParamDecl(N) == &Node; return false; } /// Matches any parameter of a function or an ObjC method declaration or a /// block. /// /// Does not match the 'this' parameter of a method. /// /// Given /// \code /// class X { void f(int x, int y, int z) {} }; /// \endcode /// cxxMethodDecl(hasAnyParameter(hasName("y"))) /// matches f(int x, int y, int z) {} /// with hasAnyParameter(...) /// matching int y /// /// For ObjectiveC, given /// \code /// @interface I - (void) f:(int) y; @end /// \endcode // /// the matcher objcMethodDecl(hasAnyParameter(hasName("y"))) /// matches the declaration of method f with hasParameter /// matching y. /// /// For blocks, given /// \code /// b = ^(int y) { printf("%d", y) }; /// \endcode /// /// the matcher blockDecl(hasAnyParameter(hasName("y"))) /// matches the declaration of the block b with hasParameter /// matching y. AST_POLYMORPHIC_MATCHER_P(hasAnyParameter, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, ObjCMethodDecl, BlockDecl), internal::Matcher<ParmVarDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.param_begin(), Node.param_end(), Finder, Builder) != Node.param_end(); } /// Matches \c FunctionDecls and \c FunctionProtoTypes that have a /// specific parameter count. /// /// Given /// \code /// void f(int i) {} /// void g(int i, int j) {} /// void h(int i, int j); /// void j(int i); /// void k(int x, int y, int z, ...); /// \endcode /// functionDecl(parameterCountIs(2)) /// matches \c g and \c h /// functionProtoType(parameterCountIs(2)) /// matches \c g and \c h /// functionProtoType(parameterCountIs(3)) /// matches \c k AST_POLYMORPHIC_MATCHER_P(parameterCountIs, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType), unsigned, N) { return Node.getNumParams() == N; } /// Matches \c FunctionDecls that have a noreturn attribute. /// /// Given /// \code /// void nope(); /// [[noreturn]] void a(); /// __attribute__((noreturn)) void b(); /// struct c { [[noreturn]] c(); }; /// \endcode /// functionDecl(isNoReturn()) /// matches all of those except /// \code /// void nope(); /// \endcode AST_MATCHER(FunctionDecl, isNoReturn) { return Node.isNoReturn(); } /// Matches the return type of a function declaration. /// /// Given: /// \code /// class X { int f() { return 1; } }; /// \endcode /// cxxMethodDecl(returns(asString("int"))) /// matches int f() { return 1; } AST_MATCHER_P(FunctionDecl, returns, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getReturnType(), Finder, Builder); } /// Matches extern "C" function or variable declarations. /// /// Given: /// \code /// extern "C" void f() {} /// extern "C" { void g() {} } /// void h() {} /// extern "C" int x = 1; /// extern "C" int y = 2; /// int z = 3; /// \endcode /// functionDecl(isExternC()) /// matches the declaration of f and g, but not the declaration of h. /// varDecl(isExternC()) /// matches the declaration of x and y, but not the declaration of z. AST_POLYMORPHIC_MATCHER(isExternC, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl)) { return Node.isExternC(); } /// Matches variable/function declarations that have "static" storage /// class specifier ("static" keyword) written in the source. /// /// Given: /// \code /// static void f() {} /// static int i = 0; /// extern int j; /// int k; /// \endcode /// functionDecl(isStaticStorageClass()) /// matches the function declaration f. /// varDecl(isStaticStorageClass()) /// matches the variable declaration i. AST_POLYMORPHIC_MATCHER(isStaticStorageClass, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl)) { return Node.getStorageClass() == SC_Static; } /// Matches deleted function declarations. /// /// Given: /// \code /// void Func(); /// void DeletedFunc() = delete; /// \endcode /// functionDecl(isDeleted()) /// matches the declaration of DeletedFunc, but not Func. AST_MATCHER(FunctionDecl, isDeleted) { return Node.isDeleted(); } /// Matches defaulted function declarations. /// /// Given: /// \code /// class A { ~A(); }; /// class B { ~B() = default; }; /// \endcode /// functionDecl(isDefaulted()) /// matches the declaration of ~B, but not ~A. AST_MATCHER(FunctionDecl, isDefaulted) { return Node.isDefaulted(); } /// Matches weak function declarations. /// /// Given: /// \code /// void foo() __attribute__((__weakref__("__foo"))); /// void bar(); /// \endcode /// functionDecl(isWeak()) /// matches the weak declaration "foo", but not "bar". AST_MATCHER(FunctionDecl, isWeak) { return Node.isWeak(); } /// Matches functions that have a dynamic exception specification. /// /// Given: /// \code /// void f(); /// void g() noexcept; /// void h() noexcept(true); /// void i() noexcept(false); /// void j() throw(); /// void k() throw(int); /// void l() throw(...); /// \endcode /// functionDecl(hasDynamicExceptionSpec()) and /// functionProtoType(hasDynamicExceptionSpec()) /// match the declarations of j, k, and l, but not f, g, h, or i. AST_POLYMORPHIC_MATCHER(hasDynamicExceptionSpec, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType)) { if (const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node)) return FnTy->hasDynamicExceptionSpec(); return false; } /// Matches functions that have a non-throwing exception specification. /// /// Given: /// \code /// void f(); /// void g() noexcept; /// void h() throw(); /// void i() throw(int); /// void j() noexcept(false); /// \endcode /// functionDecl(isNoThrow()) and functionProtoType(isNoThrow()) /// match the declarations of g, and h, but not f, i or j. AST_POLYMORPHIC_MATCHER(isNoThrow, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, FunctionProtoType)) { const FunctionProtoType *FnTy = internal::getFunctionProtoType(Node); // If the function does not have a prototype, then it is assumed to be a // throwing function (as it would if the function did not have any exception // specification). if (!FnTy) return false; // Assume the best for any unresolved exception specification. if (isUnresolvedExceptionSpec(FnTy->getExceptionSpecType())) return true; return FnTy->isNothrow(); } /// Matches constexpr variable and function declarations, /// and if constexpr. /// /// Given: /// \code /// constexpr int foo = 42; /// constexpr int bar(); /// void baz() { if constexpr(1 > 0) {} } /// \endcode /// varDecl(isConstexpr()) /// matches the declaration of foo. /// functionDecl(isConstexpr()) /// matches the declaration of bar. /// ifStmt(isConstexpr()) /// matches the if statement in baz. AST_POLYMORPHIC_MATCHER(isConstexpr, AST_POLYMORPHIC_SUPPORTED_TYPES(VarDecl, FunctionDecl, IfStmt)) { return Node.isConstexpr(); } /// Matches selection statements with initializer. /// /// Given: /// \code /// void foo() { /// if (int i = foobar(); i > 0) {} /// switch (int i = foobar(); i) {} /// for (auto& a = get_range(); auto& x : a) {} /// } /// void bar() { /// if (foobar() > 0) {} /// switch (foobar()) {} /// for (auto& x : get_range()) {} /// } /// \endcode /// ifStmt(hasInitStatement(anything())) /// matches the if statement in foo but not in bar. /// switchStmt(hasInitStatement(anything())) /// matches the switch statement in foo but not in bar. /// cxxForRangeStmt(hasInitStatement(anything())) /// matches the range for statement in foo but not in bar. AST_POLYMORPHIC_MATCHER_P(hasInitStatement, AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, SwitchStmt, CXXForRangeStmt), internal::Matcher<Stmt>, InnerMatcher) { const Stmt *Init = Node.getInit(); return Init != nullptr && InnerMatcher.matches(*Init, Finder, Builder); } /// Matches the condition expression of an if statement, for loop, /// switch statement or conditional operator. /// /// Example matches true (matcher = hasCondition(cxxBoolLiteral(equals(true)))) /// \code /// if (true) {} /// \endcode AST_POLYMORPHIC_MATCHER_P( hasCondition, AST_POLYMORPHIC_SUPPORTED_TYPES(IfStmt, ForStmt, WhileStmt, DoStmt, SwitchStmt, AbstractConditionalOperator), internal::Matcher<Expr>, InnerMatcher) { const Expr *const Condition = Node.getCond(); return (Condition != nullptr && InnerMatcher.matches(*Condition, Finder, Builder)); } /// Matches the then-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasThen(cxxBoolLiteral(equals(true))))) /// \code /// if (false) true; else false; /// \endcode AST_MATCHER_P(IfStmt, hasThen, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Then = Node.getThen(); return (Then != nullptr && InnerMatcher.matches(*Then, Finder, Builder)); } /// Matches the else-statement of an if statement. /// /// Examples matches the if statement /// (matcher = ifStmt(hasElse(cxxBoolLiteral(equals(true))))) /// \code /// if (false) false; else true; /// \endcode AST_MATCHER_P(IfStmt, hasElse, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Else = Node.getElse(); return (Else != nullptr && InnerMatcher.matches(*Else, Finder, Builder)); } /// Matches if a node equals a previously bound node. /// /// Matches a node if it equals the node previously bound to \p ID. /// /// Given /// \code /// class X { int a; int b; }; /// \endcode /// cxxRecordDecl( /// has(fieldDecl(hasName("a"), hasType(type().bind("t")))), /// has(fieldDecl(hasName("b"), hasType(type(equalsBoundNode("t")))))) /// matches the class \c X, as \c a and \c b have the same type. /// /// Note that when multiple matches are involved via \c forEach* matchers, /// \c equalsBoundNodes acts as a filter. /// For example: /// compoundStmt( /// forEachDescendant(varDecl().bind("d")), /// forEachDescendant(declRefExpr(to(decl(equalsBoundNode("d")))))) /// will trigger a match for each combination of variable declaration /// and reference to that variable declaration within a compound statement. AST_POLYMORPHIC_MATCHER_P(equalsBoundNode, AST_POLYMORPHIC_SUPPORTED_TYPES(Stmt, Decl, Type, QualType), std::string, ID) { // FIXME: Figure out whether it makes sense to allow this // on any other node types. // For *Loc it probably does not make sense, as those seem // unique. For NestedNameSepcifier it might make sense, as // those also have pointer identity, but I'm not sure whether // they're ever reused. internal::NotEqualsBoundNodePredicate Predicate; Predicate.ID = ID; Predicate.Node = DynTypedNode::create(Node); return Builder->removeBindings(Predicate); } /// Matches the condition variable statement in an if statement. /// /// Given /// \code /// if (A* a = GetAPointer()) {} /// \endcode /// hasConditionVariableStatement(...) /// matches 'A* a = GetAPointer()'. AST_MATCHER_P(IfStmt, hasConditionVariableStatement, internal::Matcher<DeclStmt>, InnerMatcher) { const DeclStmt* const DeclarationStatement = Node.getConditionVariableDeclStmt(); return DeclarationStatement != nullptr && InnerMatcher.matches(*DeclarationStatement, Finder, Builder); } /// Matches the index expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasIndex(integerLiteral())) /// matches \c i[1] with the \c integerLiteral() matching \c 1 AST_MATCHER_P(ArraySubscriptExpr, hasIndex, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getIdx()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// Matches the base expression of an array subscript expression. /// /// Given /// \code /// int i[5]; /// void f() { i[1] = 42; } /// \endcode /// arraySubscriptExpression(hasBase(implicitCastExpr( /// hasSourceExpression(declRefExpr())))) /// matches \c i[1] with the \c declRefExpr() matching \c i AST_MATCHER_P(ArraySubscriptExpr, hasBase, internal::Matcher<Expr>, InnerMatcher) { if (const Expr* Expression = Node.getBase()) return InnerMatcher.matches(*Expression, Finder, Builder); return false; } /// Matches a 'for', 'while', 'do while' statement or a function /// definition that has a given body. Note that in case of functions /// this matcher only matches the definition itself and not the other /// declarations of the same function. /// /// Given /// \code /// for (;;) {} /// \endcode /// hasBody(compoundStmt()) /// matches 'for (;;) {}' /// with compoundStmt() /// matching '{}' /// /// Given /// \code /// void f(); /// void f() {} /// \endcode /// hasBody(functionDecl()) /// matches 'void f() {}' /// with compoundStmt() /// matching '{}' /// but does not match 'void f();' AST_POLYMORPHIC_MATCHER_P(hasBody, AST_POLYMORPHIC_SUPPORTED_TYPES(DoStmt, ForStmt, WhileStmt, CXXForRangeStmt, FunctionDecl), internal::Matcher<Stmt>, InnerMatcher) { if (Finder->isTraversalIgnoringImplicitNodes() && isDefaultedHelper(&Node)) return false; const Stmt *const Statement = internal::GetBodyMatcher<NodeType>::get(Node); return (Statement != nullptr && InnerMatcher.matches(*Statement, Finder, Builder)); } /// Matches a function declaration that has a given body present in the AST. /// Note that this matcher matches all the declarations of a function whose /// body is present in the AST. /// /// Given /// \code /// void f(); /// void f() {} /// void g(); /// \endcode /// hasAnyBody(functionDecl()) /// matches both 'void f();' /// and 'void f() {}' /// with compoundStmt() /// matching '{}' /// but does not match 'void g();' AST_MATCHER_P(FunctionDecl, hasAnyBody, internal::Matcher<Stmt>, InnerMatcher) { const Stmt *const Statement = Node.getBody(); return (Statement != nullptr && InnerMatcher.matches(*Statement, Finder, Builder)); } /// Matches compound statements where at least one substatement matches /// a given matcher. Also matches StmtExprs that have CompoundStmt as children. /// /// Given /// \code /// { {}; 1+2; } /// \endcode /// hasAnySubstatement(compoundStmt()) /// matches '{ {}; 1+2; }' /// with compoundStmt() /// matching '{}' AST_POLYMORPHIC_MATCHER_P(hasAnySubstatement, AST_POLYMORPHIC_SUPPORTED_TYPES(CompoundStmt, StmtExpr), internal::Matcher<Stmt>, InnerMatcher) { const CompoundStmt *CS = CompoundStmtMatcher<NodeType>::get(Node); return CS && matchesFirstInPointerRange(InnerMatcher, CS->body_begin(), CS->body_end(), Finder, Builder) != CS->body_end(); } /// Checks that a compound statement contains a specific number of /// child statements. /// /// Example: Given /// \code /// { for (;;) {} } /// \endcode /// compoundStmt(statementCountIs(0))) /// matches '{}' /// but does not match the outer compound statement. AST_MATCHER_P(CompoundStmt, statementCountIs, unsigned, N) { return Node.size() == N; } /// Matches literals that are equal to the given value of type ValueT. /// /// Given /// \code /// f('\0', false, 3.14, 42); /// \endcode /// characterLiteral(equals(0)) /// matches '\0' /// cxxBoolLiteral(equals(false)) and cxxBoolLiteral(equals(0)) /// match false /// floatLiteral(equals(3.14)) and floatLiteral(equals(314e-2)) /// match 3.14 /// integerLiteral(equals(42)) /// matches 42 /// /// Note that you cannot directly match a negative numeric literal because the /// minus sign is not part of the literal: It is a unary operator whose operand /// is the positive numeric literal. Instead, you must use a unaryOperator() /// matcher to match the minus sign: /// /// unaryOperator(hasOperatorName("-"), /// hasUnaryOperand(integerLiteral(equals(13)))) /// /// Usable as: Matcher<CharacterLiteral>, Matcher<CXXBoolLiteralExpr>, /// Matcher<FloatingLiteral>, Matcher<IntegerLiteral> template <typename ValueT> internal::PolymorphicMatcher<internal::ValueEqualsMatcher, void(internal::AllNodeBaseTypes), ValueT> equals(const ValueT &Value) { return internal::PolymorphicMatcher<internal::ValueEqualsMatcher, void(internal::AllNodeBaseTypes), ValueT>( Value); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, IntegerLiteral), bool, Value, 0) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, IntegerLiteral), unsigned, Value, 1) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } AST_POLYMORPHIC_MATCHER_P_OVERLOAD(equals, AST_POLYMORPHIC_SUPPORTED_TYPES(CharacterLiteral, CXXBoolLiteralExpr, FloatingLiteral, IntegerLiteral), double, Value, 2) { return internal::ValueEqualsMatcher<NodeType, ParamT>(Value) .matchesNode(Node); } /// Matches the operator Name of operator expressions (binary or /// unary). /// /// Example matches a || b (matcher = binaryOperator(hasOperatorName("||"))) /// \code /// !(a || b) /// \endcode AST_POLYMORPHIC_MATCHER_P( hasOperatorName, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, UnaryOperator), std::string, Name) { if (Optional<StringRef> OpName = internal::getOpName(Node)) return *OpName == Name; return false; } /// Matches operator expressions (binary or unary) that have any of the /// specified names. /// /// hasAnyOperatorName("+", "-") /// Is equivalent to /// anyOf(hasOperatorName("+"), hasOperatorName("-")) extern const internal::VariadicFunction< internal::PolymorphicMatcher<internal::HasAnyOperatorNameMatcher, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, UnaryOperator), std::vector<std::string>>, StringRef, internal::hasAnyOperatorNameFunc> hasAnyOperatorName; /// Matches all kinds of assignment operators. /// /// Example 1: matches a += b (matcher = binaryOperator(isAssignmentOperator())) /// \code /// if (a == b) /// a += b; /// \endcode /// /// Example 2: matches s1 = s2 /// (matcher = cxxOperatorCallExpr(isAssignmentOperator())) /// \code /// struct S { S& operator=(const S&); }; /// void x() { S s1, s2; s1 = s2; } /// \endcode AST_POLYMORPHIC_MATCHER( isAssignmentOperator, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator)) { return Node.isAssignmentOp(); } /// Matches comparison operators. /// /// Example 1: matches a == b (matcher = binaryOperator(isComparisonOperator())) /// \code /// if (a == b) /// a += b; /// \endcode /// /// Example 2: matches s1 < s2 /// (matcher = cxxOperatorCallExpr(isComparisonOperator())) /// \code /// struct S { bool operator<(const S& other); }; /// void x(S s1, S s2) { bool b1 = s1 < s2; } /// \endcode AST_POLYMORPHIC_MATCHER( isComparisonOperator, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator)) { return Node.isComparisonOp(); } /// Matches the left hand side of binary operator expressions. /// /// Example matches a (matcher = binaryOperator(hasLHS())) /// \code /// a || b /// \endcode AST_POLYMORPHIC_MATCHER_P(hasLHS, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, ArraySubscriptExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *LeftHandSide = internal::getLHS(Node); return (LeftHandSide != nullptr && InnerMatcher.matches(*LeftHandSide, Finder, Builder)); } /// Matches the right hand side of binary operator expressions. /// /// Example matches b (matcher = binaryOperator(hasRHS())) /// \code /// a || b /// \endcode AST_POLYMORPHIC_MATCHER_P(hasRHS, AST_POLYMORPHIC_SUPPORTED_TYPES( BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator, ArraySubscriptExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *RightHandSide = internal::getRHS(Node); return (RightHandSide != nullptr && InnerMatcher.matches(*RightHandSide, Finder, Builder)); } /// Matches if either the left hand side or the right hand side of a /// binary operator matches. AST_POLYMORPHIC_MATCHER_P( hasEitherOperand, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator), internal::Matcher<Expr>, InnerMatcher) { return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()( anyOf(hasLHS(InnerMatcher), hasRHS(InnerMatcher))) .matches(Node, Finder, Builder); } /// Matches if both matchers match with opposite sides of the binary operator. /// /// Example matcher = binaryOperator(hasOperands(integerLiteral(equals(1), /// integerLiteral(equals(2))) /// \code /// 1 + 2 // Match /// 2 + 1 // Match /// 1 + 1 // No match /// 2 + 2 // No match /// \endcode AST_POLYMORPHIC_MATCHER_P2( hasOperands, AST_POLYMORPHIC_SUPPORTED_TYPES(BinaryOperator, CXXOperatorCallExpr, CXXRewrittenBinaryOperator), internal::Matcher<Expr>, Matcher1, internal::Matcher<Expr>, Matcher2) { return internal::VariadicDynCastAllOfMatcher<Stmt, NodeType>()( anyOf(allOf(hasLHS(Matcher1), hasRHS(Matcher2)), allOf(hasLHS(Matcher2), hasRHS(Matcher1)))) .matches(Node, Finder, Builder); } /// Matches if the operand of a unary operator matches. /// /// Example matches true (matcher = hasUnaryOperand( /// cxxBoolLiteral(equals(true)))) /// \code /// !true /// \endcode AST_POLYMORPHIC_MATCHER_P(hasUnaryOperand, AST_POLYMORPHIC_SUPPORTED_TYPES(UnaryOperator, CXXOperatorCallExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *const Operand = internal::getSubExpr(Node); return (Operand != nullptr && InnerMatcher.matches(*Operand, Finder, Builder)); } /// Matches if the cast's source expression /// or opaque value's source expression matches the given matcher. /// /// Example 1: matches "a string" /// (matcher = castExpr(hasSourceExpression(cxxConstructExpr()))) /// \code /// class URL { URL(string); }; /// URL url = "a string"; /// \endcode /// /// Example 2: matches 'b' (matcher = /// opaqueValueExpr(hasSourceExpression(implicitCastExpr(declRefExpr()))) /// \code /// int a = b ?: 1; /// \endcode AST_POLYMORPHIC_MATCHER_P(hasSourceExpression, AST_POLYMORPHIC_SUPPORTED_TYPES(CastExpr, OpaqueValueExpr), internal::Matcher<Expr>, InnerMatcher) { const Expr *const SubExpression = internal::GetSourceExpressionMatcher<NodeType>::get(Node); return (SubExpression != nullptr && InnerMatcher.matches(*SubExpression, Finder, Builder)); } /// Matches casts that has a given cast kind. /// /// Example: matches the implicit cast around \c 0 /// (matcher = castExpr(hasCastKind(CK_NullToPointer))) /// \code /// int *p = 0; /// \endcode /// /// If the matcher is use from clang-query, CastKind parameter /// should be passed as a quoted string. e.g., hasCastKind("CK_NullToPointer"). AST_MATCHER_P(CastExpr, hasCastKind, CastKind, Kind) { return Node.getCastKind() == Kind; } /// Matches casts whose destination type matches a given matcher. /// /// (Note: Clang's AST refers to other conversions as "casts" too, and calls /// actual casts "explicit" casts.) AST_MATCHER_P(ExplicitCastExpr, hasDestinationType, internal::Matcher<QualType>, InnerMatcher) { const QualType NodeType = Node.getTypeAsWritten(); return InnerMatcher.matches(NodeType, Finder, Builder); } /// Matches implicit casts whose destination type matches a given /// matcher. /// /// FIXME: Unit test this matcher AST_MATCHER_P(ImplicitCastExpr, hasImplicitDestinationType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getType(), Finder, Builder); } /// Matches TagDecl object that are spelled with "struct." /// /// Example matches S, but not C, U or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isStruct) { return Node.isStruct(); } /// Matches TagDecl object that are spelled with "union." /// /// Example matches U, but not C, S or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isUnion) { return Node.isUnion(); } /// Matches TagDecl object that are spelled with "class." /// /// Example matches C, but not S, U or E. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isClass) { return Node.isClass(); } /// Matches TagDecl object that are spelled with "enum." /// /// Example matches E, but not C, S or U. /// \code /// struct S {}; /// class C {}; /// union U {}; /// enum E {}; /// \endcode AST_MATCHER(TagDecl, isEnum) { return Node.isEnum(); } /// Matches the true branch expression of a conditional operator. /// /// Example 1 (conditional ternary operator): matches a /// \code /// condition ? a : b /// \endcode /// /// Example 2 (conditional binary operator): matches opaqueValueExpr(condition) /// \code /// condition ?: b /// \endcode AST_MATCHER_P(AbstractConditionalOperator, hasTrueExpression, internal::Matcher<Expr>, InnerMatcher) { const Expr *Expression = Node.getTrueExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// Matches the false branch expression of a conditional operator /// (binary or ternary). /// /// Example matches b /// \code /// condition ? a : b /// condition ?: b /// \endcode AST_MATCHER_P(AbstractConditionalOperator, hasFalseExpression, internal::Matcher<Expr>, InnerMatcher) { const Expr *Expression = Node.getFalseExpr(); return (Expression != nullptr && InnerMatcher.matches(*Expression, Finder, Builder)); } /// Matches if a declaration has a body attached. /// /// Example matches A, va, fa /// \code /// class A {}; /// class B; // Doesn't match, as it has no body. /// int va; /// extern int vb; // Doesn't match, as it doesn't define the variable. /// void fa() {} /// void fb(); // Doesn't match, as it has no body. /// @interface X /// - (void)ma; // Doesn't match, interface is declaration. /// @end /// @implementation X /// - (void)ma {} /// @end /// \endcode /// /// Usable as: Matcher<TagDecl>, Matcher<VarDecl>, Matcher<FunctionDecl>, /// Matcher<ObjCMethodDecl> AST_POLYMORPHIC_MATCHER(isDefinition, AST_POLYMORPHIC_SUPPORTED_TYPES(TagDecl, VarDecl, ObjCMethodDecl, FunctionDecl)) { return Node.isThisDeclarationADefinition(); } /// Matches if a function declaration is variadic. /// /// Example matches f, but not g or h. The function i will not match, even when /// compiled in C mode. /// \code /// void f(...); /// void g(int); /// template <typename... Ts> void h(Ts...); /// void i(); /// \endcode AST_MATCHER(FunctionDecl, isVariadic) { return Node.isVariadic(); } /// Matches the class declaration that the given method declaration /// belongs to. /// /// FIXME: Generalize this for other kinds of declarations. /// FIXME: What other kind of declarations would we need to generalize /// this to? /// /// Example matches A() in the last line /// (matcher = cxxConstructExpr(hasDeclaration(cxxMethodDecl( /// ofClass(hasName("A")))))) /// \code /// class A { /// public: /// A(); /// }; /// A a = A(); /// \endcode AST_MATCHER_P(CXXMethodDecl, ofClass, internal::Matcher<CXXRecordDecl>, InnerMatcher) { ASTChildrenNotSpelledInSourceScope RAII(Finder, false); const CXXRecordDecl *Parent = Node.getParent(); return (Parent != nullptr && InnerMatcher.matches(*Parent, Finder, Builder)); } /// Matches each method overridden by the given method. This matcher may /// produce multiple matches. /// /// Given /// \code /// class A { virtual void f(); }; /// class B : public A { void f(); }; /// class C : public B { void f(); }; /// \endcode /// cxxMethodDecl(ofClass(hasName("C")), /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") /// matches once, with "b" binding "A::f" and "d" binding "C::f" (Note /// that B::f is not overridden by C::f). /// /// The check can produce multiple matches in case of multiple inheritance, e.g. /// \code /// class A1 { virtual void f(); }; /// class A2 { virtual void f(); }; /// class C : public A1, public A2 { void f(); }; /// \endcode /// cxxMethodDecl(ofClass(hasName("C")), /// forEachOverridden(cxxMethodDecl().bind("b"))).bind("d") /// matches twice, once with "b" binding "A1::f" and "d" binding "C::f", and /// once with "b" binding "A2::f" and "d" binding "C::f". AST_MATCHER_P(CXXMethodDecl, forEachOverridden, internal::Matcher<CXXMethodDecl>, InnerMatcher) { BoundNodesTreeBuilder Result; bool Matched = false; for (const auto *Overridden : Node.overridden_methods()) { BoundNodesTreeBuilder OverriddenBuilder(*Builder); const bool OverriddenMatched = InnerMatcher.matches(*Overridden, Finder, &OverriddenBuilder); if (OverriddenMatched) { Matched = true; Result.addMatch(OverriddenBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches declarations of virtual methods and C++ base specifers that specify /// virtual inheritance. /// /// Example: /// \code /// class A { /// public: /// virtual void x(); // matches x /// }; /// \endcode /// /// Example: /// \code /// class Base {}; /// class DirectlyDerived : virtual Base {}; // matches Base /// class IndirectlyDerived : DirectlyDerived, Base {}; // matches Base /// \endcode /// /// Usable as: Matcher<CXXMethodDecl>, Matcher<CXXBaseSpecifier> AST_POLYMORPHIC_MATCHER(isVirtual, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXMethodDecl, CXXBaseSpecifier)) { return Node.isVirtual(); } /// Matches if the given method declaration has an explicit "virtual". /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// class B : public A { /// public: /// void x(); /// }; /// \endcode /// matches A::x but not B::x AST_MATCHER(CXXMethodDecl, isVirtualAsWritten) { return Node.isVirtualAsWritten(); } /// Matches if the given method or class declaration is final. /// /// Given: /// \code /// class A final {}; /// /// struct B { /// virtual void f(); /// }; /// /// struct C : B { /// void f() final; /// }; /// \endcode /// matches A and C::f, but not B, C, or B::f AST_POLYMORPHIC_MATCHER(isFinal, AST_POLYMORPHIC_SUPPORTED_TYPES(CXXRecordDecl, CXXMethodDecl)) { return Node.template hasAttr<FinalAttr>(); } /// Matches if the given method declaration is pure. /// /// Given /// \code /// class A { /// public: /// virtual void x() = 0; /// }; /// \endcode /// matches A::x AST_MATCHER(CXXMethodDecl, isPure) { return Node.isPure(); } /// Matches if the given method declaration is const. /// /// Given /// \code /// struct A { /// void foo() const; /// void bar(); /// }; /// \endcode /// /// cxxMethodDecl(isConst()) matches A::foo() but not A::bar() AST_MATCHER(CXXMethodDecl, isConst) { return Node.isConst(); } /// Matches if the given method declaration declares a copy assignment /// operator. /// /// Given /// \code /// struct A { /// A &operator=(const A &); /// A &operator=(A &&); /// }; /// \endcode /// /// cxxMethodDecl(isCopyAssignmentOperator()) matches the first method but not /// the second one. AST_MATCHER(CXXMethodDecl, isCopyAssignmentOperator) { return Node.isCopyAssignmentOperator(); } /// Matches if the given method declaration declares a move assignment /// operator. /// /// Given /// \code /// struct A { /// A &operator=(const A &); /// A &operator=(A &&); /// }; /// \endcode /// /// cxxMethodDecl(isMoveAssignmentOperator()) matches the second method but not /// the first one. AST_MATCHER(CXXMethodDecl, isMoveAssignmentOperator) { return Node.isMoveAssignmentOperator(); } /// Matches if the given method declaration overrides another method. /// /// Given /// \code /// class A { /// public: /// virtual void x(); /// }; /// class B : public A { /// public: /// virtual void x(); /// }; /// \endcode /// matches B::x AST_MATCHER(CXXMethodDecl, isOverride) { return Node.size_overridden_methods() > 0 || Node.hasAttr<OverrideAttr>(); } /// Matches method declarations that are user-provided. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &) = default; // #2 /// S(S &&) = delete; // #3 /// }; /// \endcode /// cxxConstructorDecl(isUserProvided()) will match #1, but not #2 or #3. AST_MATCHER(CXXMethodDecl, isUserProvided) { return Node.isUserProvided(); } /// Matches member expressions that are called with '->' as opposed /// to '.'. /// /// Member calls on the implicit this pointer match as called with '->'. /// /// Given /// \code /// class Y { /// void x() { this->x(); x(); Y y; y.x(); a; this->b; Y::b; } /// template <class T> void f() { this->f<T>(); f<T>(); } /// int a; /// static int b; /// }; /// template <class T> /// class Z { /// void x() { this->m; } /// }; /// \endcode /// memberExpr(isArrow()) /// matches this->x, x, y.x, a, this->b /// cxxDependentScopeMemberExpr(isArrow()) /// matches this->m /// unresolvedMemberExpr(isArrow()) /// matches this->f<T>, f<T> AST_POLYMORPHIC_MATCHER( isArrow, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr, CXXDependentScopeMemberExpr)) { return Node.isArrow(); } /// Matches QualType nodes that are of integer type. /// /// Given /// \code /// void a(int); /// void b(long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isInteger()))) /// matches "a(int)", "b(long)", but not "c(double)". AST_MATCHER(QualType, isInteger) { return Node->isIntegerType(); } /// Matches QualType nodes that are of unsigned integer type. /// /// Given /// \code /// void a(int); /// void b(unsigned long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isUnsignedInteger()))) /// matches "b(unsigned long)", but not "a(int)" and "c(double)". AST_MATCHER(QualType, isUnsignedInteger) { return Node->isUnsignedIntegerType(); } /// Matches QualType nodes that are of signed integer type. /// /// Given /// \code /// void a(int); /// void b(unsigned long); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isSignedInteger()))) /// matches "a(int)", but not "b(unsigned long)" and "c(double)". AST_MATCHER(QualType, isSignedInteger) { return Node->isSignedIntegerType(); } /// Matches QualType nodes that are of character type. /// /// Given /// \code /// void a(char); /// void b(wchar_t); /// void c(double); /// \endcode /// functionDecl(hasAnyParameter(hasType(isAnyCharacter()))) /// matches "a(char)", "b(wchar_t)", but not "c(double)". AST_MATCHER(QualType, isAnyCharacter) { return Node->isAnyCharacterType(); } /// Matches QualType nodes that are of any pointer type; this includes /// the Objective-C object pointer type, which is different despite being /// syntactically similar. /// /// Given /// \code /// int *i = nullptr; /// /// @interface Foo /// @end /// Foo *f; /// /// int j; /// \endcode /// varDecl(hasType(isAnyPointer())) /// matches "int *i" and "Foo *f", but not "int j". AST_MATCHER(QualType, isAnyPointer) { return Node->isAnyPointerType(); } /// Matches QualType nodes that are const-qualified, i.e., that /// include "top-level" const. /// /// Given /// \code /// void a(int); /// void b(int const); /// void c(const int); /// void d(const int*); /// void e(int const) {}; /// \endcode /// functionDecl(hasAnyParameter(hasType(isConstQualified()))) /// matches "void b(int const)", "void c(const int)" and /// "void e(int const) {}". It does not match d as there /// is no top-level const on the parameter type "const int *". AST_MATCHER(QualType, isConstQualified) { return Node.isConstQualified(); } /// Matches QualType nodes that are volatile-qualified, i.e., that /// include "top-level" volatile. /// /// Given /// \code /// void a(int); /// void b(int volatile); /// void c(volatile int); /// void d(volatile int*); /// void e(int volatile) {}; /// \endcode /// functionDecl(hasAnyParameter(hasType(isVolatileQualified()))) /// matches "void b(int volatile)", "void c(volatile int)" and /// "void e(int volatile) {}". It does not match d as there /// is no top-level volatile on the parameter type "volatile int *". AST_MATCHER(QualType, isVolatileQualified) { return Node.isVolatileQualified(); } /// Matches QualType nodes that have local CV-qualifiers attached to /// the node, not hidden within a typedef. /// /// Given /// \code /// typedef const int const_int; /// const_int i; /// int *const j; /// int *volatile k; /// int m; /// \endcode /// \c varDecl(hasType(hasLocalQualifiers())) matches only \c j and \c k. /// \c i is const-qualified but the qualifier is not local. AST_MATCHER(QualType, hasLocalQualifiers) { return Node.hasLocalQualifiers(); } /// Matches a member expression where the member is matched by a /// given matcher. /// /// Given /// \code /// struct { int first, second; } first, second; /// int i(second.first); /// int j(first.second); /// \endcode /// memberExpr(member(hasName("first"))) /// matches second.first /// but not first.second (because the member name there is "second"). AST_MATCHER_P(MemberExpr, member, internal::Matcher<ValueDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getMemberDecl(), Finder, Builder); } /// Matches a member expression where the object expression is matched by a /// given matcher. Implicit object expressions are included; that is, it matches /// use of implicit `this`. /// /// Given /// \code /// struct X { /// int m; /// int f(X x) { x.m; return m; } /// }; /// \endcode /// memberExpr(hasObjectExpression(hasType(cxxRecordDecl(hasName("X"))))) /// matches `x.m`, but not `m`; however, /// memberExpr(hasObjectExpression(hasType(pointsTo( // cxxRecordDecl(hasName("X")))))) /// matches `m` (aka. `this->m`), but not `x.m`. AST_POLYMORPHIC_MATCHER_P( hasObjectExpression, AST_POLYMORPHIC_SUPPORTED_TYPES(MemberExpr, UnresolvedMemberExpr, CXXDependentScopeMemberExpr), internal::Matcher<Expr>, InnerMatcher) { if (const auto *E = dyn_cast<UnresolvedMemberExpr>(&Node)) if (E->isImplicitAccess()) return false; if (const auto *E = dyn_cast<CXXDependentScopeMemberExpr>(&Node)) if (E->isImplicitAccess()) return false; return InnerMatcher.matches(*Node.getBase(), Finder, Builder); } /// Matches any using shadow declaration. /// /// Given /// \code /// namespace X { void b(); } /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasName("b")))) /// matches \code using X::b \endcode AST_MATCHER_P(UsingDecl, hasAnyUsingShadowDecl, internal::Matcher<UsingShadowDecl>, InnerMatcher) { return matchesFirstInPointerRange(InnerMatcher, Node.shadow_begin(), Node.shadow_end(), Finder, Builder) != Node.shadow_end(); } /// Matches a using shadow declaration where the target declaration is /// matched by the given matcher. /// /// Given /// \code /// namespace X { int a; void b(); } /// using X::a; /// using X::b; /// \endcode /// usingDecl(hasAnyUsingShadowDecl(hasTargetDecl(functionDecl()))) /// matches \code using X::b \endcode /// but not \code using X::a \endcode AST_MATCHER_P(UsingShadowDecl, hasTargetDecl, internal::Matcher<NamedDecl>, InnerMatcher) { return InnerMatcher.matches(*Node.getTargetDecl(), Finder, Builder); } /// Matches template instantiations of function, class, or static /// member variable template instantiations. /// /// Given /// \code /// template <typename T> class X {}; class A {}; X<A> x; /// \endcode /// or /// \code /// template <typename T> class X {}; class A {}; template class X<A>; /// \endcode /// or /// \code /// template <typename T> class X {}; class A {}; extern template class X<A>; /// \endcode /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) /// matches the template instantiation of X<A>. /// /// But given /// \code /// template <typename T> class X {}; class A {}; /// template <> class X<A> {}; X<A> x; /// \endcode /// cxxRecordDecl(hasName("::X"), isTemplateInstantiation()) /// does not match, as X<A> is an explicit template specialization. /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isTemplateInstantiation, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ImplicitInstantiation || Node.getTemplateSpecializationKind() == TSK_ExplicitInstantiationDefinition || Node.getTemplateSpecializationKind() == TSK_ExplicitInstantiationDeclaration); } /// Matches declarations that are template instantiations or are inside /// template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { T i; } /// A(0); /// A(0U); /// \endcode /// functionDecl(isInstantiated()) /// matches 'A(int) {...};' and 'A(unsigned) {...}'. AST_MATCHER_FUNCTION(internal::Matcher<Decl>, isInstantiated) { auto IsInstantiation = decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))); return decl(anyOf(IsInstantiation, hasAncestor(IsInstantiation))); } /// Matches statements inside of a template instantiation. /// /// Given /// \code /// int j; /// template<typename T> void A(T t) { T i; j += 42;} /// A(0); /// A(0U); /// \endcode /// declStmt(isInTemplateInstantiation()) /// matches 'int i;' and 'unsigned i'. /// unless(stmt(isInTemplateInstantiation())) /// will NOT match j += 42; as it's shared between the template definition and /// instantiation. AST_MATCHER_FUNCTION(internal::Matcher<Stmt>, isInTemplateInstantiation) { return stmt( hasAncestor(decl(anyOf(cxxRecordDecl(isTemplateInstantiation()), functionDecl(isTemplateInstantiation()))))); } /// Matches explicit template specializations of function, class, or /// static member variable template instantiations. /// /// Given /// \code /// template<typename T> void A(T t) { } /// template<> void A(int N) { } /// \endcode /// functionDecl(isExplicitTemplateSpecialization()) /// matches the specialization A<int>(). /// /// Usable as: Matcher<FunctionDecl>, Matcher<VarDecl>, Matcher<CXXRecordDecl> AST_POLYMORPHIC_MATCHER(isExplicitTemplateSpecialization, AST_POLYMORPHIC_SUPPORTED_TYPES(FunctionDecl, VarDecl, CXXRecordDecl)) { return (Node.getTemplateSpecializationKind() == TSK_ExplicitSpecialization); } /// Matches \c TypeLocs for which the given inner /// QualType-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD(internal::BindableMatcher<TypeLoc>, loc, internal::Matcher<QualType>, InnerMatcher, 0) { return internal::BindableMatcher<TypeLoc>( new internal::TypeLocTypeMatcher(InnerMatcher)); } /// Matches type \c bool. /// /// Given /// \code /// struct S { bool func(); }; /// \endcode /// functionDecl(returns(booleanType())) /// matches "bool func();" AST_MATCHER(Type, booleanType) { return Node.isBooleanType(); } /// Matches type \c void. /// /// Given /// \code /// struct S { void func(); }; /// \endcode /// functionDecl(returns(voidType())) /// matches "void func();" AST_MATCHER(Type, voidType) { return Node.isVoidType(); } template <typename NodeType> using AstTypeMatcher = internal::VariadicDynCastAllOfMatcher<Type, NodeType>; /// Matches builtin Types. /// /// Given /// \code /// struct A {}; /// A a; /// int b; /// float c; /// bool d; /// \endcode /// builtinType() /// matches "int b", "float c" and "bool d" extern const AstTypeMatcher<BuiltinType> builtinType; /// Matches all kinds of arrays. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[4]; /// void f() { int c[a[0]]; } /// \endcode /// arrayType() /// matches "int a[]", "int b[4]" and "int c[a[0]]"; extern const AstTypeMatcher<ArrayType> arrayType; /// Matches C99 complex types. /// /// Given /// \code /// _Complex float f; /// \endcode /// complexType() /// matches "_Complex float f" extern const AstTypeMatcher<ComplexType> complexType; /// Matches any real floating-point type (float, double, long double). /// /// Given /// \code /// int i; /// float f; /// \endcode /// realFloatingPointType() /// matches "float f" but not "int i" AST_MATCHER(Type, realFloatingPointType) { return Node.isRealFloatingType(); } /// Matches arrays and C99 complex types that have a specific element /// type. /// /// Given /// \code /// struct A {}; /// A a[7]; /// int b[7]; /// \endcode /// arrayType(hasElementType(builtinType())) /// matches "int b[7]" /// /// Usable as: Matcher<ArrayType>, Matcher<ComplexType> AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasElementType, getElement, AST_POLYMORPHIC_SUPPORTED_TYPES(ArrayType, ComplexType)); /// Matches C arrays with a specified constant size. /// /// Given /// \code /// void() { /// int a[2]; /// int b[] = { 2, 3 }; /// int c[b[0]]; /// } /// \endcode /// constantArrayType() /// matches "int a[2]" extern const AstTypeMatcher<ConstantArrayType> constantArrayType; /// Matches nodes that have the specified size. /// /// Given /// \code /// int a[42]; /// int b[2 * 21]; /// int c[41], d[43]; /// char *s = "abcd"; /// wchar_t *ws = L"abcd"; /// char *w = "a"; /// \endcode /// constantArrayType(hasSize(42)) /// matches "int a[42]" and "int b[2 * 21]" /// stringLiteral(hasSize(4)) /// matches "abcd", L"abcd" AST_POLYMORPHIC_MATCHER_P(hasSize, AST_POLYMORPHIC_SUPPORTED_TYPES(ConstantArrayType, StringLiteral), unsigned, N) { return internal::HasSizeMatcher<NodeType>::hasSize(Node, N); } /// Matches C++ arrays whose size is a value-dependent expression. /// /// Given /// \code /// template<typename T, int Size> /// class array { /// T data[Size]; /// }; /// \endcode /// dependentSizedArrayType /// matches "T data[Size]" extern const AstTypeMatcher<DependentSizedArrayType> dependentSizedArrayType; /// Matches C arrays with unspecified size. /// /// Given /// \code /// int a[] = { 2, 3 }; /// int b[42]; /// void f(int c[]) { int d[a[0]]; }; /// \endcode /// incompleteArrayType() /// matches "int a[]" and "int c[]" extern const AstTypeMatcher<IncompleteArrayType> incompleteArrayType; /// Matches C arrays with a specified size that is not an /// integer-constant-expression. /// /// Given /// \code /// void f() { /// int a[] = { 2, 3 } /// int b[42]; /// int c[a[0]]; /// } /// \endcode /// variableArrayType() /// matches "int c[a[0]]" extern const AstTypeMatcher<VariableArrayType> variableArrayType; /// Matches \c VariableArrayType nodes that have a specific size /// expression. /// /// Given /// \code /// void f(int b) { /// int a[b]; /// } /// \endcode /// variableArrayType(hasSizeExpr(ignoringImpCasts(declRefExpr(to( /// varDecl(hasName("b"))))))) /// matches "int a[b]" AST_MATCHER_P(VariableArrayType, hasSizeExpr, internal::Matcher<Expr>, InnerMatcher) { return InnerMatcher.matches(*Node.getSizeExpr(), Finder, Builder); } /// Matches atomic types. /// /// Given /// \code /// _Atomic(int) i; /// \endcode /// atomicType() /// matches "_Atomic(int) i" extern const AstTypeMatcher<AtomicType> atomicType; /// Matches atomic types with a specific value type. /// /// Given /// \code /// _Atomic(int) i; /// _Atomic(float) f; /// \endcode /// atomicType(hasValueType(isInteger())) /// matches "_Atomic(int) i" /// /// Usable as: Matcher<AtomicType> AST_TYPELOC_TRAVERSE_MATCHER_DECL(hasValueType, getValue, AST_POLYMORPHIC_SUPPORTED_TYPES(AtomicType)); /// Matches types nodes representing C++11 auto types. /// /// Given: /// \code /// auto n = 4; /// int v[] = { 2, 3 } /// for (auto i : v) { } /// \endcode /// autoType() /// matches "auto n" and "auto i" extern const AstTypeMatcher<AutoType> autoType; /// Matches types nodes representing C++11 decltype(<expr>) types. /// /// Given: /// \code /// short i = 1; /// int j = 42; /// decltype(i + j) result = i + j; /// \endcode /// decltypeType() /// matches "decltype(i + j)" extern const AstTypeMatcher<DecltypeType> decltypeType; /// Matches \c AutoType nodes where the deduced type is a specific type. /// /// Note: There is no \c TypeLoc for the deduced type and thus no /// \c getDeducedLoc() matcher. /// /// Given /// \code /// auto a = 1; /// auto b = 2.0; /// \endcode /// autoType(hasDeducedType(isInteger())) /// matches "auto a" /// /// Usable as: Matcher<AutoType> AST_TYPE_TRAVERSE_MATCHER(hasDeducedType, getDeducedType, AST_POLYMORPHIC_SUPPORTED_TYPES(AutoType)); /// Matches \c DecltypeType nodes to find out the underlying type. /// /// Given /// \code /// decltype(1) a = 1; /// decltype(2.0) b = 2.0; /// \endcode /// decltypeType(hasUnderlyingType(isInteger())) /// matches the type of "a" /// /// Usable as: Matcher<DecltypeType> AST_TYPE_TRAVERSE_MATCHER(hasUnderlyingType, getUnderlyingType, AST_POLYMORPHIC_SUPPORTED_TYPES(DecltypeType)); /// Matches \c FunctionType nodes. /// /// Given /// \code /// int (*f)(int); /// void g(); /// \endcode /// functionType() /// matches "int (*f)(int)" and the type of "g". extern const AstTypeMatcher<FunctionType> functionType; /// Matches \c FunctionProtoType nodes. /// /// Given /// \code /// int (*f)(int); /// void g(); /// \endcode /// functionProtoType() /// matches "int (*f)(int)" and the type of "g" in C++ mode. /// In C mode, "g" is not matched because it does not contain a prototype. extern const AstTypeMatcher<FunctionProtoType> functionProtoType; /// Matches \c ParenType nodes. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int *array_of_ptrs[4]; /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType()))) matches \c ptr_to_array but not /// \c array_of_ptrs. extern const AstTypeMatcher<ParenType> parenType; /// Matches \c ParenType nodes where the inner type is a specific type. /// /// Given /// \code /// int (*ptr_to_array)[4]; /// int (*ptr_to_func)(int); /// \endcode /// /// \c varDecl(hasType(pointsTo(parenType(innerType(functionType()))))) matches /// \c ptr_to_func but not \c ptr_to_array. /// /// Usable as: Matcher<ParenType> AST_TYPE_TRAVERSE_MATCHER(innerType, getInnerType, AST_POLYMORPHIC_SUPPORTED_TYPES(ParenType)); /// Matches block pointer types, i.e. types syntactically represented as /// "void (^)(int)". /// /// The \c pointee is always required to be a \c FunctionType. extern const AstTypeMatcher<BlockPointerType> blockPointerType; /// Matches member pointer types. /// Given /// \code /// struct A { int i; } /// A::* ptr = A::i; /// \endcode /// memberPointerType() /// matches "A::* ptr" extern const AstTypeMatcher<MemberPointerType> memberPointerType; /// Matches pointer types, but does not match Objective-C object pointer /// types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int c = 5; /// /// @interface Foo /// @end /// Foo *f; /// \endcode /// pointerType() /// matches "int *a", but does not match "Foo *f". extern const AstTypeMatcher<PointerType> pointerType; /// Matches an Objective-C object pointer type, which is different from /// a pointer type, despite being syntactically similar. /// /// Given /// \code /// int *a; /// /// @interface Foo /// @end /// Foo *f; /// \endcode /// pointerType() /// matches "Foo *f", but does not match "int *a". extern const AstTypeMatcher<ObjCObjectPointerType> objcObjectPointerType; /// Matches both lvalue and rvalue reference types. /// /// Given /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c referenceType() matches the types of \c b, \c c, \c d, \c e, and \c f. extern const AstTypeMatcher<ReferenceType> referenceType; /// Matches lvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c lValueReferenceType() matches the types of \c b, \c d, and \c e. \c e is /// matched since the type is deduced as int& by reference collapsing rules. extern const AstTypeMatcher<LValueReferenceType> lValueReferenceType; /// Matches rvalue reference types. /// /// Given: /// \code /// int *a; /// int &b = *a; /// int &&c = 1; /// auto &d = b; /// auto &&e = c; /// auto &&f = 2; /// int g = 5; /// \endcode /// /// \c rValueReferenceType() matches the types of \c c and \c f. \c e is not /// matched as it is deduced to int& by reference collapsing rules. extern const AstTypeMatcher<RValueReferenceType> rValueReferenceType; /// Narrows PointerType (and similar) matchers to those where the /// \c pointee matches a given matcher. /// /// Given /// \code /// int *a; /// int const *b; /// float const *f; /// \endcode /// pointerType(pointee(isConstQualified(), isInteger())) /// matches "int const *b" /// /// Usable as: Matcher<BlockPointerType>, Matcher<MemberPointerType>, /// Matcher<PointerType>, Matcher<ReferenceType> AST_TYPELOC_TRAVERSE_MATCHER_DECL( pointee, getPointee, AST_POLYMORPHIC_SUPPORTED_TYPES(BlockPointerType, MemberPointerType, PointerType, ReferenceType)); /// Matches typedef types. /// /// Given /// \code /// typedef int X; /// \endcode /// typedefType() /// matches "typedef int X" extern const AstTypeMatcher<TypedefType> typedefType; /// Matches enum types. /// /// Given /// \code /// enum C { Green }; /// enum class S { Red }; /// /// C c; /// S s; /// \endcode // /// \c enumType() matches the type of the variable declarations of both \c c and /// \c s. extern const AstTypeMatcher<EnumType> enumType; /// Matches template specialization types. /// /// Given /// \code /// template <typename T> /// class C { }; /// /// template class C<int>; // A /// C<char> var; // B /// \endcode /// /// \c templateSpecializationType() matches the type of the explicit /// instantiation in \c A and the type of the variable declaration in \c B. extern const AstTypeMatcher<TemplateSpecializationType> templateSpecializationType; /// Matches C++17 deduced template specialization types, e.g. deduced class /// template types. /// /// Given /// \code /// template <typename T> /// class C { public: C(T); }; /// /// C c(123); /// \endcode /// \c deducedTemplateSpecializationType() matches the type in the declaration /// of the variable \c c. extern const AstTypeMatcher<DeducedTemplateSpecializationType> deducedTemplateSpecializationType; /// Matches types nodes representing unary type transformations. /// /// Given: /// \code /// typedef __underlying_type(T) type; /// \endcode /// unaryTransformType() /// matches "__underlying_type(T)" extern const AstTypeMatcher<UnaryTransformType> unaryTransformType; /// Matches record types (e.g. structs, classes). /// /// Given /// \code /// class C {}; /// struct S {}; /// /// C c; /// S s; /// \endcode /// /// \c recordType() matches the type of the variable declarations of both \c c /// and \c s. extern const AstTypeMatcher<RecordType> recordType; /// Matches tag types (record and enum types). /// /// Given /// \code /// enum E {}; /// class C {}; /// /// E e; /// C c; /// \endcode /// /// \c tagType() matches the type of the variable declarations of both \c e /// and \c c. extern const AstTypeMatcher<TagType> tagType; /// Matches types specified with an elaborated type keyword or with a /// qualified name. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// class C {}; /// /// class C c; /// N::M::D d; /// \endcode /// /// \c elaboratedType() matches the type of the variable declarations of both /// \c c and \c d. extern const AstTypeMatcher<ElaboratedType> elaboratedType; /// Matches ElaboratedTypes whose qualifier, a NestedNameSpecifier, /// matches \c InnerMatcher if the qualifier exists. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \endcode /// /// \c elaboratedType(hasQualifier(hasPrefix(specifiesNamespace(hasName("N")))) /// matches the type of the variable declaration of \c d. AST_MATCHER_P(ElaboratedType, hasQualifier, internal::Matcher<NestedNameSpecifier>, InnerMatcher) { if (const NestedNameSpecifier *Qualifier = Node.getQualifier()) return InnerMatcher.matches(*Qualifier, Finder, Builder); return false; } /// Matches ElaboratedTypes whose named type matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// N::M::D d; /// \endcode /// /// \c elaboratedType(namesType(recordType( /// hasDeclaration(namedDecl(hasName("D")))))) matches the type of the variable /// declaration of \c d. AST_MATCHER_P(ElaboratedType, namesType, internal::Matcher<QualType>, InnerMatcher) { return InnerMatcher.matches(Node.getNamedType(), Finder, Builder); } /// Matches types that represent the result of substituting a type for a /// template type parameter. /// /// Given /// \code /// template <typename T> /// void F(T t) { /// int i = 1 + t; /// } /// \endcode /// /// \c substTemplateTypeParmType() matches the type of 't' but not '1' extern const AstTypeMatcher<SubstTemplateTypeParmType> substTemplateTypeParmType; /// Matches template type parameter substitutions that have a replacement /// type that matches the provided matcher. /// /// Given /// \code /// template <typename T> /// double F(T t); /// int i; /// double j = F(i); /// \endcode /// /// \c substTemplateTypeParmType(hasReplacementType(type())) matches int AST_TYPE_TRAVERSE_MATCHER( hasReplacementType, getReplacementType, AST_POLYMORPHIC_SUPPORTED_TYPES(SubstTemplateTypeParmType)); /// Matches template type parameter types. /// /// Example matches T, but not int. /// (matcher = templateTypeParmType()) /// \code /// template <typename T> void f(int i); /// \endcode extern const AstTypeMatcher<TemplateTypeParmType> templateTypeParmType; /// Matches injected class name types. /// /// Example matches S s, but not S<T> s. /// (matcher = parmVarDecl(hasType(injectedClassNameType()))) /// \code /// template <typename T> struct S { /// void f(S s); /// void g(S<T> s); /// }; /// \endcode extern const AstTypeMatcher<InjectedClassNameType> injectedClassNameType; /// Matches decayed type /// Example matches i[] in declaration of f. /// (matcher = valueDecl(hasType(decayedType(hasDecayedType(pointerType()))))) /// Example matches i[1]. /// (matcher = expr(hasType(decayedType(hasDecayedType(pointerType()))))) /// \code /// void f(int i[]) { /// i[1] = 0; /// } /// \endcode extern const AstTypeMatcher<DecayedType> decayedType; /// Matches the decayed type, whoes decayed type matches \c InnerMatcher AST_MATCHER_P(DecayedType, hasDecayedType, internal::Matcher<QualType>, InnerType) { return InnerType.matches(Node.getDecayedType(), Finder, Builder); } /// Matches declarations whose declaration context, interpreted as a /// Decl, matches \c InnerMatcher. /// /// Given /// \code /// namespace N { /// namespace M { /// class D {}; /// } /// } /// \endcode /// /// \c cxxRcordDecl(hasDeclContext(namedDecl(hasName("M")))) matches the /// declaration of \c class \c D. AST_MATCHER_P(Decl, hasDeclContext, internal::Matcher<Decl>, InnerMatcher) { const DeclContext *DC = Node.getDeclContext(); if (!DC) return false; return InnerMatcher.matches(*Decl::castFromDeclContext(DC), Finder, Builder); } /// Matches nested name specifiers. /// /// Given /// \code /// namespace ns { /// struct A { static void f(); }; /// void A::f() {} /// void g() { A::f(); } /// } /// ns::A a; /// \endcode /// nestedNameSpecifier() /// matches "ns::" and both "A::" extern const internal::VariadicAllOfMatcher<NestedNameSpecifier> nestedNameSpecifier; /// Same as \c nestedNameSpecifier but matches \c NestedNameSpecifierLoc. extern const internal::VariadicAllOfMatcher<NestedNameSpecifierLoc> nestedNameSpecifierLoc; /// Matches \c NestedNameSpecifierLocs for which the given inner /// NestedNameSpecifier-matcher matches. AST_MATCHER_FUNCTION_P_OVERLOAD( internal::BindableMatcher<NestedNameSpecifierLoc>, loc, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 1) { return internal::BindableMatcher<NestedNameSpecifierLoc>( new internal::LocMatcher<NestedNameSpecifierLoc, NestedNameSpecifier>( InnerMatcher)); } /// Matches nested name specifiers that specify a type matching the /// given \c QualType matcher without qualifiers. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(specifiesType( /// hasDeclaration(cxxRecordDecl(hasName("A"))) /// )) /// matches "A::" AST_MATCHER_P(NestedNameSpecifier, specifiesType, internal::Matcher<QualType>, InnerMatcher) { if (!Node.getAsType()) return false; return InnerMatcher.matches(QualType(Node.getAsType(), 0), Finder, Builder); } /// Matches nested name specifier locs that specify a type matching the /// given \c TypeLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(specifiesTypeLoc(loc(type( /// hasDeclaration(cxxRecordDecl(hasName("A"))))))) /// matches "A::" AST_MATCHER_P(NestedNameSpecifierLoc, specifiesTypeLoc, internal::Matcher<TypeLoc>, InnerMatcher) { return Node && Node.getNestedNameSpecifier()->getAsType() && InnerMatcher.matches(Node.getTypeLoc(), Finder, Builder); } /// Matches on the prefix of a \c NestedNameSpecifier. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifier(hasPrefix(specifiesType(asString("struct A")))) and /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifier, hasPrefix, internal::Matcher<NestedNameSpecifier>, InnerMatcher, 0) { const NestedNameSpecifier *NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(*NextNode, Finder, Builder); } /// Matches on the prefix of a \c NestedNameSpecifierLoc. /// /// Given /// \code /// struct A { struct B { struct C {}; }; }; /// A::B::C c; /// \endcode /// nestedNameSpecifierLoc(hasPrefix(loc(specifiesType(asString("struct A"))))) /// matches "A::" AST_MATCHER_P_OVERLOAD(NestedNameSpecifierLoc, hasPrefix, internal::Matcher<NestedNameSpecifierLoc>, InnerMatcher, 1) { NestedNameSpecifierLoc NextNode = Node.getPrefix(); if (!NextNode) return false; return InnerMatcher.matches(NextNode, Finder, Builder); } /// Matches nested name specifiers that specify a namespace matching the /// given namespace matcher. /// /// Given /// \code /// namespace ns { struct A {}; } /// ns::A a; /// \endcode /// nestedNameSpecifier(specifiesNamespace(hasName("ns"))) /// matches "ns::" AST_MATCHER_P(NestedNameSpecifier, specifiesNamespace, internal::Matcher<NamespaceDecl>, InnerMatcher) { if (!Node.getAsNamespace()) return false; return InnerMatcher.matches(*Node.getAsNamespace(), Finder, Builder); } /// Overloads for the \c equalsNode matcher. /// FIXME: Implement for other node types. /// @{ /// Matches if a node equals another node. /// /// \c Decl has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Decl, equalsNode, const Decl*, Other, 0) { return &Node == Other; } /// Matches if a node equals another node. /// /// \c Stmt has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Stmt, equalsNode, const Stmt*, Other, 1) { return &Node == Other; } /// Matches if a node equals another node. /// /// \c Type has pointer identity in the AST. AST_MATCHER_P_OVERLOAD(Type, equalsNode, const Type*, Other, 2) { return &Node == Other; } /// @} /// Matches each case or default statement belonging to the given switch /// statement. This matcher may produce multiple matches. /// /// Given /// \code /// switch (1) { case 1: case 2: default: switch (2) { case 3: case 4: ; } } /// \endcode /// switchStmt(forEachSwitchCase(caseStmt().bind("c"))).bind("s") /// matches four times, with "c" binding each of "case 1:", "case 2:", /// "case 3:" and "case 4:", and "s" respectively binding "switch (1)", /// "switch (1)", "switch (2)" and "switch (2)". AST_MATCHER_P(SwitchStmt, forEachSwitchCase, internal::Matcher<SwitchCase>, InnerMatcher) { BoundNodesTreeBuilder Result; // FIXME: getSwitchCaseList() does not necessarily guarantee a stable // iteration order. We should use the more general iterating matchers once // they are capable of expressing this matcher (for example, it should ignore // case statements belonging to nested switch statements). bool Matched = false; for (const SwitchCase *SC = Node.getSwitchCaseList(); SC; SC = SC->getNextSwitchCase()) { BoundNodesTreeBuilder CaseBuilder(*Builder); bool CaseMatched = InnerMatcher.matches(*SC, Finder, &CaseBuilder); if (CaseMatched) { Matched = true; Result.addMatch(CaseBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches each constructor initializer in a constructor definition. /// /// Given /// \code /// class A { A() : i(42), j(42) {} int i; int j; }; /// \endcode /// cxxConstructorDecl(forEachConstructorInitializer( /// forField(decl().bind("x")) /// )) /// will trigger two matches, binding for 'i' and 'j' respectively. AST_MATCHER_P(CXXConstructorDecl, forEachConstructorInitializer, internal::Matcher<CXXCtorInitializer>, InnerMatcher) { BoundNodesTreeBuilder Result; bool Matched = false; for (const auto *I : Node.inits()) { if (Finder->isTraversalIgnoringImplicitNodes() && !I->isWritten()) continue; BoundNodesTreeBuilder InitBuilder(*Builder); if (InnerMatcher.matches(*I, Finder, &InitBuilder)) { Matched = true; Result.addMatch(InitBuilder); } } *Builder = std::move(Result); return Matched; } /// Matches constructor declarations that are copy constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isCopyConstructor()) will match #2, but not #1 or #3. AST_MATCHER(CXXConstructorDecl, isCopyConstructor) { return Node.isCopyConstructor(); } /// Matches constructor declarations that are move constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isMoveConstructor()) will match #3, but not #1 or #2. AST_MATCHER(CXXConstructorDecl, isMoveConstructor) { return Node.isMoveConstructor(); } /// Matches constructor declarations that are default constructors. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(const S &); // #2 /// S(S &&); // #3 /// }; /// \endcode /// cxxConstructorDecl(isDefaultConstructor()) will match #1, but not #2 or #3. AST_MATCHER(CXXConstructorDecl, isDefaultConstructor) { return Node.isDefaultConstructor(); } /// Matches constructors that delegate to another constructor. /// /// Given /// \code /// struct S { /// S(); // #1 /// S(int) {} // #2 /// S(S &&) : S() {} // #3 /// }; /// S::S() : S(0) {} // #4 /// \endcode /// cxxConstructorDecl(isDelegatingConstructor()) will match #3 and #4, but not /// #1 or #2. AST_MATCHER(CXXConstructorDecl, isDelegatingConstructor) { return Node.isDelegatingConstructor(); } /// Matches constructor, conversion function, and deduction guide declarations /// that have an explicit specifier if this explicit specifier is resolved to /// true. /// /// Given /// \code /// template<bool b> /// struct S { /// S(int); // #1 /// explicit S(double); // #2 /// operator int(); // #3 /// explicit operator bool(); // #4 /// explicit(false) S(bool) // # 7 /// explicit(true) S(char) // # 8 /// explicit(b) S(S) // # 9 /// }; /// S(int) -> S<true> // #5 /// explicit S(double) -> S<false> // #6 /// \endcode /// cxxConstructorDecl(isExplicit()) will match #2 and #8, but not #1, #7 or #9. /// cxxConversionDecl(isExplicit()) will match #4, but not #3. /// cxxDeductionGuideDecl(isExplicit()) will match #6, but not #5. AST_POLYMORPHIC_MATCHER(isExplicit, AST_POLYMORPHIC_SUPPORTED_TYPES( CXXConstructorDecl, CXXConversionDecl, CXXDeductionGuideDecl)) { return Node.isExplicit(); } /// Matches the expression in an explicit specifier if present in the given /// declaration. /// /// Given /// \code /// template<bool b> /// struct S { /// S(int); // #1 /// explicit S(double); // #2 /// operator int(); // #3 /// explicit operator bool(); // #4 /// explicit(false) S(bool) // # 7 /// explicit(true) S(char) // # 8 /// explicit(b) S(S) // # 9 /// }; /// S(int) -> S<true> // #5 /// explicit S(double) -> S<false> // #6 /// \endcode /// cxxConstructorDecl(hasExplicitSpecifier(constantExpr())) will match #7, #8 and #9, but not #1 or #2. /// cxxConversionDecl(hasExplicitSpecifier(constantExpr())) will not match #3 or #4. /// cxxDeductionGuideDecl(hasExplicitSpecifier(constantExpr())) will not match #5 or #6. AST_MATCHER_P(FunctionDecl, hasExplicitSpecifier, internal::Matcher<Expr>, InnerMatcher) { ExplicitSpecifier ES = ExplicitSpecifier::getFromDecl(&Node); if (!ES.getExpr()) return false; ASTChildrenNotSpelledInSourceScope RAII(Finder, false); return InnerMatcher.matches(*ES.getExpr(), Finder, Builder); } /// Matches function and namespace declarations that are marked with /// the inline keyword. /// /// Given /// \code /// inline void f(); /// void g(); /// namespace n { /// inline namespace m {} /// } /// \endcode /// functionDecl(isInline()) will match ::f(). /// namespaceDecl(isInline()) will match n::m. AST_POLYMORPHIC_MATCHER(isInline, AST_POLYMORPHIC_SUPPORTED_TYPES(NamespaceDecl, FunctionDecl)) { // This is required because the spelling of the function used to determine // whether inline is specified or not differs between the polymorphic types. if (const auto *FD = dyn_cast<FunctionDecl>(&Node)) return FD->isInlineSpecified(); else if (const auto *NSD = dyn_cast<NamespaceDecl>(&Node)) return NSD->isInline(); llvm_unreachable("Not a valid polymorphic type"); } /// Matches anonymous namespace declarations. /// /// Given /// \code /// namespace n { /// namespace {} // #1 /// } /// \endcode /// namespaceDecl(isAnonymous()) will match #1 but not ::n. AST_MATCHER(NamespaceDecl, isAnonymous) { return Node.isAnonymousNamespace(); } /// Matches declarations in the namespace `std`, but not in nested namespaces. /// /// Given /// \code /// class vector {}; /// namespace foo { /// class vector {}; /// namespace std { /// class vector {}; /// } /// } /// namespace std { /// inline namespace __1 { /// class vector {}; // #1 /// namespace experimental { /// class vector {}; /// } /// } /// } /// \endcode /// cxxRecordDecl(hasName("vector"), isInStdNamespace()) will match only #1. AST_MATCHER(Decl, isInStdNamespace) { return Node.isInStdNamespace(); } /// If the given case statement does not use the GNU case range /// extension, matches the constant given in the statement. /// /// Given /// \code /// switch (1) { case 1: case 1+1: case 3 ... 4: ; } /// \endcode /// caseStmt(hasCaseConstant(integerLiteral())) /// matches "case 1:" AST_MATCHER_P(CaseStmt, hasCaseConstant, internal::Matcher<Expr>, InnerMatcher) { if (Node.getRHS()) return false; return InnerMatcher.matches(*Node.getLHS(), Finder, Builder); } /// Matches declaration that has a given attribute. /// /// Given /// \code /// __attribute__((device)) void f() { ... } /// \endcode /// decl(hasAttr(clang::attr::CUDADevice)) matches the function declaration of /// f. If the matcher is used from clang-query, attr::Kind parameter should be /// passed as a quoted string. e.g., hasAttr("attr::CUDADevice"). AST_MATCHER_P(Decl, hasAttr, attr::Kind, AttrKind) { for (const auto *Attr : Node.attrs()) { if (Attr->getKind() == AttrKind) return true; } return false; } /// Matches the return value expression of a return statement /// /// Given /// \code /// return a + b; /// \endcode /// hasReturnValue(binaryOperator()) /// matches 'return a + b' /// with binaryOperator() /// matching 'a + b' AST_MATCHER_P(ReturnStmt, hasReturnValue, internal::Matcher<Expr>, InnerMatcher) { if (const auto *RetValue = Node.getRetValue()) return InnerMatcher.matches(*RetValue, Finder, Builder); return false; } /// Matches CUDA kernel call expression. /// /// Example matches, /// \code /// kernel<<<i,j>>>(); /// \endcode extern const internal::VariadicDynCastAllOfMatcher<Stmt, CUDAKernelCallExpr> cudaKernelCallExpr; /// Matches expressions that resolve to a null pointer constant, such as /// GNU's __null, C++11's nullptr, or C's NULL macro. /// /// Given: /// \code /// void *v1 = NULL; /// void *v2 = nullptr; /// void *v3 = __null; // GNU extension /// char *cp = (char *)0; /// int *ip = 0; /// int i = 0; /// \endcode /// expr(nullPointerConstant()) /// matches the initializer for v1, v2, v3, cp, and ip. Does not match the /// initializer for i. AST_MATCHER_FUNCTION(internal::Matcher<Expr>, nullPointerConstant) { return anyOf( gnuNullExpr(), cxxNullPtrLiteralExpr(), integerLiteral(equals(0), hasParent(expr(hasType(pointerType()))))); } /// Matches the DecompositionDecl the binding belongs to. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// bindingDecl(hasName("f"), /// forDecomposition(decompositionDecl()) /// \endcode /// matches 'f' in 'auto &[f, s, t]'. AST_MATCHER_P(BindingDecl, forDecomposition, internal::Matcher<ValueDecl>, InnerMatcher) { if (const ValueDecl *VD = Node.getDecomposedDecl()) return InnerMatcher.matches(*VD, Finder, Builder); return false; } /// Matches the Nth binding of a DecompositionDecl. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// decompositionDecl(hasBinding(0, /// bindingDecl(hasName("f").bind("fBinding")))) /// \endcode /// matches the decomposition decl with 'f' bound to "fBinding". AST_MATCHER_P2(DecompositionDecl, hasBinding, unsigned, N, internal::Matcher<BindingDecl>, InnerMatcher) { if (Node.bindings().size() <= N) return false; return InnerMatcher.matches(*Node.bindings()[N], Finder, Builder); } /// Matches any binding of a DecompositionDecl. /// /// For example, in: /// \code /// void foo() /// { /// int arr[3]; /// auto &[f, s, t] = arr; /// /// f = 42; /// } /// \endcode /// The matcher: /// \code /// decompositionDecl(hasAnyBinding(bindingDecl(hasName("f").bind("fBinding")))) /// \endcode /// matches the decomposition decl with 'f' bound to "fBinding". AST_MATCHER_P(DecompositionDecl, hasAnyBinding, internal::Matcher<BindingDecl>, InnerMatcher) { return llvm::any_of(Node.bindings(), [&](const auto *Binding) { return InnerMatcher.matches(*Binding, Finder, Builder); }); } /// Matches declaration of the function the statement belongs to /// /// Given: /// \code /// F& operator=(const F& o) { /// std::copy_if(o.begin(), o.end(), begin(), [](V v) { return v > 0; }); /// return *this; /// } /// \endcode /// returnStmt(forFunction(hasName("operator="))) /// matches 'return *this' /// but does not match 'return v > 0' AST_MATCHER_P(Stmt, forFunction, internal::Matcher<FunctionDecl>, InnerMatcher) { const auto &Parents = Finder->getASTContext().getParents(Node); llvm::SmallVector<DynTypedNode, 8> Stack(Parents.begin(), Parents.end()); while(!Stack.empty()) { const auto &CurNode = Stack.back(); Stack.pop_back(); if(const auto *FuncDeclNode = CurNode.get<FunctionDecl>()) { if(InnerMatcher.matches(*FuncDeclNode, Finder, Builder)) { return true; } } else if(const auto *LambdaExprNode = CurNode.get<LambdaExpr>()) { if(InnerMatcher.matches(*LambdaExprNode->getCallOperator(), Finder, Builder)) { return true; } } else { for(const auto &Parent: Finder->getASTContext().getParents(CurNode)) Stack.push_back(Parent); } } return false; } /// Matches a declaration that has external formal linkage. /// /// Example matches only z (matcher = varDecl(hasExternalFormalLinkage())) /// \code /// void f() { /// int x; /// static int y; /// } /// int z; /// \endcode /// /// Example matches f() because it has external formal linkage despite being /// unique to the translation unit as though it has internal likage /// (matcher = functionDecl(hasExternalFormalLinkage())) /// /// \code /// namespace { /// void f() {} /// } /// \endcode AST_MATCHER(NamedDecl, hasExternalFormalLinkage) { return Node.hasExternalFormalLinkage(); } /// Matches a declaration that has default arguments. /// /// Example matches y (matcher = parmVarDecl(hasDefaultArgument())) /// \code /// void x(int val) {} /// void y(int val = 0) {} /// \endcode /// /// Deprecated. Use hasInitializer() instead to be able to /// match on the contents of the default argument. For example: /// /// \code /// void x(int val = 7) {} /// void y(int val = 42) {} /// \endcode /// parmVarDecl(hasInitializer(integerLiteral(equals(42)))) /// matches the parameter of y /// /// A matcher such as /// parmVarDecl(hasInitializer(anything())) /// is equivalent to parmVarDecl(hasDefaultArgument()). AST_MATCHER(ParmVarDecl, hasDefaultArgument) { return Node.hasDefaultArg(); } /// Matches array new expressions. /// /// Given: /// \code /// MyClass *p1 = new MyClass[10]; /// \endcode /// cxxNewExpr(isArray()) /// matches the expression 'new MyClass[10]'. AST_MATCHER(CXXNewExpr, isArray) { return Node.isArray(); } /// Matches placement new expression arguments. /// /// Given: /// \code /// MyClass *p1 = new (Storage, 16) MyClass(); /// \endcode /// cxxNewExpr(hasPlacementArg(1, integerLiteral(equals(16)))) /// matches the expression 'new (Storage, 16) MyClass()'. AST_MATCHER_P2(CXXNewExpr, hasPlacementArg, unsigned, Index, internal::Matcher<Expr>, InnerMatcher) { return Node.getNumPlacementArgs() > Index && InnerMatcher.matches(*Node.getPlacementArg(Index), Finder, Builder); } /// Matches any placement new expression arguments. /// /// Given: /// \code /// MyClass *p1 = new (Storage) MyClass(); /// \endcode /// cxxNewExpr(hasAnyPlacementArg(anything())) /// matches the expression 'new (Storage, 16) MyClass()'. AST_MATCHER_P(CXXNewExpr, hasAnyPlacementArg, internal::Matcher<Expr>, InnerMatcher) { return llvm::any_of(Node.placement_arguments(), [&](const Expr *Arg) { return InnerMatcher.matches(*Arg, Finder, Builder); }); } /// Matches array new expressions with a given array size. /// /// Given: /// \code /// MyClass *p1 = new MyClass[10]; /// \endcode /// cxxNewExpr(hasArraySize(integerLiteral(equals(10)))) /// matches the expression 'new MyClass[10]'. AST_MATCHER_P(CXXNewExpr, hasArraySize, internal::Matcher<Expr>, InnerMatcher) { return Node.isArray() && *Node.getArraySize() && InnerMatcher.matches(**Node.getArraySize(), Finder, Builder); } /// Matches a class declaration that is defined. /// /// Example matches x (matcher = cxxRecordDecl(hasDefinition())) /// \code /// class x {}; /// class y; /// \endcode AST_MATCHER(CXXRecordDecl, hasDefinition) { return Node.hasDefinition(); } /// Matches C++11 scoped enum declaration. /// /// Example matches Y (matcher = enumDecl(isScoped())) /// \code /// enum X {}; /// enum class Y {}; /// \endcode AST_MATCHER(EnumDecl, isScoped) { return Node.isScoped(); } /// Matches a function declared with a trailing return type. /// /// Example matches Y (matcher = functionDecl(hasTrailingReturn())) /// \code /// int X() {} /// auto Y() -> int {} /// \endcode AST_MATCHER(FunctionDecl, hasTrailingReturn) { if (const auto *F = Node.getType()->getAs<FunctionProtoType>()) return F->hasTrailingReturn(); return false; } /// Matches expressions that match InnerMatcher that are possibly wrapped in an /// elidable constructor and other corresponding bookkeeping nodes. /// /// In C++17, elidable copy constructors are no longer being generated in the /// AST as it is not permitted by the standard. They are, however, part of the /// AST in C++14 and earlier. So, a matcher must abstract over these differences /// to work in all language modes. This matcher skips elidable constructor-call /// AST nodes, `ExprWithCleanups` nodes wrapping elidable constructor-calls and /// various implicit nodes inside the constructor calls, all of which will not /// appear in the C++17 AST. /// /// Given /// /// \code /// struct H {}; /// H G(); /// void f() { /// H D = G(); /// } /// \endcode /// /// ``varDecl(hasInitializer(ignoringElidableConstructorCall(callExpr())))`` /// matches ``H D = G()`` in C++11 through C++17 (and beyond). AST_MATCHER_P(Expr, ignoringElidableConstructorCall, ast_matchers::internal::Matcher<Expr>, InnerMatcher) { // E tracks the node that we are examining. const Expr *E = &Node; // If present, remove an outer `ExprWithCleanups` corresponding to the // underlying `CXXConstructExpr`. This check won't cover all cases of added // `ExprWithCleanups` corresponding to `CXXConstructExpr` nodes (because the // EWC is placed on the outermost node of the expression, which this may not // be), but, it still improves the coverage of this matcher. if (const auto *CleanupsExpr = dyn_cast<ExprWithCleanups>(&Node)) E = CleanupsExpr->getSubExpr(); if (const auto *CtorExpr = dyn_cast<CXXConstructExpr>(E)) { if (CtorExpr->isElidable()) { if (const auto *MaterializeTemp = dyn_cast<MaterializeTemporaryExpr>(CtorExpr->getArg(0))) { return InnerMatcher.matches(*MaterializeTemp->getSubExpr(), Finder, Builder); } } } return InnerMatcher.matches(Node, Finder, Builder); } //----------------------------------------------------------------------------// // OpenMP handling. //----------------------------------------------------------------------------// /// Matches any ``#pragma omp`` executable directive. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp taskyield /// \endcode /// /// ``ompExecutableDirective()`` matches ``omp parallel``, /// ``omp parallel default(none)`` and ``omp taskyield``. extern const internal::VariadicDynCastAllOfMatcher<Stmt, OMPExecutableDirective> ompExecutableDirective; /// Matches standalone OpenMP directives, /// i.e., directives that can't have a structured block. /// /// Given /// /// \code /// #pragma omp parallel /// {} /// #pragma omp taskyield /// \endcode /// /// ``ompExecutableDirective(isStandaloneDirective()))`` matches /// ``omp taskyield``. AST_MATCHER(OMPExecutableDirective, isStandaloneDirective) { return Node.isStandaloneDirective(); } /// Matches the structured-block of the OpenMP executable directive /// /// Prerequisite: the executable directive must not be standalone directive. /// If it is, it will never match. /// /// Given /// /// \code /// #pragma omp parallel /// ; /// #pragma omp parallel /// {} /// \endcode /// /// ``ompExecutableDirective(hasStructuredBlock(nullStmt()))`` will match ``;`` AST_MATCHER_P(OMPExecutableDirective, hasStructuredBlock, internal::Matcher<Stmt>, InnerMatcher) { if (Node.isStandaloneDirective()) return false; // Standalone directives have no structured blocks. return InnerMatcher.matches(*Node.getStructuredBlock(), Finder, Builder); } /// Matches any clause in an OpenMP directive. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// \endcode /// /// ``ompExecutableDirective(hasAnyClause(anything()))`` matches /// ``omp parallel default(none)``. AST_MATCHER_P(OMPExecutableDirective, hasAnyClause, internal::Matcher<OMPClause>, InnerMatcher) { ArrayRef<OMPClause *> Clauses = Node.clauses(); return matchesFirstInPointerRange(InnerMatcher, Clauses.begin(), Clauses.end(), Finder, Builder) != Clauses.end(); } /// Matches OpenMP ``default`` clause. /// /// Given /// /// \code /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// #pragma omp parallel /// \endcode /// /// ``ompDefaultClause()`` matches ``default(none)``, ``default(shared)``, and /// ``default(firstprivate)`` extern const internal::VariadicDynCastAllOfMatcher<OMPClause, OMPDefaultClause> ompDefaultClause; /// Matches if the OpenMP ``default`` clause has ``none`` kind specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isNoneKind())`` matches only ``default(none)``. AST_MATCHER(OMPDefaultClause, isNoneKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_none; } /// Matches if the OpenMP ``default`` clause has ``shared`` kind specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isSharedKind())`` matches only ``default(shared)``. AST_MATCHER(OMPDefaultClause, isSharedKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_shared; } /// Matches if the OpenMP ``default`` clause has ``firstprivate`` kind /// specified. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel default(none) /// #pragma omp parallel default(shared) /// #pragma omp parallel default(firstprivate) /// \endcode /// /// ``ompDefaultClause(isFirstPrivateKind())`` matches only /// ``default(firstprivate)``. AST_MATCHER(OMPDefaultClause, isFirstPrivateKind) { return Node.getDefaultKind() == llvm::omp::OMP_DEFAULT_firstprivate; } /// Matches if the OpenMP directive is allowed to contain the specified OpenMP /// clause kind. /// /// Given /// /// \code /// #pragma omp parallel /// #pragma omp parallel for /// #pragma omp for /// \endcode /// /// `ompExecutableDirective(isAllowedToContainClause(OMPC_default))`` matches /// ``omp parallel`` and ``omp parallel for``. /// /// If the matcher is use from clang-query, ``OpenMPClauseKind`` parameter /// should be passed as a quoted string. e.g., /// ``isAllowedToContainClauseKind("OMPC_default").`` AST_MATCHER_P(OMPExecutableDirective, isAllowedToContainClauseKind, OpenMPClauseKind, CKind) { return llvm::omp::isAllowedClauseForDirective( Node.getDirectiveKind(), CKind, Finder->getASTContext().getLangOpts().OpenMP); } //----------------------------------------------------------------------------// // End OpenMP handling. //----------------------------------------------------------------------------// } // namespace ast_matchers } // namespace clang #endif // LLVM_CLANG_ASTMATCHERS_ASTMATCHERS_H
concurrent-curl-openmp.c
#include "helpers.h" #include "urls.h" #include <curl/curl.h> #include <stdio.h> #include <stdlib.h> void *dispatch_request(char *url) { CURL *curl = curl_easy_init(); int http_code = 0; if (!curl) { exit(EXIT_FAILURE); } curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, callback); curl_easy_perform(curl); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &http_code); print_response_status_code(url, http_code); curl_easy_cleanup(curl); return NULL; } int main() { int urls_length = (sizeof(urls) / sizeof(urls[0])); #pragma omp parallel for for (int i = 0; i < urls_length; i += 1) { dispatch_request(urls[i]); } }
3d25pt_var.lbpar.c
#include <omp.h> #include <math.h> #define ceild(n,d) ceil(((double)(n))/((double)(d))) #define floord(n,d) floor(((double)(n))/((double)(d))) #define max(x,y) ((x) > (y)? (x) : (y)) #define min(x,y) ((x) < (y)? (x) : (y)) /* * Order-1, 3D 25 point stencil with axis-symmetric ariable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+8; Ny = atoi(argv[2])+8; Nz = atoi(argv[3])+8; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*13); for(m=0; m<13;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 8; tile_size[1] = 8; tile_size[2] = 8; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<13; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 /* Copyright (C) 1991-2014 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */ /* This header is separate from features.h so that the compiler can include it implicitly at the start of every compilation. It must not itself include <features.h> or any other header that includes <features.h> because the implicit include comes before any feature test macros that may be defined in a source file before it first explicitly includes a system header. GCC knows the name of this header in order to preinclude it. */ /* glibc's intent is to support the IEC 559 math functionality, real and complex. If the GCC (4.9 and later) predefined macros specifying compiler intent are available, use them to determine whether the overall intent is to support these features; otherwise, presume an older compiler has intent to support these features and define these macros by default. */ /* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) / Unicode 6.0. */ /* We do not support C11 <threads.h>. */ int t1, t2, t3, t4, t5, t6, t7, t8; int lb, ub, lbp, ubp, lb2, ub2; register int lbv, ubv; /* Start of CLooG code */ if ((Nt >= 1) && (Nx >= 9) && (Ny >= 9) && (Nz >= 9)) { for (t1=-1;t1<=Nt-1;t1++) { lbp=ceild(t1+1,2); ubp=min(floord(4*Nt+Nz-9,8),floord(4*t1+Nz-2,8)); #pragma omp parallel for private(lbv,ubv,t3,t4,t5,t6,t7,t8) for (t2=lbp;t2<=ubp;t2++) { for (t3=max(ceild(t1,2),ceild(8*t2-Nz+5,8));t3<=min(floord(4*Nt+Ny-9,8),floord(4*t1+Ny-1,8));t3++) { for (t4=max(max(ceild(t1-6,8),ceild(8*t2-Nz-19,32)),ceild(8*t3-Ny-19,32));t4<=min(min(floord(4*Nt+Nx-9,32),floord(4*t1+Nx-1,32)),floord(8*t3+Nx-5,32));t4++) { for (t5=max(max(max(max(0,ceild(8*t2-Nz+5,4)),ceild(8*t3-Ny+5,4)),ceild(32*t4-Nx+5,4)),t1);t5<=min(min(min(2*t3,Nt-1),t1+1),8*t4+6);t5++) { for (t6=max(max(8*t2,4*t5+4),-8*t1+8*t2+8*t5-7);t6<=min(min(8*t2+7,-8*t1+8*t2+8*t5),4*t5+Nz-5);t6++) { for (t7=max(8*t3,4*t5+4);t7<=min(8*t3+7,4*t5+Ny-5);t7++) { lbv=max(32*t4,4*t5+4); ubv=min(32*t4+31,4*t5+Nx-5); #pragma ivdep #pragma vector always for (t8=lbv;t8<=ubv;t8++) { A[( t5 + 1) % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] = (((((((((((((coef[0][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)]) + (coef[1][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 1][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 1][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 1][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 1][ (-4*t5+t8)]))) + (coef[3][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 1] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 1]))) + (coef[4][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 2][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 2][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[5][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 2][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 2][ (-4*t5+t8)]))) + (coef[6][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 2] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 2]))) + (coef[7][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 3][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 3][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[8][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 3][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 3][ (-4*t5+t8)]))) + (coef[9][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 3] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 3]))) + (coef[10][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6) - 4][ (-4*t5+t7)][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6) + 4][ (-4*t5+t7)][ (-4*t5+t8)]))) + (coef[11][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) - 4][ (-4*t5+t8)] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7) + 4][ (-4*t5+t8)]))) + (coef[12][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8)] * (A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) - 4] + A[ t5 % 2][ (-4*t5+t6)][ (-4*t5+t7)][ (-4*t5+t8) + 4])));; } } } } } } } } } /* End of CLooG code */ gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "variable axis-symmetric") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<13;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
memdbg.h
/* ****** NOTE ****** * This header file should be the LAST header file included within every * .c file within the project. If there are .h files that have actual * code in them, then this header should be the last include within that * .h file, and that .h file should be the last one included within the * .c file. * ****** NOTE ***** */ #if !defined (__MEM_DBG_H_) #define __MEM_DBG_H_ // values to use within the MemDbg_Validate() function. #define MEMDBG_VALIDATE_MIN 0 #define MEMDBG_VALIDATE_DEEP 1 #define MEMDBG_VALIDATE_DEEPER 2 #define MEMDBG_VALIDATE_DEEPEST 3 #include <stdio.h> #include <stdlib.h> #include "os.h" #if (!AC_BUILT || HAVE_UNISTD_H) && !_MSC_VER #include <unistd.h> #endif #include <string.h> #include "memory.h" #if defined (MEMDBG_ON) /* * This software was written by Jim Fougeron jfoug AT cox dot net * in 2013. No copyright is claimed, and the software is hereby * placed in the public domain. In case this attempt to disclaim * copyright and place the software in the public domain is deemed * null and void, then the software is Copyright (c) 2013 Jim Fougeron * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ /* * memdbg.h * Memory management debugging (at runtime) * * memdbg contains routines detect, and report memory * problems, such as double frees, passing bad pointers to * free, most buffer overwrites. Also, tracking of non-freed * data, showing memory leaks, can also be shown. * * Compilation Options (provided from Makefile CFLAGS) * * MEMDBG_ON If this is NOT defined, then memdbg will * get out of your way, and most normal memory functions * will be called with no overhead at all. */ /* these functions can be called by client code. Normally Memdbg_Used() and * MemDbg_Display() would be called at program exit. That will dump a list * of any memory that was not released. The MemDbg_Validate() can be called * pretty much any time. That function will walk the memory allocation linked * lists, and sqwack if there are problems, such as overwrites, freed memory that * has been written to, etc. It would likely be good to call MemDbg_Validate() * within benchmarking, after every format is tested. * * TODO: Add a handle that can be passed to the MemDbg_Used() and MemDbg_Display() * and a function to get the 'current' state of memory as a handle. Thus, a * format self test could get a handle BEFORE starting, and then check after, and * ONLY show leaked memory from the time the handle was obtained, which was at the * start of the self test. Thus it would only show leaks from that format test. * * These functions are NOT thread safe. Do not call them within OMP blocks of code. * Normally, these would be called at program exit, or within things like format * self test code, etc, and not within OMP. But this warning is here, so that * it is known NOT to call within OMP. */ extern size_t MemDbg_Used(int show_freed); extern void MemDbg_Display(FILE *); extern void MemDbg_Validate(int level); extern void MemDbg_Validate_msg(int level, const char *pMsg); extern void MemDbg_Validate_msg2(int level, const char *pMsg, int bShowExData); /* these functions should almost NEVER be called by any client code. They * are listed here, because the macros need to know their names. Client code * should almost ALWAYS call malloc() like normal, vs calling MEMDBG_alloc() * If MEMDBG_alloc() was called, and MEMDBG_ON was not defined, then this * function would not be declared here, AND at link time, the function would * not be found. * NOTE, these functions should be thread safe in OMP builds (using #pragma omp atomic) * also note, memory allocation within OMP blocks SHOULD be avoided if possible. It is * very slow, and the thread safety required makes it even slow. This is not only talking * about these functions here, BUT malloc/free in general in OMP blocks. AVOID doing that * at almost all costs, and performance will usually go up. */ extern void *MEMDBG_alloc(size_t, char *, int); extern void *MEMDBG_alloc_align(size_t, int, char *, int); extern void *MEMDBG_calloc(size_t count, size_t, char *, int); extern void *MEMDBG_realloc(void *, size_t, char *, int); extern void MEMDBG_free(const void *, char *, int); extern char *MEMDBG_strdup(const char *, char *, int); #if !defined(__MEMDBG_C_FILE__) /* we get here on every file compiled EXCEPT memdbg.c */ #undef malloc #undef realloc #undef free #undef strdup #undef libc_free #undef libc_calloc #undef libc_malloc #define libc_free(a) MEMDBG_libc_free(a) #define libc_malloc(a) MEMDBG_libc_alloc(a) #define libc_calloc(a,b) MEMDBG_libc_calloc(a,b) #define malloc(a) MEMDBG_alloc((a),__FILE__,__LINE__) #define calloc(a,b) MEMDBG_calloc(a,b,__FILE__,__LINE__) #define realloc(a,b) MEMDBG_realloc((a),(b),__FILE__,__LINE__) #define free(a) MEMDBG_free((a),__FILE__,__LINE__) #define strdup(a) MEMDBG_strdup((a),__FILE__,__LINE__) #endif /* !defined __MEMDBG_C_FILE__ */ /* pass the file handle to write to (normally stderr) */ #define MEMDBG_PROGRAM_EXIT_CHECKS(a) do { \ if (MemDbg_Used(0) > 0 || getenv("MEMDBG")) MemDbg_Display(a); \ MemDbg_Validate_msg2(MEMDBG_VALIDATE_DEEPEST, "At Program Exit", 1); } while(0) typedef struct MEMDBG_HANDLE_t { unsigned id; unsigned alloc_cnt; size_t mem_size; } MEMDBG_HANDLE; /* * these functions give a caller some of the INSIDE information about the * allocated object. We simply return data from inside the memdbg header. * NOTE, if fence post is not valid, we still return something, BUT will * also return something in the err_msg stating this may not be valid. */ /* The count 'id' of an allocated block. Same as used in leak report */ unsigned MEMDBG_get_cnt (const void *ptr, const char **err_msg); /* the size allocated of the contained block */ size_t MEMDBG_get_size(const void *ptr, const char **err_msg); /* what file (source) did the allocation */ const char *MEMDBG_get_file(const void *ptr, const char **err_msg); /* what file (source) line number did the allocation */ unsigned MEMDBG_get_line(const void *ptr, const char **err_msg); /* * these functions allow taking a memory snapshot, calling some code, then validating that memory * is the same after the code. This will help catch memory leaks and other such problems, within * formats and such. Simply get the snapshot, run self tests (or other), when it exits, check * the snapshot to make sure nothing leaked. */ /* returning a struct (or passing as params it not super efficient but this is done so infrequently that this is not an issue. */ MEMDBG_HANDLE MEMDBG_getSnapshot(int id); /* will not exit on leaks. Does exit, on memory overwrite corruption. */ void MEMDBG_checkSnapshot(MEMDBG_HANDLE); /* same as MEMDBG_checkSnapshot() but if exit_on_any_leaks is true, will also exit if leaks found. */ void MEMDBG_checkSnapshot_possible_exit_on_error(MEMDBG_HANDLE, int exit_on_any_leaks); /* * the allocations from mem_alloc_tiny() must call this function to flag the memory they allocate * so it is not flagged as a leak, by these HANDLE snapshot functions. 'tiny' memory is expected * to leak, until program exit. At that time, any that was not freed, will be shown as leaked. * THIS function is also thread safe. The other checkSnapshot functions are NOT thread safe. */ void MEMDBG_tag_mem_from_alloc_tiny(void *); extern void MEMDBG_libc_free(void *); extern void *MEMDBG_libc_alloc(size_t size); extern void *MEMDBG_libc_calloc(size_t count, size_t size); #else #define libc_alloc alloc #define libc_calloc calloc #define libc_malloc malloc #define libc_free free #define MemDbg_Used(a) 0 #define MemDbg_Display(a) #define MemDbg_Validate(a) #define MemDbg_Validate_msg(a,b) #define MemDbg_Validate_msg2(a,b,c) #define MEMDBG_PROGRAM_EXIT_CHECKS(a) #define MEMDBG_tag_mem_from_alloc_tiny(a) #define MEMDBG_HANDLE int #define MEMDBG_getSnapshot(a) 0 #define MEMDBG_checkSnapshot(a) if (a) printf(" \b") #define MEMDBG_checkSnapshot_possible_exit_on_error(a, b) if (a) printf(" \b") #endif /* MEMDBG_ON */ #endif /* __MEMDBG_H_ */
nr_numint.c
/* Copyright 2014-2018 The PySCF Developers. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. * * Author: Qiming Sun <osirpt.sun@gmail.com> */ #include <stdlib.h> #include <string.h> #include <assert.h> #include "config.h" #include "gto/grid_ao_drv.h" #include "np_helper/np_helper.h" #include "vhf/fblas.h" #define BOXSIZE 56 int VXCao_empty_blocks(char *empty, unsigned char *non0table, int *shls_slice, int *ao_loc) { if (non0table == NULL || shls_slice == NULL || ao_loc == NULL) { return 0; } const int sh0 = shls_slice[0]; const int sh1 = shls_slice[1]; int bas_id; int box_id = 0; int bound = BOXSIZE; int has0 = 0; empty[box_id] = 1; for (bas_id = sh0; bas_id < sh1; bas_id++) { empty[box_id] &= !non0table[bas_id]; if (ao_loc[bas_id] == bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = 1; } else if (ao_loc[bas_id] > bound) { has0 |= empty[box_id]; box_id++; bound += BOXSIZE; empty[box_id] = !non0table[bas_id]; } } return has0; } static void dot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int bgrids, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; double beta = 0; if (has0) { int box_id, blen, i, j; size_t b0; for (box_id = 0; box_id < nbox; box_id++) { if (!empty[box_id]) { b0 = box_id * BOXSIZE; blen = MIN(nao-b0, BOXSIZE); dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &blen, &D1, ao+b0*ngrids, &ngrids, dm+b0*nocc, &nocc, &beta, vm, &ngrids); beta = 1.0; } } if (beta == 0) { // all empty for (i = 0; i < nocc; i++) { for (j = 0; j < bgrids; j++) { vm[i*ngrids+j] = 0; } } } } else { dgemm_(&TRANS_N, &TRANS_T, &bgrids, &nocc, &nao, &D1, ao, &ngrids, dm, &nocc, &beta, vm, &ngrids); } } /* vm[nocc,ngrids] = ao[i,ngrids] * dm[i,nocc] */ void VXCdot_ao_dm(double *vm, double *ao, double *dm, int nao, int nocc, int ngrids, int nbas, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; #pragma omp parallel { int ip, ib; #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_dm(vm+ip, ao+ip, dm, nao, nocc, ngrids, MIN(ngrids-ip, BLKSIZE), non0table+ib*nbas, shls_slice, ao_loc); } } } /* vv[n,m] = ao1[n,ngrids] * ao2[m,ngrids] */ static void dot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int bgrids, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { int nbox = (nao+BOXSIZE-1) / BOXSIZE; char empty[nbox]; int has0 = VXCao_empty_blocks(empty, non0table, shls_slice, ao_loc); const char TRANS_T = 'T'; const char TRANS_N = 'N'; const double D1 = 1; if (has0) { int ib, jb, leni, lenj; int j1 = nbox; size_t b0i, b0j; for (ib = 0; ib < nbox; ib++) { if (!empty[ib]) { b0i = ib * BOXSIZE; leni = MIN(nao-b0i, BOXSIZE); if (hermi) { j1 = ib + 1; } for (jb = 0; jb < j1; jb++) { if (!empty[jb]) { b0j = jb * BOXSIZE; lenj = MIN(nao-b0j, BOXSIZE); dgemm_(&TRANS_T, &TRANS_N, &lenj, &leni, &bgrids, &D1, ao2+b0j*ngrids, &ngrids, ao1+b0i*ngrids, &ngrids, &D1, vv+b0i*nao+b0j, &nao); } } } } } else { dgemm_(&TRANS_T, &TRANS_N, &nao, &nao, &bgrids, &D1, ao2, &ngrids, ao1, &ngrids, &D1, vv, &nao); } } /* vv[nao,nao] = ao1[i,nao] * ao2[i,nao] */ void VXCdot_ao_ao(double *vv, double *ao1, double *ao2, int nao, int ngrids, int nbas, int hermi, unsigned char *non0table, int *shls_slice, int *ao_loc) { const int nblk = (ngrids+BLKSIZE-1) / BLKSIZE; memset(vv, 0, sizeof(double) * nao * nao); #pragma omp parallel { int ip, ib; double *v_priv = calloc(nao*nao+2, sizeof(double)); #pragma omp for nowait schedule(static) for (ib = 0; ib < nblk; ib++) { ip = ib * BLKSIZE; dot_ao_ao(v_priv, ao1+ip, ao2+ip, nao, ngrids, MIN(ngrids-ip, BLKSIZE), hermi, non0table+ib*nbas, shls_slice, ao_loc); } #pragma omp critical { for (ip = 0; ip < nao*nao; ip++) { vv[ip] += v_priv[ip]; } } free(v_priv); } if (hermi != 0) { NPdsymm_triu(nao, vv, hermi); } } // 'nip,np->ip' void VXC_dscale_ao(double *aow, double *ao, double *wv, int comp, int nao, int ngrids) { #pragma omp parallel { size_t Ngrids = ngrids; size_t ao_size = nao * Ngrids; int i, j, ic; double *pao = ao; #pragma omp for schedule(static) for (i = 0; i < nao; i++) { pao = ao + i * Ngrids; for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] = pao[j] * wv[j]; } for (ic = 1; ic < comp; ic++) { for (j = 0; j < Ngrids; j++) { aow[i*Ngrids+j] += pao[ic*ao_size+j] * wv[ic*Ngrids+j]; } } } } } // 'ip,ip->p' void VXC_dcontract_rho(double *rho, double *bra, double *ket, int nao, int ngrids) { #pragma omp parallel { size_t Ngrids = ngrids; int nthread = omp_get_num_threads(); int blksize = MAX((Ngrids+nthread-1) / nthread, 1); int ib, b0, b1, i, j; #pragma omp for for (ib = 0; ib < nthread; ib++) { b0 = ib * blksize; b1 = MIN(b0 + blksize, ngrids); for (j = b0; j < b1; j++) { rho[j] = bra[j] * ket[j]; } for (i = 1; i < nao; i++) { for (j = b0; j < b1; j++) { rho[j] += bra[i*Ngrids+j] * ket[i*Ngrids+j]; } } } } }
advection.c
/* * ======================= advection ==================== * Integrate forward (advection only) by one time step. * ATMS 502 / CSE 566, Spring 2016 * * Arguments: * * q1 real array values at current step * q2 real array values at next step * c real true speed of wave * dx real grid spacing * dt real time step * i1,i2 integers indices bounding array data * nx integer number of grid points * advection_type * char if 'L', linear advection; * otherwise, nonlinear */ #include <stdio.h> #include <stdlib.h> void advection(theta_d,p,u3,u2,v3,v2,w3,w2,dx,dy,dz,dt,tstep,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH) int i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH; float theta_d[][ny][nz],p[][ny][nz],u3[][ny][nz],u2[][ny][nz],v3[][j2+2][nz],v2[][j2+2][nz],w3[][ny][k2+2],w2[][ny][k2+2],dx,dy,dz,dt,tstep; { int i,j,k; float theta1d_x[nx],theta1d_x2[nx],theta1d_y[ny],theta1d_y2[ny],theta1d_z[nz],theta1d_z2[nz]; float u1d[nx],v1d[ny],w1d[nz],courant; #pragma omp parallel for shared(u3,u2,v2,w2) private(i,j,k) for (i=i1+1;i<=i2;i++) for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { u3[i][j][k] = u3[i][j][k] - tstep*((u2[i-1][j][k]+u2[i][j][k])/2*(u2[i][j][k]-u2[i-1][j][k])/dx + (u2[i][j][k]+u2[i+1][j][k])/2*(u2[i+1][j][k]-u2[i][j][k])/dx)/2; u3[i][j][k] = u3[i][j][k] - tstep*((v2[i-1][j+1][k]+v2[i][j+1][k])/2*(u2[i][j+1][k]-u2[i][j][k])/dy + (v2[i-1][j][k]+v2[i][j][k])/2*(u2[i][j][k]-u2[i][j-1][k])/dy)/2; u3[i][j][k] = u3[i][j][k] - tstep*((w2[i-1][j][k+1]+w2[i][j][k+1])/2*(u2[i][j][k+1]-u2[i][j][k])/dz + (w2[i-1][j][k]+w2[i][j][k])/2*(u2[i][j][k]-u2[i][j][k-1])/dz)/2; } #pragma omp parallel for shared(v3,u2,v2,w2) private(i,j,k) for (i=i1;i<=i2;i++) for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { v3[i][j][k] = v3[i][j][k] - tstep*((u2[i][j-1][k]+u2[i][j][k])/2*(v2[i][j][k]-v2[i-1][j][k])/dx + (u2[i+1][j-1][k]+u2[i+1][j][k])/2*(v2[i+1][j][k]-v2[i][j][k])/dx)/2; v3[i][j][k] = v3[i][j][k] - tstep*((v2[i][j+1][k]+v2[i][j][k])/2*(v2[i][j+1][k]-v2[i][j][k])/dy + (v2[i][j][k]+v2[i][j-1][k])/2*(v2[i][j][k]-v2[i][j-1][k])/dy)/2; v3[i][j][k] = v3[i][j][k] - tstep*((w2[i][j-1][k]+w2[i][j][k])/2*(v2[i][j][k]-v2[i][j][k-1])/dz + (w2[i][j-1][k+1]+w2[i][j][k+1])/2*(v2[i][j][k+1]-v2[i][j][k])/dz)/2; } #pragma omp parallel for shared(w3,u2,v2,w2) private(i,j,k) for (i=i1;i<=i2;i++) for (j=j1;j<=j2;j++) for (k=k1+1;k<=k2;k++) { w3[i][j][k] = w3[i][j][k] - tstep*((u2[i][j][k-1]+u2[i][j][k])/2*(w2[i][j][k]-w2[i-1][j][k])/dx + (u2[i+1][j][k-1]+u2[i+1][j][k])/2*(w2[i+1][j][k]-w2[i][j][k])/dx)/2; w3[i][j][k] = w3[i][j][k] - tstep*((v2[i][j][k-1]+v2[i][j][k])/2*(w2[i][j][k]-w2[i][j-1][k])/dy + (v2[i][j+1][k-1]+v2[i][j+1][k])/2*(w2[i][j+1][k]-w2[i][j][k])/dy)/2; w3[i][j][k] = w3[i][j][k] - tstep*((w2[i][j][k+1]+w2[i][j][k])/2*(w2[i][j][k+1]-w2[i][j][k])/dz + (w2[i][j][k]+w2[i][j][k-1])/2*(w2[i][j][k]-w2[i][j][k-1])/dz)/2; } /* x array */ for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { for (i=i1-BC_WIDTH;i<=i2+BC_WIDTH;i++) { theta1d_x[i]=theta_d[i][j][k]; } for (i=i1;i<=i2+1;i++) { u1d[i]=u2[i][j][k]; } advect1d(theta1d_x,theta1d_x2,u1d,dx,dt/2,i1,i2,nx); for (i=i1;i<=i2;i++) { theta_d[i][j][k]=theta1d_x2[i]; } } bc(theta_d,p,u3,v3,w3,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH); /* y array */ for (i=i1;i<=i2;i++) for (k=k1;k<=k2;k++) { for (j=j1-BC_WIDTH;j<=j2+BC_WIDTH;j++) { theta1d_y[j]=theta_d[i][j][k]; } for (j=j1;j<=j2+1;j++) { v1d[j]=v2[i][j][k]; } advect1d(theta1d_y,theta1d_y2,v1d,dy,dt/2,j1,j2,ny); for (j=j1;j<=j2;j++) { theta_d[i][j][k]=theta1d_y2[j]; } } bc(theta_d,p,u3,v3,w3,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH); /* z array */ for (i=i1;i<=i2;i++) for (j=j1;j<=j2;j++) { for (k=k1-BC_WIDTH;k<=k2+BC_WIDTH;k++) { theta1d_z[k]=theta_d[i][j][k]; } for (k=k1;k<=k2+1;k++) { w1d[k]=w2[i][j][k]; } advect1d(theta1d_z,theta1d_z2,w1d,dz,dt,k1,k2,nz); for (k=k1;k<=k2;k++) { theta_d[i][j][k]=theta1d_z2[k]; } } bc(theta_d,p,u3,v3,w3,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH); /* y array */ for (i=i1;i<=i2;i++) for (k=k1;k<=k2;k++) { for (j=j1-BC_WIDTH;j<=j2+BC_WIDTH;j++) { theta1d_y[j]=theta_d[i][j][k]; } for (j=j1;j<=j2+1;j++) { v1d[j]=v2[i][j][k]; } advect1d(theta1d_y,theta1d_y2,v1d,dy,dt/2,j1,j2,ny); for (j=j1;j<=j2;j++) { theta_d[i][j][k]=theta1d_y2[j]; } } bc(theta_d,p,u3,v3,w3,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH); /* x array */ for (j=j1;j<=j2;j++) for (k=k1;k<=k2;k++) { for (i=i1-BC_WIDTH;i<=i2+BC_WIDTH;i++) { theta1d_x[i]=theta_d[i][j][k]; } for (i=i1;i<=i2+1;i++) { u1d[i]=u2[i][j][k]; } advect1d(theta1d_x,theta1d_x2,u1d,dx,dt/2,i1,i2,nx); for (i=i1;i<=i2;i++) { theta_d[i][j][k]=theta1d_x2[i]; } } bc(theta_d,p,u3,v3,w3,i1,i2,j1,j2,k1,k2,nx,ny,nz,BC_WIDTH); return; }
DRB002-antidep1-var-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* A loop with loop-carried anti-dependence. Data race pair: a[i+1]@67:10 vs. a[i]@67:5 */ #include <stdlib.h> #include <omp.h> int main(int argc,char *argv[]) { int i; int len = 1000; if (argc > 1) len = atoi(argv[1]); int a[len]; #pragma omp parallel for private (i) for (i = 0; i <= len - 1; i += 1) { a[i] = i; } for (i = 0; i <= len - 1 - 1; i += 1) { a[i] = a[i + 1] + 1; } for (i = 0; i <= len - 1; i += 1) { printf("%d\n",a[i]); } return 0; }
zsplit.c
#include "zsplit.h" fint zsplit_(const fnat m[static restrict 1], const fnat n[static restrict 1], const double complex A[static restrict VDL_2], const fnat ldA[static restrict 1], double Ar[static restrict VDL], const fnat ldAr[static restrict 1], double Ai[static restrict VDL], const fnat ldAi[static restrict 1]) { #ifndef NDEBUG if (IS_NOT_VFPENV) return -9; if (*m & VDL__2) return -1; if (IS_NOT_ALIGNED(A)) return -3; if (*ldA < *m) return -4; if (*ldA & VDL__2) return -4; if (IS_NOT_ALIGNED(Ar)) return -5; if (*ldAr < *m) return -6; if (*ldAr & VDL_1) return -6; if (IS_NOT_ALIGNED(Ai)) return -7; if (*ldAi < *m) return -8; if (*ldAi & VDL_1) return -8; #endif /* !NDEBUG */ #ifdef _OPENMP #pragma omp parallel for default(none) shared(m,n,A,ldA,Ar,ldAr,Ai,ldAi) for (fnat j = 0u; j < *n; ++j) { register const VI idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); const double complex *const Aj = A + j * (size_t)(*ldA); double *const Arj = Ar + j * (size_t)(*ldAr); double *const Aij = Ai + j * (size_t)(*ldAi); for (fnat i = 0u; i < *m; i += VDL_2) { register const VD ri = _mm512_permutexvar_pd(idx, _mm512_load_pd(Aj + i)); _mm256_store_pd((Arj + i), _mm512_extractf64x4_pd(ri, 0x00u)); _mm256_store_pd((Aij + i), _mm512_extractf64x4_pd(ri, 0x01u)); } } return 1; #else /* !_OPENMP */ register const VI idx = _mm512_set_epi64(7, 5, 3, 1, 6, 4, 2, 0); for (fnat j = 0u; j < *n; ++j) { const double complex *const Aj = A + j * (size_t)(*ldA); double *const Arj = Ar + j * (size_t)(*ldAr); double *const Aij = Ai + j * (size_t)(*ldAi); for (fnat i = 0u; i < *m; i += VDL_2) { register const VD ri = _mm512_permutexvar_pd(idx, _mm512_load_pd(Aj + i)); VDP(ri); _mm256_store_pd((Arj + i), _mm512_extractf64x4_pd(ri, 0x00u)); _mm256_store_pd((Aij + i), _mm512_extractf64x4_pd(ri, 0x01u)); } } return 0; #endif /* ?_OPENMP */ }
DRB074-flush-orig-yes.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This benchmark is extracted from flush_nolist.1c of OpenMP Application Programming Interface Examples Version 4.5.0 . We added one critical section to make it a test with only one pair of data races. The data race will not generate wrong result though. So the assertion always passes. Data race pair: i@70:10 vs. i@71:11 */ #include "omprace.h" #include <omp.h> #include<stdio.h> #include<assert.h> void f1(int *q) { #pragma omp critical *q = 1; #pragma omp flush } int main() { omprace_init(); int i=0, sum=0; #pragma omp parallel reduction(+:sum) num_threads(10) { f1(&i); sum+=i; } assert (sum==10); printf("sum=%d\n", sum); omprace_fini(); return 0; }
omp_master_thread.c
#include <stdio.h> #include <omp.h> #include "omp_testsuite.h" int check_omp_master_thread (FILE * logFile) { int nthreads = 0; int executing_thread = -1; #pragma omp parallel { #pragma omp master { #pragma omp critical { nthreads++; } executing_thread = omp_get_thread_num (); } /* end of master */ } /* end of parallel */ return ((nthreads == 1) && (executing_thread == 0)); } int crosscheck_omp_master_thread (FILE * logFile) { int nthreads = 0; int executing_thread = -1; #pragma omp parallel { { #pragma omp critical { nthreads++; } executing_thread = omp_get_thread_num (); } /* end of master */ } /* end of parallel */ return ((nthreads == 1) && (executing_thread == 0)); }
par_gsmg.c
/****************************************************************************** * Copyright 1998-2019 Lawrence Livermore National Security, LLC and other * HYPRE Project Developers. See the top-level COPYRIGHT file for details. * * SPDX-License-Identifier: (Apache-2.0 OR MIT) ******************************************************************************/ /****************************************************************************** * * Geometrically smooth interpolation multigrid * *****************************************************************************/ #include <stdio.h> #include <math.h> #include "_hypre_parcsr_ls.h" #include "par_amg.h" #include "_hypre_lapack.h" #ifndef ABS #define ABS(x) ((x)>0 ? (x) : -(x)) #endif #ifndef MAX #define MAX(a,b) ((a)>(b)?(a):(b)) #endif static HYPRE_Real mydnrm2(HYPRE_Int n, HYPRE_Real *x) { HYPRE_Real temp = 0.; HYPRE_Int i; for (i = 0; i < n; i++) { temp = temp + x[i] * x[i]; } return sqrt(temp); } static void mydscal(HYPRE_Int n, HYPRE_Real a, HYPRE_Real *x) { HYPRE_Int i; for (i = 0; i < n; i++) { x[i] = a * x[i]; } } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixFillSmooth * - fill in smooth matrix * - this function will scale the smooth vectors *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixFillSmooth(HYPRE_Int nsamples, HYPRE_Real *samples, hypre_ParCSRMatrix *S, hypre_ParCSRMatrix *A, HYPRE_Int num_functions, HYPRE_Int *dof_func) { hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int n = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int i, j, k, ii, index, start; HYPRE_Int num_cols_offd; HYPRE_Int num_sends; HYPRE_Int *dof_func_offd; HYPRE_Int *int_buf_data; HYPRE_Real temp; HYPRE_Real *p; HYPRE_Real *p_offd; HYPRE_Real *p_ptr; HYPRE_Real *buf_data; HYPRE_Real nm; #if 0 HYPRE_Real mx = 0., my = 1.e+10; #endif /* normalize each sample vector and divide by number of samples */ for (k = 0; k < nsamples; k++) { nm = mydnrm2(n, samples + k * n); nm = 1. / nm / nsamples; mydscal(n, nm, samples + k * n); } num_cols_offd = hypre_CSRMatrixNumCols(S_offd); num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); buf_data = hypre_CTAlloc(HYPRE_Real, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); p_offd = hypre_CTAlloc(HYPRE_Real, nsamples * num_cols_offd, HYPRE_MEMORY_HOST); p_ptr = p_offd; p = samples; for (k = 0; k < nsamples; k++) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) buf_data[index++] = p[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 1, comm_pkg, buf_data, p_offd); hypre_ParCSRCommHandleDestroy(comm_handle); p = p + n; p_offd = p_offd + num_cols_offd; } hypre_TFree(buf_data, HYPRE_MEMORY_HOST); if (num_functions > 1) { dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd, HYPRE_MEMORY_HOST); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); } for (i = 0; i < n; i++) { for (j = S_diag_i[i] + 1; j < S_diag_i[i + 1]; j++) { ii = S_diag_j[j]; /* only interpolate between like functions */ if (num_functions > 1 && dof_func[i] != dof_func[ii]) { S_diag_data[j] = 0.; continue; } /* explicit zeros */ if (A_diag_data[j] == 0.) { S_diag_data[j] = 0.; continue; } temp = 0.; p = samples; for (k = 0; k < nsamples; k++) { temp = temp + ABS(p[i] - p[ii]); p = p + n; } /* explicit zeros in matrix may cause this */ if (temp == 0.) { S_diag_data[j] = 0.; continue; } temp = 1. / temp; /* reciprocal */ #if 0 my = hypre_min(my, temp); mx = hypre_max(mx, temp); #endif S_diag_data[j] = temp; } for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++) { ii = S_offd_j[j]; /* only interpolate between like functions */ if (num_functions > 1 && dof_func[i] != dof_func_offd[ii]) { S_offd_data[j] = 0.; continue; } /* explicit zeros */ if (A_offd_data[j] == 0.) { S_offd_data[j] = 0.; continue; } temp = 0.; p = samples; p_offd = p_ptr; for (k = 0; k < nsamples; k++) { temp = temp + ABS(p[i] - p_offd[ii]); p = p + n; p_offd = p_offd + num_cols_offd; } /* explicit zeros in matrix may cause this */ if (temp == 0.) { S_offd_data[j] = 0.; continue; } temp = 1. / temp; /* reciprocal */ #if 0 my = hypre_min(my, temp); mx = hypre_max(mx, temp); #endif S_offd_data[j] = temp; } } #if 0 hypre_printf("MIN, MAX: %f %f\n", my, mx); #endif hypre_TFree(p_ptr, HYPRE_MEMORY_HOST); if (num_functions > 1) { hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); } return 0; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixChooseThresh *--------------------------------------------------------------------------*/ HYPRE_Real hypre_ParCSRMatrixChooseThresh(hypre_ParCSRMatrix *S) { MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag); HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd); HYPRE_Int n = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int i, j; HYPRE_Real mx, minimax = 1.e+10; HYPRE_Real minmin; for (i = 0; i < n; i++) { mx = 0.; for (j = S_diag_i[i]; j < S_diag_i[i + 1]; j++) { mx = hypre_max(mx, S_diag_data[j]); } for (j = S_offd_i[i]; j < S_offd_i[i + 1]; j++) { mx = hypre_max(mx, S_offd_data[j]); } if (mx != 0.) { minimax = hypre_min(minimax, mx); } } hypre_MPI_Allreduce(&minimax, &minmin, 1, HYPRE_MPI_REAL, hypre_MPI_MIN, comm); return minmin; } /*-------------------------------------------------------------------------- * hypre_ParCSRMatrixThreshold *--------------------------------------------------------------------------*/ HYPRE_Int hypre_ParCSRMatrixThreshold(hypre_ParCSRMatrix *A, HYPRE_Real thresh) { hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); HYPRE_Int *A_diag_i = hypre_CSRMatrixI(A_diag); HYPRE_Int *A_diag_j = hypre_CSRMatrixJ(A_diag); HYPRE_Real *A_diag_data = hypre_CSRMatrixData(A_diag); hypre_CSRMatrix *A_offd = hypre_ParCSRMatrixOffd(A); HYPRE_Int *A_offd_i = hypre_CSRMatrixI(A_offd); HYPRE_Int *A_offd_j = hypre_CSRMatrixJ(A_offd); HYPRE_Real *A_offd_data = hypre_CSRMatrixData(A_offd); HYPRE_Int n = hypre_CSRMatrixNumRows(A_diag); HYPRE_Int num_nonzeros_diag = A_diag_i[n]; HYPRE_Int num_nonzeros_offd = A_offd_i[n]; HYPRE_Int *S_diag_i; HYPRE_Int *S_diag_j; HYPRE_Real *S_diag_data; HYPRE_Int *S_offd_i; HYPRE_Int *S_offd_j; HYPRE_Real *S_offd_data; HYPRE_Int count, i, jS, jA; /* first count the number of nonzeros we will need */ count = 0; for (i = 0; i < num_nonzeros_diag; i++) if (A_diag_data[i] >= thresh) { count++; } /* allocate vectors */ S_diag_i = hypre_CTAlloc(HYPRE_Int, n + 1, HYPRE_MEMORY_HOST); S_diag_j = hypre_CTAlloc(HYPRE_Int, count, HYPRE_MEMORY_HOST); S_diag_data = hypre_CTAlloc(HYPRE_Real, count, HYPRE_MEMORY_HOST); jS = 0; for (i = 0; i < n; i++) { S_diag_i[i] = jS; for (jA = A_diag_i[i]; jA < A_diag_i[i + 1]; jA++) { if (A_diag_data[jA] >= thresh) { S_diag_data[jS] = A_diag_data[jA]; S_diag_j[jS] = A_diag_j[jA]; jS++; } } } S_diag_i[n] = jS; hypre_CSRMatrixNumNonzeros(A_diag) = jS; /* free the vectors we don't need */ hypre_TFree(A_diag_i, HYPRE_MEMORY_HOST); hypre_TFree(A_diag_j, HYPRE_MEMORY_HOST); hypre_TFree(A_diag_data, HYPRE_MEMORY_HOST); /* assign the new vectors */ hypre_CSRMatrixI(A_diag) = S_diag_i; hypre_CSRMatrixJ(A_diag) = S_diag_j; hypre_CSRMatrixData(A_diag) = S_diag_data; /* * Offd part */ /* first count the number of nonzeros we will need */ count = 0; for (i = 0; i < num_nonzeros_offd; i++) if (A_offd_data[i] >= thresh) { count++; } /* allocate vectors */ S_offd_i = hypre_CTAlloc(HYPRE_Int, n + 1, HYPRE_MEMORY_HOST); S_offd_j = hypre_CTAlloc(HYPRE_Int, count, HYPRE_MEMORY_HOST); S_offd_data = hypre_CTAlloc(HYPRE_Real, count, HYPRE_MEMORY_HOST); jS = 0; for (i = 0; i < n; i++) { S_offd_i[i] = jS; for (jA = A_offd_i[i]; jA < A_offd_i[i + 1]; jA++) { if (A_offd_data[jA] >= thresh) { S_offd_data[jS] = A_offd_data[jA]; S_offd_j[jS] = A_offd_j[jA]; jS++; } } } S_offd_i[n] = jS; hypre_CSRMatrixNumNonzeros(A_offd) = jS; /* free the vectors we don't need */ hypre_TFree(A_offd_i, HYPRE_MEMORY_HOST); hypre_TFree(A_offd_j, HYPRE_MEMORY_HOST); hypre_TFree(A_offd_data, HYPRE_MEMORY_HOST); /* assign the new vectors */ hypre_CSRMatrixI(A_offd) = S_offd_i; hypre_CSRMatrixJ(A_offd) = S_offd_j; hypre_CSRMatrixData(A_offd) = S_offd_data; return 0; } /*-------------------------------------------------------------------------- * CreateSmoothVecs * - smoother depends on the level being used *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSmoothVecs(void *data, hypre_ParCSRMatrix *A, HYPRE_Int num_sweeps, HYPRE_Int level, HYPRE_Real **SmoothVecs_p) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) data; MPI_Comm comm = hypre_ParCSRMatrixComm(A); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(A); hypre_CSRMatrix *A_diag = hypre_ParCSRMatrixDiag(A); hypre_ParVector *Zero; hypre_ParVector *Temp; hypre_ParVector *U; hypre_ParVector *Qtemp = NULL; HYPRE_Int i; HYPRE_BigInt n = hypre_ParCSRMatrixGlobalNumRows(A); HYPRE_Int n_local = hypre_CSRMatrixNumRows(A_diag); HYPRE_BigInt *starts = hypre_ParCSRMatrixRowStarts(A); HYPRE_Int sample; HYPRE_Int nsamples = hypre_ParAMGDataNumSamples(amg_data); HYPRE_Int ret; HYPRE_Real *datax, *bp, *p; HYPRE_Int rlx_type; HYPRE_Int smooth_type; HYPRE_Int smooth_option = 0; HYPRE_Int smooth_num_levels; HYPRE_Solver *smoother; HYPRE_Int debug_flag = hypre_ParAMGDataDebugFlag(amg_data); HYPRE_Int num_threads; num_threads = hypre_NumThreads(); if (!comm_pkg) { hypre_MatvecCommPkgCreate(A); comm_pkg = hypre_ParCSRMatrixCommPkg(A); } if (debug_flag >= 1) hypre_printf("Creating smooth dirs, %d sweeps, %d samples\n", num_sweeps, nsamples); smooth_type = hypre_ParAMGDataSmoothType(amg_data); smooth_num_levels = hypre_ParAMGDataSmoothNumLevels(amg_data); if (smooth_num_levels > level) { smooth_option = smooth_type; smoother = hypre_ParAMGDataSmoother(amg_data); num_sweeps = hypre_ParAMGDataSmoothNumSweeps(amg_data); } rlx_type = hypre_ParAMGDataGridRelaxType(amg_data)[0]; /* rlx_wt = hypre_ParAMGDataRelaxWeight(amg_data)[level]; */ /* omega = hypre_ParAMGDataOmega(amg_data)[level]; */ /* generate par vectors */ Zero = hypre_ParVectorCreate(comm, n, starts); hypre_ParVectorInitialize(Zero); datax = hypre_VectorData(hypre_ParVectorLocalVector(Zero)); for (i = 0; i < n_local; i++) { datax[i] = 0.; } Temp = hypre_ParVectorCreate(comm, n, starts); hypre_ParVectorInitialize(Temp); datax = hypre_VectorData(hypre_ParVectorLocalVector(Temp)); for (i = 0; i < n_local; i++) { datax[i] = 0.; } U = hypre_ParVectorCreate(comm, n, starts); hypre_ParVectorInitialize(U); datax = hypre_VectorData(hypre_ParVectorLocalVector(U)); if (num_threads > 1) { Qtemp = hypre_ParVectorCreate(comm, n, starts); hypre_ParVectorInitialize(Qtemp); } /* allocate space for the vectors */ bp = hypre_CTAlloc(HYPRE_Real, nsamples * n_local, HYPRE_MEMORY_HOST); p = bp; /* generate random vectors */ for (sample = 0; sample < nsamples; sample++) { for (i = 0; i < n_local; i++) { datax[i] = hypre_Rand() - .5; } for (i = 0; i < num_sweeps; i++) { if (smooth_option == 6) { HYPRE_SchwarzSolve(smoother[level], (HYPRE_ParCSRMatrix) A, (HYPRE_ParVector) Zero, (HYPRE_ParVector) U); } else { ret = hypre_BoomerAMGRelax(A, Zero, NULL /*CFmarker*/, rlx_type, 0 /*rel pts*/, 1.0 /*weight*/, 1.0 /*omega*/, NULL, U, Temp, Qtemp); hypre_assert(ret == 0); } } /* copy out the solution */ for (i = 0; i < n_local; i++) { *p++ = datax[i]; } } hypre_ParVectorDestroy(Zero); hypre_ParVectorDestroy(Temp); hypre_ParVectorDestroy(U); if (num_threads > 1) { hypre_ParVectorDestroy(Qtemp); } *SmoothVecs_p = bp; return 0; } /*-------------------------------------------------------------------------- * CreateSmoothDirs replaces CreateS in AMG * - smoother depends on the level being used * - in this version, CreateSmoothVecs must be called prior to this function *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGCreateSmoothDirs(void *data, hypre_ParCSRMatrix *A, HYPRE_Real *SmoothVecs, HYPRE_Real thresh, HYPRE_Int num_functions, HYPRE_Int *dof_func, hypre_ParCSRMatrix **S_ptr) { hypre_ParAMGData *amg_data = (hypre_ParAMGData*) data; hypre_ParCSRMatrix *S; HYPRE_Real minimax; HYPRE_Int debug_flag = hypre_ParAMGDataDebugFlag(amg_data); S = hypre_ParCSRMatrixClone(A, 0); /* Traverse S and fill in differences */ hypre_ParCSRMatrixFillSmooth( hypre_ParAMGDataNumSamples(amg_data), SmoothVecs, S, A, num_functions, dof_func); minimax = hypre_ParCSRMatrixChooseThresh(S); if (debug_flag >= 1) { hypre_printf("Minimax chosen: %f\n", minimax); } /* Threshold and compress */ hypre_ParCSRMatrixThreshold(S, thresh * minimax); *S_ptr = S; return 0; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGNormalizeVecs * * Normalize the smooth vectors and also make the first vector the constant * vector * * inputs: * n = length of smooth vectors * num = number of smooth vectors * V = smooth vectors (array of length n*num), also an output * * output: * V = adjusted smooth vectors *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGNormalizeVecs(HYPRE_Int n, HYPRE_Int num, HYPRE_Real *V) { HYPRE_Int i, j; HYPRE_Real nrm; /* change first vector to the constant vector */ for (i = 0; i < n; i++) { V[i] = 1.0; } for (j = 0; j < num; j++) { nrm = mydnrm2(n, &V[j * n]); mydscal(n, 1. / nrm, &V[j * n]); } return 0; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGFitVectors * * Construct interpolation weights based on fitting smooth vectors * * inputs: * ip = row number of row in P being processed (0-based) * n = length of smooth vectors * num = number of smooth vectors * V = smooth vectors (array of length n*num), also an output * nc = number of coarse grid points * ind = indices of coarse grid points (0-based) * * output: * val = interpolation weights for the coarse grid points * V = smooth vectors; first one has been changed to constant vector; * vectors have also been normalized; this is also an input *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGFitVectors(HYPRE_Int ip, HYPRE_Int n, HYPRE_Int num, const HYPRE_Real *V, HYPRE_Int nc, const HYPRE_Int *ind, HYPRE_Real *val) { HYPRE_Real *a, *b; HYPRE_Real *ap; HYPRE_Int i, j; HYPRE_Real *work; HYPRE_Int work_size; HYPRE_Int info; HYPRE_Int temp; /* hypre_printf("Fit: row %d, n %d num %d, nc = %d ", ip, n, num, nc); for (i=0; i<nc; i++) hypre_printf("%d ", ind[i]); hypre_printf("\n"); */ if (nc == 0) { return 0; } work_size = 2000 * 64; work = hypre_CTAlloc(HYPRE_Real, work_size, HYPRE_MEMORY_HOST); a = hypre_CTAlloc(HYPRE_Real, num * nc, HYPRE_MEMORY_HOST); ap = a; for (j = 0; j < nc; j++) { for (i = 0; i < num; i++) { *ap = V[i * n + ind[j]]; ap++; } } temp = MAX(nc, num); b = hypre_CTAlloc(HYPRE_Real, temp, HYPRE_MEMORY_HOST); for (i = 0; i < num; i++) { b[i] = V[i * n + ip]; } { char trans = 'N'; HYPRE_Int one = 1; hypre_dgels(&trans, &num, &nc, &one, a, &num, b, &temp, work, &work_size, &info); if (info != 0) { hypre_error_w_msg(HYPRE_ERROR_GENERIC, "par_gsmg: dgels returned %d\n"); } /* copy solution into output vector */ for (j = 0; j < nc; j++) { val[j] = b[j]; } } hypre_TFree(b, HYPRE_MEMORY_HOST); hypre_TFree(a, HYPRE_MEMORY_HOST); hypre_TFree(work, HYPRE_MEMORY_HOST); return info; } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildInterpLS * * Interpolation built from fitting smooth vectors * - sequential version only *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildInterpLS( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, HYPRE_Int num_smooth, HYPRE_Real *SmoothVecs, hypre_ParCSRMatrix **P_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); /* HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag); */ HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); /* HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); */ HYPRE_Int num_cols_S_offd = hypre_CSRMatrixNumCols(S_offd); /* HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd(S); */ hypre_ParCSRMatrix *P; HYPRE_BigInt *col_map_offd_P; HYPRE_Int *tmp_map_offd = NULL; HYPRE_Int *CF_marker_offd; HYPRE_Int *dof_func_offd = NULL; hypre_CSRMatrix *S_ext; //HYPRE_Real *S_ext_data; //HYPRE_Int *S_ext_i; //HYPRE_BigInt *S_ext_j; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data; HYPRE_Int *P_diag_i; HYPRE_Int *P_diag_j; HYPRE_Real *P_offd_data; HYPRE_Int *P_offd_i; HYPRE_Int *P_offd_j; HYPRE_Int P_diag_size; HYPRE_Int P_offd_size; HYPRE_Int *P_marker; /* HYPRE_Int *P_marker_offd; */ HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int *jj_count, *jj_count_offd; /* HYPRE_Int jj_begin_row,jj_begin_row_offd; HYPRE_Int jj_end_row,jj_end_row_offd; */ HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int *fine_to_coarse; //HYPRE_BigInt *fine_to_coarse_offd; HYPRE_Int *coarse_counter; HYPRE_Int coarse_shift; HYPRE_BigInt total_global_cpts; HYPRE_Int num_cols_P_offd; //HYPRE_BigInt my_first_cpt; HYPRE_Int i, i1; HYPRE_Int j, jl, jj; HYPRE_Int start; HYPRE_Real one = 1.0; HYPRE_Int my_id; HYPRE_Int num_procs; HYPRE_Int num_threads; HYPRE_Int num_sends; HYPRE_Int index; HYPRE_Int ns, ne, size, rest; HYPRE_Int *int_buf_data; //HYPRE_BigInt *big_buf_data; HYPRE_Real wall_time; /* for debugging instrumentation */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); num_threads = hypre_NumThreads(); //my_first_cpt = num_cpts_global[my_id]; total_global_cpts = num_cpts_global[num_procs]; /*------------------------------------------------------------------- * Get the CF_marker data for the off-processor columns *-------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST); if (num_functions > 1 && num_cols_S_offd) { dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST); } if (!comm_pkg) { hypre_MatvecCommPkgCreate(S); comm_pkg = hypre_ParCSRMatrixCommPkg(S); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); if (num_functions > 1) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n", my_id, wall_time); fflush(NULL); } /*---------------------------------------------------------------------- * Get the ghost rows of S *---------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } if (num_procs > 1) { S_ext = hypre_ParCSRMatrixExtractBExt(S, S, 1); //S_ext_i = hypre_CSRMatrixI(S_ext); //S_ext_j = hypre_CSRMatrixBigJ(S_ext); //S_ext_data = hypre_CSRMatrixData(S_ext); } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Comm 2 Get S_ext = %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; } jj_counter = start_indexing; jj_counter_offd = start_indexing; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ /* RDF: this looks a little tricky, but doable */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n_fine / num_threads; rest = n_fine - size * num_threads; if (j < rest) { ns = j * size + j; ne = (j + 1) * size + j + 1; } else { ns = j * size + rest; ne = (j + 1) * size + rest; } for (i = ns; i < ne; i++) { /*-------------------------------------------------------------------- * If i is a C-point, interpolation is the identity. Also set up * mapping vector. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { jj_count[j]++; fine_to_coarse[i] = coarse_counter[j]; coarse_counter[j]++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i. *--------------------------------------------------------------------*/ else { for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] >= 0) { jj_count[j]++; } } if (num_procs > 1) { /* removed */ } } } } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ for (i = 0; i < num_threads - 1; i++) { coarse_counter[i + 1] += coarse_counter[i]; jj_count[i + 1] += jj_count[i]; jj_count_offd[i + 1] += jj_count_offd[i]; } i = num_threads - 1; jj_counter = jj_count[i]; jj_counter_offd = jj_count_offd[i]; P_diag_size = jj_counter; P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST); P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); P_diag_i[n_fine] = jj_counter; P_offd_size = jj_counter_offd; P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST); P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Intialize some stuff. *-----------------------------------------------------------------------*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Internal work 1 = %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Send and receive fine_to_coarse info. *-----------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } /*fine_to_coarse_offd = hypre_CTAlloc(HYPRE_BigInt, num_cols_S_offd, HYPRE_MEMORY_HOST); big_buf_data = hypre_CTAlloc(HYPRE_BigInt, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST);*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,ns,ne,size,rest,coarse_shift) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { coarse_shift = 0; if (j > 0) { coarse_shift = coarse_counter[j - 1]; } size = n_fine / num_threads; rest = n_fine - size * num_threads; if (j < rest) { ns = j * size + j; ne = (j + 1) * size + j + 1; } else { ns = j * size + rest; ne = (j + 1) * size + rest; } for (i = ns; i < ne; i++) { fine_to_coarse[i] += coarse_shift; } } /*index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++) big_buf_data[index++] = my_first_cpt+(HYPRE_BigInt)fine_to_coarse[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 21, comm_pkg, big_buf_data, fine_to_coarse_offd); hypre_ParCSRCommHandleDestroy(comm_handle); if (debug_flag==4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Comm 4 FineToCoarse = %f\n", my_id, wall_time); fflush(NULL); } if (debug_flag==4) wall_time = time_getWallclockSeconds();*/ /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jl,i1,jj,ns,ne,size,rest,P_marker,jj_counter,jj_counter_offd) HYPRE_SMP_SCHEDULE #endif for (jl = 0; jl < num_threads; jl++) { size = n_fine / num_threads; rest = n_fine - size * num_threads; if (jl < rest) { ns = jl * size + jl; ne = (jl + 1) * size + jl + 1; } else { ns = jl * size + rest; ne = (jl + 1) * size + rest; } jj_counter = 0; if (jl > 0) { jj_counter = jj_count[jl - 1]; } jj_counter_offd = 0; if (jl > 0) { jj_counter_offd = jj_count_offd[jl - 1]; } for (i = ns; i < ne; i++) { /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_i[i] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else { HYPRE_Int kk; HYPRE_Int indices[1000]; /* kludge */ /* Diagonal part of P */ P_diag_i[i] = jj_counter; kk = 0; for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { P_diag_j[jj_counter] = fine_to_coarse[i1]; jj_counter++; indices[kk] = i1; kk++; } } hypre_BoomerAMGFitVectors(i, n_fine, num_smooth, SmoothVecs, kk, indices, &P_diag_data[P_diag_i[i]]); /* Off-Diagonal part of P */ /* undone */ } } } P_diag_i[i] = jj_counter; /* check that this is in right place for threads */ P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(S), total_global_cpts, hypre_ParCSRMatrixColStarts(S), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, 0); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } num_cols_P_offd = 0; if (P_offd_size) { P_marker = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) { P_marker[i] = P_offd_j[i]; } hypre_qsort0(P_marker, 0, P_offd_size - 1); num_cols_P_offd = 1; index = P_marker[0]; for (i = 1; i < P_offd_size; i++) { if (P_marker[i] > index) { index = P_marker[i]; P_marker[num_cols_P_offd++] = index; } } col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST); tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_P_offd; i++) { tmp_map_offd[i] = P_marker[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) P_offd_j[i] = hypre_BinarySearch(tmp_map_offd, P_offd_j[i], num_cols_P_offd); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); } if (num_cols_P_offd) { hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P; hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd; } hypre_GetCommPkgRTFromCommPkgA(P, S, fine_to_coarse, tmp_map_offd); *P_ptr = P; hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST); hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); //hypre_TFree(big_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST); hypre_TFree(jj_count, HYPRE_MEMORY_HOST); hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); } return (0); } /*--------------------------------------------------------------------------- * hypre_BoomerAMGBuildInterpGSMG * * Difference with hypre_BoomerAMGBuildInterp is that S contains values * and is used to build interpolation weights. Matrix A is not used. *--------------------------------------------------------------------------*/ HYPRE_Int hypre_BoomerAMGBuildInterpGSMG( hypre_ParCSRMatrix *A, HYPRE_Int *CF_marker, hypre_ParCSRMatrix *S, HYPRE_BigInt *num_cpts_global, HYPRE_Int num_functions, HYPRE_Int *dof_func, HYPRE_Int debug_flag, HYPRE_Real trunc_factor, hypre_ParCSRMatrix **P_ptr) { MPI_Comm comm = hypre_ParCSRMatrixComm(S); hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S); hypre_ParCSRCommHandle *comm_handle; hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S); HYPRE_Real *S_diag_data = hypre_CSRMatrixData(S_diag); HYPRE_Int *S_diag_i = hypre_CSRMatrixI(S_diag); HYPRE_Int *S_diag_j = hypre_CSRMatrixJ(S_diag); hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S); HYPRE_Real *S_offd_data = hypre_CSRMatrixData(S_offd); HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd); HYPRE_Int *S_offd_j = hypre_CSRMatrixJ(S_offd); HYPRE_Int num_cols_S_offd = hypre_CSRMatrixNumCols(S_offd); HYPRE_BigInt *col_map_offd = hypre_ParCSRMatrixColMapOffd(S); HYPRE_Int *tmp_map_offd = NULL; hypre_ParCSRMatrix *P; HYPRE_BigInt *col_map_offd_P; HYPRE_Int *CF_marker_offd; HYPRE_Int *dof_func_offd = NULL; hypre_CSRMatrix *S_ext; HYPRE_Real *S_ext_data; HYPRE_Int *S_ext_i; HYPRE_BigInt *S_ext_j; hypre_CSRMatrix *P_diag; hypre_CSRMatrix *P_offd; HYPRE_Real *P_diag_data; HYPRE_Int *P_diag_i; HYPRE_Int *P_diag_j; HYPRE_Real *P_offd_data; HYPRE_Int *P_offd_i; HYPRE_Int *P_offd_j; HYPRE_Int P_diag_size, P_offd_size; HYPRE_Int *P_marker, *P_marker_offd; HYPRE_Int jj_counter, jj_counter_offd; HYPRE_Int *jj_count, *jj_count_offd; HYPRE_Int jj_begin_row, jj_begin_row_offd; HYPRE_Int jj_end_row, jj_end_row_offd; HYPRE_Int start_indexing = 0; /* start indexing for P_data at 0 */ HYPRE_Int n_fine = hypre_CSRMatrixNumRows(S_diag); HYPRE_Int strong_f_marker; HYPRE_Int *fine_to_coarse; HYPRE_Int *coarse_counter; //HYPRE_Int coarse_shift; HYPRE_BigInt total_global_cpts; HYPRE_Int num_cols_P_offd; //HYPRE_BigInt my_first_cpt; HYPRE_BigInt big_i2; HYPRE_Int i, i1, i2; HYPRE_Int j, jl, jj, jj1; HYPRE_Int start; HYPRE_Int c_num; HYPRE_Real sum; HYPRE_Real distribute; HYPRE_Real zero = 0.0; HYPRE_Real one = 1.0; HYPRE_Int my_id; HYPRE_Int num_procs; HYPRE_Int num_threads; HYPRE_Int num_sends; HYPRE_Int index; HYPRE_Int ns, ne, size, rest; HYPRE_Int *int_buf_data; HYPRE_BigInt col_1 = hypre_ParCSRMatrixFirstRowIndex(S); HYPRE_Int local_numrows = hypre_CSRMatrixNumRows(S_diag); HYPRE_BigInt col_n = col_1 + (HYPRE_BigInt)local_numrows; HYPRE_Real wall_time; /* for debugging instrumentation */ hypre_MPI_Comm_size(comm, &num_procs); hypre_MPI_Comm_rank(comm, &my_id); num_threads = hypre_NumThreads(); //my_first_cpt = num_cpts_global[0]; total_global_cpts = 0; /* we will set this later for the matrix in the setup */ /* if (myid == (num_procs -1)) total_global_cpts = coarse_pts_global[1]; hypre_MPI_Bcast(&total_global_cpts, 1, HYPRE_MPI_INT, num_procs-1, comm);*/ /*------------------------------------------------------------------- * Get the CF_marker data for the off-processor columns *-------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST); if (num_functions > 1 && num_cols_S_offd) { dof_func_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST); } if (!comm_pkg) { hypre_MatvecCommPkgCreate(S); comm_pkg = hypre_ParCSRMatrixCommPkg(S); } num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg); int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg, num_sends), HYPRE_MEMORY_HOST); index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, CF_marker_offd); hypre_ParCSRCommHandleDestroy(comm_handle); if (num_functions > 1) { index = 0; for (i = 0; i < num_sends; i++) { start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i); for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i + 1); j++) int_buf_data[index++] = dof_func[hypre_ParCSRCommPkgSendMapElmt(comm_pkg, j)]; } comm_handle = hypre_ParCSRCommHandleCreate( 11, comm_pkg, int_buf_data, dof_func_offd); hypre_ParCSRCommHandleDestroy(comm_handle); } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Comm 1 CF_marker = %f\n", my_id, wall_time); fflush(NULL); } /*---------------------------------------------------------------------- * Get the ghost rows of S *---------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } if (num_procs > 1) { S_ext = hypre_ParCSRMatrixExtractBExt(S, S, 1); S_ext_i = hypre_CSRMatrixI(S_ext); S_ext_j = hypre_CSRMatrixBigJ(S_ext); S_ext_data = hypre_CSRMatrixData(S_ext); } if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Comm 2 Get S_ext = %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * First Pass: Determine size of P and fill in fine_to_coarse mapping. *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * Intialize counters and allocate mapping vector. *-----------------------------------------------------------------------*/ coarse_counter = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); jj_count_offd = hypre_CTAlloc(HYPRE_Int, num_threads, HYPRE_MEMORY_HOST); fine_to_coarse = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < n_fine; i++) { fine_to_coarse[i] = -1; } jj_counter = start_indexing; jj_counter_offd = start_indexing; /*----------------------------------------------------------------------- * Loop over fine grid. *-----------------------------------------------------------------------*/ /* RDF: this looks a little tricky, but doable */ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,i1,jj,ns,ne,size,rest) HYPRE_SMP_SCHEDULE #endif for (j = 0; j < num_threads; j++) { size = n_fine / num_threads; rest = n_fine - size * num_threads; if (j < rest) { ns = j * size + j; ne = (j + 1) * size + j + 1; } else { ns = j * size + rest; ne = (j + 1) * size + rest; } for (i = ns; i < ne; i++) { /*-------------------------------------------------------------------- * If i is a C-point, interpolation is the identity. Also set up * mapping vector. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { jj_count[j]++; fine_to_coarse[i] = coarse_counter[j]; coarse_counter[j]++; } /*-------------------------------------------------------------------- * If i is an F-point, interpolation is from the C-points that * strongly influence i. *--------------------------------------------------------------------*/ else { for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; if (CF_marker[i1] >= 0) { jj_count[j]++; } } if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; if (CF_marker_offd[i1] >= 0) { jj_count_offd[j]++; } } } } } } /*----------------------------------------------------------------------- * Allocate arrays. *-----------------------------------------------------------------------*/ for (i = 0; i < num_threads - 1; i++) { coarse_counter[i + 1] += coarse_counter[i]; jj_count[i + 1] += jj_count[i]; jj_count_offd[i + 1] += jj_count_offd[i]; } i = num_threads - 1; jj_counter = jj_count[i]; jj_counter_offd = jj_count_offd[i]; P_diag_size = jj_counter; P_diag_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST); P_diag_j = hypre_CTAlloc(HYPRE_Int, P_diag_size, HYPRE_MEMORY_HOST); P_diag_data = hypre_CTAlloc(HYPRE_Real, P_diag_size, HYPRE_MEMORY_HOST); P_diag_i[n_fine] = jj_counter; P_offd_size = jj_counter_offd; P_offd_i = hypre_CTAlloc(HYPRE_Int, n_fine + 1, HYPRE_MEMORY_HOST); P_offd_j = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); P_offd_data = hypre_CTAlloc(HYPRE_Real, P_offd_size, HYPRE_MEMORY_HOST); /*----------------------------------------------------------------------- * Intialize some stuff. *-----------------------------------------------------------------------*/ jj_counter = start_indexing; jj_counter_offd = start_indexing; if (debug_flag == 4) { wall_time = time_getWallclockSeconds() - wall_time; hypre_printf("Proc = %d Interp: Internal work 1 = %f\n", my_id, wall_time); fflush(NULL); } /*----------------------------------------------------------------------- * Send and receive fine_to_coarse info. *-----------------------------------------------------------------------*/ if (debug_flag == 4) { wall_time = time_getWallclockSeconds(); } /*----------------------------------------------------------------------- * Loop over fine grid points. *-----------------------------------------------------------------------*/ #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i,j,jl,i1,i2,jj,jj1,ns,ne,size,rest,sum,distribute,P_marker,P_marker_offd,strong_f_marker,jj_counter,jj_counter_offd,c_num,jj_begin_row,jj_end_row,jj_begin_row_offd,jj_end_row_offd) HYPRE_SMP_SCHEDULE #endif for (jl = 0; jl < num_threads; jl++) { size = n_fine / num_threads; rest = n_fine - size * num_threads; if (jl < rest) { ns = jl * size + jl; ne = (jl + 1) * size + jl + 1; } else { ns = jl * size + rest; ne = (jl + 1) * size + rest; } jj_counter = 0; if (jl > 0) { jj_counter = jj_count[jl - 1]; } jj_counter_offd = 0; if (jl > 0) { jj_counter_offd = jj_count_offd[jl - 1]; } P_marker = hypre_CTAlloc(HYPRE_Int, n_fine, HYPRE_MEMORY_HOST); P_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_S_offd, HYPRE_MEMORY_HOST); for (i = 0; i < n_fine; i++) { P_marker[i] = -1; } for (i = 0; i < num_cols_S_offd; i++) { P_marker_offd[i] = -1; } strong_f_marker = -2; for (i = ns; i < ne; i++) { /*-------------------------------------------------------------------- * If i is a c-point, interpolation is the identity. *--------------------------------------------------------------------*/ if (CF_marker[i] >= 0) { P_diag_i[i] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i]; P_diag_data[jj_counter] = one; jj_counter++; } /*-------------------------------------------------------------------- * If i is an F-point, build interpolation. *--------------------------------------------------------------------*/ else { /* Diagonal part of P */ P_diag_i[i] = jj_counter; jj_begin_row = jj_counter; for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_diag_j * and initialize interpolation weight to zero. *--------------------------------------------------------------*/ if (CF_marker[i1] >= 0) { P_marker[i1] = jj_counter; P_diag_j[jj_counter] = fine_to_coarse[i1]; P_diag_data[jj_counter] = zero; jj_counter++; } /*-------------------------------------------------------------- * If neighbor i1 is an F-point, mark it as a strong F-point * whose connection needs to be distributed. *--------------------------------------------------------------*/ else { P_marker[i1] = strong_f_marker; } } jj_end_row = jj_counter; /* Off-Diagonal part of P */ P_offd_i[i] = jj_counter_offd; jj_begin_row_offd = jj_counter_offd; if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; /*----------------------------------------------------------- * If neighbor i1 is a C-point, set column number in P_offd_j * and initialize interpolation weight to zero. *-----------------------------------------------------------*/ if (CF_marker_offd[i1] >= 0) { P_marker_offd[i1] = jj_counter_offd; P_offd_j[jj_counter_offd] = i1; P_offd_data[jj_counter_offd] = zero; jj_counter_offd++; } /*----------------------------------------------------------- * If neighbor i1 is an F-point, mark it as a strong F-point * whose connection needs to be distributed. *-----------------------------------------------------------*/ else { P_marker_offd[i1] = strong_f_marker; } } } jj_end_row_offd = jj_counter_offd; /* Loop over ith row of S. First, the diagonal part of S */ for (jj = S_diag_i[i]; jj < S_diag_i[i + 1]; jj++) { i1 = S_diag_j[jj]; /*-------------------------------------------------------------- * Case 1: neighbor i1 is a C-point and strongly influences i, * accumulate a_{i,i1} into the interpolation weight. *--------------------------------------------------------------*/ if (P_marker[i1] >= jj_begin_row) { P_diag_data[P_marker[i1]] += S_diag_data[jj]; } /*-------------------------------------------------------------- * Case 2: neighbor i1 is an F-point and strongly influences i, * distribute a_{i,i1} to C-points that strongly infuence i. * Note: currently no distribution to the diagonal in this case. *--------------------------------------------------------------*/ else if (P_marker[i1] == strong_f_marker) { sum = zero; /*----------------------------------------------------------- * Loop over row of S for point i1 and calculate the sum * of the connections to c-points that strongly influence i. *-----------------------------------------------------------*/ /* Diagonal block part of row i1 */ for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1 + 1]; jj1++) { i2 = S_diag_j[jj1]; if (P_marker[i2] >= jj_begin_row) { sum += S_diag_data[jj1]; } } /* Off-Diagonal block part of row i1 */ if (num_procs > 1) { for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1 + 1]; jj1++) { i2 = S_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd) { sum += S_offd_data[jj1]; } } } if (sum != 0) { distribute = S_diag_data[jj] / sum; /*----------------------------------------------------------- * Loop over row of S for point i1 and do the distribution. *-----------------------------------------------------------*/ /* Diagonal block part of row i1 */ for (jj1 = S_diag_i[i1]; jj1 < S_diag_i[i1 + 1]; jj1++) { i2 = S_diag_j[jj1]; if (P_marker[i2] >= jj_begin_row) P_diag_data[P_marker[i2]] += distribute * S_diag_data[jj1]; } /* Off-Diagonal block part of row i1 */ if (num_procs > 1) { for (jj1 = S_offd_i[i1]; jj1 < S_offd_i[i1 + 1]; jj1++) { i2 = S_offd_j[jj1]; if (P_marker_offd[i2] >= jj_begin_row_offd) P_offd_data[P_marker_offd[i2]] += distribute * S_offd_data[jj1]; } } } else { /* do nothing */ } } /*-------------------------------------------------------------- * Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1} * into the diagonal. *--------------------------------------------------------------*/ else { /* do nothing */ } } /*---------------------------------------------------------------- * Still looping over ith row of S. Next, loop over the * off-diagonal part of S *---------------------------------------------------------------*/ if (num_procs > 1) { for (jj = S_offd_i[i]; jj < S_offd_i[i + 1]; jj++) { i1 = S_offd_j[jj]; /*-------------------------------------------------------------- * Case 1: neighbor i1 is a C-point and strongly influences i, * accumulate a_{i,i1} into the interpolation weight. *--------------------------------------------------------------*/ if (P_marker_offd[i1] >= jj_begin_row_offd) { P_offd_data[P_marker_offd[i1]] += S_offd_data[jj]; } /*------------------------------------------------------------ * Case 2: neighbor i1 is an F-point and strongly influences i, * distribute a_{i,i1} to C-points that strongly infuence i. * Note: currently no distribution to the diagonal in this case. *-----------------------------------------------------------*/ else if (P_marker_offd[i1] == strong_f_marker) { sum = zero; /*--------------------------------------------------------- * Loop over row of S_ext for point i1 and calculate the sum * of the connections to c-points that strongly influence i. *---------------------------------------------------------*/ /* find row number */ c_num = S_offd_j[jj]; for (jj1 = S_ext_i[c_num]; jj1 < S_ext_i[c_num + 1]; jj1++) { big_i2 = S_ext_j[jj1]; if (big_i2 >= col_1 && big_i2 < col_n) { /* in the diagonal block */ if (P_marker[(HYPRE_Int)(big_i2 - col_1)] >= jj_begin_row) { sum += S_ext_data[jj1]; } } else { /* in the off_diagonal block */ j = hypre_BigBinarySearch(col_map_offd, big_i2, num_cols_S_offd); if (j != -1) { if (P_marker_offd[j] >= jj_begin_row_offd) { sum += S_ext_data[jj1]; } } } } if (sum != 0) { distribute = S_offd_data[jj] / sum; /*--------------------------------------------------------- * Loop over row of S_ext for point i1 and do * the distribution. *--------------------------------------------------------*/ /* Diagonal block part of row i1 */ for (jj1 = S_ext_i[c_num]; jj1 < S_ext_i[c_num + 1]; jj1++) { big_i2 = S_ext_j[jj1]; if (big_i2 >= col_1 && big_i2 < col_n) /* in the diagonal block */ { if (P_marker[(HYPRE_Int)(big_i2 - col_1)] >= jj_begin_row) P_diag_data[P_marker[(HYPRE_Int)(big_i2 - col_1)]] += distribute * S_ext_data[jj1]; } else { /* check to see if it is in the off_diagonal block */ j = hypre_BigBinarySearch(col_map_offd, big_i2, num_cols_S_offd); if (j != -1) { if (P_marker_offd[j] >= jj_begin_row_offd) P_offd_data[P_marker_offd[j]] += distribute * S_ext_data[jj1]; } } } } else { /* do nothing */ } } /*----------------------------------------------------------- * Case 3: neighbor i1 weakly influences i, accumulate a_{i,i1} * into the diagonal. *-----------------------------------------------------------*/ else { /* do nothing */ } } } /*----------------------------------------------------------------- * Set interpolation weight by dividing by the diagonal. *-----------------------------------------------------------------*/ sum = 0.; for (jj = jj_begin_row; jj < jj_end_row; jj++) { sum += P_diag_data[jj]; } for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { sum += P_offd_data[jj]; } for (jj = jj_begin_row; jj < jj_end_row; jj++) { P_diag_data[jj] /= sum; } for (jj = jj_begin_row_offd; jj < jj_end_row_offd; jj++) { P_offd_data[jj] /= sum; } } strong_f_marker--; P_offd_i[i + 1] = jj_counter_offd; } hypre_TFree(P_marker, HYPRE_MEMORY_HOST); hypre_TFree(P_marker_offd, HYPRE_MEMORY_HOST); } P = hypre_ParCSRMatrixCreate(comm, hypre_ParCSRMatrixGlobalNumRows(S), total_global_cpts, hypre_ParCSRMatrixColStarts(S), num_cpts_global, 0, P_diag_i[n_fine], P_offd_i[n_fine]); P_diag = hypre_ParCSRMatrixDiag(P); hypre_CSRMatrixData(P_diag) = P_diag_data; hypre_CSRMatrixI(P_diag) = P_diag_i; hypre_CSRMatrixJ(P_diag) = P_diag_j; P_offd = hypre_ParCSRMatrixOffd(P); hypre_CSRMatrixData(P_offd) = P_offd_data; hypre_CSRMatrixI(P_offd) = P_offd_i; hypre_CSRMatrixJ(P_offd) = P_offd_j; /* Compress P, removing coefficients smaller than trunc_factor * Max */ if (trunc_factor != 0.0) { hypre_BoomerAMGInterpTruncation(P, trunc_factor, 0); P_diag_data = hypre_CSRMatrixData(P_diag); P_diag_i = hypre_CSRMatrixI(P_diag); P_diag_j = hypre_CSRMatrixJ(P_diag); P_offd_data = hypre_CSRMatrixData(P_offd); P_offd_i = hypre_CSRMatrixI(P_offd); P_offd_j = hypre_CSRMatrixJ(P_offd); P_diag_size = P_diag_i[n_fine]; P_offd_size = P_offd_i[n_fine]; } num_cols_P_offd = 0; if (P_offd_size) { P_marker = hypre_CTAlloc(HYPRE_Int, P_offd_size, HYPRE_MEMORY_HOST); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) { P_marker[i] = P_offd_j[i]; } hypre_qsort0(P_marker, 0, P_offd_size - 1); num_cols_P_offd = 1; index = P_marker[0]; for (i = 1; i < P_offd_size; i++) { if (P_marker[i] > index) { index = P_marker[i]; P_marker[num_cols_P_offd++] = index; } } col_map_offd_P = hypre_CTAlloc(HYPRE_BigInt, num_cols_P_offd, HYPRE_MEMORY_HOST); tmp_map_offd = hypre_CTAlloc(HYPRE_Int, num_cols_P_offd, HYPRE_MEMORY_HOST); for (i = 0; i < num_cols_P_offd; i++) { tmp_map_offd[i] = P_marker[i]; } #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(i) HYPRE_SMP_SCHEDULE #endif for (i = 0; i < P_offd_size; i++) P_offd_j[i] = hypre_BinarySearch(tmp_map_offd, P_offd_j[i], num_cols_P_offd); hypre_TFree(P_marker, HYPRE_MEMORY_HOST); } if (num_cols_P_offd) { hypre_ParCSRMatrixColMapOffd(P) = col_map_offd_P; hypre_CSRMatrixNumCols(P_offd) = num_cols_P_offd; } hypre_GetCommPkgRTFromCommPkgA(P, S, fine_to_coarse, tmp_map_offd); *P_ptr = P; hypre_TFree(CF_marker_offd, HYPRE_MEMORY_HOST); hypre_TFree(dof_func_offd, HYPRE_MEMORY_HOST); hypre_TFree(int_buf_data, HYPRE_MEMORY_HOST); hypre_TFree(fine_to_coarse, HYPRE_MEMORY_HOST); hypre_TFree(tmp_map_offd, HYPRE_MEMORY_HOST); hypre_TFree(coarse_counter, HYPRE_MEMORY_HOST); hypre_TFree(jj_count, HYPRE_MEMORY_HOST); hypre_TFree(jj_count_offd, HYPRE_MEMORY_HOST); if (num_procs > 1) { hypre_CSRMatrixDestroy(S_ext); } return (0); }
openbsdsoftraid_fmt_plug.c
/* * Copyright (c) 2014 Thiébaud Weksteen <thiebaud at weksteen dot fr> * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * Fixed BE issues, and build problems (Fall 2014), JimF. */ #include "arch.h" #if FMT_EXTERNS_H extern struct fmt_main fmt_openbsd_softraid; #elif FMT_REGISTERS_H john_register_one(&fmt_openbsd_softraid); #else #include "aes.h" #include "hmac_sha.h" #include "sha.h" #include "common.h" #include "formats.h" #include "pbkdf2_hmac_sha1.h" #include "loader.h" #ifdef _OPENMP static int omp_t = 1; #include <omp.h> #ifndef OMP_SCALE #define OMP_SCALE 1 #endif #endif #include "memdbg.h" #define PLAINTEXT_LENGTH 125 #define SALT_SIZE sizeof(struct custom_salt) #define SALT_ALIGN 4 #ifdef SIMD_COEF_32 #define MIN_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #define MAX_KEYS_PER_CRYPT SSE_GROUP_SZ_SHA1 #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif #define OPENBSD_SOFTRAID_SALTLENGTH 128 #define OPENBSD_SOFTRAID_KEYS 32 #define OPENBSD_SOFTRAID_KEYLENGTH 64 /* AES-XTS-256 keys are 512 bits long */ #define OPENBSD_SOFTRAID_MACLENGTH 20 #define BINARY_SIZE OPENBSD_SOFTRAID_MACLENGTH #define BINARY_ALIGN sizeof(ARCH_WORD_32) static char (*key_buffer)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_32 (*crypt_out)[BINARY_SIZE / sizeof(ARCH_WORD_32)]; static struct custom_salt { unsigned int num_iterations; unsigned char salt[OPENBSD_SOFTRAID_SALTLENGTH]; unsigned char masked_keys[OPENBSD_SOFTRAID_KEYLENGTH * OPENBSD_SOFTRAID_KEYS]; } *cur_salt; static void init(struct fmt_main *self) { #ifdef _OPENMP omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif key_buffer = mem_calloc(sizeof(*key_buffer), self->params.max_keys_per_crypt); crypt_out = mem_calloc(sizeof(*crypt_out), self->params.max_keys_per_crypt); } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(key_buffer); } static int valid(char* ciphertext, struct fmt_main *self) { char *ctcopy; char *keeptr; char *p; if (strncmp(ciphertext, "$openbsd-softraid$", 18) != 0) return 0; /* handle 'chopped' .pot lines */ if (ldr_isa_pot_source(ciphertext)) return 1; ctcopy = strdup(ciphertext); keeptr = ctcopy; ctcopy += 18; if ((p = strtokm(ctcopy, "$")) == NULL) goto err; if (!isdec(p)) /* iterations */ goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (strlen(p) != 2 * 128) /* salt */ goto err; if (!ishexlc(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (strlen(p) != 2 * 32 * 64) /* masked keys */ goto err; if (!ishexlc(p)) goto err; if ((p = strtokm(NULL, "$")) == NULL) goto err; if (strlen(p) != 2 * BINARY_SIZE) /* HMAC-SHA1 */ goto err; if (!ishexlc(p)) goto err; MEM_FREE(keeptr); return 1; err: MEM_FREE(keeptr); return 0; } static void set_salt(void *salt) { cur_salt = (struct custom_salt *)salt; } static void* get_salt(char *ciphertext) { static struct custom_salt cs; char *ctcopy = strdup(ciphertext); char *keeptr = ctcopy; int i; char *p; ctcopy += 18; p = strtokm(ctcopy, "$"); /* iterations */ cs.num_iterations = atoi(p); p = strtokm(NULL, "$"); /* salt */ for (i = 0; i < OPENBSD_SOFTRAID_SALTLENGTH ; i++) cs.salt[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; p = strtokm(NULL, "$"); /* masked keys */ for (i = 0; i < OPENBSD_SOFTRAID_KEYLENGTH * OPENBSD_SOFTRAID_KEYS; i++) cs.masked_keys[i] = atoi16[ARCH_INDEX(p[i * 2])] * 16 + atoi16[ARCH_INDEX(p[i * 2 + 1])]; MEM_FREE(keeptr); return (void *)&cs; } static void *get_binary(char *ciphertext) { static union { unsigned char c[BINARY_SIZE]; ARCH_WORD dummy; } buf; unsigned char *out = buf.c; char *p; int i; /* should work just fine for redeced lengtth .pot format lines as is */ p = strrchr(ciphertext, '$') + 1; for (i = 0; i < BINARY_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } return out; } static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { AES_KEY akey; unsigned char mask_key[MAX_KEYS_PER_CRYPT][32]; unsigned char unmasked_keys[OPENBSD_SOFTRAID_KEYLENGTH * OPENBSD_SOFTRAID_KEYS]; unsigned char hashed_mask_key[20]; int i, j; /* derive masking key from password */ #ifdef SSE_GROUP_SZ_SHA1 int lens[SSE_GROUP_SZ_SHA1]; unsigned char *pin[SSE_GROUP_SZ_SHA1], *pout[SSE_GROUP_SZ_SHA1]; for (i = 0; i < SSE_GROUP_SZ_SHA1; ++i) { lens[i] = strlen(key_buffer[index+i]); pin[i] = (unsigned char*)key_buffer[index+i]; pout[i] = mask_key[i]; } pbkdf2_sha1_sse((const unsigned char **)pin, lens, cur_salt->salt, OPENBSD_SOFTRAID_SALTLENGTH, cur_salt->num_iterations, (unsigned char**)pout, 32, 0); #else pbkdf2_sha1((const unsigned char*)(key_buffer[index]), strlen(key_buffer[index]), cur_salt->salt, OPENBSD_SOFTRAID_SALTLENGTH, cur_salt->num_iterations, mask_key[0], 32, 0); #endif for (i = 0; i < MAX_KEYS_PER_CRYPT; ++i) { /* decrypt sector keys */ AES_set_decrypt_key(mask_key[i], 256, &akey); for(j = 0; j < (OPENBSD_SOFTRAID_KEYLENGTH * OPENBSD_SOFTRAID_KEYS) / 16; j++) { AES_decrypt(&cur_salt->masked_keys[16*j], &unmasked_keys[16*j], &akey); } /* get SHA1 of mask_key */ SHA1(mask_key[i], 32, hashed_mask_key); hmac_sha1(hashed_mask_key, OPENBSD_SOFTRAID_MACLENGTH, unmasked_keys, OPENBSD_SOFTRAID_KEYLENGTH * OPENBSD_SOFTRAID_KEYS, (unsigned char*)crypt_out[index+i], 20); } } return count; } static int cmp_all(void *binary, int count) { int index = 0; for (; index < count; index++) if (*(ARCH_WORD_32*)binary == *(ARCH_WORD_32*)(crypt_out[index])) return 1; return 0; } static int cmp_one(void *binary, int index) { return (*(ARCH_WORD_32*)binary == *(ARCH_WORD_32*)(crypt_out[index])); } static int cmp_exact(char *source, int index) { void *bin = get_binary(source); return !memcmp(bin, crypt_out[index], 20); } static void jtr_set_key(char* key, int index) { strcpy(key_buffer[index], key); } static char *get_key(int index) { return key_buffer[index]; } /* report iteration count as tunable cost */ static unsigned int iteration_count(void *salt) { return ((struct custom_salt*)salt)->num_iterations; } static struct fmt_tests tests_openbsdsoftraid[] = { // too long of line was causing my Sparc box to fail to compile this code {"\ $openbsd-softraid$8192$c2891132ca5305d1189a7da94d32de29182abc2f56dc641d685e471935f2646e06b79f1d6c102c2f62f3757a20efb0a110b8ae207f9129f0dc5eea8ab05cc8280e0ba2460faf979dbac9f577c4a083349064364556b7ad15468c17c4d794c3da0ddf5990cc66751a6ded8d534531dd9aa9fce2f43e68d6a7200e135beb55e752$311c42d1d8daf1e47e0150c8d4a455a0567b062970c1838faaedcd3e43795545de64971c7598902a6e2c3fffcf8abe2ef78979164d0c9089fbb931c4c9dac8b86c85eeace11095e38487e41eb7b6094d96c339e86686121fbe1c32dbff3c00706926b22ec3a1329f346c599d132105b5d182a380161504d535f9836bb7286331adce1e47e4e251a0249612a94312bb309a6f4558568467731c1ae8c9b910d27102dca2a72228ffde7bfc60004c8ab33ca2b01aa476c4f42f99a3d1f904e3bbc56270edb314a62e92cf68185ace93731ef4ce08dff3c695c45e35b57ed8ab1552114635eb2ff531437ba5c3a08ebf3e73b6bbb7fe1ad98373da349f09284ae819b6a2f6fc5a10aec347f3c2331abc1d6617e77d68f314fdb683294f3ef351869491c4fb096969924215d711c15e5fce533dc5acaed4a473b14c595bababc178e62ef065770716520ecddc7cbf1cbed1250b7e004ab975bc29780c952087ec382bf6e77447720a10a8c2993262a2b21f8a3f47e35daa5b620573626b474d3e8abf8e73164664b041a18fe35c2a1905fad617bf6e6c380fdeeb680fa89b6c6dc7676ad93fde25076ecb8855d623b45af9a16a62a957d85c4c70896019be1827ad9320a69f18bdfc2674f04babdbfcd679c0ef22f7ab2a18818b9b425e61d8c06196a23babd0aefd5a00f1b297a66d973daae40f4dbd9be60d8953fafbd51f7745e2d04b5c80b63ad1f550cd939490b346d4fe7c1fc266d593bcafac0d8989994e174de6d1ef4ce78b3224ea4e68ccbf998654a067558537be332f5cae4b44c18664428d45b71cde5b53bedddf8a7daf47fce212578b72\ 7e420c91de0baa1108683dd5b5534e81f4fe945d27fd9d28934afc8d15d95932952c0be717d4d87bb8255bf658a083c3aed643f7a6cfb56fbcbdab9e0a7348b0a3a91e3d560d1ec96f5769551e64beb54a499f6d6dd37e4361d484fe4f7bac4dc26c8a1a2609592d527b134c8212d71b3578217e0ec1da317c69e7e8c39d2d5b2d4073fa9c618a01a092b61613f6f1e41e6ab43d8ca010f177947aeab2884e9a4dd28453ff5bdadb765680733e7af1463ec1b20b879ae01c9256da0207811f956b3950f6db743a9e34a6d8f0fdfa5c47b4f807f0017c2092d72dc19d111711e796ffc4035da3a4caa6a5301491d0473b0d47cd01b705ff11a10263867013a11c65462c311fa5ac9a2598142779b55f09dbec89ac18049c29e5baf3aa38696a3b92d08b02cb10af5389e06058b3ad8be09b121e4e320520413775b7c6fbb3f2b332e3ac0295a4a4dfb4a56ea1c32bc28c149ffaa3b426f5a17a11afe56426b38966c86734654fe05a611c8f025ee4092656c097bbf59743c31508fa9e80ff86a2ae33d401ec316e65eef251d173e9565ffc1672b8b341174427a851a6a4c42554848c637283d13d4ba5b5414b4e61ade6ec7ef7b77186a81adff381e6a79d3dac2c68bf386f100fef1c354221a2ba3d8a7a10460f637eaa152ab79027ab94e5965660de3ed66dac4a0f8e75b85d768e51c8e82a26cb81249ca8d249d8c5cdc8bd55289679d3915a397d31863334df18e2fe3ef9069b064c4ef6b418e5388817040ae9922e5e9f57a8bf3b3fe04748b9cf5068ac86f942b4068853602a6c6c794423569b665b359d5f947c2e5ff194d23d953b435b2b3834513fdfda2b66fcea22883690b1cc56c2fcaa5600895ff8d8ae9e3a6a2b6258ff873242d1128b20e7d1e843ade1bd206b541eba02a214a95cd83860865f947cb4adbd465957055060df05e53fa9ea4b29867c92b224be939d3715be0e61b7aa0e24a8f25bccfa3b7901a3f0a8cb25498d7c9899d435b409220723dcde1d38ab6d4e7cfb42d443c9b65a37\ 53891f46adb9bc52574699a7b642955702ed662d04cbe21aeec7c15db7e325dcaa74c85c5e3ed54424642d5bd8d3109c2d4c0079b3d2c5f2da12ad5b25407ae48f6fe4fc653b23a7f2d56a93c898dd0bd59ba02295934c9f7ffb433ef611d51b7c203f374cf9e8b69d4952ccc44593447ad41540270b0e30c349401048cbce10a0e1bae373de15c878982b0af837fb5432cd2471516d1e218296ce462a59fd5412921bbd3f75cf65070f7bafe21105ba83f7ffe8ece71534863c0dd731a2f3c29fff97b8ce798890a1b158a8891bb6f2dd751e75c0cb0db7ea152d7cdc91663f46f85d12ce0015351dba5225b2a87b64cc30518b23e31b2bfbb0b2a5042eeaea1234a57549a3e55ddd708e3380df032e93071b10b3e6902152c90ffd99bda0177a197779341307c5d9f335e698259ade70564eab9d2856aa1aa814211e71ba2885ef9cd5f5bdd225af2f6eebf775cc0bbdb3e519edb7c49a9a1984cc0cc012679aca8fd1d002fa64b2df095b4a9e2b496e3f4b544955c817efb29562cf8b3d2eeccbe4d364ce71d2d12b504b11de4747139ef505bdd12f382eb02fa3f5272b710644a9c20660ca5b4fa74be60984240b555c1f34261ee1d72d9eb2cc680f32b4603865503addc3a1fdc49d2b158d3407a282edd72ef51ad021338fdebf413726e1778e3bc3909b670d3f40e824391c5525b162ea01c29205e12f8e62bdd8cd0f21f6f7b44af4521c2dd23a7f3508e5dc6fffa3365e4ca1cac33bb515a5c5495dc059a94396de7d802758b65bb4cecb90bf69ab4126eab85958cb8b64eedf3a0955ab42cdc98ef90620e10cc854b9c02bfaff60742494a0c3bb34ef6d6bb861b275d975bdc4a10ac922dc70c1b03a4c01943a704af36ec8d79cf2f9ce0f602f01bef4a32edeb8fbba863c945552efc814410ac6bb839349ea65879644003bdda35d40eabdc9dcfb2d67d945b7f111ab62591763a0dd2d338594eff004237e5acce69dd9d2cdbb9ce121bd$5337e4ba9d877a1e84559688386fbc844c5fe557", "password1" }, {NULL} }; #ifdef SIMD_COEF_32 #define ALGORITHM_NAME "PBKDF2-SHA1 " SHA1_ALGORITHM_NAME #else #define ALGORITHM_NAME "PBKDF2-SHA1 32/" ARCH_BITS_STR #endif struct fmt_main fmt_openbsd_softraid = { { "OpenBSD-SoftRAID", // FORMAT_LABEL "", // FORMAT_NAME ALGORITHM_NAME, " (8192 iterations)", // BENCHMARK_COMMENT -1, // BENCHMARK_LENGTH 0, PLAINTEXT_LENGTH, sizeof(ARCH_WORD_32), //BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP, { "iteration count", }, tests_openbsdsoftraid }, { init, done, fmt_default_reset, fmt_default_prepare, valid, fmt_default_split, get_binary, get_salt, { iteration_count, }, fmt_default_source, { fmt_default_binary_hash }, fmt_default_salt_hash, NULL, set_salt, jtr_set_key, get_key, fmt_default_clear_keys, crypt_all, { fmt_default_get_hash }, cmp_all, cmp_one, cmp_exact } }; #endif
LAGraph_grread.c
//------------------------------------------------------------------------------ // LAGraph_grread: read a matrix from a binary file //------------------------------------------------------------------------------ /* LAGraph: graph algorithms based on GraphBLAS Copyright 2019 LAGraph Contributors. (see Contributors.txt for a full list of Contributors; see ContributionInstructions.txt for information on how you can Contribute to this project). All Rights Reserved. NO WARRANTY. THIS MATERIAL IS FURNISHED ON AN "AS-IS" BASIS. THE LAGRAPH CONTRIBUTORS MAKE NO WARRANTIES OF ANY KIND, EITHER EXPRESSED OR IMPLIED, AS TO ANY MATTER INCLUDING, BUT NOT LIMITED TO, WARRANTY OF FITNESS FOR PURPOSE OR MERCHANTABILITY, EXCLUSIVITY, OR RESULTS OBTAINED FROM USE OF THE MATERIAL. THE CONTRIBUTORS DO NOT MAKE ANY WARRANTY OF ANY KIND WITH RESPECT TO FREEDOM FROM PATENT, TRADEMARK, OR COPYRIGHT INFRINGEMENT. Released under a BSD license, please see the LICENSE file distributed with this Software or contact permission@sei.cmu.edu for full terms. Created, in part, with funding and support from the United States Government. (see Acknowledgments.txt file). This program includes and/or can make use of certain third party source code, object code, documentation and other files ("Third Party Software"). See LICENSE file for more details. */ //------------------------------------------------------------------------------ // LAGraph_grread: read a matrix from a binary file. // Contributed by Tim Davis, Texas A&M, based on the Galois graph reader // file format. // The file format consists of a header, with the following content: // uint64_t version : TODO what is this? // This value is returned to the caller, but is otherwise unused. // uint64_t esize : the size of the edge weight, as sizeof (edgetype). // For example, if the file contains edge weights of type int32_t, // esize is sizeof (int32_t) == 4. The caller must specify the // corresponding GrB_Type, and its size must match esize. // uint64_t n : the number of node in the graph. The GrB_Matrix is // n-by-n. Rectangular matrices are not supported by this format. // uint64_t e : the number of edges in the graph // This header is followed by a matrix in CSR format: // Gp : an array of size ((n+1) * sizeof (uint64_t)) bytes, but Cp [0] = 0 // does not appear in the file. This section of the file is thus // (n * sizeof (uint64_t)) bytes in length. // Gj : an array of size (e * sizeof (int32_t)), containing the adjaceny // lists. Note that the indices are 32 bit, not 64 bit, and thus // this format is limited to graphs with n < 2^32. // Gx : an array of size (e * esize), containing the edge weights. // LAgraph_grread returns its status: GrB_SUCCESS if succesful, // GrB_OUT_OF_MEMORY if out of memory, GrB_INVALID_VALUE if a file I/O error // occurs or the edge size is not what was expected. #include "LAGraph_internal.h" #include <fcntl.h> #include <sys/types.h> #include <sys/uio.h> #include <unistd.h> //------------------------------------------------------------------------------ // gr_header //------------------------------------------------------------------------------ // The gr_header specifies the first 4 * sizeof(uint64_t) bytes of the file. typedef struct { uint64_t version ; // TODO what is this? uint64_t esize ; // sizeof (edgetype) uint64_t n ; // # of nodes in the graph uint64_t e ; // # of edges in the graph } gr_header ; //------------------------------------------------------------------------------ // LAGraph_binary_read //------------------------------------------------------------------------------ // Read a block of binary data from a file. Returns GrB_SUCCESS if successful, // GrB_INVALID_VALUE otherwise. static GrB_Info LAGraph_binary_read ( int fd, // file descriptor to read from void *buffer, // buffer of size nbytes to read into size_t nbytes // # of bytes to read ) { if (fd < 0) { fprintf (stderr, "LAGraph_grread: file I/O error\n") ; return (GrB_INVALID_VALUE) ; } if (read (fd, buffer, nbytes) != nbytes) { fprintf (stderr, "LAGraph_grread: file I/O error\n") ; return (GrB_INVALID_VALUE) ; } return (GrB_SUCCESS) ; } //------------------------------------------------------------------------------ // LAGRAPH_FREE_ALL //------------------------------------------------------------------------------ // Free all allocated space; used only for error return. #define LAGRAPH_FREE_ALL \ { \ GrB_free (G) ; \ LAGRAPH_FREE (Gp) ; \ LAGRAPH_FREE (Gj) ; \ LAGRAPH_FREE (Gj_32) ; \ LAGRAPH_FREE (Gx) ; \ if (fd >= 0) close (fd) ; \ } //------------------------------------------------------------------------------ // LAGraph_grread //------------------------------------------------------------------------------ GrB_Info LAGraph_grread // read a matrix from a binary file ( GrB_Matrix *G, // handle of matrix to create uint64_t *G_version, // the version in the file const char *filename, // name of file to open GrB_Type gtype // type of matrix to read, NULL if no edge weights // (in that case, G has type GrB_BOOL with all // edge weights equal to 1). ) { //-------------------------------------------------------------------------- // check inputs //-------------------------------------------------------------------------- GrB_Info info ; GrB_Index *Gp = NULL ; int32_t *Gj_32 = NULL ; GrB_Index *Gj = NULL ; void *Gx = NULL ; int fd = -1 ; if (G == NULL || G_version == NULL || filename == NULL) { LAGRAPH_ERROR ("invalid input arguments", GrB_NULL_POINTER) ; } (*G) = NULL ; (*G_version) = 0 ; //-------------------------------------------------------------------------- // open the file //-------------------------------------------------------------------------- fd = open (filename, O_RDONLY) ; if (fd < 0) { fprintf (stderr, "LAGraph_grread: file not found: %s\n", filename) ; LAGRAPH_ERROR ("input file not found", GrB_INVALID_VALUE) ; } //-------------------------------------------------------------------------- // open the file and read the gr_header //-------------------------------------------------------------------------- gr_header header ; LAGRAPH_OK (LAGraph_binary_read (fd, &header, sizeof (gr_header))) ; (*G_version) = header.version ; // version, TODO: what is this? uint64_t esize = header.esize ; // sizeof (edge type) uint64_t n = header.n ; // # of nodes uint64_t e = header.e ; // # of edges size_t esize_expected = 0 ; if (gtype != NULL) { LAGRAPH_OK (GxB_Type_size (&esize_expected, gtype)) ; } if (esize != esize_expected) { fprintf (stderr, "LAGraph_grread: esize in file (%g) does not match" " gtype size (%g)\n", (double) esize, (double) esize_expected) ; LAGRAPH_ERROR ("unexpected edge size", GrB_INVALID_VALUE) ; } if (n > UINT32_MAX) { LAGRAPH_ERROR ("problem too large", GrB_INVALID_VALUE) ; } //-------------------------------------------------------------------------- // allocate and read in the pointers //-------------------------------------------------------------------------- Gp = LAGraph_malloc (n+1, sizeof (GrB_Index)) ; if (Gp == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } Gp [0] = 0 ; LAGRAPH_OK (LAGraph_binary_read (fd, Gp+1, n * sizeof (GrB_Index))) ; //-------------------------------------------------------------------------- // allocate and read in the indices //-------------------------------------------------------------------------- Gj = LAGraph_malloc (e, sizeof (GrB_Index)) ; Gj_32 = LAGraph_malloc (e, sizeof (int32_t)) ; if (Gj_32 == NULL || Gj == NULL) { LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; } // indices are in 32-bit format in the file LAGRAPH_OK (LAGraph_binary_read (fd, Gj_32, e * sizeof (int32_t))) ; // convert to 64-bit #pragma omp parallel for schedule(static) for (GrB_Index p = 0 ; p < e ; p++) { Gj [p] = (GrB_Index) Gj_32 [p] ; } LAGRAPH_FREE (Gj_32) ; //-------------------------------------------------------------------------- // read in the values //-------------------------------------------------------------------------- bool no_edge_weights = (gtype == NULL) ; if (no_edge_weights) { // the input file has no edge weights gtype = GrB_BOOL ; esize = sizeof (bool) ; } Gx = LAGraph_malloc (e, esize) ; if (Gx == NULL) LAGRAPH_ERROR ("out of memory", GrB_OUT_OF_MEMORY) ; if (no_edge_weights) { // set all edge weights to boolean true bool *Gbool = (bool *) Gx ; #pragma omp parallel for schedule(static) for (GrB_Index p = 0 ; p < e ; p++) { Gbool [p] = true ; } } else { // read in the edge weights LAGRAPH_OK (LAGraph_binary_read (fd, Gx, e * esize)) ; } //-------------------------------------------------------------------------- // import the data into the GrB_Matrix //-------------------------------------------------------------------------- LAGRAPH_OK (GxB_Matrix_import_CSR (G, gtype, n, n, e, -1, &Gp, &Gj, &Gx, NULL)) ; //-------------------------------------------------------------------------- // close the file and return result //-------------------------------------------------------------------------- close (fd) ; return (GrB_SUCCESS) ; }
backend.c
/* Copyright 2013 Samsung R&D Institute Russia 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. */ /*! @file backend.c * @brief FFTF backends engine implementation. * @author Markovtsev Vadim <v.markovtsev@samsung.com> * @version 1.0 * * @section Notes * This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>. * * @section Copyright * Copyright 2013 Samsung R&D Institute Russia */ #include "src/backend.h" #include <assert.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <sys/types.h> #include <unistd.h> #include "src/engine_kiss.h" #include "src/engine_ooura.h" #include "src/engine_libav.h" #ifndef __arm__ #include "src/engine_ipp.h" #include "src/engine_mkl.h" #endif #ifdef GPL #include "src/engine_fftw3.h" #endif #ifdef OPENCL #include "src/engine_appml.h" #include "src/engine_viennacl.h" #endif #ifdef CUDA #include "src/engine_cufft.h" #endif #ifndef strdup char *strdup(const char *str) { int n = strlen(str) + 1; char *dup = malloc(n); if (dup) { strcpy(dup, str); } return dup; } #endif #define BACKEND_INIT(id, lib) \ { id, lib, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, \ NULL, NULL, NULL } Backend Backends[FFTF_COUNT_BACKENDS] = { { FFTF_BACKEND_KISS, NULL, 0, NULL, NULL, init_kiss, NULL, calc_kiss, NULL, destroy_kiss, NULL, malloc_kiss, free_kiss, NULL, NULL }, { FFTF_BACKEND_OOURA, NULL, 1, NULL, NULL, init_ooura, NULL, calc_ooura, NULL, destroy_ooura, NULL, NULL, NULL, NULL, NULL }, #ifdef GPL { FFTF_BACKEND_FFTW3, "libfftw3f.so.3", 0, load_fftw3, unload_fftw3, init_fftw3, NULL, calc_fftw3, NULL, destroy_fftw3, NULL, malloc_fftw3, free_fftw3, NULL, NULL }, #endif { FFTF_BACKEND_LIBAV, "libavcodec.so.53", 1, load_libav, unload_libav, init_libav, NULL, calc_libav, NULL, destroy_libav, NULL, malloc_libav, free_libav, NULL, NULL }, #ifndef __arm__ { FFTF_BACKEND_IMKL, "libmkl_rt.so", 1, load_mkl, unload_mkl, init_mkl, NULL, calc_mkl, NULL, destroy_mkl, NULL, malloc_mkl, free_mkl, NULL, NULL }, { FFTF_BACKEND_IIPP, "libipps.so", 1, load_ipp, unload_ipp, init_ipp, NULL, calc_ipp, NULL, destroy_ipp, NULL, malloc_ipp, free_ipp, NULL, NULL }, #endif #ifdef CUDA { FFTF_BACKEND_CUFFT, "libcufft.so", 0, load_cufft, unload_cufft, NULL, init_many_cufft, NULL, calc_many_cufft, NULL, destroy_many_cufft, NULL, NULL, NULL, NULL }, #endif #ifdef OPENCL { FFTF_BACKEND_APPML, "libclAmdFft.Runtime.so", 0, load_appml, unload_appml, NULL, init_many_appml, NULL, calc_many_appml, NULL, destroy_many_appml, NULL, NULL, NULL, NULL }, { FFTF_BACKEND_VIENNACL, NULL, 1, NULL, NULL, NULL, init_many_viennacl, NULL, calc_many_viennacl, NULL, destroy_many_viennacl, NULL, NULL, NULL, NULL }, #endif }; const char **BackendAdditionalPaths = NULL; FFTFBackend BackendAdditionalLibs[FFTF_COUNT_BACKENDS] = { { FFTF_BACKEND_KISS, NULL}, { FFTF_BACKEND_OOURA, NULL}, #ifdef GPL { FFTF_BACKEND_FFTW3, NULL}, #endif { FFTF_BACKEND_LIBAV, NULL}, #ifndef __arm__ { FFTF_BACKEND_IMKL, NULL}, { FFTF_BACKEND_IIPP, NULL}, #endif #ifdef CUDA { FFTF_BACKEND_CUFFT, NULL}, #endif #ifdef OPENCL { FFTF_BACKEND_APPML, NULL}, { FFTF_BACKEND_VIENNACL,NULL} #endif }; int InstancesCount = 0; pthread_mutex_t InstancesMutex = PTHREAD_MUTEX_INITIALIZER; static void unload_backend(FFTFBackend *lib) { pthread_mutex_lock(&InstancesMutex); assert(Backends[lib->id].unload != NULL); Backends[lib->id].unload(Backends[lib->id].internalData); bzero(&Backends[lib->id].libraryCurrentPath, offsetof(Backend, internalData) - offsetof(Backend, libraryCurrentPath)); pthread_mutex_unlock(&InstancesMutex); } static int load_backend_internal(FFTFBackendId id, const char *path, int trial) { assert(Backends[id].load != NULL); pthread_mutex_lock(&InstancesMutex); int res = Backends[id].load(path, &Backends[id].internalData, trial); if (res) { Backends[id].libraryCurrentPath = path; } pthread_mutex_unlock(&InstancesMutex); return res; } FFTF_SET_BACKEND_RESULT load_backend(FFTFBackend *lib, int trial) { assert(lib != NULL); // These are built-in if (lib->id == FFTF_BACKEND_KISS || lib->id == FFTF_BACKEND_OOURA #ifdef OPENCL || lib->id == FFTF_BACKEND_VIENNACL #endif ) { return FFTF_SET_BACKEND_SUCCESS; } assert(Backends[lib->id].load != NULL); // Unload the previous library if (Backends[lib->id].libraryCurrentPath != NULL) { unload_backend(lib); } int loaded = 0; lib->path = NULL; if (BackendAdditionalLibs[lib->id].path != NULL) { if (load_backend_internal(lib->id, BackendAdditionalLibs[lib->id].path, trial)) { loaded = 1; } } if (!loaded && BackendAdditionalPaths != NULL) { for (int i = 0; BackendAdditionalPaths[i] != NULL; i++) { char libpath[strlen(BackendAdditionalPaths[i]) + strlen(Backends[lib->id].libraryDefaultPath) + 2]; snprintf(libpath, sizeof(libpath), "%s/%s", BackendAdditionalPaths[i], Backends[lib->id].libraryDefaultPath); if (load_backend_internal(lib->id, libpath, trial)) { loaded = 1; break; } } } if (!loaded) { if (!load_backend_internal(lib->id, Backends[lib->id].libraryDefaultPath, trial)) { if (BackendAdditionalPaths == NULL && BackendAdditionalLibs[lib->id].path == NULL) { void *handle = dlopen(Backends[lib->id].libraryDefaultPath, RTLD_NOW); if (handle == NULL) { return FFTF_SET_BACKEND_NO_LIBS_FOUND; } dlclose(handle); } return FFTF_SET_BACKEND_FAILED_TO_LOAD; } } lib->path = Backends[lib->id].libraryCurrentPath; return FFTF_SET_BACKEND_SUCCESS; } static void copy_paths_and_libs(const char *const *additionalPaths, const FFTFBackend *additionalLibs) { // free() old paths if (BackendAdditionalPaths != NULL) { for (int i = 0; BackendAdditionalPaths[i] != NULL; i++) { free((char *)BackendAdditionalPaths[i]); } free(BackendAdditionalPaths); } // copy new paths if (additionalPaths != NULL) { int i; for (i = 1; additionalPaths[i] != NULL; i++); BackendAdditionalPaths = malloc(sizeof(const char *) * (i + 1)); for (i = 0; additionalPaths[i] != NULL; i++) { BackendAdditionalPaths[i] = strdup(additionalPaths[i]); } BackendAdditionalPaths[i] = NULL; } else { BackendAdditionalPaths = NULL; } // copy new libs if (additionalLibs != NULL) { int i; for (i = 0; additionalLibs[i].id != FFTF_BACKEND_NONE; i++) { assert(additionalLibs[i].path != NULL); if (BackendAdditionalLibs[additionalLibs[i].id].path != NULL) { free((char *)BackendAdditionalLibs[additionalLibs[i].id].path); } BackendAdditionalLibs[additionalLibs[i].id].path = strdup(additionalLibs[i].path); } } } void scan_backends(FFTFBackend *libs, const char *const *additionalPaths, const FFTFBackend *additionalLibs) { pthread_mutex_lock(&InstancesMutex); // Do not let the backends reloading invalidate any existing FFTF instances assert(InstancesCount == 0); pthread_mutex_unlock(&InstancesMutex); copy_paths_and_libs(additionalPaths, additionalLibs); for (int i = FFTF_BACKEND_NONE + 1; i < FFTF_COUNT_BACKENDS; i++) { // TODO: implement all backends and remove this check if (Backends[i].load == NULL) continue; load_backend(&libs[i], 1); } } void free_backends(FFTFBackend *libs) { for (int i = FFTF_BACKEND_NONE + 1; i < FFTF_COUNT_BACKENDS; i++) { // TODO: implement all backends and remove this check if (Backends[i].load == NULL) continue; if (Backends[i].libraryCurrentPath != NULL) { unload_backend(&libs[i]); } } } #define FFTF_SINGLE_INSTANCE(instance, i) { \ instance->id, \ instance->internalData[i], \ instance->type, \ instance->direction, \ instance->dimension, \ instance->options, \ instance->lengths, \ instance->lengths[0], \ instance->inputs[i], \ instance->outputs[i] } FFTFInstance *backend_init(FFTFBackendId id, FFTFType type, FFTFDirection direction, FFTFDimension dimension, const int *lengths, FFTFOptions options, int batchSize, const float *const *inputs, float *const *outputs) { assert((!Backends[id].only1d || dimension == FFTF_DIMENSION_1D) && "Not implemented"); pthread_mutex_lock(&InstancesMutex); FFTFInstance *instance = malloc(sizeof(FFTFInstance)); instance->id = id; size_t ptr_table_size = sizeof(void *) * batchSize; instance->internalData = NULL; instance->batchSize = batchSize; instance->inputs = malloc(ptr_table_size); memcpy((const float **)instance->inputs, inputs, ptr_table_size); size_t lengths_size = sizeof(*lengths) * dimension; instance->lengths = malloc(lengths_size); memcpy((int *)instance->lengths, lengths, lengths_size); instance->direction = direction; instance->options = options; instance->outputs = malloc(ptr_table_size); memcpy((const float **)instance->outputs, outputs, ptr_table_size); instance->type = type; instance->dimension = dimension; assert(pthread_mutex_init(&instance->lock, NULL) == 0); if (Backends[id].init == NULL) { assert(Backends[id].calc == NULL); assert(Backends[id].init_many != NULL); assert(Backends[id].calc_many != NULL); Backends[id].init_many(Backends[id].internalData, instance); } else { instance->internalData = malloc(ptr_table_size); bzero(instance->internalData, ptr_table_size); if (batchSize == 1) { FFTFSingleInstance si = FFTF_SINGLE_INSTANCE(instance, 0); Backends[id].init(Backends[id].internalData, &si); instance->internalData[0] = si.internalData; } else { for (int i = 0; i < batchSize; i++) { FFTFSingleInstance si = FFTF_SINGLE_INSTANCE(instance, i); Backends[id].init(Backends[id].internalData, &si); instance->internalData[i] = si.internalData; } } } InstancesCount++; pthread_mutex_unlock(&InstancesMutex); return instance; } void backend_calc(const FFTFInstance *instance) { pthread_mutex_lock((pthread_mutex_t *)&instance->lock); assert(instance->id != FFTF_BACKEND_NONE); if (Backends[instance->id].calc == NULL) { assert(Backends[instance->id].calc_many != NULL); Backends[instance->id].calc_many(Backends[instance->id].internalData, instance); } else if (instance->batchSize == 1) { FFTFSingleInstance si = FFTF_SINGLE_INSTANCE(instance, 0); Backends[instance->id].calc(Backends[instance->id].internalData, &si); } else { #pragma omp parallel for num_threads(fftf_get_openmp_num_threads()) for (int i = 0; i < instance->batchSize; i++) { FFTFSingleInstance si = FFTF_SINGLE_INSTANCE(instance, i); Backends[instance->id].calc(Backends[instance->id].internalData, &si); } } pthread_mutex_unlock((pthread_mutex_t *)&instance->lock); } void backend_destroy(FFTFInstance *instance) { pthread_mutex_lock(&InstancesMutex); pthread_mutex_lock(&instance->lock); assert(instance->id != FFTF_BACKEND_NONE); if (Backends[instance->id].destroy != NULL) { assert(Backends[instance->id].destroy_many == NULL); for (int i = 0; i < instance->batchSize; i++) { FFTFSingleInstance si = FFTF_SINGLE_INSTANCE(instance, i); Backends[instance->id].destroy(Backends[instance->id].internalData, &si); } } else { assert(Backends[instance->id].destroy_many != NULL); Backends[instance->id].destroy_many(Backends[instance->id].internalData, instance); } if (Backends[instance->id].init != NULL) { free(instance->internalData); } free((const float **)instance->inputs); free((const float **)instance->outputs); free((int *)instance->lengths); instance->id = FFTF_BACKEND_NONE; pthread_mutex_unlock(&instance->lock); // Give a chance for any pending fftf_calc() to assert. sched_yield(); pthread_mutex_destroy(&instance->lock); free(instance); InstancesCount--; pthread_mutex_unlock(&InstancesMutex); } void *backend_malloc(FFTFBackendId id, size_t size) { if (Backends[id].malloc != NULL) { return Backends[id].malloc(Backends[id].internalData, size); } return malloc(size); } void backend_free(FFTFBackendId id, void *ptr) { if (Backends[id].free != NULL) { Backends[id].free(Backends[id].internalData, ptr); } else { free(ptr); } } void copy_input_to_output(const FFTFSingleInstance *instance) { if (instance->output != instance->input) { int length = 0; for (int i = 0; i < (int)instance->dimension; i++) { length += instance->lengths[i]; } size_t size = length * sizeof(float) * (instance->type == FFTF_TYPE_COMPLEX? 2 : 1); memcpy(instance->output, instance->input, size); } }
040_distributed_array.c
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <omp.h> #define NR_DIMS 2 int main(int argc, char *argv[]) { const int periodic[NR_DIMS] = {0, 0}; const int reorder = 0; const int local_rows = 300, local_cols = 400; int proc_rows, proc_cols; int row, col; int rank, size; int dims[NR_DIMS] = {0, 0}; int cart_coords[NR_DIMS]; double sum = 0.0, avg; double *data; int data_size = local_rows*local_cols*sizeof(double); MPI_Comm cart_comm; MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Dims_create(size, NR_DIMS, dims); MPI_Cart_create(MPI_COMM_WORLD, NR_DIMS, dims, periodic, reorder, &cart_comm); if (!(data = (double *) malloc(data_size))) { fprintf(stderr, "### error: rank %d can't allocate memory\n", rank); MPI_Abort(MPI_COMM_WORLD, 1); } MPI_Cart_coords(cart_comm, rank, NR_DIMS, cart_coords); fprintf(stderr, "rank %d: (%d, %d)\n", rank, cart_coords[0], cart_coords[1]); srand(rank); for (row = 0; row < local_rows; row++) for (col = 0; col < local_cols; col++) data[row*local_cols + col] = ((double) rand())/RAND_MAX; #pragma omp parallel { int thread_num = omp_get_thread_num(); printf("rank %d:%d has %d threads\n", rank, thread_num, omp_get_num_threads()); #pragma omp for reduction(+:sum) for (row = 0; row < local_rows; row++) { int col; for (col = 0; col < local_cols; col++) sum += data[row*local_cols + col]; } } MPI_Reduce(&sum, &avg, 1, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD); if (rank == 0) printf("average = %le\n", avg); free(data); MPI_Finalize(); return 0; }
lister.c
/* * `Restless reachability in temporal graphs: algebraic methods and applications` * * This experimental source code is supplied to accompany the * aforementioned paper. * * The source code is configured for a gcc build to a native * microarchitecture that must support the AVX2 and PCLMULQDQ * instruction set extensions. Other builds are possible but * require manual configuration of 'Makefile' and 'builds.h'. * * The source code is subject to the following license. * * The MIT License (MIT) * * Copyright (c) 2020 Anonymous authors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<time.h> #include<sys/utsname.h> #include<string.h> #include<stdarg.h> #include<assert.h> #include<ctype.h> #include<omp.h> /************************************************************* Configuration. */ #define MAX_K 32 #define MAX_SHADES 32 #define PREFETCH_PAD 32 #define MAX_THREADS 128 #define UNDEFINED -1 #define MATH_INF ((index_t)0x3FFFFFFF) #include"builds.h" // get build config typedef long int index_t; // default to 64-bit indexing #include"gf.h" // finite fields #include"ffprng.h" // fast-forward pseudorandom number generator #define MIN(x,y) (x)<(y) ? (x) : (y) #define MAX(x,y) (x)>(y) ? (x) : (y) /********************************************************************* Flags. */ /************************************************************* Common macros. */ /* Linked list navigation macros. */ #define pnlinknext(to,el) { (el)->next = (to)->next; (el)->prev = (to); (to)->next->prev = (el); (to)->next = (el); } #define pnlinkprev(to,el) { (el)->prev = (to)->prev; (el)->next = (to); (to)->prev->next = (el); (to)->prev = (el); } #define pnunlink(el) { (el)->next->prev = (el)->prev; (el)->prev->next = (el)->next; } #define pnrelink(el) { (el)->next->prev = (el); (el)->prev->next = (el); } /*********************************************************** Error reporting. */ #define ERROR(...) error(__FILE__,__LINE__,__func__,__VA_ARGS__); static void error(const char *fn, int line, const char *func, const char *format, ...) { va_list args; va_start(args, format); fprintf(stderr, "ERROR [file = %s, line = %d]\n" "%s: ", fn, line, func); vfprintf(stderr, format, args); fprintf(stderr, "\n"); va_end(args); abort(); } /********************************************************* Get the host name. */ #define MAX_HOSTNAME 256 const char *sysdep_hostname(void) { static char hn[MAX_HOSTNAME]; struct utsname undata; uname(&undata); strcpy(hn, undata.nodename); return hn; } /********************************************************* Available threads. */ index_t num_threads(void) { #ifdef BUILD_PARALLEL return omp_get_max_threads(); #else return 1; #endif } /********************************************** Memory allocation & tracking. */ #define MALLOC(x) malloc_wrapper(x) #define FREE(x) free_wrapper(x) index_t malloc_balance = 0; struct malloc_track_struct { void *p; size_t size; struct malloc_track_struct *prev; struct malloc_track_struct *next; }; typedef struct malloc_track_struct malloc_track_t; malloc_track_t malloc_track_root; size_t malloc_total = 0; #define MEMTRACK_STACK_CAPACITY 256 size_t memtrack_stack[MEMTRACK_STACK_CAPACITY]; index_t memtrack_stack_top = -1; void *malloc_wrapper(size_t size) { if(malloc_balance == 0) { malloc_track_root.prev = &malloc_track_root; malloc_track_root.next = &malloc_track_root; } void *p = malloc(size); if(p == NULL) ERROR("malloc fails"); malloc_balance++; malloc_track_t *t = (malloc_track_t *) malloc(sizeof(malloc_track_t)); t->p = p; t->size = size; pnlinkprev(&malloc_track_root, t); malloc_total += size; for(index_t i = 0; i <= memtrack_stack_top; i++) if(memtrack_stack[i] < malloc_total) memtrack_stack[i] = malloc_total; return p; } void free_wrapper(void *p) { malloc_track_t *t = malloc_track_root.next; for(; t != &malloc_track_root; t = t->next) { if(t->p == p) break; } if(t == &malloc_track_root) ERROR("FREE issued on a non-tracked pointer %p", p); malloc_total -= t->size; pnunlink(t); free(t); free(p); malloc_balance--; } index_t *alloc_idxtab(index_t n) { index_t *t = (index_t *) MALLOC(sizeof(index_t)*n); return t; } void push_memtrack(void) { assert(memtrack_stack_top + 1 < MEMTRACK_STACK_CAPACITY); memtrack_stack[++memtrack_stack_top] = malloc_total; } size_t pop_memtrack(void) { assert(memtrack_stack_top >= 0); return memtrack_stack[memtrack_stack_top--]; } size_t current_mem(void) { return malloc_total; } double inGiB(size_t s) { return (double) s / (1 << 30); } void print_current_mem(void) { fprintf(stdout, "{curr: %.2lfGiB}", inGiB(current_mem())); fflush(stdout); } void print_pop_memtrack(void) { fprintf(stdout, "{peak: %.2lfGiB}", inGiB(pop_memtrack())); fflush(stdout); } /******************************************************** Timing subroutines. */ #define TIME_STACK_CAPACITY 256 double start_stack[TIME_STACK_CAPACITY]; index_t start_stack_top = -1; void push_time(void) { assert(start_stack_top + 1 < TIME_STACK_CAPACITY); start_stack[++start_stack_top] = omp_get_wtime(); } double pop_time(void) { double wstop = omp_get_wtime(); assert(start_stack_top >= 0); double wstart = start_stack[start_stack_top--]; return (double) (1000.0*(wstop-wstart)); } /******************************************************************* Sorting. */ void shellsort(index_t n, index_t *a) { index_t h = 1; index_t i; for(i = n/3; h < i; h = 3*h+1) ; do { for(i = h; i < n; i++) { index_t v = a[i]; index_t j = i; do { index_t t = a[j-h]; if(t <= v) break; a[j] = t; j -= h; } while(j >= h); a[j] = v; } h /= 3; } while(h > 0); } #define LEFT(x) (x<<1) #define RIGHT(x) ((x<<1)+1) #define PARENT(x) (x>>1) void heapsort_indext(index_t n, index_t *a) { /* Shift index origin from 0 to 1 for convenience. */ a--; /* Build heap */ for(index_t i = 2; i <= n; i++) { index_t x = i; while(x > 1) { index_t y = PARENT(x); if(a[x] <= a[y]) { /* heap property ok */ break; } /* Exchange a[x] and a[y] to enforce heap property */ index_t t = a[x]; a[x] = a[y]; a[y] = t; x = y; } } /* Repeat delete max and insert */ for(index_t i = n; i > 1; i--) { index_t t = a[i]; /* Delete max */ a[i] = a[1]; /* Insert t */ index_t x = 1; index_t y, z; while((y = LEFT(x)) < i) { z = RIGHT(x); if(z < i && a[y] < a[z]) { index_t s = z; z = y; y = s; } /* Invariant: a[y] >= a[z] */ if(t >= a[y]) { /* ok to insert here without violating heap property */ break; } /* Move a[y] up the heap */ a[x] = a[y]; x = y; } /* Insert here */ a[x] = t; } } /*************************************************** Random numbers and such. */ index_t irand(void) { return (((index_t) rand())<<31)^((index_t) rand()); } /***************************************************** (Parallel) prefix sum. */ index_t prefixsum(index_t n, index_t *a, index_t k) { #ifdef BUILD_PARALLEL index_t s[MAX_THREADS]; index_t nt = num_threads(); assert(nt < MAX_THREADS); index_t length = n; index_t block_size = length/nt; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t tsum = (stop-start+1)*k; for(index_t u = start; u <= stop; u++) tsum += a[u]; s[t] = tsum; } index_t run = 0; for(index_t t = 1; t <= nt; t++) { index_t v = s[t-1]; s[t-1] = run; run += v; } s[nt] = run; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t trun = s[t]; for(index_t u = start; u <= stop; u++) { index_t tv = a[u]; a[u] = trun; trun += tv + k; } assert(trun == s[t+1]); } #else index_t run = 0; for(index_t u = 0; u < n; u++) { index_t tv = a[u]; a[u] = run; run += tv + k; } #endif return run; } /************************************************************* Parallel sum. */ index_t parallelsum(index_t n, index_t *a) { index_t sum = 0; #ifdef BUILD_PARALLEL index_t s[MAX_THREADS]; index_t nt = num_threads(); assert(nt < MAX_THREADS); index_t length = n; index_t block_size = length/nt; #pragma omp parallel for for(index_t t = 0; t < nt; t++) { index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); index_t tsum = 0; for(index_t u = start; u <= stop; u++) tsum += a[u]; s[t] = tsum; } for(index_t t = 0; t < nt; t++) sum += s[t]; #else for(index_t i = 0; i < n; i++) { sum += a[i]; } #endif return sum; } // count number of non-zero values in an array index_t parallelcount(index_t n, index_t *a) { index_t total_cnt = 0; #ifdef BUILD_PARALLEL index_t nt = num_threads(); index_t block_size = n/nt; index_t *cnt_nt = alloc_idxtab(nt); #pragma omp parallel for for(index_t th = 0; th <nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); index_t cnt = 0; for(index_t i = start; i <= stop; i++) cnt += (a[i] ? 1 : 0); cnt_nt[th] = cnt; } for(index_t th = 0; th < nt; th++) total_cnt += cnt_nt[th]; #else for(index_t i = 0; i < n; i++) total_cnt += (a[i] ? 1 : 0); #endif return total_cnt; } /************************ Search for an interval of values in a sorted array. */ index_t get_interval(index_t n, index_t *a, index_t lo_val, index_t hi_val, index_t *iv_start, index_t *iv_end) { assert(n >= 0); if(n == 0) { *iv_start = 0; return 0; } assert(lo_val <= hi_val); // find first element in interval (if any) with binary search index_t lo = 0; index_t hi = n-1; // at or above lo, and at or below hi (if any) while(lo < hi) { index_t mid = (lo+hi)/2; // lo <= mid < hi index_t v = a[mid]; if(hi_val < v) { hi = mid-1; // at or below hi (if any) } else { if(v < lo_val) lo = mid+1; // at or above lo (if any), lo <= hi else hi = mid; // at or below hi (exists) } // 0 <= lo <= n-1 } if(a[lo] < lo_val || a[lo] > hi_val) { // array contains no values in interval if(a[lo] < lo_val) { lo++; assert(lo == n || a[lo+1] > hi_val); } else { assert(lo == 0 || a[lo-1] < lo_val); } *iv_start = lo; *iv_end = hi; return 0; } assert(lo_val <= a[lo] && a[lo] <= hi_val); *iv_start = lo; // find interval end (last index in interval) with binary search lo = 0; hi = n-1; // last index (if any) is at or above lo, and at or below hi while(lo < hi) { index_t mid = (lo+hi+1)/2; // lo < mid <= hi index_t v = a[mid]; if(hi_val < v) { hi = mid-1; // at or below hi, lo <= hi } else { if(v < lo_val) lo = mid+1; // at or above lo else lo = mid; // at or above lo, lo <= hi } } assert(lo == hi); *iv_end = lo; // lo == hi return 1+*iv_end-*iv_start; // return cut size } /******************************************************************** Stack. */ typedef struct stack_node { index_t u; index_t l; index_t t; } stack_node_t; typedef struct stack { index_t size; // size of stack index_t n; // number of elements stack_node_t *a; }stk_t; stk_t * stack_alloc(index_t size) { stk_t *s = (stk_t *) malloc(sizeof(stk_t)); s->size = size; s->n = 0; s->a = (stack_node_t *) malloc(s->size*sizeof(stack_node_t)); #ifdef DEBUG for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; e->u = UNDEFINED; e->l = UNDEFINED; e->t = UNDEFINED; } #endif return s; } void stack_free(stk_t *s) { free(s->a); free(s); } void stack_push(stk_t *s, stack_node_t *e_in) { assert(s->n < s->size); stack_node_t *e = s->a + s->n; e->u = e_in->u; e->l = e_in->l; e->t = e_in->t; s->n++; } void stack_pop(stk_t *s, stack_node_t *e_out) { assert(s->n > 0); s->n--; stack_node_t *e = s->a + s->n; e_out->u = e->u; e_out->l = e->l; e_out->t = e->t; #ifdef DEBUG e->u = UNDEFINED; e->l = UNDEFINED; e->t = UNDEFINED; #endif } void stack_top(stk_t *s, stack_node_t *e_out) { assert(s->n >= 0); stack_node_t *e = s->a + s->n-1; e_out->u = e->u; e_out->l = e->l; e_out->t = e->t; } void stack_empty(stk_t *s) { s->n = 0; } void stack_get_vertices(stk_t *s, index_t *uu) { for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; uu[i] = e->u; } } void stack_get_timestamps(stk_t *s, index_t *tt) { for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; tt[i] = e->t; } } #ifdef DEBUG void print_stack(stk_t *s) { fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "print stack\n"); fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "size: %ld\n", s->size); fprintf(stdout, "n: %ld\n", s->n); fprintf(stdout, "a: "); for(index_t i = 0; i < s->n; i++) { stack_node_t *e = s->a + i; fprintf(stdout, "[%ld, %ld, %ld]%s", e->u, e->l, e->t, (i==s->n-1)?"\n":" "); } fprintf(stdout, "-----------------------------------------------\n"); } void print_stacknode(stack_node_t *e) { fprintf(stdout, "print stack-node: [%ld, %ld, %ld]\n", e->u, e->l, e->t); } #endif /****************************************************************** Sieving. */ long long int num_muls; long long int trans_bytes; #define SHADE_LINES ((MAX_SHADES+SCALARS_IN_LINE-1)/SCALARS_IN_LINE) typedef unsigned int shade_map_t; void constrained_sieve_pre(index_t n, index_t k, index_t g, index_t pfx, index_t num_shades, shade_map_t *d_s, ffprng_scalar_t seed, line_array_t *d_x) { assert(g == SCALARS_IN_LINE); assert(num_shades <= MAX_SHADES); line_t wdj[SHADE_LINES*MAX_K]; ffprng_t base; FFPRNG_INIT(base, seed); for(index_t j = 0; j < k; j++) { for(index_t dl = 0; dl < SHADE_LINES; dl++) { index_t jsdl = j*SHADE_LINES+dl; LINE_SET_ZERO(wdj[jsdl]); for(index_t a = 0; a < SCALARS_IN_LINE; a++) { ffprng_scalar_t rnd; FFPRNG_RAND(rnd, base); scalar_t rs = (scalar_t) rnd; LINE_STORE_SCALAR(wdj[jsdl], a, rs); // W: [cached] } } } index_t nt = num_threads(); index_t length = n; index_t block_size = length/nt; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { ffprng_t gen; index_t start = t*block_size; index_t stop = (t == nt-1) ? length-1 : (start+block_size-1); FFPRNG_FWD(gen, SHADE_LINES*SCALARS_IN_LINE*start, base); line_t vd[SHADE_LINES]; for(index_t j = 0; j < SHADE_LINES; j++) { LINE_SET_ZERO(vd[j]); // to cure an annoying compiler warning } for(index_t u = start; u <= stop; u++) { scalar_t uu[MAX_K]; shade_map_t shades_u = d_s[u]; // R: n shade_map_t for(index_t dl = 0; dl < SHADE_LINES; dl++) { for(index_t a = 0; a < SCALARS_IN_LINE; a++) { index_t d = dl*SCALARS_IN_LINE + a; ffprng_scalar_t rnd; FFPRNG_RAND(rnd, gen); scalar_t rs = (scalar_t) rnd; rs = rs & (-((scalar_t)((shades_u >> d)&(d < num_shades)))); LINE_STORE_SCALAR(vd[dl], a, rs); // W: [cached] } } for(index_t j = 0; j < k; j++) { scalar_t uj; SCALAR_SET_ZERO(uj); for(index_t dl = 0; dl < SHADE_LINES; dl++) { index_t jsdl = j*SHADE_LINES+dl; line_t ln; LINE_MUL(ln, wdj[jsdl], vd[dl]); // R: [cached] // MUL: n*SHADE_LINES*g*k scalar_t lns; LINE_SUM(lns, ln); SCALAR_ADD(uj, uj, lns); } uu[j] = uj; } line_t ln; LINE_SET_ZERO(ln); for(index_t a = 0; a < SCALARS_IN_LINE; a++) { index_t ap = a < (1L << k) ? pfx+a : 0; scalar_t xua; SCALAR_SET_ZERO(xua); for(index_t j = 0; j < k; j++) { scalar_t z_uj = uu[j]; // R: [cached] z_uj = z_uj & (-((scalar_t)(((ap) >> j)&1))); SCALAR_ADD(xua, xua, z_uj); } LINE_STORE_SCALAR(ln, a, xua); } LINE_STORE(d_x, u, ln); // W: ng scalar_t } } num_muls += n*SHADE_LINES*g*k; trans_bytes += sizeof(scalar_t)*n*g + sizeof(shade_map_t)*n; } /***************************************************************** Line sum. */ scalar_t line_sum(index_t l, index_t g, line_array_t *d_s) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < nt; t++) { SCALAR_SET_ZERO(ts[t]); index_t start = t*block_size; index_t stop = (t == nt-1) ? l-1 : (start+block_size-1); line_t ln; line_t acc; LINE_SET_ZERO(acc); for(index_t i = start; i <= stop; i++) { LINE_LOAD(ln, d_s, i); // R: lg scalar_t LINE_ADD(acc, acc, ln); } scalar_t lsum; LINE_SUM(lsum, acc); ts[t] = lsum; } scalar_t sum; SCALAR_SET_ZERO(sum); for(index_t t = 0; t < nt; t++) { SCALAR_ADD(sum, sum, ts[t]); } trans_bytes += sizeof(scalar_t)*l*g; return sum; } void vertex_acc(index_t l, // n index_t g, // g index_t stride, // k line_array_t *d_s, scalar_t *out) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); //scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { //SCALAR_SET_ZERO(ts[t]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; scalar_t lsum; for(index_t i = start; i <= stop; i++) { LINE_LOAD(ln, d_s, i); // R: lg scalar_t LINE_SUM(lsum, ln); out[i] ^= lsum; // R: scalar_t, W: scalar_t } } //scalar_t sum; //SCALAR_SET_ZERO(sum); //for(index_t t = 0; t < nt; t++) { // SCALAR_ADD(sum, sum, ts[t]); //} trans_bytes += sizeof(scalar_t)*(l*g+2); } scalar_t line_sum_stride(index_t l, index_t g, index_t stride, line_array_t *d_s) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { SCALAR_SET_ZERO(ts[th]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; line_t acc; LINE_SET_ZERO(acc); for(index_t i = start; i <= stop; i++) { index_t ii = i*stride; LINE_LOAD(ln, d_s, ii); // R: lg scalar_t LINE_ADD(acc, acc, ln); } scalar_t lsum; LINE_SUM(lsum, acc); ts[th] = lsum; } scalar_t sum; SCALAR_SET_ZERO(sum); for(index_t th = 0; th < nt; th++) { SCALAR_ADD(sum, sum, ts[th]); } trans_bytes += sizeof(scalar_t)*l*g; return sum; } void vertex_acc_stride(index_t l, index_t g, index_t stride, line_array_t *d_s, scalar_t *out) { index_t nt = num_threads(); index_t block_size = l/nt; assert(nt < MAX_THREADS); //scalar_t ts[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { //SCALAR_SET_ZERO(ts[th]); index_t start = th*block_size; index_t stop = (th == nt-1) ? l-1 : (start+block_size-1); line_t ln; scalar_t lsum; for(index_t i = start; i <= stop; i++) { index_t ii = i*stride; LINE_LOAD(ln, d_s, ii); // R: lg scalar_t LINE_SUM(lsum, ln); out[i] ^= lsum; // R: scalar_t, W: scalar_t } } //scalar_t sum; //SCALAR_SET_ZERO(sum); //for(index_t th = 0; th < nt; th++) { // SCALAR_ADD(sum, sum, ts[th]); //} trans_bytes += sizeof(scalar_t)*(l*g+2); } /***************************************** k-temppath generating function. */ #ifdef DEBUG #define PRINT_LINE(source) \ { \ scalar_t *s = (scalar_t *)&source; \ for(index_t i = 0; i < SCALARS_IN_LINE; i++) { \ fprintf(stdout, SCALAR_FORMAT_STRING"%s", \ (long) s[i], \ i==SCALARS_IN_LINE-1 ? "\n":" "); \ } \ } #endif #if BUILD_GENF == 2 #define TEMP_PATH_LINE_IDX2(n, k, tmax, u, l, i) (((u)*(tmax+1))+(i)) #ifdef DEBUG void print_ds(index_t n, index_t tmax, line_array_t *d_s) { for(index_t u = 0; u < n; u++) { fprintf(stdout, "--------------------------------------------------\n"); fprintf(stdout, "u: %ld\n", u+1); fprintf(stdout, "--------------------------------------------------\n"); for(index_t i = 0; i <= tmax; i++) { fprintf(stdout, "%ld: ", i); index_t i_uli = TEMP_PATH_LINE_IDX2(n, k, tmax, 1, i, u); line_t p_uli; LINE_LOAD(p_uli, d_s, i_uli); PRINT_LINE(p_uli); scalar_t sum; LINE_SUM(sum, p_uli); fprintf(stdout, "line sum: "SCALAR_FORMAT_STRING"\n",sum); } } } #endif scalar_t vloc_finegrain(index_t n, index_t g, index_t k, index_t tmax, line_array_t *d_s, scalar_t *out) { index_t nt = num_threads(); index_t block_size = n/nt; assert(nt < MAX_THREADS); scalar_t tsum[MAX_THREADS]; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { SCALAR_SET_ZERO(tsum[th]); index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); line_t ln; scalar_t lsum; scalar_t acc; SCALAR_SET_ZERO(acc); for(index_t u = start; u <= stop; u++) { index_t i_ul0 = TEMP_PATH_LINE_IDX2(n, k, tmax, u, k, 0); index_t i_u0 = (u*(tmax+1)); for(index_t i = 0; i <= tmax; i++) { index_t i_uli = i_ul0 + i; index_t i_ui = i_u0 + i; LINE_LOAD(ln, d_s, i_uli); LINE_SUM(lsum, ln); out[i_ui] ^= lsum; acc ^= lsum; } } tsum[th] = acc; } scalar_t sum; SCALAR_SET_ZERO(sum); for(index_t th = 0; th < nt; th++) SCALAR_ADD(sum, sum, tsum[th]); //TODO: update bandwidth computation trans_bytes += LINE_ARRAY_SIZE((tmax+1)*n*g); return sum; } void init_ds(index_t n, index_t k, index_t tmax, line_array_t *d_s) { line_t p_zero; LINE_SET_ZERO(p_zero); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_u10 = TEMP_PATH_LINE_IDX2(n, k, tmax, u, 1, 0); for(index_t i= 0; i <= tmax; i++) { index_t i_u1i = i_u10 + i; LINE_STORE(d_s, i_u1i, p_zero); } } } void k_temp_path_round(index_t n, index_t m, index_t k, index_t tmax, index_t rtmax, index_t t, index_t g, index_t l, index_t *d_pos, index_t *d_adj, index_t yl_seed, index_t *rtime, line_array_t *d_x, line_array_t *d_l1, line_array_t *d_l) { assert(g == SCALARS_IN_LINE); index_t nt = num_threads(); index_t length = n; index_t block_size = length/nt; index_t i = t; ffprng_t y_base; FFPRNG_INIT(y_base, yl_seed); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? length-1 : (start+block_size-1); ffprng_t y_gen; // forward the psuedo-random number generator index_t y_pos = (d_pos[start] - start) * rtmax; FFPRNG_FWD(y_gen, y_pos, y_base); for(index_t u = start; u <= stop; u++) { index_t pu = d_pos[n*(i-1)+u]; index_t deg = d_adj[pu]; line_t p_uli; LINE_SET_ZERO(p_uli); for(index_t d = 1; d <= deg; d++) { index_t v = d_adj[pu+d]; index_t dv = (i > rtime[v]) ? rtime[v] : i-1; // i-j > 0 index_t i_vl1idv = TEMP_PATH_LINE_IDX2(n, k, tmax, v, l-1, i-dv); for(index_t j = 0; j <= dv; j++) { line_t p_vl1ij; index_t i_vl1ij = i_vl1idv + j; LINE_LOAD(p_vl1ij, d_l1, i_vl1ij); #ifdef BUILD_PREFETCH // prefetch next line P_{v,l-1,i-j+1} index_t i_vl1ij1 = i_vl1idv + (j==dv) ? dv : j+1; LINE_PREFETCH(d_l1, i_vl1ij1); #endif ffprng_scalar_t rnd; FFPRNG_RAND(rnd, y_gen); scalar_t y_uvlij = (scalar_t) rnd; line_t sy; LINE_MUL_SCALAR(sy, p_vl1ij, y_uvlij); LINE_ADD(p_uli, p_uli, sy); } } line_t xu; LINE_LOAD(xu, d_x, u); LINE_MUL(p_uli, p_uli, xu); index_t i_uli = TEMP_PATH_LINE_IDX2(n, k, tmax, u, l, i); LINE_STORE(d_l, i_uli, p_uli); // W: ng scalar_t } } //TODO: update bandwidth computation // total edges at time `i` index_t m_i = d_pos[n*(i-1) + n-1] - d_pos[n*(i-1)] - (n-1) + d_adj[d_pos[n*(i-1)+(n-1)]]; trans_bytes += ((2*n*tmax)+m_i)*sizeof(index_t) + (2*n+m_i)*g*sizeof(scalar_t); num_muls += (n*g+m_i); } scalar_t k_temp_path(index_t n, index_t m, index_t k, index_t tmax, index_t rtmax, index_t g, index_t vert_loc, index_t *d_pos, index_t *d_adj, ffprng_scalar_t y_seed, index_t *rtime, line_array_t *d_x, scalar_t *vsum) { assert( g == SCALARS_IN_LINE); assert( k >= 1); line_array_t *d_l1 = (line_array_t *) MALLOC(LINE_ARRAY_SIZE((tmax+1)*n*g)); line_array_t *d_l = (line_array_t *) MALLOC(LINE_ARRAY_SIZE((tmax+1)*n*g)); init_ds(n, 1, tmax, d_l); // initialise: l = 1 #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_u10 = TEMP_PATH_LINE_IDX2(n, k, tmax, u, 1, 0); for(index_t i = 0; i <= tmax; i++) { line_t xu; LINE_LOAD(xu, d_x, u); index_t i_u1i = i_u10 + i; LINE_STORE(d_l1, i_u1i, xu); } } srand(y_seed); for(index_t l = 2; l <= k; l++) { for(index_t i = l-1; i <= tmax; i++) { ffprng_scalar_t yl_seed = irand(); // new seed for each l k_temp_path_round(n, m, k, tmax, rtmax, i, g, l, d_pos, d_adj, yl_seed, rtime, d_x, d_l1, d_l); } // swap and initialise line_array_t *d_temp = d_l1; d_l1 = d_l; d_l = d_temp; init_ds(n, 1, tmax, d_l); } // sum up //index_t ii = TEMP_PATH_LINE_IDX2(n, k, tmax, 1, tmax, 0); scalar_t sum = vloc_finegrain(n, g, k, tmax, d_l1, vsum); // free memory FREE(d_l1); FREE(d_l); return sum; } #endif /************************************************************ The oracle(s). */ index_t temppath_oracle(index_t n, index_t k, index_t tmax, index_t rtmax, index_t *h_pos, index_t *h_adj, index_t num_shades, index_t *rtime, shade_map_t *h_s, ffprng_scalar_t y_seed, ffprng_scalar_t z_seed, index_t vert_loc, scalar_t *master_vsum) { push_memtrack(); assert(k >= 1 && k < 31); //index_t m = h_pos[n-1]+h_adj[h_pos[n-1]]+1-n; index_t m = h_pos[n*(tmax-1)+n-1]+h_adj[h_pos[n*(tmax-1)+n-1]]+1-(n*tmax); index_t sum_size = 1 << k; index_t g = SCALARS_IN_LINE; index_t outer = (sum_size + g-1) / g; // number of iterations for outer loop num_muls = 0; trans_bytes = 0; index_t *d_pos = h_pos; index_t *d_adj = h_adj; line_array_t *d_x = (line_array_t *) MALLOC(LINE_ARRAY_SIZE(n*g)); /* Run the work & time it. */ push_time(); scalar_t master_sum; SCALAR_SET_ZERO(master_sum); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t i_u0 = (u*(tmax+1)); for(index_t i = 0; i <= tmax; i++) { index_t i_ui = i_u0 + i; SCALAR_SET_ZERO(master_vsum[i_ui]); } } for(index_t out = 0; out < outer; out++) { // Eq. (3) constrained_sieve_pre(n, k, g, g*out, num_shades, h_s, z_seed, d_x); #define GENF_TYPE "restless_path_genf" // Eq. (4) scalar_t sum = k_temp_path(n, m, k, tmax, rtmax, g, vert_loc, d_pos, d_adj, y_seed, rtime, d_x, master_vsum); SCALAR_ADD(master_sum, master_sum, sum); } double time = pop_time(); //double trans_rate = trans_bytes / (time/1000.0); //double mul_rate = num_muls / time; FREE(d_x); fprintf(stdout, SCALAR_FORMAT_STRING " %.2lf ms" //" [%.2lfGiB/s, %.2lfGHz]" " %d", (long) master_sum, time, //trans_rate/((double) (1 << 30)), //mul_rate/((double) 1e6), master_sum != 0); fprintf(stdout, " "); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fflush(stdout); return master_sum != 0; } /************************************************* Rudimentary graph builder. */ typedef struct { index_t is_directed; index_t num_vertices; index_t num_edges; index_t max_time; index_t max_resttime; index_t edge_capacity; index_t *edges; index_t *rest_time; } graph_t; static index_t *enlarge(index_t m, index_t m_was, index_t *was) { assert(m >= 0 && m_was >= 0); index_t *a = (index_t *) MALLOC(sizeof(index_t)*m); index_t i; if(was != (void *) 0) { for(i = 0; i < m_was; i++) { a[i] = was[i]; } FREE(was); } return a; } graph_t *graph_alloc(index_t n) { assert(n >= 0); graph_t *g = (graph_t *) MALLOC(sizeof(graph_t)); g->is_directed = 0; // default: undirected graph g->num_vertices = n; g->num_edges = 0; g->edge_capacity = 100; g->edges = enlarge(3*g->edge_capacity, 0, (void *) 0); g->rest_time = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) g->rest_time[u] = UNDEFINED; return g; } void graph_free(graph_t *g) { FREE(g->edges); FREE(g->rest_time); FREE(g); } void graph_add_edge(graph_t *g, index_t u, index_t v, index_t t) { assert(u >= 0 && v >= 0 && u < g->num_vertices && v < g->num_vertices); assert(t>=0); //assert(t>=0 && t < g->max_time); if(g->num_edges == g->edge_capacity) { g->edges = enlarge(6*g->edge_capacity, 3*g->edge_capacity, g->edges); g->edge_capacity *= 2; } assert(g->num_edges < g->edge_capacity); index_t *e = g->edges + 3*g->num_edges; e[0] = u; e[1] = v; e[2] = t; g->num_edges++; } index_t *graph_edgebuf(graph_t *g, index_t cap) { g->edges = enlarge(3*g->edge_capacity+3*cap, 3*g->edge_capacity, g->edges); index_t *e = g->edges + 3*g->num_edges; g->edge_capacity += cap; g->num_edges += cap; return e; } //void graph_set_color(graph_t *g, index_t u, index_t c) //{ // assert(u >= 0 && u < g->num_vertices && c >= 0); // g->colors[u] = c; //} void graph_set_is_directed(graph_t *g, index_t is_dir) { assert(is_dir == 0 || is_dir == 1); g->is_directed = is_dir; } void graph_set_max_time(graph_t *g, index_t tmax) { assert(tmax > 0); g->max_time = tmax; } void graph_set_resttime(graph_t *g, index_t u, index_t rt) { assert(u >= 0 && u < g->num_vertices && rt >= 0 && rt <= g->max_resttime); g->rest_time[u] = rt; } void graph_set_max_resttime(graph_t *g, index_t rtmax) { assert(rtmax > 0); g->max_resttime = rtmax; } #ifdef DEBUG void print_graph(graph_t *g) { index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; index_t rtmax = g->max_resttime; index_t is_dir = g->is_directed; fprintf(stdout, "p motif %ld %ld %ld %ld %ld\n", n, m, tmax, rtmax, is_dir); index_t *e = g->edges; for(index_t i = 0; i < 3*m; i+=3) { fprintf(stdout, "e %ld %ld %ld\n", e[i]+1, e[i+1]+1, e[i+2]+1); } index_t *c = g->colors; for(index_t i = 0; i < n; i++) fprintf(stdout, "n %ld %ld\n", i+1, c[i]==UNDEFINED ? c[i] : c[i]+1); index_t *rt = g->rest_time; for(index_t i = 0; i < n; i++) fprintf(stdout, "r %ld %ld\n", i+1, rt[i]); } #endif /************************************* Basic motif query processing routines. */ struct temppathq_struct { index_t is_stub; index_t n; index_t k; index_t tmax; index_t *pos; index_t *adj; index_t nl; index_t *l; index_t ns; shade_map_t *shade; index_t rtmax; index_t *rtime; index_t vert_loc; scalar_t *vsum; }; typedef struct temppathq_struct temppathq_t; void adjsort(index_t n, index_t *pos, index_t *adj) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t pu = pos[u]; index_t deg = adj[pu]; heapsort_indext(deg, adj + pu + 1); } } void temppathq_free(temppathq_t *q) { if(!q->is_stub) { FREE(q->pos); FREE(q->adj); FREE(q->l); FREE(q->shade); FREE(q->rtime); FREE(q->vsum); } FREE(q); } index_t temppathq_execute(temppathq_t *q) { if(q->is_stub) return 0; return temppath_oracle(q->n, q->k, q->tmax, q->rtmax, q->pos, q->adj, q->ns, q->rtime, q->shade, irand(), irand(), q->vert_loc, q->vsum); } #ifdef DEBUG void print_temppathq(temppathq_t *q) { index_t n = q->n; index_t k = q->k; index_t tmax = q->tmax; index_t *pos = q->pos; index_t *adj = q->adj; fprintf(stdout, "-----------------------------------------------\n"); fprintf(stdout, "printing temppathq\n"); fprintf(stdout, "is_stub = %ld\n", q->is_stub); fprintf(stdout, "n = %ld\n", n); fprintf(stdout, "k = %ld\n", k); fprintf(stdout, "tmax = %ld\n", tmax); fprintf(stdout, "pos\n"); fprintf(stdout, "----\n "); for(index_t i = 0; i < n*tmax; i++) { fprintf(stdout, "%ld%s", pos[i], i%n==n-1 ? "\n ":" "); } fprintf(stdout, "adjacency list:\n"); fprintf(stdout, "---------------\n"); for(index_t t = 0; t < tmax; t++) { fprintf(stdout, "t: %ld\n", t+1); fprintf(stdout, "---------------\n"); index_t *pos_t = pos + n*t; for(index_t u = 0; u < n; u++) { index_t pu = pos_t[u]; index_t nu = adj[pu]; index_t *adj_u = adj + pu + 1; fprintf(stdout, "%4ld:", u+1); for(index_t i = 0; i < nu; i++) { fprintf(stdout, " %4ld", adj_u[i]+1); } fprintf(stdout, "\n"); } } index_t nl = q->nl; index_t *l = q->l; fprintf(stdout, "nl = %ld\n", nl); fprintf(stdout, "l:\n"); for(index_t i = 0; i < nl; i++) fprintf(stdout, "%8ld : %8ld\n", nl, l[i]); index_t ns = q ->ns; shade_map_t *shade = q->shade; fprintf(stdout, "ns : %ld\n", ns); fprintf(stdout, "shades:\n"); for(index_t u = 0; u < n; u++) fprintf(stdout, "%10ld : 0x%08X\n", u+1, shade[u]); index_t rtmax = q->rtmax; index_t *rtime = q->rtime; fprintf(stdout, "rtmax: %ld", rtmax); fprintf(stdout, "rest time:\n"); for(index_t u = 0; u < n; u++) fprintf(stdout, "%10ld : %8ld\n", u+1, rtime[u]); scalar_t *vsum = q->vsum; fprintf(stdout, "vert_loc: %ld\n", q->vert_loc); fprintf(stdout, "vsum:\n"); for(index_t u = 0; u < n; u++) fprintf(stdout, "%10ld : "SCALAR_FORMAT_STRING"\n", u+1, vsum[u]); fprintf(stdout, "-----------------------------------------------\n"); } void print_array(const char *name, index_t n, index_t *a, index_t offset) { fprintf(stdout, "%s (%ld):", name, n); for(index_t i = 0; i < n; i++) { fprintf(stdout, " %ld", a[i] == -1 ? -1 : a[i]+offset); } fprintf(stdout, "\n"); } #endif /******************************************************** Root query builder. */ // Query builder for directed graphs temppathq_t *build_temppathq_dir(graph_t *g) { push_memtrack(); index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; index_t *pos = alloc_idxtab(n*tmax); index_t *adj = alloc_idxtab(n*tmax+2*m); index_t *rtime = (index_t *) MALLOC(sizeof(index_t)*n); //index_t ns = k; shade_map_t *shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); temppathq_t *root = (temppathq_t *) MALLOC(sizeof(temppathq_t)); root->is_stub = 0; root->n = g->num_vertices; //root->k = k; root->tmax = tmax; root->pos = pos; root->adj = adj; root->nl = 0; root->l = (index_t *) MALLOC(sizeof(index_t)*root->nl); //root->ns = ns; root->shade = shade; root->rtime = rtime; root->vert_loc = 1; root->vsum = (scalar_t *) MALLOC(sizeof(scalar_t)*(root->n)*(root->tmax+1)); //assert(tmax >= k-1); push_time(); fprintf(stdout, "build query: "); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) pos[u] = 0; double time = pop_time(); fprintf(stdout, "[zero: %.2lf ms] ", time); fflush(stdout); push_time(); index_t *e = g->edges; #ifdef BUILD_PARALLEL // Parallel occurrence count // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges index_t nt = num_threads(); index_t block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { //index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = (pos + (n*t)); //if(start <= u && u <= stop) { // // I am responsible for u, record adjacency to u // pos_t[u]++; //} if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v pos_t[v]++; } } } #else for(index_t j = 0; j < 3*m; j+=3) { //index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = pos + n*t; //pos_t[u]++; pos_t[v]++; } #endif index_t run = prefixsum(n*tmax, pos, 1); assert(run == (n*tmax+m)); time = pop_time(); fprintf(stdout, "[pos: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) adj[pos[u]] = 0; e = g->edges; #ifdef BUILD_PARALLEL // Parallel aggregation to bins // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges nt = num_threads(); block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; //if(start <= u && u <= stop) { // // I am responsible for u, record adjacency to u // index_t pu = pos[n*t+u]; // adj[pu + 1 + adj[pu]++] = v; //} if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v index_t pv = pos[n*t+v]; adj[pv + 1 + adj[pv]++] = u; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; //index_t pu = pos[n*t+u]; index_t pv = pos[n*t+v]; //adj[pu + 1 + adj[pu]++] = v; adj[pv + 1 + adj[pv]++] = u; } #endif time = pop_time(); fprintf(stdout, "[adj: %.2lf ms] ", time); fflush(stdout); //print_temppathq(root); push_time(); adjsort(n*tmax, pos, adj); time = pop_time(); fprintf(stdout, "[adjsort: %.2lf ms] ", time); fflush(stdout); // copy shades //push_time(); //#ifdef BUILD_PARALLEL //#pragma omp parallel for //#endif //for(index_t u = 0; u < n; u++) { // shade_map_t s = 0; // for(index_t j = 0; j < k; j++) // if(colors[u] == kk[j]) // s |= 1UL << j; // shade[u] = s; // //fprintf(stdout, "%4ld: 0x%08X\n", u, shade[u]); //} //time = pop_time(); //fprintf(stdout, "[shade: %.2lf ms] ", time); //fflush(stdout); // copy resting time push_time(); index_t *rest_time = g->rest_time; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) rtime[u] = rest_time[u]; time = pop_time(); fprintf(stdout, "[rtime: %.2lf ms] ", time); fflush(stdout); time = pop_time(); fprintf(stdout, "done. [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); return root; } // Query builder for undirected graphs // temppathq_t *build_temppathq(graph_t *g) { push_memtrack(); index_t n = g->num_vertices; index_t m = g->num_edges; index_t tmax = g->max_time; index_t *pos = alloc_idxtab(n*tmax); index_t *adj = alloc_idxtab(n*tmax+2*m); index_t *rtime = (index_t *) MALLOC(sizeof(index_t)*n); //index_t ns = k; shade_map_t *shade = (shade_map_t *) MALLOC(sizeof(shade_map_t)*n); temppathq_t *root = (temppathq_t *) MALLOC(sizeof(temppathq_t)); root->is_stub = 0; root->n = g->num_vertices; //root->k = k; root->tmax = tmax; root->pos = pos; root->adj = adj; root->nl = 0; root->l = (index_t *) MALLOC(sizeof(index_t)*root->nl); //root->ns = ns; root->shade = shade; root->rtime = rtime; root->vert_loc = 0; root->vsum = (scalar_t *) MALLOC(sizeof(index_t)*(root->n)*(root->tmax+1)); //assert(tmax >= k-1); push_time(); fprintf(stdout, "build query: "); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) pos[u] = 0; double time = pop_time(); fprintf(stdout, "[zero: %.2lf ms] ", time); fflush(stdout); push_time(); index_t *e = g->edges; #ifdef BUILD_PARALLEL // Parallel occurrence count // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges index_t nt = num_threads(); index_t block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = (pos + (n*t)); if(start <= u && u <= stop) { // I am responsible for u, record adjacency to u pos_t[u]++; } if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v pos_t[v]++; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j]; index_t v = e[j+1]; index_t t = e[j+2]; index_t *pos_t = pos + n*t; pos_t[u]++; pos_t[v]++; } #endif index_t run = prefixsum(n*tmax, pos, 1); assert(run == (n*tmax+2*m)); time = pop_time(); fprintf(stdout, "[pos: %.2lf ms] ", time); fflush(stdout); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n*tmax; u++) { adj[pos[u]] = 0; } e = g->edges; #ifdef BUILD_PARALLEL // Parallel aggregation to bins // -- each thread is responsible for a group of bins, // all threads scan the entire list of edges nt = num_threads(); block_size = n/nt; #pragma omp parallel for for(index_t th = 0; th < nt; th++) { index_t start = th*block_size; index_t stop = (th == nt-1) ? n-1 : (start+block_size-1); for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; if(start <= u && u <= stop) { // I am responsible for u, record adjacency to u index_t pu = pos[n*t+u]; adj[pu + 1 + adj[pu]++] = v; } if(start <= v && v <= stop) { // I am responsible for v, record adjacency to v index_t pv = pos[n*t+v]; adj[pv + 1 + adj[pv]++] = u; } } } #else for(index_t j = 0; j < 3*m; j+=3) { index_t u = e[j+0]; index_t v = e[j+1]; index_t t = e[j+2]; index_t pu = pos[n*t+u]; index_t pv = pos[n*t+v]; adj[pu + 1 + adj[pu]++] = v; adj[pv + 1 + adj[pv]++] = u; } #endif /* // TODO: works only for single source // update this part later #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < tmax; t++) { index_t *pos_t = (pos + (n*t)); for(index_t i = 0; i < num_srcs; i++) { index_t s = sources[i]; index_t ps = pos_t[s]; adj[ps] = 0; } } */ time = pop_time(); fprintf(stdout, "[adj: %.2lf ms] ", time); fflush(stdout); push_time(); adjsort(n*tmax, pos, adj); time = pop_time(); fprintf(stdout, "[adjsort: %.2lf ms] ", time); fflush(stdout); // copy shades //push_time(); //#ifdef BUILD_PARALLEL //#pragma omp parallel for //#endif // for(index_t u = 0; u < n; u++) { // shade_map_t s = 0; // for(index_t j = 0; j < k; j++) // if(colors[u] == kk[j]) // s |= 1UL << j; // shade[u] = s; // fprintf(stdout, "%4ld: 0x%08X\n", u, shade[u]); // // // } // time = pop_time(); // fprintf(stdout, "[shade: %.2lf ms] ", time); // fflush(stdout); // copy resting time push_time(); index_t *rest_time = g->rest_time; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) rtime[u] = rest_time[u]; time = pop_time(); fprintf(stdout, "[rtime: %.2lf ms] ", time); fflush(stdout); time = pop_time(); fprintf(stdout, "done. [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fflush(stdout); //print_temppathq(root); return root; } void update_sources_adj(index_t n, index_t tmax, index_t num_srcs, index_t *sources, index_t *pos, index_t *adj) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t t = 0; t < tmax; t++) { index_t *pos_t = (pos + (n*t)); for(index_t i = 0; i < num_srcs; i++) { index_t s = sources[i]; index_t ps = pos_t[s]; adj[ps] = 0; } } } void update_colors(index_t n, index_t k, index_t num_srcs, index_t *sources, index_t num_seps, index_t *separators, index_t *color) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) color[u] = 2; // currently handling single source for(index_t i = 0; i < num_srcs; i++) { index_t u = sources[i]; color[u] = 1; } #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t i = 0; i < num_seps; i++) { index_t u = separators[i]; color[u] = 3; } } void get_motif_colors(index_t k, index_t *kk) { kk[0] = 1; // not worth parallelising for(index_t i = 1; i < k; i++) kk[i] = 2; } void temppathq_update_shades(index_t k, index_t *kk, index_t *color, temppathq_t *root) { shade_map_t *shade = root->shade; index_t n = root->n; root->k = k; root->ns = k; //update shades #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { shade_map_t s = 0; for(index_t j = 0; j < k; j++) if(color[u] == kk[j]) s |= 1UL << j; shade[u] = s; //fprintf(stdout, "%4ld: 0x%08X\n", u, shade[u]); } } /****************************************************** Input reader (ASCII). */ void skipws(FILE *in) { int c; do { c = fgetc(in); if(c == '#') { do { c = fgetc(in); } while(c != EOF && c != '\n'); } } while(c != EOF && isspace(c)); if(c != EOF) ungetc(c, in); } #define CMD_NOP 0 #define CMD_RUN_ORACLE 6 #define CMD_VLOC 7 #define CMD_VLOC_FINEGRAIN 8 #define CMD_EXHAUST_SEARCH 9 char *cmd_legend[] = { "no operation", "run oracle", "localised", "localised (fine-grained)", "exhaustive search"}; void reader_ascii(FILE *in, graph_t **g_out, index_t *num_srcs_out, index_t **sources_out, index_t *num_seps_out, index_t **separators_out) { push_time(); push_memtrack(); index_t n = 0; index_t m = 0; index_t tmax = 0; index_t rtmax = 0; index_t is_dir = 0; graph_t *g = (graph_t *) 0; index_t num_srcs = 0; index_t *sources = (index_t *) 0; index_t num_seps = 0; index_t *separators = (index_t *) 0; index_t i, j, t, rt; skipws(in); while(!feof(in)) { skipws(in); int c = fgetc(in); switch(c) { case 'p': if(g != (graph_t *) 0) ERROR("duplicate parameter line"); skipws(in); if(fscanf(in, "motif %ld %ld %ld %ld %ld", &n, &m, &tmax, &rtmax, &is_dir) != 5) ERROR("invalid parameter line"); if(n <= 0 || m < 0 || tmax < 1 || rtmax < 1) { ERROR("invalid input parameters (n = %ld, m = %ld, tmax = %ld, rtmax = %ld)", n, m, tmax, rtmax); } g = graph_alloc(n); graph_set_is_directed(g, is_dir); graph_set_max_time(g, tmax); graph_set_max_resttime(g, rtmax); break; case 'e': if(g == (graph_t *) 0) ERROR("parameter line must be given before edges"); skipws(in); if(fscanf(in, "%ld %ld %ld", &i, &j, &t) != 3) ERROR("invalid edge line"); graph_add_edge(g, i-1, j-1, t-1); break; case 'r': if(g == (graph_t *) 0) ERROR("parameter line must be given before motif"); skipws(in); if(fscanf(in, "%ld %ld", &i, &rt) != 2) ERROR("invalid rest time line"); if(i < 1 || i > n || rt < 1 || rt > rtmax) ERROR("invalid rest time line (u = %ld, rt = %ld with n = %ld and rtmax = %ld)", i, rt, n, rtmax); graph_set_resttime(g, i-1, rt); break; case 's': if(g == (graph_t *) 0) ERROR("parameter line must be given before sources"); skipws(in); if(fscanf(in, "%ld", &num_srcs) != 1) ERROR("invalid sources line"); if(num_srcs < 1 || num_srcs > n) ERROR("invalid sources line (num-sources = %ld with n = %d)", num_srcs, n); if(num_srcs > 1) ERROR("current implementation only support single source (num-sources = %ld)", num_srcs); sources = alloc_idxtab(num_srcs); for(index_t i = 0; i < num_srcs; i++) { index_t s; skipws(in); if(fscanf(in, "%ld", &s) != 1) ERROR("error parsing sources line"); if(s < 1 || s > n) ERROR("invalid sources line (s = %ld)", s); sources[i] = s-1; } break; case 't': if(g == (graph_t *) 0) ERROR("parameter line must be given before separators"); skipws(in); if(fscanf(in, "%ld", &num_seps) != 1) ERROR("invalid separators line"); if(num_seps < 1 || num_seps > n) ERROR("invalid separators line (num-separators = %ld with n = %d)", num_seps, n); separators = alloc_idxtab(num_seps); for(index_t i = 0; i < num_seps; i++) { index_t s; skipws(in); if(fscanf(in, "%ld", &s) != 1) ERROR("error parsing sources line"); if(s < 1 || s > n) ERROR("invalid separator (s = %ld)", s); separators[i] = s-1; } break; case EOF: break; default: ERROR("parse error"); } } if(g == (graph_t *) 0) ERROR("no graph given in input"); double time = pop_time(); fprintf(stdout, "input: n = %ld, m = %ld, t = %ld, rt = %ld [%.2lf ms] ", g->num_vertices, g->num_edges, g->max_time, g->max_resttime, time); print_pop_memtrack(); fprintf(stdout, " "); print_current_mem(); fprintf(stdout, "\n"); fprintf(stdout, "sources [%ld]: ", num_srcs); for(index_t i = 0; i < num_srcs; i++) fprintf(stdout, " %ld", sources[i]+1); fprintf(stdout, "\n"); fprintf(stdout, "separators [%ld]: ", num_seps); for(index_t i = 0; i < num_seps; i++) fprintf(stdout, "%ld", separators[i]+1); fprintf(stdout, "\n"); *g_out = g; *num_srcs_out = num_srcs; *sources_out = sources; *num_seps_out = num_seps; *separators_out = separators; } /************************************************************ Temporal DFS. */ index_t temp_dfs(index_t n, index_t k, index_t tmax, index_t *pos, index_t *adj, index_t *in_stack, index_t *rtime, index_t *reach_time, stk_t *s) { // reached depth 'k' if(s->n == k) // TODO: fix this to s->n == k return 1; stack_node_t e; stack_top(s, &e); index_t u = e.u; index_t l = e.l; index_t min_t = e.t; index_t max_t = MIN(tmax, e.t + rtime[u]); for(index_t t = min_t; t <= max_t; t++) { index_t *pos_t = pos + (t-1)*n; index_t pu = pos_t[u]; index_t nu = adj[pu]; if(nu == 0) continue; index_t *adj_u = adj + pu; for(index_t i = 1; i <= nu; i++) { index_t v = adj_u[i]; if(in_stack[v]) continue; stack_node_t e; e.u = v; e.l = l+1; e.t = t; stack_push(s, &e); in_stack[v] = 1; reach_time[v] = MIN(reach_time[v], t); temp_dfs(n, k, tmax, pos, adj, in_stack, rtime, reach_time, s); stack_pop(s, &e); in_stack[v] = 0; } } return 0; // not found } void exhaustive_search(temppathq_t *root, index_t src, index_t *reach_time) { push_time(); index_t n = root->n; index_t k = root->k; index_t tmax = root->tmax; index_t *pos = root->pos; index_t *adj = root->adj; index_t *rtime = root->rtime; index_t *in_stack = alloc_idxtab(n); push_time(); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) in_stack[u] = 0; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) reach_time[u] = MATH_INF; rtime[src] = tmax; stk_t *s = stack_alloc(k); stack_node_t es; es.u = src; es.l = 0; es.t = 1; stack_push(s, &es); in_stack[src] = 1; double preproc_time = pop_time(); push_time(); temp_dfs(n, k, tmax, pos, adj, in_stack, rtime, reach_time, s); double dfs_time = pop_time(); FREE(in_stack); stack_free(s); fprintf(stdout, " [%.2lfms %.2lfms %.2lfms]", preproc_time, dfs_time, pop_time()); } /**************************************************** get minimum timestamp. */ void vloc_min_timestamp(index_t n, index_t k, index_t *vloc_time, index_t *vloc_min_time) { #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { index_t *vloc_time_u = vloc_time + (u*(k-1)); index_t min_time = MATH_INF; for(index_t l = 2; l <= k; l++) { index_t cur_time = vloc_time_u[l-2]; if(cur_time < min_time) min_time = cur_time; } vloc_min_time[u] = min_time; } } void vloc_table_out(FILE *out, index_t n, index_t k, index_t *vloc_time, index_t *vloc_min_time, char *out_type) { if(!strcmp(out_type, "csv")) { for(index_t u = 0; u < n; u++) { for(index_t l = 2; l <=k; l++) { index_t t_vloc = vloc_time[u*(k-1) + (l-2)]; fprintf(out, "%ld;", t_vloc==MATH_INF?UNDEFINED:t_vloc); } fprintf(out, "%ld\n", vloc_min_time[u]==MATH_INF?UNDEFINED:vloc_min_time[u]); fflush(out); } } else { for(index_t u = 0; u < n; u++) { fprintf(out, "%5ld:", u+1); for(index_t l = 2; l <=k; l++) { //index_t t_vloc = vloc_time[(l-2)*n + u]; index_t t_vloc = vloc_time[u*(k-1) + (l-2)]; fprintf(out, " %6ld", t_vloc==MATH_INF?UNDEFINED:t_vloc); } fprintf(out, " %6ld\n", vloc_min_time[u]==MATH_INF?UNDEFINED:vloc_min_time[u]); fflush(out); } } } /****************************************************** program entry point. */ int main(int argc, char **argv) { GF_PRECOMPUTE; push_time(); push_memtrack(); index_t arg_cmd = CMD_NOP; index_t flag_help = 0; index_t flag_test = 0; index_t have_seed = 0; index_t have_input = 0; index_t have_output = 0; index_t have_karg = 0; index_t k_arg = 0; index_t k = 0; index_t seed = 123456789; char *filename = (char *) 0; char *filename_out = (char *) 0; for(index_t f = 1; f < argc; f++) { if(argv[f][0] == '-') { if(!strcmp(argv[f], "-h") || !strcmp(argv[f], "-help")) { flag_help = 1; break; } if(!strcmp(argv[f], "-oracle")) { arg_cmd = CMD_RUN_ORACLE; } if(!strcmp(argv[f], "-vloc")) { arg_cmd = CMD_VLOC; } if(!strcmp(argv[f], "-vloc-finegrain")) { arg_cmd = CMD_VLOC_FINEGRAIN; } if(!strcmp(argv[f], "-baseline")) { arg_cmd = CMD_EXHAUST_SEARCH; } if(!strcmp(argv[f], "-seed")) { if(f == argc - 1) ERROR("random seed missing from command line"); seed = atol(argv[++f]); have_seed = 1; } if(!strcmp(argv[f], "-k")) { if(f == argc -1) ERROR("path length missing from command line"); k_arg = atol(argv[++f]); have_karg = 1; } if(!strcmp(argv[f], "-in")) { if(f == argc - 1) ERROR("input file missing from command line"); have_input = 1; filename = argv[++f]; } if(!strcmp(argv[f], "-out")) { if(f == argc - 1) ERROR("output file missing from command line"); have_output = 1; filename_out = argv[++f]; } if(!strcmp(argv[f], "-test")) { flag_test = 1; } } } fprintf(stdout, "invoked as:"); for(index_t f = 0; f < argc; f++) fprintf(stdout, " %s", argv[f]); fprintf(stdout, "\n"); if(flag_help) { fprintf(stdout, "usage: %s -pre <value> -optimal -<command-type> -seed <value> -in <input-file> -<file-type> \n" " %s -h/help\n" "\n" " -<command-type> : oracle - decide existence of a solution\n" " vloc - single run of vertex localisation\n" " vloc-finegrain - fine-grained evaluation of the oracle\n" " baseline - exhaustive-search algorithm\n" " -k <value> : integer value in range 1 to n-1\n" " -seed <value> : integer value in range 1 to 2^32 -1\n" " default value `%ld`\n" " -in <input-file> : path to input file, `stdin` by default \n" " -out <output-file> : path to output file, `reachability.out` by default \n" " -min : reports minimum reachable time for each vertex to `output-file`\n" " -h or -help : help\n" "\n" , argv[0], argv[0], seed); return 0; } if(have_seed == 0) { fprintf(stdout, "no random seed given, defaulting to %ld\n", seed); } fprintf(stdout, "random seed = %ld\n", seed); FILE *in = stdin; if(have_input) { in = fopen(filename, "r"); if(in == NULL) { ERROR("unable to open file '%s'", filename); } else { fprintf(stdout, "no input file specified, defaulting to stdin\n"); } fflush(stdout); } FILE *out = stdout; if(have_output) { out = fopen(filename_out, "w"); if(out == NULL) ERROR("unable to open file '%s'", filename_out); } else { out = fopen("reachability.out", "w"); fprintf(stdout, "no output file specified, defaulting to `reachability.out`\n"); } fflush(stdout); if(have_karg) { k = k_arg; fprintf(stdout, "path length specified in command line, changing to `k = %ld`\n", k); } else { k = 2; fprintf(stdout, "no path length specified, defaulting to `k = %ld`\n", k); } fflush(stdout); // initilize random number generator srand(seed); index_t num_srcs; index_t num_seps; graph_t *g = (graph_t *) 0; index_t *kk = (index_t *) 0; index_t *sources = (index_t *) 0; index_t *separators = (index_t *) 0; index_t *color = (index_t *) 0; index_t cmd = arg_cmd; // by default execute command in input stream // read input graph : current implementation supports only ascii inputs reader_ascii(in, &g, &num_srcs, &sources, &num_seps, &separators); if(have_input) fclose(in); //close file-descriptor // build root query temppathq_t *root = (temppathq_t *) 0; if(g->is_directed) { root = build_temppathq_dir(g); } else { root = build_temppathq(g); } graph_free(g); // free graph if(arg_cmd != CMD_EXHAUST_SEARCH) { // update adjacency list update_sources_adj(root->n, root->tmax, num_srcs, sources, root->pos, root->adj); // update vertex colors color = alloc_idxtab(root->n); update_colors(root->n, k, num_srcs, sources, num_seps, separators, color); } push_time(); // execute command switch(cmd) { case CMD_NOP: { // no operation temppathq_free(root); break; } case CMD_RUN_ORACLE: { // --- run oracle --- fprintf(stdout, "oracle [temppath]: "); fflush(stdout); if(temppathq_execute(root)) fprintf(stdout, " -- true\n"); else fprintf(stdout, " -- false\n"); temppathq_free(root); } break; case CMD_VLOC: { // --- run oracle --- fprintf(stdout, "oracle [temppath]: "); fflush(stdout); kk = alloc_idxtab(k); get_motif_colors(k, kk); temppathq_update_shades(k, kk, color, root); if(temppathq_execute(root)) fprintf(stdout, " -- true\n"); else fprintf(stdout, " -- false\n"); scalar_t *vsum = root->vsum; index_t n = root->n; index_t tmax = root->tmax; index_t *vloc_time = (index_t *) MALLOC(sizeof(index_t)*n); #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { vloc_time[u] = UNDEFINED; index_t i_u0 = (u*(tmax+1)); for(index_t i = 0; i <= tmax; i++) { index_t i_ui = i_u0 + i; if(vsum[i_ui]) { vloc_time[u] = i; break; } } } fprintf(stdout, "time:\n"); for(index_t u = 0; u < n; u++) { if(vloc_time[u] != UNDEFINED) fprintf(stdout,"%10ld: %4ld\n", u+1, vloc_time[u]); } fflush(stdout); FREE(vloc_time); temppathq_free(root); } break; case CMD_VLOC_FINEGRAIN: { index_t n = root->n; //index_t k = root->k; index_t tmax = root->tmax; index_t *vloc_time = (index_t *) MALLOC(sizeof(index_t)*n*(k-1)); kk = alloc_idxtab(k); for(index_t l = 2; l <= k; l++) { push_time(); push_time(); // time update shades get_motif_colors(l, kk); root->k = l; temppathq_update_shades(l, kk, color, root); fprintf(stdout, "finegrained-oracle [%ld, shade:%.2fms]: ", l, pop_time()); push_time(); // run oracle and time it //execute oracle if(temppathq_execute(root)) { fprintf(stdout, " [%.2lf ms]-- true", pop_time()); } else { fprintf(stdout, " [%.2lf ms]-- false", pop_time()); } push_time(); scalar_t *vsum = root->vsum; #ifdef BUILD_PARALLEL #pragma omp parallel for #endif for(index_t u = 0; u < n; u++) { vloc_time[u*(k-1) + l-2] = MATH_INF; index_t i_u0 = (u*(tmax+1)); for(index_t i = 0; i <= tmax; i++) { index_t i_ui = i_u0 + i; if(vsum[i_ui]) { vloc_time[u*(k-1) + l-2] = i; break; } } } fprintf(stdout, " [%.2lfms, %.2lfms]\n", pop_time(), pop_time()); fflush(stdout); } index_t *vloc_min_time = alloc_idxtab(n); vloc_min_timestamp(n, k, vloc_time, vloc_min_time); if(flag_test) { for(index_t u = 0; u < n; u++) { fprintf(out, "%ld\n", vloc_min_time[u]==MATH_INF?UNDEFINED:vloc_min_time[u]); } fflush(out); } else { if(have_output) { vloc_table_out(out, n, k, vloc_time, vloc_min_time, "csv"); } else { vloc_table_out(out, n, k, vloc_time, vloc_min_time, "default"); } } FREE(vloc_time); FREE(vloc_min_time); temppathq_free(root); } break; case CMD_EXHAUST_SEARCH: { push_time(); index_t n = root->n; index_t *reach_time = alloc_idxtab(n); kk = alloc_idxtab(k); get_motif_colors(k, kk); root->k = k; fprintf(stdout, "exhaustive-search [%ld]:", k); exhaustive_search(root, sources[0], reach_time); push_time(); if(have_output) { for(index_t u = 0; u < n; u++) { fprintf(out, "%ld\n", reach_time[u]==MATH_INF?UNDEFINED:reach_time[u]); } fflush(out); } else { for(index_t u = 0; u < n; u++) { fprintf(out, "%6ld\n", reach_time[u]==MATH_INF?UNDEFINED:reach_time[u]); } fflush(out); } // free memory FREE(reach_time); temppathq_free(root); fprintf(stdout, " [%.2lfms %.2lfms]\n", pop_time(), pop_time()); fflush(stdout); } break; default: assert(0); break; } if(kk != (index_t *) 0) { FREE(kk); } if(sources != (index_t *) 0) { FREE(sources); } if(separators != (index_t *) 0) { FREE(separators); } if(color != (index_t *) 0) { FREE(color); } if(have_output) fclose(out); //clode file descriptor double cmd_time = pop_time(); double time = pop_time(); fprintf(stdout, "command done [ %.2lf ms %.2lf ms]\n", cmd_time, time); //if(input_cmd != CMD_NOP) // FREE(cmd_args); //time = pop_time(); fprintf(stdout, "grand total [%.2lf ms] ", time); print_pop_memtrack(); fprintf(stdout, "\n"); fprintf(stdout, "host: %s\n", sysdep_hostname()); fprintf(stdout, "build: %s, %s, %s, %ld x %s\n", #ifdef BUILD_PARALLEL "multithreaded", #else "single thread", #endif #ifdef BUILD_PREFETCH "prefetch", #else "no prefetch", #endif GENF_TYPE, LIMBS_IN_LINE, LIMB_TYPE); fprintf(stdout, "compiler: gcc %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); fflush(stdout); assert(malloc_balance == 0); assert(memtrack_stack_top < 0); assert(start_stack_top < 0); return 0; }
schur_eliminator_impl.h
// Ceres Solver - A fast non-linear least squares minimizer // Copyright 2010, 2011, 2012 Google Inc. All rights reserved. // http://code.google.com/p/ceres-solver/ // // 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 Google Inc. 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. // // Author: sameeragarwal@google.com (Sameer Agarwal) // // TODO(sameeragarwal): row_block_counter can perhaps be replaced by // Chunk::start ? #ifndef CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_ #define CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_ #ifdef CERES_USE_OPENMP #include <omp.h> #endif // Eigen has an internal threshold switching between different matrix // multiplication algorithms. In particular for matrices larger than // EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD it uses a cache friendly // matrix matrix product algorithm that has a higher setup cost. For // matrix sizes close to this threshold, especially when the matrices // are thin and long, the default choice may not be optimal. This is // the case for us, as the default choice causes a 30% performance // regression when we moved from Eigen2 to Eigen3. #define EIGEN_CACHEFRIENDLY_PRODUCT_THRESHOLD 10 #include <algorithm> #include <map> #include <glog/logging.h> #include "Eigen/Dense" #include "ceres/block_random_access_matrix.h" #include "ceres/block_sparse_matrix.h" #include "ceres/block_structure.h" #include "ceres/map_util.h" #include "ceres/schur_eliminator.h" #include "ceres/stl_util.h" #include "ceres/internal/eigen.h" #include "ceres/internal/scoped_ptr.h" namespace ceres { namespace internal { template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>::~SchurEliminator() { STLDeleteElements(&rhs_locks_); } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: Init(int num_eliminate_blocks, const CompressedRowBlockStructure* bs) { CHECK_GT(num_eliminate_blocks, 0) << "SchurComplementSolver cannot be initialized with " << "num_eliminate_blocks = 0."; num_eliminate_blocks_ = num_eliminate_blocks; const int num_col_blocks = bs->cols.size(); const int num_row_blocks = bs->rows.size(); buffer_size_ = 1; chunks_.clear(); lhs_row_layout_.clear(); int lhs_num_rows = 0; // Add a map object for each block in the reduced linear system // and build the row/column block structure of the reduced linear // system. lhs_row_layout_.resize(num_col_blocks - num_eliminate_blocks_); for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) { lhs_row_layout_[i - num_eliminate_blocks_] = lhs_num_rows; lhs_num_rows += bs->cols[i].size; } int r = 0; // Iterate over the row blocks of A, and detect the chunks. The // matrix should already have been ordered so that all rows // containing the same y block are vertically contiguous. Along // the way also compute the amount of space each chunk will need // to perform the elimination. while (r < num_row_blocks) { const int chunk_block_id = bs->rows[r].cells.front().block_id; if (chunk_block_id >= num_eliminate_blocks_) { break; } chunks_.push_back(Chunk()); Chunk& chunk = chunks_.back(); chunk.size = 0; chunk.start = r; int buffer_size = 0; const int e_block_size = bs->cols[chunk_block_id].size; // Add to the chunk until the first block in the row is // different than the one in the first row for the chunk. while (r + chunk.size < num_row_blocks) { const CompressedRow& row = bs->rows[r + chunk.size]; if (row.cells.front().block_id != chunk_block_id) { break; } // Iterate over the blocks in the row, ignoring the first // block since it is the one to be eliminated. for (int c = 1; c < row.cells.size(); ++c) { const Cell& cell = row.cells[c]; if (InsertIfNotPresent( &(chunk.buffer_layout), cell.block_id, buffer_size)) { buffer_size += e_block_size * bs->cols[cell.block_id].size; } } buffer_size_ = max(buffer_size, buffer_size_); ++chunk.size; } CHECK_GT(chunk.size, 0); r += chunk.size; } const Chunk& chunk = chunks_.back(); uneliminated_row_begins_ = chunk.start + chunk.size; if (num_threads_ > 1) { random_shuffle(chunks_.begin(), chunks_.end()); } buffer_.reset(new double[buffer_size_ * num_threads_]); STLDeleteElements(&rhs_locks_); rhs_locks_.resize(num_col_blocks - num_eliminate_blocks_); for (int i = 0; i < num_col_blocks - num_eliminate_blocks_; ++i) { rhs_locks_[i] = new Mutex; } VLOG(1) << "Eliminator threads: " << num_threads_; } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: Eliminate(const BlockSparseMatrixBase* A, const double* b, const double* D, BlockRandomAccessMatrix* lhs, double* rhs) { if (lhs->num_rows() > 0) { lhs->SetZero(); VectorRef(rhs, lhs->num_rows()).setZero(); } const CompressedRowBlockStructure* bs = A->block_structure(); const int num_col_blocks = bs->cols.size(); // Add the diagonal to the schur complement. if (D != NULL) { #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = num_eliminate_blocks_; i < num_col_blocks; ++i) { const int block_id = i - num_eliminate_blocks_; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block_id, block_id, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { const int block_size = bs->cols[i].size; typename EigenTypes<kFBlockSize>::ConstVectorRef diag(D + bs->cols[i].position, block_size); MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); m.block(r, c, block_size, block_size).diagonal() += diag.array().square().matrix(); } } } // Eliminate y blocks one chunk at a time. For each chunk,x3 // compute the entries of the normal equations and the gradient // vector block corresponding to the y block and then apply // Gaussian elimination to them. The matrix ete stores the normal // matrix corresponding to the block being eliminated and array // buffer_ contains the non-zero blocks in the row corresponding // to this y block in the normal equations. This computation is // done in ChunkDiagonalBlockAndGradient. UpdateRhs then applies // gaussian elimination to the rhs of the normal equations, // updating the rhs of the reduced linear system by modifying rhs // blocks for all the z blocks that share a row block/residual // term with the y block. EliminateRowOuterProduct does the // corresponding operation for the lhs of the reduced linear // system. #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = 0; i < chunks_.size(); ++i) { #ifdef CERES_USE_OPENMP int thread_id = omp_get_thread_num(); #else int thread_id = 0; #endif double* buffer = buffer_.get() + thread_id * buffer_size_; const Chunk& chunk = chunks_[i]; const int e_block_id = bs->rows[chunk.start].cells.front().block_id; const int e_block_size = bs->cols[e_block_id].size; VectorRef(buffer, buffer_size_).setZero(); typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix ete(e_block_size, e_block_size); if (D != NULL) { const typename EigenTypes<kEBlockSize>::ConstVectorRef diag(D + bs->cols[e_block_id].position, e_block_size); ete = diag.array().square().matrix().asDiagonal(); } else { ete.setZero(); } typename EigenTypes<kEBlockSize>::Vector g(e_block_size); g.setZero(); // We are going to be computing // // S += F'F - F'E(E'E)^{-1}E'F // // for each Chunk. The computation is broken down into a number of // function calls as below. // Compute the outer product of the e_blocks with themselves (ete // = E'E). Compute the product of the e_blocks with the // corresonding f_blocks (buffer = E'F), the gradient of the terms // in this chunk (g) and add the outer product of the f_blocks to // Schur complement (S += F'F). ChunkDiagonalBlockAndGradient( chunk, A, b, chunk.start, &ete, &g, buffer, lhs); // Normally one wouldn't compute the inverse explicitly, but // e_block_size will typically be a small number like 3, in // which case its much faster to compute the inverse once and // use it to multiply other matrices/vectors instead of doing a // Solve call over and over again. typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix inverse_ete = ete .template selfadjointView<Eigen::Upper>() .ldlt() .solve(Matrix::Identity(e_block_size, e_block_size)); // For the current chunk compute and update the rhs of the reduced // linear system. // // rhs = F'b - F'E(E'E)^(-1) E'b UpdateRhs(chunk, A, b, chunk.start, inverse_ete * g, rhs); // S -= F'E(E'E)^{-1}E'F ChunkOuterProduct(bs, inverse_ete, buffer, chunk.buffer_layout, lhs); } // For rows with no e_blocks, the schur complement update reduces to // S += F'F. NoEBlockRowsUpdate(A, b, uneliminated_row_begins_, lhs, rhs); } template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: BackSubstitute(const BlockSparseMatrixBase* A, const double* b, const double* D, const double* z, double* y) { const CompressedRowBlockStructure* bs = A->block_structure(); #pragma omp parallel for num_threads(num_threads_) schedule(dynamic) for (int i = 0; i < chunks_.size(); ++i) { const Chunk& chunk = chunks_[i]; const int e_block_id = bs->rows[chunk.start].cells.front().block_id; const int e_block_size = bs->cols[e_block_id].size; typename EigenTypes<kEBlockSize>::VectorRef y_block( y + bs->cols[e_block_id].position, e_block_size); typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix ete(e_block_size, e_block_size); if (D != NULL) { const typename EigenTypes<kEBlockSize>::ConstVectorRef diag(D + bs->cols[e_block_id].position, e_block_size); ete = diag.array().square().matrix().asDiagonal(); } else { ete.setZero(); } for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[chunk.start + j]; const double* row_values = A->RowBlockValues(chunk.start + j); const Cell& e_cell = row.cells.front(); DCHECK_EQ(e_block_id, e_cell.block_id); const typename EigenTypes<kRowBlockSize, kEBlockSize>::ConstMatrixRef e_block(row_values + e_cell.position, row.block.size, e_block_size); typename EigenTypes<kRowBlockSize>::Vector sj = typename EigenTypes<kRowBlockSize>::ConstVectorRef (b + bs->rows[chunk.start + j].block.position, row.block.size); for (int c = 1; c < row.cells.size(); ++c) { const int f_block_id = row.cells[c].block_id; const int f_block_size = bs->cols[f_block_id].size; const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef f_block(row_values + row.cells[c].position, row.block.size, f_block_size); const int r_block = f_block_id - num_eliminate_blocks_; sj -= f_block * typename EigenTypes<kFBlockSize>::ConstVectorRef (z + lhs_row_layout_[r_block], f_block_size); } y_block += e_block.transpose() * sj; ete.template selfadjointView<Eigen::Upper>() .rankUpdate(e_block.transpose(), 1.0); } y_block = ete .template selfadjointView<Eigen::Upper>() .ldlt() .solve(y_block); } } // Update the rhs of the reduced linear system. Compute // // F'b - F'E(E'E)^(-1) E'b template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: UpdateRhs(const Chunk& chunk, const BlockSparseMatrixBase* A, const double* b, int row_block_counter, const Vector& inverse_ete_g, double* rhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const int e_block_size = inverse_ete_g.rows(); int b_pos = bs->rows[row_block_counter].block.position; for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[row_block_counter + j]; const double *row_values = A->RowBlockValues(row_block_counter + j); const Cell& e_cell = row.cells.front(); const typename EigenTypes<kRowBlockSize, kEBlockSize>::ConstMatrixRef e_block(row_values + e_cell.position, row.block.size, e_block_size); const typename EigenTypes<kRowBlockSize>::Vector sj = typename EigenTypes<kRowBlockSize>::ConstVectorRef (b + b_pos, row.block.size) - e_block * (inverse_ete_g); for (int c = 1; c < row.cells.size(); ++c) { const int block_id = row.cells[c].block_id; const int block_size = bs->cols[block_id].size; const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef b(row_values + row.cells[c].position, row.block.size, block_size); const int block = block_id - num_eliminate_blocks_; MutexLock l(rhs_locks_[block]); typename EigenTypes<kFBlockSize>::VectorRef (rhs + lhs_row_layout_[block], block_size).noalias() += b.transpose() * sj; } b_pos += row.block.size; } } // Given a Chunk - set of rows with the same e_block, e.g. in the // following Chunk with two rows. // // E F // [ y11 0 0 0 | z11 0 0 0 z51] // [ y12 0 0 0 | z12 z22 0 0 0] // // this function computes twp matrices. The diagonal block matrix // // ete = y11 * y11' + y12 * y12' // // and the off diagonal blocks in the Guass Newton Hessian. // // buffer = [y11'(z11 + z12), y12' * z22, y11' * z51] // // which are zero compressed versions of the block sparse matrices E'E // and E'F. // // and the gradient of the e_block, E'b. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: ChunkDiagonalBlockAndGradient( const Chunk& chunk, const BlockSparseMatrixBase* A, const double* b, int row_block_counter, typename EigenTypes<kEBlockSize, kEBlockSize>::Matrix* ete, typename EigenTypes<kEBlockSize>::Vector* g, double* buffer, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); int b_pos = bs->rows[row_block_counter].block.position; const int e_block_size = ete->rows(); // Iterate over the rows in this chunk, for each row, compute the // contribution of its F blocks to the Schur complement, the // contribution of its E block to the matrix EE' (ete), and the // corresponding block in the gradient vector. for (int j = 0; j < chunk.size; ++j) { const CompressedRow& row = bs->rows[row_block_counter + j]; const double *row_values = A->RowBlockValues(row_block_counter + j); if (row.cells.size() > 1) { EBlockRowOuterProduct(A, row_block_counter + j, lhs); } // Extract the e_block, ETE += E_i' E_i const Cell& e_cell = row.cells.front(); const typename EigenTypes<kRowBlockSize, kEBlockSize>::ConstMatrixRef e_block(row_values + e_cell.position, row.block.size, e_block_size); ete->template selfadjointView<Eigen::Upper>() .rankUpdate(e_block.transpose(), 1.0); // g += E_i' b_i g->noalias() += e_block.transpose() * typename EigenTypes<kRowBlockSize>::ConstVectorRef (b + b_pos, row.block.size); // buffer = E'F. This computation is done by iterating over the // f_blocks for each row in the chunk. for (int c = 1; c < row.cells.size(); ++c) { const int f_block_id = row.cells[c].block_id; const int f_block_size = bs->cols[f_block_id].size; const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef f_block(row_values + row.cells[c].position, row.block.size, f_block_size); double* buffer_ptr = buffer + FindOrDie(chunk.buffer_layout, f_block_id); typename EigenTypes<kEBlockSize, kFBlockSize>::MatrixRef (buffer_ptr, e_block_size, f_block_size).noalias() += e_block.transpose() * f_block; } b_pos += row.block.size; } } // Compute the outer product F'E(E'E)^{-1}E'F and subtract it from the // Schur complement matrix, i.e // // S -= F'E(E'E)^{-1}E'F. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: ChunkOuterProduct(const CompressedRowBlockStructure* bs, const Matrix& inverse_ete, const double* buffer, const BufferLayoutType& buffer_layout, BlockRandomAccessMatrix* lhs) { // This is the most computationally expensive part of this // code. Profiling experiments reveal that the bottleneck is not the // computation of the right-hand matrix product, but memory // references to the left hand side. const int e_block_size = inverse_ete.rows(); BufferLayoutType::const_iterator it1 = buffer_layout.begin(); // S(i,j) -= bi' * ete^{-1} b_j for (; it1 != buffer_layout.end(); ++it1) { const int block1 = it1->first - num_eliminate_blocks_; const int block1_size = bs->cols[it1->first].size; const typename EigenTypes<kEBlockSize, kFBlockSize>::ConstMatrixRef b1(buffer + it1->second, e_block_size, block1_size); const typename EigenTypes<kFBlockSize, kEBlockSize>::Matrix b1_transpose_inverse_ete = b1.transpose() * inverse_ete; BufferLayoutType::const_iterator it2 = it1; for (; it2 != buffer_layout.end(); ++it2) { const int block2 = it2->first - num_eliminate_blocks_; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info == NULL) { continue; } const int block2_size = bs->cols[it2->first].size; const typename EigenTypes<kEBlockSize, kFBlockSize>::ConstMatrixRef b2(buffer + it2->second, e_block_size, block2_size); MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); // We explicitly construct a block object here instead of using // m.block(), as m.block() variant of the constructor does not // allow mixing of template sizing and runtime sizing parameters // like the Matrix class does. Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize> block(m, r, c, block1_size, block2_size); block.noalias() -= b1_transpose_inverse_ete * b2; } } } // For rows with no e_blocks, the schur complement update reduces to S // += F'F. This function iterates over the rows of A with no e_block, // and calls NoEBlockRowOuterProduct on each row. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: NoEBlockRowsUpdate(const BlockSparseMatrixBase* A, const double* b, int row_block_counter, BlockRandomAccessMatrix* lhs, double* rhs) { const CompressedRowBlockStructure* bs = A->block_structure(); for (; row_block_counter < bs->rows.size(); ++row_block_counter) { const CompressedRow& row = bs->rows[row_block_counter]; const double *row_values = A->RowBlockValues(row_block_counter); for (int c = 0; c < row.cells.size(); ++c) { const int block_id = row.cells[c].block_id; const int block_size = bs->cols[block_id].size; const int block = block_id - num_eliminate_blocks_; VectorRef(rhs + lhs_row_layout_[block], block_size).noalias() += (ConstMatrixRef(row_values + row.cells[c].position, row.block.size, block_size).transpose() * ConstVectorRef(b + row.block.position, row.block.size)); } NoEBlockRowOuterProduct(A, row_block_counter, lhs); } } // A row r of A, which has no e_blocks gets added to the Schur // Complement as S += r r'. This function is responsible for computing // the contribution of a single row r to the Schur complement. It is // very similar in structure to EBlockRowOuterProduct except for // one difference. It does not use any of the template // parameters. This is because the algorithm used for detecting the // static structure of the matrix A only pays attention to rows with // e_blocks. This is becase rows without e_blocks are rare and // typically arise from regularization terms in the original // optimization problem, and have a very different structure than the // rows with e_blocks. Including them in the static structure // detection will lead to most template parameters being set to // dynamic. Since the number of rows without e_blocks is small, the // lack of templating is not an issue. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: NoEBlockRowOuterProduct(const BlockSparseMatrixBase* A, int row_block_index, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const CompressedRow& row = bs->rows[row_block_index]; const double *row_values = A->RowBlockValues(row_block_index); for (int i = 0; i < row.cells.size(); ++i) { const int block1 = row.cells[i].block_id - num_eliminate_blocks_; DCHECK_GE(block1, 0); const int block1_size = bs->cols[row.cells[i].block_id].size; const ConstMatrixRef b1(row_values + row.cells[i].position, row.block.size, block1_size); int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block1, &r, &c, &row_stride, &col_stride); if (cell_info != NULL) { MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); m.block(r, c, block1_size, block1_size) .selfadjointView<Eigen::Upper>() .rankUpdate(b1.transpose(), 1.0); } for (int j = i + 1; j < row.cells.size(); ++j) { const int block2 = row.cells[j].block_id - num_eliminate_blocks_; DCHECK_GE(block2, 0); DCHECK_LT(block1, block2); int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info == NULL) { continue; } const int block2_size = bs->cols[row.cells[j].block_id].size; MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); m.block(r, c, block1_size, block2_size).noalias() += b1.transpose() * ConstMatrixRef(row_values + row.cells[j].position, row.block.size, block2_size); } } } // For a row with an e_block, compute the contribition S += F'F. This // function has the same structure as NoEBlockRowOuterProduct, except // that this function uses the template parameters. template <int kRowBlockSize, int kEBlockSize, int kFBlockSize> void SchurEliminator<kRowBlockSize, kEBlockSize, kFBlockSize>:: EBlockRowOuterProduct(const BlockSparseMatrixBase* A, int row_block_index, BlockRandomAccessMatrix* lhs) { const CompressedRowBlockStructure* bs = A->block_structure(); const CompressedRow& row = bs->rows[row_block_index]; const double *row_values = A->RowBlockValues(row_block_index); for (int i = 1; i < row.cells.size(); ++i) { const int block1 = row.cells[i].block_id - num_eliminate_blocks_; DCHECK_GE(block1, 0); const int block1_size = bs->cols[row.cells[i].block_id].size; const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef b1(row_values + row.cells[i].position, row.block.size, block1_size); { int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block1, &r, &c, &row_stride, &col_stride); if (cell_info == NULL) { continue; } MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize> block(m, r, c, block1_size, block1_size); block.template selfadjointView<Eigen::Upper>() .rankUpdate(b1.transpose(), 1.0); } for (int j = i + 1; j < row.cells.size(); ++j) { const int block2 = row.cells[j].block_id - num_eliminate_blocks_; DCHECK_GE(block2, 0); DCHECK_LT(block1, block2); const int block2_size = bs->cols[row.cells[j].block_id].size; int r, c, row_stride, col_stride; CellInfo* cell_info = lhs->GetCell(block1, block2, &r, &c, &row_stride, &col_stride); if (cell_info == NULL) { continue; } const typename EigenTypes<kRowBlockSize, kFBlockSize>::ConstMatrixRef b2(row_values + row.cells[j].position, row.block.size, block2_size); MutexLock l(&cell_info->m); MatrixRef m(cell_info->values, row_stride, col_stride); Eigen::Block<MatrixRef, kFBlockSize, kFBlockSize> block(m, r, c, block1_size, block2_size); block.noalias() += b1.transpose() * b2; } } } } // namespace internal } // namespace ceres #endif // CERES_INTERNAL_SCHUR_ELIMINATOR_IMPL_H_
Layers.h
// // smarties // Copyright (c) 2018 CSE-Lab, ETH Zurich, Switzerland. All rights reserved. // Distributed under the terms of the MIT license. // // Created by Guido Novati (novatig@ethz.ch). // #ifndef smarties_Layers_h #define smarties_Layers_h #include "Parameters.h" #include "Activation.h" #include "Functions.h" #ifndef __STDC_VERSION__ //it should never be defined with g++ #define __STDC_VERSION__ 0 #endif #if defined(USE_MKL) #include "mkl_cblas.h" #elif defined(USE_OPENBLAS) #include "cblas.h" #else #define USE_OMPSIMD_BLAS #endif //#include <immintrin.h> namespace smarties { #ifdef USE_OMPSIMD_BLAS template<typename T> inline static void GEMVomp(const Uint NX, const Uint NY, const Uint S, const T * __restrict__ const _W, const T * __restrict__ const _X, T * __restrict__ const _Y) { assert(_W not_eq nullptr && _X not_eq nullptr && _Y not_eq nullptr); #if 0 for (Uint o=0; o<NY; ++o) { const T* __restrict__ const W = _W + S * o; T Y = 0; #pragma omp simd aligned(_X, W : VEC_WIDTH) reduction(+:Y) for (Uint i=0; i<NX; ++i) Y += W[i] * _X[i]; _Y[o] += Y; } #else static constexpr Uint cacheLineLen = 64 / sizeof(T); for (Uint I=0; I<NX; I+=cacheLineLen) for (Uint o=0; o<NY; ++o) { const T* __restrict__ const W = _W + S * o; T Y = 0; const Uint Ninner = std::min(NX, I+cacheLineLen); #pragma omp simd aligned(_X, W : VEC_WIDTH) reduction(+:Y) for (Uint i=I; i<Ninner; ++i) Y += W[i] * _X[i]; _Y[o] += Y; } #endif } #endif // Base class of all layer types. To insert a new layer type, overwrite all // virtual functions. class Layer { public: const Uint size, ID, link, bInput; Uint bOutput; Uint spanCompInpGrads = 0, startCompInpGrads = 0; inline Uint number() const { return ID; } inline Uint nOutputs() const { return size; } // Should return the number of weights and biases required by layer virtual void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const = 0; // Should return work memory that allows the network to compute forward step // and then, without re-calling forward, compute backward step. // See the LSTM class for an example on working out of the box. virtual void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const = 0; // Some classes might allow user to specify an initial value for the bias // vector (eg. parametric layer or linear output layer) virtual void biasInitialValues(const std::vector<Real> init) = 0; Layer( Uint _ID, Uint _size, bool bOut, bool bInp = false, Uint _link = 0): size(_size), ID(_ID), link(_link), bInput(bInp), bOutput(bOut) {} virtual std::string printSpecs() const = 0; virtual ~Layer() {} virtual void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const = 0; // forward step without recurrent connection: inline void forward( const Activation*const curr, const Parameters*const para) const { return forward(nullptr, curr, para); } virtual void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const = 0; // forward step without recurrent connection: inline void backward( const Activation*const curr, const Parameters*const grad, const Parameters*const para) const { return backward(nullptr, curr, nullptr, grad, para); } void backward(const Uint NI, const Uint NO, const Uint NOsimd, const Uint NR, const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const { const nnReal* const deltas = curr->E(ID); if(NO == 0) return; if( spanCompInpGrads ) { nnReal* const errors = curr->E(ID-link); const nnReal* const weight = para->W(ID); #ifdef USE_OMPSIMD_BLAS GEMVomp(NO, spanCompInpGrads, NOsimd, weight + startCompInpGrads * NOsimd, deltas, errors + startCompInpGrads); #else SMARTIES_gemv(CblasRowMajor, CblasNoTrans, spanCompInpGrads, NO, 1, weight + startCompInpGrads * NOsimd, NOsimd, deltas, 1, 1, errors + startCompInpGrads, 1); #endif } if(NR && prev not_eq nullptr) { nnReal* const errors = prev->E(ID); const nnReal* const weight = para->W(ID) +NOsimd*NI; #ifdef USE_OMPSIMD_BLAS GEMVomp(NO, NR, NOsimd, weight, deltas, errors); #else SMARTIES_gemv(CblasRowMajor, CblasNoTrans, NR, NO, 1, weight, NOsimd, deltas, 1, 1, errors, 1); #endif } if(grad == nullptr) return; { nnReal* const grad_b = grad->B(ID); #pragma omp simd aligned(deltas, grad_b : VEC_WIDTH) for(Uint o=0; o<NO; ++o) grad_b[o] += deltas[o]; } { const nnReal* const inputs = curr->Y(ID-link); nnReal* const grad_w = grad->W(ID); for(Uint i=0; i<NI; ++i) { nnReal* const G = grad_w + NOsimd*i; #pragma omp simd aligned(deltas,inputs,G : VEC_WIDTH) for(Uint o=0; o<NO; ++o) G[o] += inputs[i] * deltas[o]; } } if(NR && prev not_eq nullptr) { const nnReal* const inputs = prev->Y(ID); nnReal* const grad_w = grad->W(ID) +NOsimd*NI; for(Uint i=0; i<NR; ++i) { nnReal* const G = grad_w + NOsimd*i; #pragma omp simd aligned(deltas, inputs, G : VEC_WIDTH) for(Uint o=0; o<NO; ++o) G[o] += inputs[i] * deltas[o]; } } } // Initialize the weights and biases. Probably by sampling. virtual void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const = 0; virtual size_t save(const Parameters * const para, float * tmp) const = 0; virtual size_t restart(const Parameters * const para, const float * tmp) const = 0; }; class InputLayer: public Layer { public: InputLayer(Uint _size, Uint _ID) : Layer(_ID, _size, false, true) { } std::string printSpecs() const override { return "(" + std::to_string(ID) + ") Input Layer of size:" + std::to_string(size) + "\n"; } void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const override { assert(nWeight.size() == 0 && nBiases.size() == 0); nWeight.push_back(0); nBiases.push_back(0); } void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const override { assert(sizes.size() == 0 && bOutputs.size() == 0); sizes.push_back(size); bOutputs.push_back(false); bInputs.push_back(bInput); } void biasInitialValues(const std::vector<Real> init) override { } void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const override { #ifdef SMARTIES_INPUT_SANITIZE // In case input has a very wide kurtosis, network grads might explode. // (Remember that smarties gradually learns mean and stdev, so each input // variable to the net can be thought to have mean 0 and stdev 1) // Almost all inputs will be from -6 and 6 stdevs and will be untouched. // From from 6 to 111 stdevs away, we smoothly transition to sqrt(x). // Beyond 111 stdevs away we log the input to avoid exploding gradients. nnReal* const ret = curr->Y(ID); for (Uint j=0; j<size; ++j) { const nnReal sign = ret[j]>0 ? 1 : -1, absX = std::fabs(ret[j]); if (absX > 111) { ret[j] = sign * 9.02 * std::log(absX - 56.88); } else if (absX > 6) { ret[j] = sign * std::sqrt(12 * absX - 36); } // else leave as is } #endif } void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const override { } void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const override { } size_t save(const Parameters * const para, float * tmp) const override { return 0; } size_t restart(const Parameters * const para, const float * tmp) const override { return 0; } }; class JoinLayer: public Layer { const Uint nJoin; public: JoinLayer(Uint _ID, Uint _N, Uint _nJ): Layer(_ID,_N,false), nJoin(_nJ) { assert(nJoin>1); } std::string printSpecs() const override { return "(" + std::to_string(ID) + ") Join Layer of size:" + std::to_string(size) + " joining the previous " + std::to_string(nJoin) + " layers\n"; } void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const override { assert(nWeight.size() == 0 && nBiases.size() == 0); nWeight.push_back(0); nBiases.push_back(0); } void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const override { assert(sizes.size() == 0 && bOutputs.size() == 0); sizes.push_back(size); bOutputs.push_back(bOutput); bInputs.push_back(bInput); } void biasInitialValues(const std::vector<Real> init) override { } void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const override { nnReal* const ret = curr->Y(ID); Uint k = 0; for (Uint i=1; i<=nJoin; ++i) { const nnReal* const inputs = curr->Y(ID-i); for (Uint j=0; j<curr->sizes[ID-i]; ++j) ret[k++] = inputs[j]; } assert(k==size); } void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const override { const nnReal* const errors = curr->E(ID); Uint k = 0; for (Uint i=1; i<=nJoin; ++i) { nnReal* const ret = curr->E(ID-i); for (Uint j=0; j<curr->sizes[ID-i]; ++j) ret[j] = errors[k++]; } assert(k==size); } void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const override { } size_t save(const Parameters * const para, float * tmp) const override { return 0; } size_t restart(const Parameters * const para, const float * tmp) const override { return 0; } }; class ParametricResidualLayer: public Layer { public: ParametricResidualLayer(Uint _ID, Uint _N): Layer(_ID, _N, false) { } std::string printSpecs() const override { return "("+ std::to_string(ID) +") Parametric Residual Connection of size:" + std::to_string(size) + "\n"; } void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const override { nWeight.push_back(size); nBiases.push_back(size); } void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const override { sizes.push_back(size); bOutputs.push_back(bOutput); bInputs.push_back(false); } void biasInitialValues(const std::vector<Real> init) override { } void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const override { nnReal* const ret = curr->Y(ID); assert(curr->sizes[ID-1] >= size); memcpy(ret, curr->Y(ID-1), size * sizeof(nnReal)); const nnReal* const W = para->W(ID); const nnReal* const B = para->B(ID); const nnReal* const inp = curr->Y(ID-2); const Uint sizeInp = std::min(curr->sizes[ID-2], size); #pragma omp simd aligned(ret, inp, W, B : VEC_WIDTH) for (Uint j=0; j<sizeInp; ++j) ret[j] += inp[j] * W[j] + B[j]; } void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const override { const nnReal* const delta = curr->E(ID); assert(curr->sizes[ID-1] >= size); memcpy(curr->E(ID-1), delta, size * sizeof(nnReal) ); nnReal* const gradInp = curr->E(ID-2); const nnReal* const W = para->W(ID); const nnReal* const inp = curr->Y(ID-2); const Uint sizeInp = std::min(curr->sizes[ID-2], size); if(grad == nullptr) { #pragma omp simd aligned(delta, W, gradInp : VEC_WIDTH) for (Uint j=0; j<sizeInp; ++j) gradInp[j] += delta[j] * W[j]; return; } nnReal* const gradB = grad->B(ID); nnReal* const gradW = grad->W(ID); #pragma omp simd aligned(delta,inp,W, gradB,gradW,gradInp : VEC_WIDTH) for (Uint j=0; j<sizeInp; ++j) { gradInp[j] += delta[j] * W[j]; gradW[j] += delta[j] * inp[j]; gradB[j] += delta[j]; } } void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const override { for(Uint o=0; o<size; ++o) W->B(ID)[o] = 0.0; for(Uint o=0; o<size; ++o) W->W(ID)[o] = 1.0; } size_t save(const Parameters * const para, float * tmp) const override { const nnReal* const bias = para->B(ID); const nnReal* const weight = para->W(ID); for(Uint o=0; o<size; ++o) *(tmp++) = (float) weight[o]; for(Uint o=0; o<size; ++o) *(tmp++) = (float) bias[o]; return 2*size; } size_t restart(const Parameters * const para, const float * tmp) const override { nnReal* const bias = para->B(ID); nnReal* const weight = para->W(ID); for (Uint n=0; n<size; ++n) weight[n] = (nnReal) *(tmp++); for (Uint n=0; n<size; ++n) bias[n] = (nnReal) *(tmp++); return 2*size; } }; class ResidualLayer: public Layer { public: ResidualLayer(Uint _ID, Uint _N): Layer(_ID,_N,false) { } std::string printSpecs() const override { return "(" + std::to_string(ID) + ") Residual Connection of size:" + std::to_string(size) + "\n"; } void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const override { nWeight.push_back(0); nBiases.push_back(0); } void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const override { sizes.push_back(size); bOutputs.push_back(bOutput); bInputs.push_back(false); } void biasInitialValues(const std::vector<Real> init) override { } void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const override { nnReal* const ret = curr->Y(ID); std::memset( ret, 0, size * sizeof(nnReal) ); for (Uint i=1; i<=2; ++i) { const Uint sizeInp = std::min(curr->sizes[ID-i], size); const nnReal* const inputs = curr->Y(ID-i); #pragma omp simd aligned(ret, inputs : VEC_WIDTH) for (Uint j=0; j<sizeInp; ++j) ret[j] += inputs[j]; } } void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const override { const nnReal* const errors = curr->E(ID); for (Uint i=1; i<=2; ++i) { const Uint sizeInp = std::min(curr->sizes[ID-i], size); memcpy( curr->E(ID-i), errors, sizeInp * sizeof(nnReal) ); } } void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const override { } size_t save(const Parameters * const para, float * tmp) const override { return 0; } size_t restart(const Parameters * const para, const float * tmp) const override { return 0; } }; class ParamLayer: public Layer { const std::unique_ptr<Function> func; std::vector<nnReal> initVals; public: ParamLayer(Uint _ID, Uint _size, std::string funcType, std::vector<Real>init) : Layer(_ID, _size, true), func(makeFunction(funcType)) { biasInitialValues(init); } std::string printSpecs() const override { std::string ret = "(" + std::to_string(ID) + ") Parameter Layer of size:" + std::to_string(size) + ". Initialized:"; for(Uint i=0; i<size; ++i) { ret += " " + std::to_string(initVals[i]); } return ret + "\n"; } void requiredParameters(std::vector<Uint>& nWeight, std::vector<Uint>& nBiases ) const override { nWeight.push_back(0); nBiases.push_back(size); } void requiredActivation(std::vector<Uint>& sizes, std::vector<Uint>& bOutputs, std::vector<Uint>& bInputs) const override { sizes.push_back(size); bOutputs.push_back(true); bInputs.push_back(bInput); } void biasInitialValues(const std::vector<Real> init) override { if(init.size() != size) _die("size of init:%lu.", init.size()); initVals.resize(size, 0); std::copy(init.begin(), init.end(), initVals.begin()); } void forward( const Activation*const prev, const Activation*const curr, const Parameters*const para) const override { nnReal* const inputs = curr->X(ID); nnReal* const output = curr->Y(ID); const nnReal* const bias = para->B(ID); for (Uint n=0; n<size; ++n) { inputs[n] = bias[n]; output[n] = func->eval(bias[n]); } } void backward( const Activation*const prev, const Activation*const curr, const Activation*const next, const Parameters*const grad, const Parameters*const para) const override { const nnReal* const inputs = curr->X(ID); const nnReal* const outval = curr->Y(ID); nnReal* const deltas = curr->E(ID); if(grad == nullptr) { for(Uint o=0; o<size; ++o) deltas[o] *= func->evalDiff(inputs[o], outval[o]); } else { nnReal* const grad_b = grad->B(ID); for(Uint o=0; o<size; ++o) { deltas[o] *= func->evalDiff(inputs[o], outval[o]); grad_b[o] += deltas[o]; } } } void initialize(std::mt19937& G, const Parameters*const W, Real initializationFac) const override { nnReal* const biases = W->B(ID); for(Uint o=0; o<size; ++o) biases[o] = func->inverse(initVals[o]); } size_t save(const Parameters * const para, float * tmp) const override { const nnReal* const bias = para->B(ID); for (Uint n=0; n<size; ++n) tmp[n] = (float) bias[n]; return size; } size_t restart(const Parameters * const para, const float * tmp) const override { nnReal* const bias = para->B(ID); for (Uint n=0; n<size; ++n) bias[n] = (nnReal) tmp[n]; return size; } }; } // end namespace smarties #endif // smarties_Quadratic_term_h
_interpolate3d.c
/* Generated by Cython 0.22 */ #define PY_SSIZE_T_CLEAN #ifndef CYTHON_USE_PYLONG_INTERNALS #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 0 #else #include "pyconfig.h" #ifdef PYLONG_BITS_IN_DIGIT #define CYTHON_USE_PYLONG_INTERNALS 1 #else #define CYTHON_USE_PYLONG_INTERNALS 0 #endif #endif #endif #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03020000) #error Cython requires Python 2.6+ or Python 3.2+. #else #define CYTHON_ABI "0_22" #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #if PY_MAJOR_VERSION >= 3 #define Py_TPFLAGS_CHECKTYPES 0 #define Py_TPFLAGS_HAVE_INDEX 0 #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE) #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #else #define CYTHON_PEP393_ENABLED 0 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #define __Pyx_PyFrozenSet_Size(s) PyObject_Size(s) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #define __Pyx_PyFrozenSet_Size(s) PySet_Size(s) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #ifndef CYTHON_INLINE #if defined(__GNUC__) #define CYTHON_INLINE __inline__ #elif defined(_MSC_VER) #define CYTHON_INLINE __inline #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_INLINE inline #else #define CYTHON_INLINE #endif #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { /* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is a quiet NaN. */ float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #define __Pyx_void_to_None(void_result) (void_result, Py_INCREF(Py_None), Py_None) #ifdef __cplusplus template<typename T> void __Pyx_call_destructor(T* x) { x->~T(); } template<typename T> class __Pyx_FakeReference { public: __Pyx_FakeReference() : ptr(NULL) { } __Pyx_FakeReference(T& ref) : ptr(&ref) { } T *operator->() { return ptr; } operator T&() { return *ptr; } private: T *ptr; }; #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #define __PYX_HAVE___interpolate3d #define __PYX_HAVE_API___interpolate3d #include "string.h" #include "stdio.h" #include "stdlib.h" #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "math.h" #include "pythread.h" #include "pystate.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #ifdef PYREX_WITHOUT_ASSERTIONS #define CYTHON_WITHOUT_ASSERTIONS #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \ (sizeof(type) < sizeof(Py_ssize_t)) || \ (sizeof(type) > sizeof(Py_ssize_t) && \ likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX) && \ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \ v == (type)PY_SSIZE_T_MIN))) || \ (sizeof(type) == sizeof(Py_ssize_t) && \ (is_signed || likely(v < (type)PY_SSIZE_T_MAX || \ v == (type)PY_SSIZE_T_MAX))) ) static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) #if PY_MAJOR_VERSION < 3 static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #else #define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen #endif #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x); static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_COMPILING_IN_CPYTHON #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static PyObject *__pyx_m; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "_interpolate3d.pyx", "__init__.pxd", "stringsource", "type.pxd", }; #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; struct __pyx_memoryview_obj; typedef struct { struct __pyx_memoryview_obj *memview; char *data; Py_ssize_t shape[8]; Py_ssize_t strides[8]; Py_ssize_t suboffsets[8]; } __Pyx_memviewslice; #include <pythread.h> #ifndef CYTHON_ATOMICS #define CYTHON_ATOMICS 1 #endif #define __pyx_atomic_int_type int #if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \ (__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \ !defined(__i386__) #define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1) #define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1) #ifdef __PYX_DEBUG_ATOMICS #warning "Using GNU atomics" #endif #elif CYTHON_ATOMICS && MSC_VER #include <Windows.h> #define __pyx_atomic_int_type LONG #define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #warning "Using MSVC atomics" #endif #elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0 #define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value) #define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value) #ifdef __PYX_DEBUG_ATOMICS #warning "Using Intel atomics" #endif #else #undef CYTHON_ATOMICS #define CYTHON_ATOMICS 0 #ifdef __PYX_DEBUG_ATOMICS #warning "Not using atomics" #endif #endif typedef volatile __pyx_atomic_int_type __pyx_atomic_int; #if CYTHON_ATOMICS #define __pyx_add_acquisition_count(memview) \ __pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview) \ __pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock) #else #define __pyx_add_acquisition_count(memview) \ __pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #define __pyx_sub_acquisition_count(memview) \ __pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock) #endif /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":726 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":727 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":728 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":729 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":733 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":734 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":735 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":736 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":740 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":741 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":750 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":751 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":752 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":754 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":755 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":756 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":758 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":759 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":761 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":762 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":763 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif /*--- Type declarations ---*/ struct __pyx_array_obj; struct __pyx_MemviewEnum_obj; struct __pyx_memoryview_obj; struct __pyx_memoryviewslice_obj; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":765 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":766 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":767 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":769 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; /* "View.MemoryView":99 * * @cname("__pyx_array") * cdef class array: # <<<<<<<<<<<<<< * * cdef: */ struct __pyx_array_obj { PyObject_HEAD char *data; Py_ssize_t len; char *format; int ndim; Py_ssize_t *_shape; Py_ssize_t *_strides; Py_ssize_t itemsize; PyObject *mode; PyObject *_format; void (*callback_free_data)(void *); int free_data; int dtype_is_object; }; /* "View.MemoryView":269 * * @cname('__pyx_MemviewEnum') * cdef class Enum(object): # <<<<<<<<<<<<<< * cdef object name * def __init__(self, name): */ struct __pyx_MemviewEnum_obj { PyObject_HEAD PyObject *name; }; /* "View.MemoryView":302 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_memoryview_obj { PyObject_HEAD struct __pyx_vtabstruct_memoryview *__pyx_vtab; PyObject *obj; PyObject *_size; PyObject *_array_interface; PyThread_type_lock lock; __pyx_atomic_int acquisition_count[2]; __pyx_atomic_int *acquisition_count_aligned_p; Py_buffer view; int flags; int dtype_is_object; __Pyx_TypeInfo *typeinfo; }; /* "View.MemoryView":921 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_memoryviewslice_obj { struct __pyx_memoryview_obj __pyx_base; __Pyx_memviewslice from_slice; PyObject *from_object; PyObject *(*to_object_func)(char *); int (*to_dtype_func)(char *, PyObject *); }; /* "View.MemoryView":302 * * @cname('__pyx_memoryview') * cdef class memoryview(object): # <<<<<<<<<<<<<< * * cdef object obj */ struct __pyx_vtabstruct_memoryview { char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *); PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *); PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *); PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *); }; static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview; /* "View.MemoryView":921 * * @cname('__pyx_memoryviewslice') * cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<< * "Internal class for passing memoryview slices to Python" * */ struct __pyx_vtabstruct__memoryviewslice { struct __pyx_vtabstruct_memoryview __pyx_base; }; static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice; /* --- Runtime support code (head) --- */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil) \ if (acquire_gil) { \ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ PyGILState_Release(__pyx_gilstate_save); \ } else { \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil) \ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext() \ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_XDECREF(tmp); \ } while (0) #define __Pyx_DECREF_SET(r, v) do { \ PyObject *tmp = (PyObject *) r; \ r = v; __Pyx_DECREF(tmp); \ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif static PyObject *__Pyx_GetBuiltinName(PyObject *name); static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \ const char* function_name); static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); static CYTHON_INLINE int __Pyx_PyDict_Contains(PyObject* item, PyObject* dict, int eq) { int result = PyDict_Contains(dict, item); return unlikely(result < 0) ? result : (result == (eq == Py_EQ)); } #if PY_MAJOR_VERSION >= 3 static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); #define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ __Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \ (is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \ __Pyx_SetItemInt_Generic(o, to_py_func(i), v))) static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v); static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, int wraparound, int boundscheck); static CYTHON_INLINE int __Pyx_IterFinish(void); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg); #endif #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func); #else #define __Pyx_PyObject_CallNoArg(func) __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL) #endif static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg); static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name); static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); static void __Pyx_UnpackTupleError(PyObject *, Py_ssize_t index); static CYTHON_INLINE int __Pyx_unpack_tuple2(PyObject* tuple, PyObject** value1, PyObject** value2, int is_tuple, int has_known_size, int decref_tuple); static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* dict, int is_dict, PyObject* method_name, Py_ssize_t* p_orig_length, int* p_is_dict); static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* dict_or_iter, Py_ssize_t orig_length, Py_ssize_t* ppos, PyObject** pkey, PyObject** pvalue, PyObject** pitem, int is_dict); #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_PyList_Append(L,x) PyList_Append(L,x) #endif static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact); static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); #define __Pyx_BufPtrStrided1d(type, buf, i0, s0) (type)((char*)buf + i0 * s0) static CYTHON_INLINE long __Pyx_div_long(long, long); /* proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif #define __Pyx_BufPtrStrided3d(type, buf, i0, s0, i1, s1, i2, s2) (type)((char*)buf + i0 * s0 + i1 * s1 + i2 * s2) static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); #include <string.h> static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals #else #define __Pyx_PyString_Equals __Pyx_PyBytes_Equals #endif static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t, Py_ssize_t); /* proto */ #define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)); static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ __Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \ (is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \ __Pyx_GetItemInt_Generic(o, to_py_func(i)))) #define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ __Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); #define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \ (__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \ __Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \ (PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL)) static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j); static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck); static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) { PyListObject* L = (PyListObject*) list; Py_ssize_t len = Py_SIZE(list); if (likely(L->allocated > len)) { Py_INCREF(x); PyList_SET_ITEM(list, len, x); Py_SIZE(list) = len+1; return 0; } return PyList_Append(list, x); } #else #define __Pyx_ListComp_Append(L,x) PyList_Append(L,x) #endif static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) { #if CYTHON_COMPILING_IN_CPYTHON PyObject* none = _PyList_Extend((PyListObject*)L, v); if (unlikely(!none)) return -1; Py_DECREF(none); return 0; #else return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v); #endif } static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname); static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback); static int __Pyx_SetVtable(PyObject *dict, void *vtable); static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type); #define __Pyx_CyFunction_USED 1 #include <structmember.h> #define __Pyx_CYFUNCTION_STATICMETHOD 0x01 #define __Pyx_CYFUNCTION_CLASSMETHOD 0x02 #define __Pyx_CYFUNCTION_CCLASS 0x04 #define __Pyx_CyFunction_GetClosure(f) \ (((__pyx_CyFunctionObject *) (f))->func_closure) #define __Pyx_CyFunction_GetClassObj(f) \ (((__pyx_CyFunctionObject *) (f))->func_classobj) #define __Pyx_CyFunction_Defaults(type, f) \ ((type *)(((__pyx_CyFunctionObject *) (f))->defaults)) #define __Pyx_CyFunction_SetDefaultsGetter(f, g) \ ((__pyx_CyFunctionObject *) (f))->defaults_getter = (g) typedef struct { PyCFunctionObject func; #if PY_VERSION_HEX < 0x030500A0 PyObject *func_weakreflist; #endif PyObject *func_dict; PyObject *func_name; PyObject *func_qualname; PyObject *func_doc; PyObject *func_globals; PyObject *func_code; PyObject *func_closure; PyObject *func_classobj; void *defaults; int defaults_pyobjects; int flags; PyObject *defaults_tuple; PyObject *defaults_kwdict; PyObject *(*defaults_getter)(PyObject *); PyObject *func_annotations; } __pyx_CyFunctionObject; static PyTypeObject *__pyx_CyFunctionType = 0; #define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ __Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code) static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *self, PyObject *module, PyObject *globals, PyObject* code); static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m, size_t size, int pyobjects); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m, PyObject *tuple); static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m, PyObject *dict); static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m, PyObject *dict); static int __Pyx_CyFunction_init(void); typedef struct { __pyx_CyFunctionObject func; PyObject *__signatures__; PyObject *type; PyObject *self; } __pyx_FusedFunctionObject; #define __pyx_FusedFunction_NewEx(ml, flags, qualname, self, module, globals, code) \ __pyx_FusedFunction_New(__pyx_FusedFunctionType, ml, flags, qualname, self, module, globals, code) static PyObject *__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject *qualname, PyObject *self, PyObject *module, PyObject *globals, PyObject *code); static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self); static PyTypeObject *__pyx_FusedFunctionType = NULL; static int __pyx_FusedFunction_init(void); #define __Pyx_FusedFunction_USED typedef struct { int code_line; PyCodeObject* code_object; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); #define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d #define __Pyx_MEMVIEW_DIRECT 1 #define __Pyx_MEMVIEW_PTR 2 #define __Pyx_MEMVIEW_FULL 4 #define __Pyx_MEMVIEW_CONTIG 8 #define __Pyx_MEMVIEW_STRIDED 16 #define __Pyx_MEMVIEW_FOLLOW 32 #define __Pyx_IS_C_CONTIG 1 #define __Pyx_IS_F_CONTIG 2 static int __Pyx_init_memviewslice( struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference); static CYTHON_INLINE int __pyx_add_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); static CYTHON_INLINE int __pyx_sub_acquisition_count_locked( __pyx_atomic_int *acquisition_count, PyThread_type_lock lock); #define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p) #define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview)) #define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__) #define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__) static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int); static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int); static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b); static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_float(PyObject *); static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *); static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0}; static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1}; static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *); static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character); #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); #if CYTHON_CCOMPLEX #define __Pyx_c_eqf(a, b) ((a)==(b)) #define __Pyx_c_sumf(a, b) ((a)+(b)) #define __Pyx_c_difff(a, b) ((a)-(b)) #define __Pyx_c_prodf(a, b) ((a)*(b)) #define __Pyx_c_quotf(a, b) ((a)/(b)) #define __Pyx_c_negf(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zerof(z) ((z)==(float)0) #define __Pyx_c_conjf(z) (::std::conj(z)) #if 1 #define __Pyx_c_absf(z) (::std::abs(z)) #define __Pyx_c_powf(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zerof(z) ((z)==0) #define __Pyx_c_conjf(z) (conjf(z)) #if 1 #define __Pyx_c_absf(z) (cabsf(z)) #define __Pyx_c_powf(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); #if CYTHON_CCOMPLEX #define __Pyx_c_eq(a, b) ((a)==(b)) #define __Pyx_c_sum(a, b) ((a)+(b)) #define __Pyx_c_diff(a, b) ((a)-(b)) #define __Pyx_c_prod(a, b) ((a)*(b)) #define __Pyx_c_quot(a, b) ((a)/(b)) #define __Pyx_c_neg(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero(z) ((z)==(double)0) #define __Pyx_c_conj(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs(z) (::std::abs(z)) #define __Pyx_c_pow(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero(z) ((z)==0) #define __Pyx_c_conj(z) (conj(z)) #if 1 #define __Pyx_c_abs(z) (cabs(z)) #define __Pyx_c_pow(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, char order, int ndim); static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize); static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object); static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig); static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); static int __Pyx_check_binary_version(void); #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif static PyObject *__Pyx_ImportModule(const char *name); static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto*/ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src); /* proto*/ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp); /* proto*/ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value); /* proto*/ /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from 'cpython.object' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'libc.stdlib' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'cython.view' */ /* Module declarations from 'cython' */ /* Module declarations from '_interpolate3d' */ static PyTypeObject *__pyx_array_type = 0; static PyTypeObject *__pyx_MemviewEnum_type = 0; static PyTypeObject *__pyx_memoryview_type = 0; static PyTypeObject *__pyx_memoryviewslice_type = 0; static PyObject *generic = 0; static PyObject *strided = 0; static PyObject *indirect = 0; static PyObject *contiguous = 0; static PyObject *indirect_contiguous = 0; static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/ static void *__pyx_align_pointer(void *, size_t); /*proto*/ static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/ static PyObject *_unellipsify(PyObject *, int); /*proto*/ static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/ static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/ static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/ static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/ static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/ static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/ static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/ static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/ static int __pyx_memoryview_err(PyObject *, char *); /*proto*/ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/ static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "_interpolate3d" int __pyx_module_is_main__interpolate3d = 0; /* Implementation of '_interpolate3d' */ static PyObject *__pyx_builtin_ImportError; static PyObject *__pyx_builtin_AttributeError; static PyObject *__pyx_builtin_TypeError; static PyObject *__pyx_builtin_ord; static PyObject *__pyx_builtin_zip; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_enumerate; static PyObject *__pyx_builtin_Ellipsis; static PyObject *__pyx_builtin_id; static PyObject *__pyx_builtin_IndexError; static PyObject *__pyx_pf_14_interpolate3d_interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */ static PyObject *__pyx_pf_14_interpolate3d_2interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED int __pyx_v_n, PyArrayObject *__pyx_v_x, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_z, int __pyx_v_n_x_vals, PyArrayObject *__pyx_v_x_vals, int __pyx_v_n_y_vals, PyArrayObject *__pyx_v_y_vals, int __pyx_v_n_z_vals, PyArrayObject *__pyx_v_z_vals, PyArrayObject *__pyx_v_vals, PyArrayObject *__pyx_v_result_array); /* proto */ static PyObject *__pyx_pf_14_interpolate3d_4interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED int __pyx_v_n, PyArrayObject *__pyx_v_x, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_z, int __pyx_v_n_x_vals, PyArrayObject *__pyx_v_x_vals, int __pyx_v_n_y_vals, PyArrayObject *__pyx_v_y_vals, int __pyx_v_n_z_vals, PyArrayObject *__pyx_v_z_vals, PyArrayObject *__pyx_v_vals, PyArrayObject *__pyx_v_result_array); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */ static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */ static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */ static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */ static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */ static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */ static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */ static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */ static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/ static char __pyx_k_[] = "()"; static char __pyx_k_B[] = "B"; static char __pyx_k_H[] = "H"; static char __pyx_k_I[] = "I"; static char __pyx_k_L[] = "L"; static char __pyx_k_O[] = "O"; static char __pyx_k_Q[] = "Q"; static char __pyx_k_b[] = "b"; static char __pyx_k_c[] = "c"; static char __pyx_k_d[] = "d"; static char __pyx_k_f[] = "f"; static char __pyx_k_g[] = "g"; static char __pyx_k_h[] = "h"; static char __pyx_k_i[] = "i"; static char __pyx_k_l[] = "l"; static char __pyx_k_n[] = "n"; static char __pyx_k_q[] = "q"; static char __pyx_k_x[] = "x"; static char __pyx_k_y[] = "y"; static char __pyx_k_z[] = "z"; static char __pyx_k_Zd[] = "Zd"; static char __pyx_k_Zf[] = "Zf"; static char __pyx_k_Zg[] = "Zg"; static char __pyx_k__3[] = "|"; static char __pyx_k_id[] = "id"; static char __pyx_k_np[] = "np"; static char __pyx_k_v0[] = "v0"; static char __pyx_k_v1[] = "v1"; static char __pyx_k_xi[] = "xi"; static char __pyx_k_yi[] = "yi"; static char __pyx_k_zi[] = "zi"; static char __pyx_k_obj[] = "obj"; static char __pyx_k_ord[] = "ord"; static char __pyx_k_sys[] = "sys"; static char __pyx_k_v00[] = "v00"; static char __pyx_k_v01[] = "v01"; static char __pyx_k_v10[] = "v10"; static char __pyx_k_v11[] = "v11"; static char __pyx_k_zip[] = "zip"; static char __pyx_k_args[] = "args"; static char __pyx_k_base[] = "base"; static char __pyx_k_kind[] = "kind"; static char __pyx_k_main[] = "__main__"; static char __pyx_k_mode[] = "mode"; static char __pyx_k_name[] = "name"; static char __pyx_k_ndim[] = "ndim"; static char __pyx_k_pack[] = "pack"; static char __pyx_k_size[] = "size"; static char __pyx_k_step[] = "step"; static char __pyx_k_stop[] = "stop"; static char __pyx_k_test[] = "__test__"; static char __pyx_k_v000[] = "v000"; static char __pyx_k_v001[] = "v001"; static char __pyx_k_v010[] = "v010"; static char __pyx_k_v011[] = "v011"; static char __pyx_k_v100[] = "v100"; static char __pyx_k_v101[] = "v101"; static char __pyx_k_v110[] = "v110"; static char __pyx_k_v111[] = "v111"; static char __pyx_k_vals[] = "vals"; static char __pyx_k_class[] = "__class__"; static char __pyx_k_dtype[] = "dtype"; static char __pyx_k_error[] = "error"; static char __pyx_k_flags[] = "flags"; static char __pyx_k_float[] = "float"; static char __pyx_k_numpy[] = "numpy"; static char __pyx_k_range[] = "range"; static char __pyx_k_shape[] = "shape"; static char __pyx_k_split[] = "split"; static char __pyx_k_start[] = "start"; static char __pyx_k_strip[] = "strip"; static char __pyx_k_x_fac[] = "x_fac"; static char __pyx_k_y_fac[] = "y_fac"; static char __pyx_k_z_fac[] = "z_fac"; static char __pyx_k_double[] = "double"; static char __pyx_k_format[] = "format"; static char __pyx_k_import[] = "__import__"; static char __pyx_k_kwargs[] = "kwargs"; static char __pyx_k_name_2[] = "__name__"; static char __pyx_k_struct[] = "struct"; static char __pyx_k_unpack[] = "unpack"; static char __pyx_k_x_vals[] = "x_vals"; static char __pyx_k_y_vals[] = "y_vals"; static char __pyx_k_z_vals[] = "z_vals"; static char __pyx_k_fortran[] = "fortran"; static char __pyx_k_memview[] = "memview"; static char __pyx_k_mid_ind[] = "mid_ind"; static char __pyx_k_ndarray[] = "ndarray"; static char __pyx_k_Ellipsis[] = "Ellipsis"; static char __pyx_k_defaults[] = "defaults"; static char __pyx_k_itemsize[] = "itemsize"; static char __pyx_k_n_x_vals[] = "n_x_vals"; static char __pyx_k_n_y_vals[] = "n_y_vals"; static char __pyx_k_n_z_vals[] = "n_z_vals"; static char __pyx_k_TypeError[] = "TypeError"; static char __pyx_k_enumerate[] = "enumerate"; static char __pyx_k_x_bot_ind[] = "x_bot_ind"; static char __pyx_k_x_top_ind[] = "x_top_ind"; static char __pyx_k_y_bot_ind[] = "y_bot_ind"; static char __pyx_k_y_top_ind[] = "y_top_ind"; static char __pyx_k_z_bot_ind[] = "z_bot_ind"; static char __pyx_k_z_top_ind[] = "z_top_ind"; static char __pyx_k_IndexError[] = "IndexError"; static char __pyx_k_ValueError[] = "ValueError"; static char __pyx_k_pyx_vtable[] = "__pyx_vtable__"; static char __pyx_k_signatures[] = "signatures"; static char __pyx_k_ImportError[] = "ImportError"; static char __pyx_k_MemoryError[] = "MemoryError"; static char __pyx_k_RuntimeError[] = "RuntimeError"; static char __pyx_k_result_array[] = "result_array"; static char __pyx_k_interpolate3d[] = "interpolate3d"; static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer"; static char __pyx_k_AttributeError[] = "AttributeError"; static char __pyx_k_allocate_buffer[] = "allocate_buffer"; static char __pyx_k_dtype_is_object[] = "dtype_is_object"; static char __pyx_k_interpolate3d_2[] = "_interpolate3d"; static char __pyx_k_strided_and_direct[] = "<strided and direct>"; static char __pyx_k_strided_and_indirect[] = "<strided and indirect>"; static char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>"; static char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>"; static char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>"; static char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>"; static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'"; static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)"; static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct"; static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d."; static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)"; static char __pyx_k_No_matching_signature_found[] = "No matching signature found"; static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)"; static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array"; static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static char __pyx_k_Expected_at_least_d_arguments[] = "Expected at least %d arguments"; static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data."; static char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>"; static char __pyx_k_mnt_pact_ds381_seren3_src_analy[] = "/mnt/pact/ds381/seren3/src/analysis/_interpolate3d.pyx"; static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced"; static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides"; static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory."; static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions"; static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array"; static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static char __pyx_k_Function_call_with_ambiguous_arg[] = "Function call with ambiguous argument types"; static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported"; static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s"; static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)"; static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object"; static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)"; static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static char __pyx_k_unable_to_allocate_shape_and_str[] = "unable to allocate shape and strides."; static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_kp_s_; static PyObject *__pyx_n_s_AttributeError; static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri; static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is; static PyObject *__pyx_kp_s_Cannot_index_with_type_s; static PyObject *__pyx_n_s_Ellipsis; static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr; static PyObject *__pyx_kp_s_Expected_at_least_d_arguments; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_kp_s_Function_call_with_ambiguous_arg; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_n_s_IndexError; static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte; static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr; static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x; static PyObject *__pyx_kp_s_MemoryView_of_r_object; static PyObject *__pyx_kp_s_No_matching_signature_found; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_b_O; static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_TypeError; static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_kp_s__3; static PyObject *__pyx_n_s_allocate_buffer; static PyObject *__pyx_n_s_args; static PyObject *__pyx_n_s_base; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_u_c; static PyObject *__pyx_n_s_class; static PyObject *__pyx_kp_s_contiguous_and_direct; static PyObject *__pyx_kp_s_contiguous_and_indirect; static PyObject *__pyx_n_s_defaults; static PyObject *__pyx_n_s_double; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_dtype_is_object; static PyObject *__pyx_n_s_enumerate; static PyObject *__pyx_n_s_error; static PyObject *__pyx_n_s_flags; static PyObject *__pyx_n_s_float; static PyObject *__pyx_n_s_format; static PyObject *__pyx_n_s_fortran; static PyObject *__pyx_n_u_fortran; static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_id; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_interpolate3d; static PyObject *__pyx_n_s_interpolate3d_2; static PyObject *__pyx_n_s_itemsize; static PyObject *__pyx_kp_s_itemsize_0_for_cython_array; static PyObject *__pyx_n_s_kind; static PyObject *__pyx_n_s_kwargs; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_memview; static PyObject *__pyx_n_s_mid_ind; static PyObject *__pyx_kp_s_mnt_pact_ds381_seren3_src_analy; static PyObject *__pyx_n_s_mode; static PyObject *__pyx_n_s_n; static PyObject *__pyx_n_s_n_x_vals; static PyObject *__pyx_n_s_n_y_vals; static PyObject *__pyx_n_s_n_z_vals; static PyObject *__pyx_n_s_name; static PyObject *__pyx_n_s_name_2; static PyObject *__pyx_n_s_ndarray; static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; static PyObject *__pyx_n_s_ndim; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_n_s_obj; static PyObject *__pyx_n_s_ord; static PyObject *__pyx_n_s_pack; static PyObject *__pyx_n_s_pyx_getbuffer; static PyObject *__pyx_n_s_pyx_vtable; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_result_array; static PyObject *__pyx_n_s_shape; static PyObject *__pyx_n_s_signatures; static PyObject *__pyx_n_s_size; static PyObject *__pyx_n_s_split; static PyObject *__pyx_n_s_start; static PyObject *__pyx_n_s_step; static PyObject *__pyx_n_s_stop; static PyObject *__pyx_kp_s_strided_and_direct; static PyObject *__pyx_kp_s_strided_and_direct_or_indirect; static PyObject *__pyx_kp_s_strided_and_indirect; static PyObject *__pyx_n_s_strip; static PyObject *__pyx_n_s_struct; static PyObject *__pyx_n_s_sys; static PyObject *__pyx_n_s_test; static PyObject *__pyx_kp_s_unable_to_allocate_array_data; static PyObject *__pyx_kp_s_unable_to_allocate_shape_and_str; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_unpack; static PyObject *__pyx_n_s_v0; static PyObject *__pyx_n_s_v00; static PyObject *__pyx_n_s_v000; static PyObject *__pyx_n_s_v001; static PyObject *__pyx_n_s_v01; static PyObject *__pyx_n_s_v010; static PyObject *__pyx_n_s_v011; static PyObject *__pyx_n_s_v1; static PyObject *__pyx_n_s_v10; static PyObject *__pyx_n_s_v100; static PyObject *__pyx_n_s_v101; static PyObject *__pyx_n_s_v11; static PyObject *__pyx_n_s_v110; static PyObject *__pyx_n_s_v111; static PyObject *__pyx_n_s_vals; static PyObject *__pyx_n_s_x; static PyObject *__pyx_n_s_x_bot_ind; static PyObject *__pyx_n_s_x_fac; static PyObject *__pyx_n_s_x_top_ind; static PyObject *__pyx_n_s_x_vals; static PyObject *__pyx_n_s_xi; static PyObject *__pyx_n_s_y; static PyObject *__pyx_n_s_y_bot_ind; static PyObject *__pyx_n_s_y_fac; static PyObject *__pyx_n_s_y_top_ind; static PyObject *__pyx_n_s_y_vals; static PyObject *__pyx_n_s_yi; static PyObject *__pyx_n_s_z; static PyObject *__pyx_n_s_z_bot_ind; static PyObject *__pyx_n_s_z_fac; static PyObject *__pyx_n_s_z_top_ind; static PyObject *__pyx_n_s_z_vals; static PyObject *__pyx_n_s_zi; static PyObject *__pyx_n_s_zip; static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_int_neg_1; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_slice__21; static PyObject *__pyx_slice__22; static PyObject *__pyx_slice__23; static PyObject *__pyx_tuple__10; static PyObject *__pyx_tuple__11; static PyObject *__pyx_tuple__12; static PyObject *__pyx_tuple__13; static PyObject *__pyx_tuple__14; static PyObject *__pyx_tuple__15; static PyObject *__pyx_tuple__16; static PyObject *__pyx_tuple__17; static PyObject *__pyx_tuple__18; static PyObject *__pyx_tuple__19; static PyObject *__pyx_tuple__20; static PyObject *__pyx_tuple__24; static PyObject *__pyx_tuple__25; static PyObject *__pyx_tuple__27; static PyObject *__pyx_tuple__28; static PyObject *__pyx_tuple__29; static PyObject *__pyx_tuple__30; static PyObject *__pyx_tuple__31; static PyObject *__pyx_codeobj__26; /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ /* Python wrapper */ static PyObject *__pyx_pw_14_interpolate3d_1interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_mdef_14_interpolate3d_1interpolate3d = {"interpolate3d", (PyCFunction)__pyx_pw_14_interpolate3d_1interpolate3d, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_pw_14_interpolate3d_1interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_signatures = 0; PyObject *__pyx_v_args = 0; PyObject *__pyx_v_kwargs = 0; CYTHON_UNUSED PyObject *__pyx_v_defaults = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_signatures,&__pyx_n_s_args,&__pyx_n_s_kwargs,&__pyx_n_s_defaults,0}; PyObject* values[4] = {0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 4) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); } __pyx_v_signatures = values[0]; __pyx_v_args = values[1]; __pyx_v_kwargs = values[2]; __pyx_v_defaults = values[3]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("_interpolate3d.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_pf_14_interpolate3d_interpolate3d(__pyx_self, __pyx_v_signatures, __pyx_v_args, __pyx_v_kwargs, __pyx_v_defaults); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_14_interpolate3d_interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) { PyObject *__pyx_v_dest_sig = NULL; PyObject *__pyx_v_ndarray = 0; PyObject *__pyx_v_numpy = NULL; __Pyx_memviewslice __pyx_v_memslice; Py_ssize_t __pyx_v_itemsize; CYTHON_UNUSED int __pyx_v_dtype_signed; char __pyx_v_kind; PyObject *__pyx_v_arg = NULL; PyObject *__pyx_v_dtype = NULL; PyObject *__pyx_v_arg_base = NULL; PyObject *__pyx_v_candidates = NULL; PyObject *__pyx_v_sig = NULL; int __pyx_v_match_found; PyObject *__pyx_v_src_type = NULL; PyObject *__pyx_v_dst_type = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; Py_ssize_t __pyx_t_10; char __pyx_t_11; Py_ssize_t __pyx_t_12; int __pyx_t_13; Py_ssize_t __pyx_t_14; PyObject *(*__pyx_t_15)(PyObject *); PyObject *__pyx_t_16 = NULL; PyObject *__pyx_t_17 = NULL; PyObject *__pyx_t_18 = NULL; PyObject *(*__pyx_t_19)(PyObject *); int __pyx_t_20; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("interpolate3d", 0); __Pyx_INCREF(__pyx_v_kwargs); __pyx_t_1 = PyList_New(1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_INCREF(Py_None); PyList_SET_ITEM(__pyx_t_1, 0, Py_None); __Pyx_GIVEREF(Py_None); __pyx_v_dest_sig = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; __pyx_t_2 = (__pyx_v_kwargs == Py_None); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1); __pyx_t_1 = 0; goto __pyx_L3; } __pyx_L3:; { __Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); __Pyx_XGOTREF(__pyx_t_6); /*try:*/ { __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_numpy = __pyx_t_1; __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_1); if (!(likely(PyType_CheckExact(__pyx_t_1))||((__pyx_t_1) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "type", Py_TYPE(__pyx_t_1)->tp_name), 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __pyx_v_ndarray = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; } __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; goto __pyx_L11_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError) || PyErr_ExceptionMatches(__pyx_builtin_AttributeError) || PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_7) { __Pyx_AddTraceback("_interpolate3d.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_9); __Pyx_INCREF(Py_None); __Pyx_XDECREF_SET(__pyx_v_ndarray, ((PyObject*)Py_None)); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L5_exception_handled; } goto __pyx_L6_except_error; __pyx_L6_except_error:; __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_XGIVEREF(__pyx_t_6); __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); goto __pyx_L1_error; __pyx_L5_exception_handled:; __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_XGIVEREF(__pyx_t_6); __Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6); __pyx_L11_try_end:; } __pyx_v_itemsize = -1; if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((1 < __pyx_t_10) != 0); if (__pyx_t_3) { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_9 = PyTuple_GET_ITEM(((PyObject*)__pyx_v_args), 1); __Pyx_INCREF(__pyx_t_9); __pyx_v_arg = __pyx_t_9; __pyx_t_9 = 0; goto __pyx_L14; } if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_3 = (__Pyx_PyDict_Contains(__pyx_n_s_x, ((PyObject*)__pyx_v_kwargs), Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_3 != 0); if (__pyx_t_2) { if (unlikely(__pyx_v_kwargs == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_9 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_kwargs), __pyx_n_s_x); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_9); __pyx_v_arg = __pyx_t_9; __pyx_t_9 = 0; goto __pyx_L14; } /*else*/ { if (unlikely(__pyx_v_args == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_10 = PyTuple_GET_SIZE(((PyObject*)__pyx_v_args)); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L14:; if (0) { goto __pyx_L15; } /*else*/ { while (1) { if (!1) break; __pyx_t_2 = (__pyx_v_ndarray != ((PyObject*)Py_None)); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { __pyx_t_3 = __Pyx_TypeCheck(__pyx_v_arg, __pyx_v_ndarray); __pyx_t_2 = (__pyx_t_3 != 0); if (__pyx_t_2) { __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_v_dtype = __pyx_t_8; __pyx_t_8 = 0; goto __pyx_L19; } __pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0); if (__pyx_t_2) { __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_v_arg_base = __pyx_t_8; __pyx_t_8 = 0; __pyx_t_2 = __Pyx_TypeCheck(__pyx_v_arg_base, __pyx_v_ndarray); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg_base, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_v_dtype = __pyx_t_8; __pyx_t_8 = 0; goto __pyx_L20; } /*else*/ { __Pyx_INCREF(Py_None); __pyx_v_dtype = Py_None; } __pyx_L20:; goto __pyx_L19; } /*else*/ { __Pyx_INCREF(Py_None); __pyx_v_dtype = Py_None; } __pyx_L19:; __pyx_v_itemsize = -1; __pyx_t_3 = (__pyx_v_dtype != Py_None); __pyx_t_2 = (__pyx_t_3 != 0); if (__pyx_t_2) { __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_v_itemsize = __pyx_t_10; __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8); __Pyx_GIVEREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_11 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_11 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_v_kind = __pyx_t_11; __pyx_v_dtype_signed = (__pyx_v_kind == 'i'); switch (__pyx_v_kind) { case 'i': case 'u': break; case 'f': __pyx_t_3 = (((sizeof(float)) == __pyx_v_itemsize) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L23_bool_binop_done; } __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L23_bool_binop_done:; if (__pyx_t_2) { if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17_break; } __pyx_t_3 = (((sizeof(double)) == __pyx_v_itemsize) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L26_bool_binop_done; } __pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_3 = ((((Py_ssize_t)__pyx_t_10) == 1) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L26_bool_binop_done:; if (__pyx_t_2) { if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17_break; } break; case 'c': break; case 'O': break; default: break; } goto __pyx_L21; } __pyx_L21:; goto __pyx_L18; } __pyx_L18:; __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); if (!__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L29_bool_binop_done; } __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(float))) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L29_bool_binop_done:; if (__pyx_t_2) { __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_float(__pyx_v_arg); __pyx_t_2 = (__pyx_v_memslice.memview != 0); if (__pyx_t_2) { __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17_break; } /*else*/ { PyErr_Clear(); } goto __pyx_L28; } __pyx_L28:; __pyx_t_3 = ((__pyx_v_itemsize == -1) != 0); if (!__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L33_bool_binop_done; } __pyx_t_3 = ((__pyx_v_itemsize == (sizeof(double))) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L33_bool_binop_done:; if (__pyx_t_2) { __pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_ds_double(__pyx_v_arg); __pyx_t_2 = (__pyx_v_memslice.memview != 0); if (__pyx_t_2) { __PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1); if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17_break; } /*else*/ { PyErr_Clear(); } goto __pyx_L32; } __pyx_L32:; if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L17_break; } __pyx_L17_break:; } __pyx_L15:; __pyx_t_8 = PyList_New(0); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __pyx_v_candidates = ((PyObject*)__pyx_t_8); __pyx_t_8 = 0; __pyx_t_10 = 0; if (unlikely(__pyx_v_signatures == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_9 = __Pyx_dict_iterator(((PyObject*)__pyx_v_signatures), 1, ((PyObject *)NULL), (&__pyx_t_12), (&__pyx_t_7)); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = __pyx_t_9; __pyx_t_9 = 0; while (1) { __pyx_t_13 = __Pyx_dict_iter_next(__pyx_t_8, __pyx_t_12, &__pyx_t_10, &__pyx_t_9, NULL, NULL, __pyx_t_7); if (unlikely(__pyx_t_13 == 0)) break; if (unlikely(__pyx_t_13 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_9); __pyx_t_9 = 0; __pyx_v_match_found = 0; __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_9, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_dest_sig); PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dest_sig); __Pyx_GIVEREF(__pyx_v_dest_sig); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; if (likely(PyList_CheckExact(__pyx_t_1)) || PyTuple_CheckExact(__pyx_t_1)) { __pyx_t_9 = __pyx_t_1; __Pyx_INCREF(__pyx_t_9); __pyx_t_14 = 0; __pyx_t_15 = NULL; } else { __pyx_t_14 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_15 = Py_TYPE(__pyx_t_9)->tp_iternext; if (unlikely(!__pyx_t_15)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; for (;;) { if (likely(!__pyx_t_15)) { if (likely(PyList_CheckExact(__pyx_t_9))) { if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_9)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_1 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_9)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_1 = PySequence_ITEM(__pyx_t_9, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } } else { __pyx_t_1 = __pyx_t_15(__pyx_t_9); if (unlikely(!__pyx_t_1)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_1); } if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) { PyObject* sequence = __pyx_t_1; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON if (likely(PyTuple_CheckExact(sequence))) { __pyx_t_16 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_17 = PyTuple_GET_ITEM(sequence, 1); } else { __pyx_t_16 = PyList_GET_ITEM(sequence, 0); __pyx_t_17 = PyList_GET_ITEM(sequence, 1); } __Pyx_INCREF(__pyx_t_16); __Pyx_INCREF(__pyx_t_17); #else __pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_16); __pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_17); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { Py_ssize_t index = -1; __pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_18); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext; index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L40_unpacking_failed; __Pyx_GOTREF(__pyx_t_16); index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L40_unpacking_failed; __Pyx_GOTREF(__pyx_t_17); if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_19 = NULL; __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; goto __pyx_L41_unpacking_done; __pyx_L40_unpacking_failed:; __Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0; __pyx_t_19 = NULL; if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_L41_unpacking_done:; } __Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16); __pyx_t_16 = 0; __Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17); __pyx_t_17 = 0; __pyx_t_2 = (__pyx_v_dst_type != Py_None); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { __pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_3) { __pyx_v_match_found = 1; goto __pyx_L43; } /*else*/ { __pyx_v_match_found = 0; goto __pyx_L39_break; } __pyx_L43:; goto __pyx_L42; } __pyx_L42:; } __pyx_L39_break:; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_3 = (__pyx_v_match_found != 0); if (__pyx_t_3) { __pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L44; } __pyx_L44:; } __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __pyx_t_3 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0); __pyx_t_2 = ((!__pyx_t_3) != 0); if (__pyx_t_2) { __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_12 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_12 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = ((__pyx_t_12 > 1) != 0); if (__pyx_t_2) { __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /*else*/ { __Pyx_XDECREF(__pyx_r); if (unlikely(__pyx_v_signatures == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_8 = __Pyx_PyDict_GetItem(((PyObject*)__pyx_v_signatures), PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_8 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_8); __pyx_r = __pyx_t_8; __pyx_t_8 = 0; goto __pyx_L0; } /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_16); __Pyx_XDECREF(__pyx_t_17); __Pyx_XDECREF(__pyx_t_18); __Pyx_AddTraceback("_interpolate3d.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_dest_sig); __Pyx_XDECREF(__pyx_v_ndarray); __Pyx_XDECREF(__pyx_v_numpy); __Pyx_XDECREF(__pyx_v_arg); __Pyx_XDECREF(__pyx_v_dtype); __Pyx_XDECREF(__pyx_v_arg_base); __Pyx_XDECREF(__pyx_v_candidates); __Pyx_XDECREF(__pyx_v_sig); __Pyx_XDECREF(__pyx_v_src_type); __Pyx_XDECREF(__pyx_v_dst_type); __Pyx_XDECREF(__pyx_v_kwargs); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_fuse_0__pyx_pw_14_interpolate3d_3interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_fuse_0__pyx_mdef_14_interpolate3d_3interpolate3d = {"__pyx_fuse_0interpolate3d", (PyCFunction)__pyx_fuse_0__pyx_pw_14_interpolate3d_3interpolate3d, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_fuse_0__pyx_pw_14_interpolate3d_3interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { CYTHON_UNUSED int __pyx_v_n; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; int __pyx_v_n_x_vals; PyArrayObject *__pyx_v_x_vals = 0; int __pyx_v_n_y_vals; PyArrayObject *__pyx_v_y_vals = 0; int __pyx_v_n_z_vals; PyArrayObject *__pyx_v_z_vals = 0; PyArrayObject *__pyx_v_vals = 0; PyArrayObject *__pyx_v_result_array = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("interpolate3d (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n,&__pyx_n_s_x,&__pyx_n_s_y,&__pyx_n_s_z,&__pyx_n_s_n_x_vals,&__pyx_n_s_x_vals,&__pyx_n_s_n_y_vals,&__pyx_n_s_y_vals,&__pyx_n_s_n_z_vals,&__pyx_n_s_z_vals,&__pyx_n_s_vals,&__pyx_n_s_result_array,0}; PyObject* values[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_x_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_y_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_z_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result_array)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "interpolate3d") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 12) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); } __pyx_v_n = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_n == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x = ((PyArrayObject *)values[1]); __pyx_v_y = ((PyArrayObject *)values[2]); __pyx_v_z = ((PyArrayObject *)values[3]); __pyx_v_n_x_vals = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_n_x_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x_vals = ((PyArrayObject *)values[5]); __pyx_v_n_y_vals = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_n_y_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y_vals = ((PyArrayObject *)values[7]); __pyx_v_n_z_vals = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_n_z_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z_vals = ((PyArrayObject *)values[9]); __pyx_v_vals = ((PyArrayObject *)values[10]); __pyx_v_result_array = ((PyArrayObject *)values[11]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("_interpolate3d.interpolate3d", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x), __pyx_ptype_5numpy_ndarray, 1, "x", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_z), __pyx_ptype_5numpy_ndarray, 1, "z", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_vals), __pyx_ptype_5numpy_ndarray, 1, "x_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y_vals), __pyx_ptype_5numpy_ndarray, 1, "y_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_z_vals), __pyx_ptype_5numpy_ndarray, 1, "z_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_vals), __pyx_ptype_5numpy_ndarray, 1, "vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_result_array), __pyx_ptype_5numpy_ndarray, 1, "result_array", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_14_interpolate3d_2interpolate3d(__pyx_self, __pyx_v_n, __pyx_v_x, __pyx_v_y, __pyx_v_z, __pyx_v_n_x_vals, __pyx_v_x_vals, __pyx_v_n_y_vals, __pyx_v_y_vals, __pyx_v_n_z_vals, __pyx_v_z_vals, __pyx_v_vals, __pyx_v_result_array); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_14_interpolate3d_2interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED int __pyx_v_n, PyArrayObject *__pyx_v_x, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_z, int __pyx_v_n_x_vals, PyArrayObject *__pyx_v_x_vals, int __pyx_v_n_y_vals, PyArrayObject *__pyx_v_y_vals, int __pyx_v_n_z_vals, PyArrayObject *__pyx_v_z_vals, PyArrayObject *__pyx_v_vals, PyArrayObject *__pyx_v_result_array) { int __pyx_v_x_top_ind; int __pyx_v_x_bot_ind; int __pyx_v_y_top_ind; int __pyx_v_y_bot_ind; int __pyx_v_z_top_ind; int __pyx_v_z_bot_ind; int __pyx_v_mid_ind; double __pyx_v_x_fac; double __pyx_v_y_fac; double __pyx_v_z_fac; double __pyx_v_v0; double __pyx_v_v1; double __pyx_v_v00; double __pyx_v_v01; double __pyx_v_v10; double __pyx_v_v11; double __pyx_v_v000; double __pyx_v_v001; double __pyx_v_v010; double __pyx_v_v011; double __pyx_v_v100; double __pyx_v_v101; double __pyx_v_v110; double __pyx_v_v111; double __pyx_v_xi; double __pyx_v_yi; double __pyx_v_zi; Py_ssize_t __pyx_v_i; __Pyx_LocalBuf_ND __pyx_pybuffernd_result_array; __Pyx_Buffer __pyx_pybuffer_result_array; __Pyx_LocalBuf_ND __pyx_pybuffernd_vals; __Pyx_Buffer __pyx_pybuffer_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_x_vals; __Pyx_Buffer __pyx_pybuffer_x_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_y_vals; __Pyx_Buffer __pyx_pybuffer_y_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_z_vals; __Pyx_Buffer __pyx_pybuffer_z_vals; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; __pyx_t_5numpy_float64_t __pyx_t_12; int __pyx_t_13; int __pyx_t_14; __pyx_t_5numpy_float64_t __pyx_t_15; int __pyx_t_16; int __pyx_t_17; int __pyx_t_18; int __pyx_t_19; int __pyx_t_20; int __pyx_t_21; int __pyx_t_22; int __pyx_t_23; int __pyx_t_24; int __pyx_t_25; int __pyx_t_26; int __pyx_t_27; int __pyx_t_28; int __pyx_t_29; int __pyx_t_30; int __pyx_t_31; int __pyx_t_32; int __pyx_t_33; int __pyx_t_34; int __pyx_t_35; int __pyx_t_36; int __pyx_t_37; int __pyx_t_38; int __pyx_t_39; int __pyx_t_40; int __pyx_t_41; int __pyx_t_42; int __pyx_t_43; int __pyx_t_44; int __pyx_t_45; long __pyx_t_46; int __pyx_t_47; int __pyx_t_48; long __pyx_t_49; int __pyx_t_50; int __pyx_t_51; long __pyx_t_52; int __pyx_t_53; int __pyx_t_54; long __pyx_t_55; int __pyx_t_56; int __pyx_t_57; Py_ssize_t __pyx_t_58; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_fuse_0interpolate3d", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_x_vals.pybuffer.buf = NULL; __pyx_pybuffer_x_vals.refcount = 0; __pyx_pybuffernd_x_vals.data = NULL; __pyx_pybuffernd_x_vals.rcbuffer = &__pyx_pybuffer_x_vals; __pyx_pybuffer_y_vals.pybuffer.buf = NULL; __pyx_pybuffer_y_vals.refcount = 0; __pyx_pybuffernd_y_vals.data = NULL; __pyx_pybuffernd_y_vals.rcbuffer = &__pyx_pybuffer_y_vals; __pyx_pybuffer_z_vals.pybuffer.buf = NULL; __pyx_pybuffer_z_vals.refcount = 0; __pyx_pybuffernd_z_vals.data = NULL; __pyx_pybuffernd_z_vals.rcbuffer = &__pyx_pybuffer_z_vals; __pyx_pybuffer_vals.pybuffer.buf = NULL; __pyx_pybuffer_vals.refcount = 0; __pyx_pybuffernd_vals.data = NULL; __pyx_pybuffernd_vals.rcbuffer = &__pyx_pybuffer_vals; __pyx_pybuffer_result_array.pybuffer.buf = NULL; __pyx_pybuffer_result_array.refcount = 0; __pyx_pybuffernd_result_array.data = NULL; __pyx_pybuffernd_result_array.rcbuffer = &__pyx_pybuffer_result_array; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_float, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_float, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_float, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_x_vals.diminfo[0].strides = __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_vals.diminfo[0].shape = __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_y_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_y_vals.diminfo[0].strides = __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y_vals.diminfo[0].shape = __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_z_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_z_vals.diminfo[0].strides = __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z_vals.diminfo[0].shape = __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_vals.diminfo[0].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_vals.diminfo[0].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_vals.diminfo[1].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_vals.diminfo[1].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_vals.diminfo[2].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_vals.diminfo[2].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[2]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer, (PyObject*)__pyx_v_result_array, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_result_array.diminfo[0].strides = __pyx_pybuffernd_result_array.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_result_array.diminfo[0].shape = __pyx_pybuffernd_result_array.rcbuffer->pybuffer.shape[0]; /* "_interpolate3d.pyx":32 * cdef Py_ssize_t i * * for i in prange(n,nogil=True) : # <<<<<<<<<<<<<< * if n_x_vals > 0 : * xi = x[i] */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { __pyx_t_1 = __pyx_v_n; if (1 == 0) abort(); { double __pyx_parallel_temp0 = __PYX_NAN(); double __pyx_parallel_temp1 = __PYX_NAN(); int __pyx_parallel_temp2 = 0xbad0bad0; double __pyx_parallel_temp3 = __PYX_NAN(); double __pyx_parallel_temp4 = __PYX_NAN(); double __pyx_parallel_temp5 = __PYX_NAN(); int __pyx_parallel_temp6 = 0xbad0bad0; int __pyx_parallel_temp7 = 0xbad0bad0; double __pyx_parallel_temp8 = __PYX_NAN(); double __pyx_parallel_temp9 = __PYX_NAN(); double __pyx_parallel_temp10 = __PYX_NAN(); double __pyx_parallel_temp11 = __PYX_NAN(); double __pyx_parallel_temp12 = __PYX_NAN(); double __pyx_parallel_temp13 = __PYX_NAN(); double __pyx_parallel_temp14 = __PYX_NAN(); int __pyx_parallel_temp15 = 0xbad0bad0; int __pyx_parallel_temp16 = 0xbad0bad0; double __pyx_parallel_temp17 = __PYX_NAN(); double __pyx_parallel_temp18 = __PYX_NAN(); int __pyx_parallel_temp19 = 0xbad0bad0; Py_ssize_t __pyx_parallel_temp20 = 0xbad0bad0; double __pyx_parallel_temp21 = __PYX_NAN(); double __pyx_parallel_temp22 = __PYX_NAN(); int __pyx_parallel_temp23 = 0xbad0bad0; double __pyx_parallel_temp24 = __PYX_NAN(); double __pyx_parallel_temp25 = __PYX_NAN(); double __pyx_parallel_temp26 = __PYX_NAN(); double __pyx_parallel_temp27 = __PYX_NAN(); const char *__pyx_parallel_filename = NULL; int __pyx_parallel_lineno = 0, __pyx_parallel_clineno = 0; PyObject *__pyx_parallel_exc_type = NULL, *__pyx_parallel_exc_value = NULL, *__pyx_parallel_exc_tb = NULL; int __pyx_parallel_why; __pyx_parallel_why = 0; #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_3 = (__pyx_t_1 - 0) / 1; if (__pyx_t_3 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_28, __pyx_t_38, __pyx_t_20, __pyx_t_27, __pyx_t_29, __pyx_t_44, __pyx_t_45, __pyx_t_32, __pyx_t_7, __pyx_t_21, __pyx_t_24, __pyx_t_8, __pyx_t_14, __pyx_t_19, __pyx_t_41, __pyx_t_35, __pyx_t_50, __pyx_t_13, __pyx_t_18, __pyx_t_42, __pyx_t_31, __pyx_t_57, __pyx_t_17, __pyx_t_46, __pyx_t_49, __pyx_t_53, __pyx_t_4, __pyx_t_34, __pyx_t_12, __pyx_t_37, __pyx_t_30, __pyx_t_52, __pyx_t_25, __pyx_t_11, __pyx_t_16, __pyx_t_36, __pyx_t_33, __pyx_t_56, __pyx_t_22, __pyx_t_10, __pyx_t_15, __pyx_t_39, __pyx_t_43, __pyx_t_54, __pyx_t_47, __pyx_t_51, __pyx_t_5, __pyx_t_6, __pyx_t_48, __pyx_t_9, __pyx_t_26, __pyx_t_40, __pyx_t_58, __pyx_t_55) private(__pyx_filename, __pyx_lineno, __pyx_clineno) shared(__pyx_parallel_why, __pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb) #endif /* _OPENMP */ { #ifdef _OPENMP #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif Py_BEGIN_ALLOW_THREADS #endif /* _OPENMP */ #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_v1) lastprivate(__pyx_v_yi) lastprivate(__pyx_v_z_top_ind) lastprivate(__pyx_v_v00) lastprivate(__pyx_v_v011) lastprivate(__pyx_v_v01) lastprivate(__pyx_v_x_bot_ind) lastprivate(__pyx_v_x_top_ind) lastprivate(__pyx_v_v001) lastprivate(__pyx_v_v100) lastprivate(__pyx_v_v000) lastprivate(__pyx_v_v010) lastprivate(__pyx_v_v10) lastprivate(__pyx_v_v111) lastprivate(__pyx_v_x_fac) lastprivate(__pyx_v_y_top_ind) lastprivate(__pyx_v_z_bot_ind) lastprivate(__pyx_v_xi) lastprivate(__pyx_v_zi) lastprivate(__pyx_v_mid_ind) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_v110) lastprivate(__pyx_v_v101) lastprivate(__pyx_v_y_bot_ind) lastprivate(__pyx_v_y_fac) lastprivate(__pyx_v_z_fac) lastprivate(__pyx_v_v0) lastprivate(__pyx_v_v11) #endif /* _OPENMP */ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ if (__pyx_parallel_why < 2) { __pyx_v_i = 0 + 1 * __pyx_t_2; /* Initialize private variables to invalid values */ __pyx_v_v1 = ((double)__PYX_NAN()); __pyx_v_yi = ((double)__PYX_NAN()); __pyx_v_z_top_ind = ((int)0xbad0bad0); __pyx_v_v00 = ((double)__PYX_NAN()); __pyx_v_v011 = ((double)__PYX_NAN()); __pyx_v_v01 = ((double)__PYX_NAN()); __pyx_v_x_bot_ind = ((int)0xbad0bad0); __pyx_v_x_top_ind = ((int)0xbad0bad0); __pyx_v_v001 = ((double)__PYX_NAN()); __pyx_v_v100 = ((double)__PYX_NAN()); __pyx_v_v000 = ((double)__PYX_NAN()); __pyx_v_v010 = ((double)__PYX_NAN()); __pyx_v_v10 = ((double)__PYX_NAN()); __pyx_v_v111 = ((double)__PYX_NAN()); __pyx_v_x_fac = ((double)__PYX_NAN()); __pyx_v_y_top_ind = ((int)0xbad0bad0); __pyx_v_z_bot_ind = ((int)0xbad0bad0); __pyx_v_xi = ((double)__PYX_NAN()); __pyx_v_zi = ((double)__PYX_NAN()); __pyx_v_mid_ind = ((int)0xbad0bad0); __pyx_v_v110 = ((double)__PYX_NAN()); __pyx_v_v101 = ((double)__PYX_NAN()); __pyx_v_y_bot_ind = ((int)0xbad0bad0); __pyx_v_y_fac = ((double)__PYX_NAN()); __pyx_v_z_fac = ((double)__PYX_NAN()); __pyx_v_v0 = ((double)__PYX_NAN()); __pyx_v_v11 = ((double)__PYX_NAN()); /* "_interpolate3d.pyx":33 * * for i in prange(n,nogil=True) : * if n_x_vals > 0 : # <<<<<<<<<<<<<< * xi = x[i] * yi = y[i] */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":34 * for i in prange(n,nogil=True) : * if n_x_vals > 0 : * xi = x[i] # <<<<<<<<<<<<<< * yi = y[i] * zi = z[i] */ __pyx_t_5 = __pyx_v_i; __pyx_v_xi = (*__Pyx_BufPtrStrided1d(float *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_x.diminfo[0].strides)); goto __pyx_L10; } __pyx_L10:; /* "_interpolate3d.pyx":35 * if n_x_vals > 0 : * xi = x[i] * yi = y[i] # <<<<<<<<<<<<<< * zi = z[i] * */ __pyx_t_6 = __pyx_v_i; __pyx_v_yi = (*__Pyx_BufPtrStrided1d(float *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_y.diminfo[0].strides)); /* "_interpolate3d.pyx":36 * xi = x[i] * yi = y[i] * zi = z[i] # <<<<<<<<<<<<<< * * if n_x_vals > 0 : */ __pyx_t_7 = __pyx_v_i; __pyx_v_zi = (*__Pyx_BufPtrStrided1d(float *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_z.diminfo[0].strides)); /* "_interpolate3d.pyx":38 * zi = z[i] * * if n_x_vals > 0 : # <<<<<<<<<<<<<< * # find x indices * x_top_ind = n_x_vals - 1 */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":40 * if n_x_vals > 0 : * # find x indices * x_top_ind = n_x_vals - 1 # <<<<<<<<<<<<<< * x_bot_ind = 0 * */ __pyx_v_x_top_ind = (__pyx_v_n_x_vals - 1); /* "_interpolate3d.pyx":41 * # find x indices * x_top_ind = n_x_vals - 1 * x_bot_ind = 0 # <<<<<<<<<<<<<< * * while(x_top_ind > x_bot_ind + 1) : */ __pyx_v_x_bot_ind = 0; /* "_interpolate3d.pyx":43 * x_bot_ind = 0 * * while(x_top_ind > x_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_x_top_ind > (__pyx_v_x_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":44 * * while(x_top_ind > x_bot_ind + 1) : * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind # <<<<<<<<<<<<<< * if (xi > x_vals[mid_ind]) : * x_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_x_top_ind - __pyx_v_x_bot_ind), 2)) + __pyx_v_x_bot_ind); /* "_interpolate3d.pyx":45 * while(x_top_ind > x_bot_ind + 1) : * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : # <<<<<<<<<<<<<< * x_bot_ind = mid_ind * else : */ __pyx_t_8 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_xi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_x_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":46 * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : * x_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * x_top_ind = mid_ind */ __pyx_v_x_bot_ind = __pyx_v_mid_ind; goto __pyx_L14; } /*else*/ { /* "_interpolate3d.pyx":48 * x_bot_ind = mid_ind * else : * x_top_ind = mid_ind # <<<<<<<<<<<<<< * * else : */ __pyx_v_x_top_ind = __pyx_v_mid_ind; } __pyx_L14:; } goto __pyx_L11; } /*else*/ { /* "_interpolate3d.pyx":51 * * else : * x_top_ind = 0 # <<<<<<<<<<<<<< * x_bot_ind = 0 * */ __pyx_v_x_top_ind = 0; /* "_interpolate3d.pyx":52 * else : * x_top_ind = 0 * x_bot_ind = 0 # <<<<<<<<<<<<<< * * # find y indices */ __pyx_v_x_bot_ind = 0; } __pyx_L11:; /* "_interpolate3d.pyx":55 * * # find y indices * y_top_ind = n_y_vals - 1 # <<<<<<<<<<<<<< * y_bot_ind = 0 * */ __pyx_v_y_top_ind = (__pyx_v_n_y_vals - 1); /* "_interpolate3d.pyx":56 * # find y indices * y_top_ind = n_y_vals - 1 * y_bot_ind = 0 # <<<<<<<<<<<<<< * * while(y_top_ind > y_bot_ind + 1) : */ __pyx_v_y_bot_ind = 0; /* "_interpolate3d.pyx":58 * y_bot_ind = 0 * * while(y_top_ind > y_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_y_top_ind > (__pyx_v_y_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":59 * * while(y_top_ind > y_bot_ind + 1) : * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind # <<<<<<<<<<<<<< * if (yi > y_vals[mid_ind]) : * y_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_y_top_ind - __pyx_v_y_bot_ind), 2)) + __pyx_v_y_bot_ind); /* "_interpolate3d.pyx":60 * while(y_top_ind > y_bot_ind + 1) : * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : # <<<<<<<<<<<<<< * y_bot_ind = mid_ind * else : */ __pyx_t_9 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_yi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_y_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":61 * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : * y_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * y_top_ind = mid_ind */ __pyx_v_y_bot_ind = __pyx_v_mid_ind; goto __pyx_L17; } /*else*/ { /* "_interpolate3d.pyx":63 * y_bot_ind = mid_ind * else : * y_top_ind = mid_ind # <<<<<<<<<<<<<< * * # find z indices */ __pyx_v_y_top_ind = __pyx_v_mid_ind; } __pyx_L17:; } /* "_interpolate3d.pyx":66 * * # find z indices * z_top_ind = n_z_vals - 1 # <<<<<<<<<<<<<< * z_bot_ind = 0 * */ __pyx_v_z_top_ind = (__pyx_v_n_z_vals - 1); /* "_interpolate3d.pyx":67 * # find z indices * z_top_ind = n_z_vals - 1 * z_bot_ind = 0 # <<<<<<<<<<<<<< * * while(z_top_ind > z_bot_ind + 1) : */ __pyx_v_z_bot_ind = 0; /* "_interpolate3d.pyx":69 * z_bot_ind = 0 * * while(z_top_ind > z_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_z_top_ind > (__pyx_v_z_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":70 * * while(z_top_ind > z_bot_ind + 1) : * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind # <<<<<<<<<<<<<< * if (zi > z_vals[mid_ind]) : * z_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_z_top_ind - __pyx_v_z_bot_ind), 2)) + __pyx_v_z_bot_ind); /* "_interpolate3d.pyx":71 * while(z_top_ind > z_bot_ind + 1) : * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : # <<<<<<<<<<<<<< * z_bot_ind = mid_ind * else : */ __pyx_t_10 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_zi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_z_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":72 * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : * z_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * z_top_ind = mid_ind */ __pyx_v_z_bot_ind = __pyx_v_mid_ind; goto __pyx_L20; } /*else*/ { /* "_interpolate3d.pyx":74 * z_bot_ind = mid_ind * else : * z_top_ind = mid_ind # <<<<<<<<<<<<<< * * if n_x_vals > 0 : */ __pyx_v_z_top_ind = __pyx_v_mid_ind; } __pyx_L20:; } /* "_interpolate3d.pyx":76 * z_top_ind = mid_ind * * if n_x_vals > 0 : # <<<<<<<<<<<<<< * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) * */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":77 * * if n_x_vals > 0 : * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) # <<<<<<<<<<<<<< * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) */ __pyx_t_11 = __pyx_v_x_bot_ind; __pyx_t_12 = (__pyx_v_xi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_x_vals.diminfo[0].strides))); __pyx_t_13 = __pyx_v_x_top_ind; __pyx_t_14 = __pyx_v_x_bot_ind; __pyx_t_15 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_x_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_x_vals.diminfo[0].strides))); if (unlikely(__pyx_t_15 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_x_fac = (__pyx_t_12 / __pyx_t_15); goto __pyx_L21; } __pyx_L21:; /* "_interpolate3d.pyx":79 * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) # <<<<<<<<<<<<<< * z_fac = (zi - z_vals[z_bot_ind])/(z_vals[z_top_ind] - z_vals[z_bot_ind]) * */ __pyx_t_16 = __pyx_v_y_bot_ind; __pyx_t_15 = (__pyx_v_yi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_y_vals.diminfo[0].strides))); __pyx_t_17 = __pyx_v_y_top_ind; __pyx_t_18 = __pyx_v_y_bot_ind; __pyx_t_12 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_y_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y_vals.diminfo[0].strides))); if (unlikely(__pyx_t_12 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_y_fac = (__pyx_t_15 / __pyx_t_12); /* "_interpolate3d.pyx":80 * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) * z_fac = (zi - z_vals[z_bot_ind])/(z_vals[z_top_ind] - z_vals[z_bot_ind]) # <<<<<<<<<<<<<< * * # vertex values */ __pyx_t_19 = __pyx_v_z_bot_ind; __pyx_t_12 = (__pyx_v_zi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_z_vals.diminfo[0].strides))); __pyx_t_20 = __pyx_v_z_top_ind; __pyx_t_21 = __pyx_v_z_bot_ind; __pyx_t_15 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_z_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_z_vals.diminfo[0].strides))); if (unlikely(__pyx_t_15 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_z_fac = (__pyx_t_12 / __pyx_t_15); /* "_interpolate3d.pyx":83 * * # vertex values * if n_x_vals > 0 : # <<<<<<<<<<<<<< * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":84 * # vertex values * if n_x_vals > 0 : * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] # <<<<<<<<<<<<<< * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] */ __pyx_t_22 = __pyx_v_x_bot_ind; __pyx_t_23 = __pyx_v_y_bot_ind; __pyx_t_24 = __pyx_v_z_bot_ind; __pyx_v_v000 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_24, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":85 * if n_x_vals > 0 : * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] # <<<<<<<<<<<<<< * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] */ __pyx_t_25 = __pyx_v_x_bot_ind; __pyx_t_26 = __pyx_v_y_bot_ind; __pyx_t_27 = __pyx_v_z_top_ind; __pyx_v_v001 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_27, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":86 * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] # <<<<<<<<<<<<<< * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] */ __pyx_t_28 = __pyx_v_x_bot_ind; __pyx_t_29 = __pyx_v_y_top_ind; __pyx_t_30 = __pyx_v_z_bot_ind; __pyx_v_v010 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_29, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_30, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":87 * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] # <<<<<<<<<<<<<< * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] */ __pyx_t_31 = __pyx_v_x_bot_ind; __pyx_t_32 = __pyx_v_y_top_ind; __pyx_t_33 = __pyx_v_z_top_ind; __pyx_v_v011 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_31, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_32, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_33, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":88 * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] # <<<<<<<<<<<<<< * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] */ __pyx_t_34 = __pyx_v_x_top_ind; __pyx_t_35 = __pyx_v_y_bot_ind; __pyx_t_36 = __pyx_v_z_bot_ind; __pyx_v_v100 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_35, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_36, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":89 * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] # <<<<<<<<<<<<<< * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] * v111 = vals[x_top_ind,y_top_ind,z_top_ind] */ __pyx_t_37 = __pyx_v_x_top_ind; __pyx_t_38 = __pyx_v_y_bot_ind; __pyx_t_39 = __pyx_v_z_top_ind; __pyx_v_v101 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_37, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_38, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_39, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":90 * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] # <<<<<<<<<<<<<< * v111 = vals[x_top_ind,y_top_ind,z_top_ind] * */ __pyx_t_40 = __pyx_v_x_top_ind; __pyx_t_41 = __pyx_v_y_top_ind; __pyx_t_42 = __pyx_v_z_bot_ind; __pyx_v_v110 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_41, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_42, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":91 * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] * v111 = vals[x_top_ind,y_top_ind,z_top_ind] # <<<<<<<<<<<<<< * * v00 = v000*(1.0-x_fac) + v100*x_fac */ __pyx_t_43 = __pyx_v_x_top_ind; __pyx_t_44 = __pyx_v_y_top_ind; __pyx_t_45 = __pyx_v_z_top_ind; __pyx_v_v111 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_43, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_44, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_45, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":93 * v111 = vals[x_top_ind,y_top_ind,z_top_ind] * * v00 = v000*(1.0-x_fac) + v100*x_fac # <<<<<<<<<<<<<< * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac */ __pyx_v_v00 = ((__pyx_v_v000 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v100 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":94 * * v00 = v000*(1.0-x_fac) + v100*x_fac * v10 = v010*(1.0-x_fac) + v110*x_fac # <<<<<<<<<<<<<< * v01 = v001*(1.0-x_fac) + v101*x_fac * v11 = v011*(1.0-x_fac) + v111*x_fac */ __pyx_v_v10 = ((__pyx_v_v010 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v110 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":95 * v00 = v000*(1.0-x_fac) + v100*x_fac * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac # <<<<<<<<<<<<<< * v11 = v011*(1.0-x_fac) + v111*x_fac * */ __pyx_v_v01 = ((__pyx_v_v001 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v101 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":96 * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac * v11 = v011*(1.0-x_fac) + v111*x_fac # <<<<<<<<<<<<<< * * else : */ __pyx_v_v11 = ((__pyx_v_v011 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v111 * __pyx_v_x_fac)); goto __pyx_L22; } /*else*/ { /* "_interpolate3d.pyx":99 * * else : * v00 = vals[0, y_bot_ind, z_bot_ind] # <<<<<<<<<<<<<< * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] */ __pyx_t_46 = 0; __pyx_t_47 = __pyx_v_y_bot_ind; __pyx_t_48 = __pyx_v_z_bot_ind; __pyx_v_v00 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_46, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_47, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_48, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":100 * else : * v00 = vals[0, y_bot_ind, z_bot_ind] * v01 = vals[0, y_bot_ind, z_top_ind] # <<<<<<<<<<<<<< * v10 = vals[0, y_top_ind, z_bot_ind] * v11 = vals[0, y_top_ind, z_top_ind] */ __pyx_t_49 = 0; __pyx_t_50 = __pyx_v_y_bot_ind; __pyx_t_51 = __pyx_v_z_top_ind; __pyx_v_v01 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_49, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_50, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_51, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":101 * v00 = vals[0, y_bot_ind, z_bot_ind] * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] # <<<<<<<<<<<<<< * v11 = vals[0, y_top_ind, z_top_ind] * */ __pyx_t_52 = 0; __pyx_t_53 = __pyx_v_y_top_ind; __pyx_t_54 = __pyx_v_z_bot_ind; __pyx_v_v10 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_52, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_53, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_54, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":102 * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] * v11 = vals[0, y_top_ind, z_top_ind] # <<<<<<<<<<<<<< * * v0 = v00*(1.0-y_fac) + v10*y_fac */ __pyx_t_55 = 0; __pyx_t_56 = __pyx_v_y_top_ind; __pyx_t_57 = __pyx_v_z_top_ind; __pyx_v_v11 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_55, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_56, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_57, __pyx_pybuffernd_vals.diminfo[2].strides)); } __pyx_L22:; /* "_interpolate3d.pyx":104 * v11 = vals[0, y_top_ind, z_top_ind] * * v0 = v00*(1.0-y_fac) + v10*y_fac # <<<<<<<<<<<<<< * v1 = v01*(1.0-y_fac) + v11*y_fac * */ __pyx_v_v0 = ((__pyx_v_v00 * (1.0 - __pyx_v_y_fac)) + (__pyx_v_v10 * __pyx_v_y_fac)); /* "_interpolate3d.pyx":105 * * v0 = v00*(1.0-y_fac) + v10*y_fac * v1 = v01*(1.0-y_fac) + v11*y_fac # <<<<<<<<<<<<<< * * result_array[i] = v0*(1-z_fac) + v1*z_fac */ __pyx_v_v1 = ((__pyx_v_v01 * (1.0 - __pyx_v_y_fac)) + (__pyx_v_v11 * __pyx_v_y_fac)); /* "_interpolate3d.pyx":107 * v1 = v01*(1.0-y_fac) + v11*y_fac * * result_array[i] = v0*(1-z_fac) + v1*z_fac # <<<<<<<<<<<<<< * * */ __pyx_t_58 = __pyx_v_i; *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_result_array.rcbuffer->pybuffer.buf, __pyx_t_58, __pyx_pybuffernd_result_array.diminfo[0].strides) = ((__pyx_v_v0 * (1.0 - __pyx_v_z_fac)) + (__pyx_v_v1 * __pyx_v_z_fac)); goto __pyx_L24; __pyx_L8_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #ifdef _OPENMP #pragma omp flush(__pyx_parallel_exc_type) #endif /* _OPENMP */ if (!__pyx_parallel_exc_type) { __Pyx_ErrFetch(&__pyx_parallel_exc_type, &__pyx_parallel_exc_value, &__pyx_parallel_exc_tb); __pyx_parallel_filename = __pyx_filename; __pyx_parallel_lineno = __pyx_lineno; __pyx_parallel_clineno = __pyx_clineno; __Pyx_GOTREF(__pyx_parallel_exc_type); } #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_parallel_why = 4; goto __pyx_L23; __pyx_L23:; #ifdef _OPENMP #pragma omp critical(__pyx_parallel_lastprivates0) #endif /* _OPENMP */ { __pyx_parallel_temp0 = __pyx_v_v1; __pyx_parallel_temp1 = __pyx_v_yi; __pyx_parallel_temp2 = __pyx_v_z_top_ind; __pyx_parallel_temp3 = __pyx_v_v00; __pyx_parallel_temp4 = __pyx_v_v011; __pyx_parallel_temp5 = __pyx_v_v01; __pyx_parallel_temp6 = __pyx_v_x_bot_ind; __pyx_parallel_temp7 = __pyx_v_x_top_ind; __pyx_parallel_temp8 = __pyx_v_v001; __pyx_parallel_temp9 = __pyx_v_v100; __pyx_parallel_temp10 = __pyx_v_v000; __pyx_parallel_temp11 = __pyx_v_v010; __pyx_parallel_temp12 = __pyx_v_v10; __pyx_parallel_temp13 = __pyx_v_v111; __pyx_parallel_temp14 = __pyx_v_x_fac; __pyx_parallel_temp15 = __pyx_v_y_top_ind; __pyx_parallel_temp16 = __pyx_v_z_bot_ind; __pyx_parallel_temp17 = __pyx_v_xi; __pyx_parallel_temp18 = __pyx_v_zi; __pyx_parallel_temp19 = __pyx_v_mid_ind; __pyx_parallel_temp20 = __pyx_v_i; __pyx_parallel_temp21 = __pyx_v_v110; __pyx_parallel_temp22 = __pyx_v_v101; __pyx_parallel_temp23 = __pyx_v_y_bot_ind; __pyx_parallel_temp24 = __pyx_v_y_fac; __pyx_parallel_temp25 = __pyx_v_z_fac; __pyx_parallel_temp26 = __pyx_v_v0; __pyx_parallel_temp27 = __pyx_v_v11; } __pyx_L24:; #ifdef _OPENMP #pragma omp flush(__pyx_parallel_why) #endif /* _OPENMP */ } } #ifdef _OPENMP Py_END_ALLOW_THREADS #else { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #endif /* _OPENMP */ /* Clean up any temporaries */ #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif #ifndef _OPENMP } #endif /* _OPENMP */ } } if (__pyx_parallel_exc_type) { /* This may have been overridden by a continue, break or return in another thread. Prefer the error. */ __pyx_parallel_why = 4; } if (__pyx_parallel_why) { __pyx_v_v1 = __pyx_parallel_temp0; __pyx_v_yi = __pyx_parallel_temp1; __pyx_v_z_top_ind = __pyx_parallel_temp2; __pyx_v_v00 = __pyx_parallel_temp3; __pyx_v_v011 = __pyx_parallel_temp4; __pyx_v_v01 = __pyx_parallel_temp5; __pyx_v_x_bot_ind = __pyx_parallel_temp6; __pyx_v_x_top_ind = __pyx_parallel_temp7; __pyx_v_v001 = __pyx_parallel_temp8; __pyx_v_v100 = __pyx_parallel_temp9; __pyx_v_v000 = __pyx_parallel_temp10; __pyx_v_v010 = __pyx_parallel_temp11; __pyx_v_v10 = __pyx_parallel_temp12; __pyx_v_v111 = __pyx_parallel_temp13; __pyx_v_x_fac = __pyx_parallel_temp14; __pyx_v_y_top_ind = __pyx_parallel_temp15; __pyx_v_z_bot_ind = __pyx_parallel_temp16; __pyx_v_xi = __pyx_parallel_temp17; __pyx_v_zi = __pyx_parallel_temp18; __pyx_v_mid_ind = __pyx_parallel_temp19; __pyx_v_i = __pyx_parallel_temp20; __pyx_v_v110 = __pyx_parallel_temp21; __pyx_v_v101 = __pyx_parallel_temp22; __pyx_v_y_bot_ind = __pyx_parallel_temp23; __pyx_v_y_fac = __pyx_parallel_temp24; __pyx_v_z_fac = __pyx_parallel_temp25; __pyx_v_v0 = __pyx_parallel_temp26; __pyx_v_v11 = __pyx_parallel_temp27; switch (__pyx_parallel_why) { case 3: goto __pyx_L3_return; case 4: { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_GIVEREF(__pyx_parallel_exc_type); __Pyx_ErrRestore(__pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb); __pyx_filename = __pyx_parallel_filename; __pyx_lineno = __pyx_parallel_lineno; __pyx_clineno = __pyx_parallel_clineno; #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } goto __pyx_L4_error; } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "_interpolate3d.pyx":32 * cdef Py_ssize_t i * * for i in prange(n,nogil=True) : # <<<<<<<<<<<<<< * if n_x_vals > 0 : * xi = x[i] */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L3_return: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L0; } __pyx_L4_error: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L1_error; } __pyx_L5:; } } /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("_interpolate3d.interpolate3d", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* Python wrapper */ static PyObject *__pyx_fuse_1__pyx_pw_14_interpolate3d_5interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static PyMethodDef __pyx_fuse_1__pyx_mdef_14_interpolate3d_5interpolate3d = {"__pyx_fuse_1interpolate3d", (PyCFunction)__pyx_fuse_1__pyx_pw_14_interpolate3d_5interpolate3d, METH_VARARGS|METH_KEYWORDS, 0}; static PyObject *__pyx_fuse_1__pyx_pw_14_interpolate3d_5interpolate3d(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { CYTHON_UNUSED int __pyx_v_n; PyArrayObject *__pyx_v_x = 0; PyArrayObject *__pyx_v_y = 0; PyArrayObject *__pyx_v_z = 0; int __pyx_v_n_x_vals; PyArrayObject *__pyx_v_x_vals = 0; int __pyx_v_n_y_vals; PyArrayObject *__pyx_v_y_vals = 0; int __pyx_v_n_z_vals; PyArrayObject *__pyx_v_z_vals = 0; PyArrayObject *__pyx_v_vals = 0; PyArrayObject *__pyx_v_result_array = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("interpolate3d (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_n,&__pyx_n_s_x,&__pyx_n_s_y,&__pyx_n_s_z,&__pyx_n_s_n_x_vals,&__pyx_n_s_x_vals,&__pyx_n_s_n_y_vals,&__pyx_n_s_y_vals,&__pyx_n_s_n_z_vals,&__pyx_n_s_z_vals,&__pyx_n_s_vals,&__pyx_n_s_result_array,0}; PyObject* values[12] = {0,0,0,0,0,0,0,0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 12: values[11] = PyTuple_GET_ITEM(__pyx_args, 11); case 11: values[10] = PyTuple_GET_ITEM(__pyx_args, 10); case 10: values[9] = PyTuple_GET_ITEM(__pyx_args, 9); case 9: values[8] = PyTuple_GET_ITEM(__pyx_args, 8); case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7); case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6); case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5); case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_x_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 5: if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 6: if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_y_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 7: if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_y_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 8: if (likely((values[8] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_z_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 8); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 9: if (likely((values[9] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_z_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 9); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 10: if (likely((values[10] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_vals)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 10); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 11: if (likely((values[11] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result_array)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, 11); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "interpolate3d") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 12) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); values[5] = PyTuple_GET_ITEM(__pyx_args, 5); values[6] = PyTuple_GET_ITEM(__pyx_args, 6); values[7] = PyTuple_GET_ITEM(__pyx_args, 7); values[8] = PyTuple_GET_ITEM(__pyx_args, 8); values[9] = PyTuple_GET_ITEM(__pyx_args, 9); values[10] = PyTuple_GET_ITEM(__pyx_args, 10); values[11] = PyTuple_GET_ITEM(__pyx_args, 11); } __pyx_v_n = __Pyx_PyInt_As_int(values[0]); if (unlikely((__pyx_v_n == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x = ((PyArrayObject *)values[1]); __pyx_v_y = ((PyArrayObject *)values[2]); __pyx_v_z = ((PyArrayObject *)values[3]); __pyx_v_n_x_vals = __Pyx_PyInt_As_int(values[4]); if (unlikely((__pyx_v_n_x_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_x_vals = ((PyArrayObject *)values[5]); __pyx_v_n_y_vals = __Pyx_PyInt_As_int(values[6]); if (unlikely((__pyx_v_n_y_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_y_vals = ((PyArrayObject *)values[7]); __pyx_v_n_z_vals = __Pyx_PyInt_As_int(values[8]); if (unlikely((__pyx_v_n_z_vals == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_z_vals = ((PyArrayObject *)values[9]); __pyx_v_vals = ((PyArrayObject *)values[10]); __pyx_v_result_array = ((PyArrayObject *)values[11]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("interpolate3d", 1, 12, 12, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("_interpolate3d.interpolate3d", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x), __pyx_ptype_5numpy_ndarray, 1, "x", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 15; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y), __pyx_ptype_5numpy_ndarray, 1, "y", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 16; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_z), __pyx_ptype_5numpy_ndarray, 1, "z", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 17; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x_vals), __pyx_ptype_5numpy_ndarray, 1, "x_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 18; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_y_vals), __pyx_ptype_5numpy_ndarray, 1, "y_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 19; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_z_vals), __pyx_ptype_5numpy_ndarray, 1, "z_vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 20; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_vals), __pyx_ptype_5numpy_ndarray, 1, "vals", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 21; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_result_array), __pyx_ptype_5numpy_ndarray, 1, "result_array", 0))) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 22; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = __pyx_pf_14_interpolate3d_4interpolate3d(__pyx_self, __pyx_v_n, __pyx_v_x, __pyx_v_y, __pyx_v_z, __pyx_v_n_x_vals, __pyx_v_x_vals, __pyx_v_n_y_vals, __pyx_v_y_vals, __pyx_v_n_z_vals, __pyx_v_z_vals, __pyx_v_vals, __pyx_v_result_array); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_14_interpolate3d_4interpolate3d(CYTHON_UNUSED PyObject *__pyx_self, CYTHON_UNUSED int __pyx_v_n, PyArrayObject *__pyx_v_x, PyArrayObject *__pyx_v_y, PyArrayObject *__pyx_v_z, int __pyx_v_n_x_vals, PyArrayObject *__pyx_v_x_vals, int __pyx_v_n_y_vals, PyArrayObject *__pyx_v_y_vals, int __pyx_v_n_z_vals, PyArrayObject *__pyx_v_z_vals, PyArrayObject *__pyx_v_vals, PyArrayObject *__pyx_v_result_array) { int __pyx_v_x_top_ind; int __pyx_v_x_bot_ind; int __pyx_v_y_top_ind; int __pyx_v_y_bot_ind; int __pyx_v_z_top_ind; int __pyx_v_z_bot_ind; int __pyx_v_mid_ind; double __pyx_v_x_fac; double __pyx_v_y_fac; double __pyx_v_z_fac; double __pyx_v_v0; double __pyx_v_v1; double __pyx_v_v00; double __pyx_v_v01; double __pyx_v_v10; double __pyx_v_v11; double __pyx_v_v000; double __pyx_v_v001; double __pyx_v_v010; double __pyx_v_v011; double __pyx_v_v100; double __pyx_v_v101; double __pyx_v_v110; double __pyx_v_v111; double __pyx_v_xi; double __pyx_v_yi; double __pyx_v_zi; Py_ssize_t __pyx_v_i; __Pyx_LocalBuf_ND __pyx_pybuffernd_result_array; __Pyx_Buffer __pyx_pybuffer_result_array; __Pyx_LocalBuf_ND __pyx_pybuffernd_vals; __Pyx_Buffer __pyx_pybuffer_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; __Pyx_LocalBuf_ND __pyx_pybuffernd_x_vals; __Pyx_Buffer __pyx_pybuffer_x_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_y; __Pyx_Buffer __pyx_pybuffer_y; __Pyx_LocalBuf_ND __pyx_pybuffernd_y_vals; __Pyx_Buffer __pyx_pybuffer_y_vals; __Pyx_LocalBuf_ND __pyx_pybuffernd_z; __Pyx_Buffer __pyx_pybuffer_z; __Pyx_LocalBuf_ND __pyx_pybuffernd_z_vals; __Pyx_Buffer __pyx_pybuffer_z_vals; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; int __pyx_t_4; Py_ssize_t __pyx_t_5; Py_ssize_t __pyx_t_6; Py_ssize_t __pyx_t_7; int __pyx_t_8; int __pyx_t_9; int __pyx_t_10; int __pyx_t_11; __pyx_t_5numpy_float64_t __pyx_t_12; int __pyx_t_13; int __pyx_t_14; __pyx_t_5numpy_float64_t __pyx_t_15; int __pyx_t_16; int __pyx_t_17; int __pyx_t_18; int __pyx_t_19; int __pyx_t_20; int __pyx_t_21; int __pyx_t_22; int __pyx_t_23; int __pyx_t_24; int __pyx_t_25; int __pyx_t_26; int __pyx_t_27; int __pyx_t_28; int __pyx_t_29; int __pyx_t_30; int __pyx_t_31; int __pyx_t_32; int __pyx_t_33; int __pyx_t_34; int __pyx_t_35; int __pyx_t_36; int __pyx_t_37; int __pyx_t_38; int __pyx_t_39; int __pyx_t_40; int __pyx_t_41; int __pyx_t_42; int __pyx_t_43; int __pyx_t_44; int __pyx_t_45; long __pyx_t_46; int __pyx_t_47; int __pyx_t_48; long __pyx_t_49; int __pyx_t_50; int __pyx_t_51; long __pyx_t_52; int __pyx_t_53; int __pyx_t_54; long __pyx_t_55; int __pyx_t_56; int __pyx_t_57; Py_ssize_t __pyx_t_58; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__pyx_fuse_1interpolate3d", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; __pyx_pybuffer_y.pybuffer.buf = NULL; __pyx_pybuffer_y.refcount = 0; __pyx_pybuffernd_y.data = NULL; __pyx_pybuffernd_y.rcbuffer = &__pyx_pybuffer_y; __pyx_pybuffer_z.pybuffer.buf = NULL; __pyx_pybuffer_z.refcount = 0; __pyx_pybuffernd_z.data = NULL; __pyx_pybuffernd_z.rcbuffer = &__pyx_pybuffer_z; __pyx_pybuffer_x_vals.pybuffer.buf = NULL; __pyx_pybuffer_x_vals.refcount = 0; __pyx_pybuffernd_x_vals.data = NULL; __pyx_pybuffernd_x_vals.rcbuffer = &__pyx_pybuffer_x_vals; __pyx_pybuffer_y_vals.pybuffer.buf = NULL; __pyx_pybuffer_y_vals.refcount = 0; __pyx_pybuffernd_y_vals.data = NULL; __pyx_pybuffernd_y_vals.rcbuffer = &__pyx_pybuffer_y_vals; __pyx_pybuffer_z_vals.pybuffer.buf = NULL; __pyx_pybuffer_z_vals.refcount = 0; __pyx_pybuffernd_z_vals.data = NULL; __pyx_pybuffernd_z_vals.rcbuffer = &__pyx_pybuffer_z_vals; __pyx_pybuffer_vals.pybuffer.buf = NULL; __pyx_pybuffer_vals.refcount = 0; __pyx_pybuffernd_vals.data = NULL; __pyx_pybuffernd_vals.rcbuffer = &__pyx_pybuffer_vals; __pyx_pybuffer_result_array.pybuffer.buf = NULL; __pyx_pybuffer_result_array.refcount = 0; __pyx_pybuffernd_result_array.data = NULL; __pyx_pybuffernd_result_array.rcbuffer = &__pyx_pybuffer_result_array; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y.rcbuffer->pybuffer, (PyObject*)__pyx_v_y, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_y.diminfo[0].strides = __pyx_pybuffernd_y.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y.diminfo[0].shape = __pyx_pybuffernd_y.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z.rcbuffer->pybuffer, (PyObject*)__pyx_v_z, &__Pyx_TypeInfo_double, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_z.diminfo[0].strides = __pyx_pybuffernd_z.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z.diminfo[0].shape = __pyx_pybuffernd_z.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_x_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_x_vals.diminfo[0].strides = __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x_vals.diminfo[0].shape = __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_y_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_y_vals.diminfo[0].strides = __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_y_vals.diminfo[0].shape = __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_z_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_z_vals.diminfo[0].strides = __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_z_vals.diminfo[0].shape = __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.shape[0]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_vals.rcbuffer->pybuffer, (PyObject*)__pyx_v_vals, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES, 3, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_vals.diminfo[0].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_vals.diminfo[0].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_vals.diminfo[1].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_vals.diminfo[1].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_vals.diminfo[2].strides = __pyx_pybuffernd_vals.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_vals.diminfo[2].shape = __pyx_pybuffernd_vals.rcbuffer->pybuffer.shape[2]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer, (PyObject*)__pyx_v_result_array, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_STRIDES| PyBUF_WRITABLE, 1, 0, __pyx_stack) == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_pybuffernd_result_array.diminfo[0].strides = __pyx_pybuffernd_result_array.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_result_array.diminfo[0].shape = __pyx_pybuffernd_result_array.rcbuffer->pybuffer.shape[0]; /* "_interpolate3d.pyx":32 * cdef Py_ssize_t i * * for i in prange(n,nogil=True) : # <<<<<<<<<<<<<< * if n_x_vals > 0 : * xi = x[i] */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS #endif /*try:*/ { __pyx_t_1 = __pyx_v_n; if (1 == 0) abort(); { double __pyx_parallel_temp0 = __PYX_NAN(); double __pyx_parallel_temp1 = __PYX_NAN(); double __pyx_parallel_temp2 = __PYX_NAN(); double __pyx_parallel_temp3 = __PYX_NAN(); int __pyx_parallel_temp4 = 0xbad0bad0; double __pyx_parallel_temp5 = __PYX_NAN(); double __pyx_parallel_temp6 = __PYX_NAN(); int __pyx_parallel_temp7 = 0xbad0bad0; double __pyx_parallel_temp8 = __PYX_NAN(); int __pyx_parallel_temp9 = 0xbad0bad0; double __pyx_parallel_temp10 = __PYX_NAN(); double __pyx_parallel_temp11 = __PYX_NAN(); double __pyx_parallel_temp12 = __PYX_NAN(); double __pyx_parallel_temp13 = __PYX_NAN(); int __pyx_parallel_temp14 = 0xbad0bad0; double __pyx_parallel_temp15 = __PYX_NAN(); int __pyx_parallel_temp16 = 0xbad0bad0; double __pyx_parallel_temp17 = __PYX_NAN(); double __pyx_parallel_temp18 = __PYX_NAN(); double __pyx_parallel_temp19 = __PYX_NAN(); double __pyx_parallel_temp20 = __PYX_NAN(); int __pyx_parallel_temp21 = 0xbad0bad0; int __pyx_parallel_temp22 = 0xbad0bad0; double __pyx_parallel_temp23 = __PYX_NAN(); double __pyx_parallel_temp24 = __PYX_NAN(); Py_ssize_t __pyx_parallel_temp25 = 0xbad0bad0; double __pyx_parallel_temp26 = __PYX_NAN(); double __pyx_parallel_temp27 = __PYX_NAN(); const char *__pyx_parallel_filename = NULL; int __pyx_parallel_lineno = 0, __pyx_parallel_clineno = 0; PyObject *__pyx_parallel_exc_type = NULL, *__pyx_parallel_exc_value = NULL, *__pyx_parallel_exc_tb = NULL; int __pyx_parallel_why; __pyx_parallel_why = 0; #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) (x) #define unlikely(x) (x) #endif __pyx_t_3 = (__pyx_t_1 - 0) / 1; if (__pyx_t_3 > 0) { #ifdef _OPENMP #pragma omp parallel private(__pyx_t_23, __pyx_t_28, __pyx_t_38, __pyx_t_20, __pyx_t_27, __pyx_t_29, __pyx_t_44, __pyx_t_45, __pyx_t_32, __pyx_t_7, __pyx_t_21, __pyx_t_24, __pyx_t_8, __pyx_t_14, __pyx_t_19, __pyx_t_41, __pyx_t_35, __pyx_t_50, __pyx_t_13, __pyx_t_18, __pyx_t_42, __pyx_t_31, __pyx_t_57, __pyx_t_17, __pyx_t_46, __pyx_t_49, __pyx_t_53, __pyx_t_4, __pyx_t_34, __pyx_t_12, __pyx_t_37, __pyx_t_30, __pyx_t_52, __pyx_t_25, __pyx_t_11, __pyx_t_16, __pyx_t_36, __pyx_t_33, __pyx_t_56, __pyx_t_22, __pyx_t_10, __pyx_t_15, __pyx_t_39, __pyx_t_43, __pyx_t_54, __pyx_t_47, __pyx_t_51, __pyx_t_5, __pyx_t_6, __pyx_t_48, __pyx_t_9, __pyx_t_26, __pyx_t_40, __pyx_t_58, __pyx_t_55) private(__pyx_filename, __pyx_lineno, __pyx_clineno) shared(__pyx_parallel_why, __pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb) #endif /* _OPENMP */ { #ifdef _OPENMP #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif Py_BEGIN_ALLOW_THREADS #endif /* _OPENMP */ #ifdef _OPENMP #pragma omp for lastprivate(__pyx_v_y_fac) lastprivate(__pyx_v_z_fac) lastprivate(__pyx_v_v10) lastprivate(__pyx_v_v010) lastprivate(__pyx_v_z_bot_ind) lastprivate(__pyx_v_yi) lastprivate(__pyx_v_v1) lastprivate(__pyx_v_x_bot_ind) lastprivate(__pyx_v_v0) lastprivate(__pyx_v_x_top_ind) lastprivate(__pyx_v_xi) lastprivate(__pyx_v_v011) lastprivate(__pyx_v_v00) lastprivate(__pyx_v_v100) lastprivate(__pyx_v_z_top_ind) lastprivate(__pyx_v_v110) lastprivate(__pyx_v_y_bot_ind) lastprivate(__pyx_v_v01) lastprivate(__pyx_v_v101) lastprivate(__pyx_v_zi) lastprivate(__pyx_v_v111) lastprivate(__pyx_v_y_top_ind) lastprivate(__pyx_v_mid_ind) lastprivate(__pyx_v_v000) lastprivate(__pyx_v_v001) firstprivate(__pyx_v_i) lastprivate(__pyx_v_i) lastprivate(__pyx_v_v11) lastprivate(__pyx_v_x_fac) #endif /* _OPENMP */ for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_3; __pyx_t_2++){ if (__pyx_parallel_why < 2) { __pyx_v_i = 0 + 1 * __pyx_t_2; /* Initialize private variables to invalid values */ __pyx_v_y_fac = ((double)__PYX_NAN()); __pyx_v_z_fac = ((double)__PYX_NAN()); __pyx_v_v10 = ((double)__PYX_NAN()); __pyx_v_v010 = ((double)__PYX_NAN()); __pyx_v_z_bot_ind = ((int)0xbad0bad0); __pyx_v_yi = ((double)__PYX_NAN()); __pyx_v_v1 = ((double)__PYX_NAN()); __pyx_v_x_bot_ind = ((int)0xbad0bad0); __pyx_v_v0 = ((double)__PYX_NAN()); __pyx_v_x_top_ind = ((int)0xbad0bad0); __pyx_v_xi = ((double)__PYX_NAN()); __pyx_v_v011 = ((double)__PYX_NAN()); __pyx_v_v00 = ((double)__PYX_NAN()); __pyx_v_v100 = ((double)__PYX_NAN()); __pyx_v_z_top_ind = ((int)0xbad0bad0); __pyx_v_v110 = ((double)__PYX_NAN()); __pyx_v_y_bot_ind = ((int)0xbad0bad0); __pyx_v_v01 = ((double)__PYX_NAN()); __pyx_v_v101 = ((double)__PYX_NAN()); __pyx_v_zi = ((double)__PYX_NAN()); __pyx_v_v111 = ((double)__PYX_NAN()); __pyx_v_y_top_ind = ((int)0xbad0bad0); __pyx_v_mid_ind = ((int)0xbad0bad0); __pyx_v_v000 = ((double)__PYX_NAN()); __pyx_v_v001 = ((double)__PYX_NAN()); __pyx_v_v11 = ((double)__PYX_NAN()); __pyx_v_x_fac = ((double)__PYX_NAN()); /* "_interpolate3d.pyx":33 * * for i in prange(n,nogil=True) : * if n_x_vals > 0 : # <<<<<<<<<<<<<< * xi = x[i] * yi = y[i] */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":34 * for i in prange(n,nogil=True) : * if n_x_vals > 0 : * xi = x[i] # <<<<<<<<<<<<<< * yi = y[i] * zi = z[i] */ __pyx_t_5 = __pyx_v_i; __pyx_v_xi = (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_x.rcbuffer->pybuffer.buf, __pyx_t_5, __pyx_pybuffernd_x.diminfo[0].strides)); goto __pyx_L10; } __pyx_L10:; /* "_interpolate3d.pyx":35 * if n_x_vals > 0 : * xi = x[i] * yi = y[i] # <<<<<<<<<<<<<< * zi = z[i] * */ __pyx_t_6 = __pyx_v_i; __pyx_v_yi = (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_y.rcbuffer->pybuffer.buf, __pyx_t_6, __pyx_pybuffernd_y.diminfo[0].strides)); /* "_interpolate3d.pyx":36 * xi = x[i] * yi = y[i] * zi = z[i] # <<<<<<<<<<<<<< * * if n_x_vals > 0 : */ __pyx_t_7 = __pyx_v_i; __pyx_v_zi = (*__Pyx_BufPtrStrided1d(double *, __pyx_pybuffernd_z.rcbuffer->pybuffer.buf, __pyx_t_7, __pyx_pybuffernd_z.diminfo[0].strides)); /* "_interpolate3d.pyx":38 * zi = z[i] * * if n_x_vals > 0 : # <<<<<<<<<<<<<< * # find x indices * x_top_ind = n_x_vals - 1 */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":40 * if n_x_vals > 0 : * # find x indices * x_top_ind = n_x_vals - 1 # <<<<<<<<<<<<<< * x_bot_ind = 0 * */ __pyx_v_x_top_ind = (__pyx_v_n_x_vals - 1); /* "_interpolate3d.pyx":41 * # find x indices * x_top_ind = n_x_vals - 1 * x_bot_ind = 0 # <<<<<<<<<<<<<< * * while(x_top_ind > x_bot_ind + 1) : */ __pyx_v_x_bot_ind = 0; /* "_interpolate3d.pyx":43 * x_bot_ind = 0 * * while(x_top_ind > x_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_x_top_ind > (__pyx_v_x_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":44 * * while(x_top_ind > x_bot_ind + 1) : * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind # <<<<<<<<<<<<<< * if (xi > x_vals[mid_ind]) : * x_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_x_top_ind - __pyx_v_x_bot_ind), 2)) + __pyx_v_x_bot_ind); /* "_interpolate3d.pyx":45 * while(x_top_ind > x_bot_ind + 1) : * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : # <<<<<<<<<<<<<< * x_bot_ind = mid_ind * else : */ __pyx_t_8 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_xi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_8, __pyx_pybuffernd_x_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":46 * mid_ind = floor((x_top_ind-x_bot_ind)/2)+x_bot_ind * if (xi > x_vals[mid_ind]) : * x_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * x_top_ind = mid_ind */ __pyx_v_x_bot_ind = __pyx_v_mid_ind; goto __pyx_L14; } /*else*/ { /* "_interpolate3d.pyx":48 * x_bot_ind = mid_ind * else : * x_top_ind = mid_ind # <<<<<<<<<<<<<< * * else : */ __pyx_v_x_top_ind = __pyx_v_mid_ind; } __pyx_L14:; } goto __pyx_L11; } /*else*/ { /* "_interpolate3d.pyx":51 * * else : * x_top_ind = 0 # <<<<<<<<<<<<<< * x_bot_ind = 0 * */ __pyx_v_x_top_ind = 0; /* "_interpolate3d.pyx":52 * else : * x_top_ind = 0 * x_bot_ind = 0 # <<<<<<<<<<<<<< * * # find y indices */ __pyx_v_x_bot_ind = 0; } __pyx_L11:; /* "_interpolate3d.pyx":55 * * # find y indices * y_top_ind = n_y_vals - 1 # <<<<<<<<<<<<<< * y_bot_ind = 0 * */ __pyx_v_y_top_ind = (__pyx_v_n_y_vals - 1); /* "_interpolate3d.pyx":56 * # find y indices * y_top_ind = n_y_vals - 1 * y_bot_ind = 0 # <<<<<<<<<<<<<< * * while(y_top_ind > y_bot_ind + 1) : */ __pyx_v_y_bot_ind = 0; /* "_interpolate3d.pyx":58 * y_bot_ind = 0 * * while(y_top_ind > y_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_y_top_ind > (__pyx_v_y_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":59 * * while(y_top_ind > y_bot_ind + 1) : * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind # <<<<<<<<<<<<<< * if (yi > y_vals[mid_ind]) : * y_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_y_top_ind - __pyx_v_y_bot_ind), 2)) + __pyx_v_y_bot_ind); /* "_interpolate3d.pyx":60 * while(y_top_ind > y_bot_ind + 1) : * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : # <<<<<<<<<<<<<< * y_bot_ind = mid_ind * else : */ __pyx_t_9 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_yi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_9, __pyx_pybuffernd_y_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":61 * mid_ind = floor((y_top_ind-y_bot_ind)/2)+y_bot_ind * if (yi > y_vals[mid_ind]) : * y_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * y_top_ind = mid_ind */ __pyx_v_y_bot_ind = __pyx_v_mid_ind; goto __pyx_L17; } /*else*/ { /* "_interpolate3d.pyx":63 * y_bot_ind = mid_ind * else : * y_top_ind = mid_ind # <<<<<<<<<<<<<< * * # find z indices */ __pyx_v_y_top_ind = __pyx_v_mid_ind; } __pyx_L17:; } /* "_interpolate3d.pyx":66 * * # find z indices * z_top_ind = n_z_vals - 1 # <<<<<<<<<<<<<< * z_bot_ind = 0 * */ __pyx_v_z_top_ind = (__pyx_v_n_z_vals - 1); /* "_interpolate3d.pyx":67 * # find z indices * z_top_ind = n_z_vals - 1 * z_bot_ind = 0 # <<<<<<<<<<<<<< * * while(z_top_ind > z_bot_ind + 1) : */ __pyx_v_z_bot_ind = 0; /* "_interpolate3d.pyx":69 * z_bot_ind = 0 * * while(z_top_ind > z_bot_ind + 1) : # <<<<<<<<<<<<<< * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : */ while (1) { __pyx_t_4 = ((__pyx_v_z_top_ind > (__pyx_v_z_bot_ind + 1)) != 0); if (!__pyx_t_4) break; /* "_interpolate3d.pyx":70 * * while(z_top_ind > z_bot_ind + 1) : * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind # <<<<<<<<<<<<<< * if (zi > z_vals[mid_ind]) : * z_bot_ind = mid_ind */ __pyx_v_mid_ind = (floor(__Pyx_div_long((__pyx_v_z_top_ind - __pyx_v_z_bot_ind), 2)) + __pyx_v_z_bot_ind); /* "_interpolate3d.pyx":71 * while(z_top_ind > z_bot_ind + 1) : * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : # <<<<<<<<<<<<<< * z_bot_ind = mid_ind * else : */ __pyx_t_10 = __pyx_v_mid_ind; __pyx_t_4 = ((__pyx_v_zi > (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_10, __pyx_pybuffernd_z_vals.diminfo[0].strides))) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":72 * mid_ind = floor((z_top_ind-z_bot_ind)/2)+z_bot_ind * if (zi > z_vals[mid_ind]) : * z_bot_ind = mid_ind # <<<<<<<<<<<<<< * else : * z_top_ind = mid_ind */ __pyx_v_z_bot_ind = __pyx_v_mid_ind; goto __pyx_L20; } /*else*/ { /* "_interpolate3d.pyx":74 * z_bot_ind = mid_ind * else : * z_top_ind = mid_ind # <<<<<<<<<<<<<< * * if n_x_vals > 0 : */ __pyx_v_z_top_ind = __pyx_v_mid_ind; } __pyx_L20:; } /* "_interpolate3d.pyx":76 * z_top_ind = mid_ind * * if n_x_vals > 0 : # <<<<<<<<<<<<<< * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) * */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":77 * * if n_x_vals > 0 : * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) # <<<<<<<<<<<<<< * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) */ __pyx_t_11 = __pyx_v_x_bot_ind; __pyx_t_12 = (__pyx_v_xi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_11, __pyx_pybuffernd_x_vals.diminfo[0].strides))); __pyx_t_13 = __pyx_v_x_top_ind; __pyx_t_14 = __pyx_v_x_bot_ind; __pyx_t_15 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_13, __pyx_pybuffernd_x_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_x_vals.rcbuffer->pybuffer.buf, __pyx_t_14, __pyx_pybuffernd_x_vals.diminfo[0].strides))); if (unlikely(__pyx_t_15 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 77; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_x_fac = (__pyx_t_12 / __pyx_t_15); goto __pyx_L21; } __pyx_L21:; /* "_interpolate3d.pyx":79 * x_fac = (xi - x_vals[x_bot_ind])/(x_vals[x_top_ind] - x_vals[x_bot_ind]) * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) # <<<<<<<<<<<<<< * z_fac = (zi - z_vals[z_bot_ind])/(z_vals[z_top_ind] - z_vals[z_bot_ind]) * */ __pyx_t_16 = __pyx_v_y_bot_ind; __pyx_t_15 = (__pyx_v_yi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_16, __pyx_pybuffernd_y_vals.diminfo[0].strides))); __pyx_t_17 = __pyx_v_y_top_ind; __pyx_t_18 = __pyx_v_y_bot_ind; __pyx_t_12 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_17, __pyx_pybuffernd_y_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_y_vals.rcbuffer->pybuffer.buf, __pyx_t_18, __pyx_pybuffernd_y_vals.diminfo[0].strides))); if (unlikely(__pyx_t_12 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 79; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_y_fac = (__pyx_t_15 / __pyx_t_12); /* "_interpolate3d.pyx":80 * * y_fac = (yi - y_vals[y_bot_ind])/(y_vals[y_top_ind] - y_vals[y_bot_ind]) * z_fac = (zi - z_vals[z_bot_ind])/(z_vals[z_top_ind] - z_vals[z_bot_ind]) # <<<<<<<<<<<<<< * * # vertex values */ __pyx_t_19 = __pyx_v_z_bot_ind; __pyx_t_12 = (__pyx_v_zi - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_19, __pyx_pybuffernd_z_vals.diminfo[0].strides))); __pyx_t_20 = __pyx_v_z_top_ind; __pyx_t_21 = __pyx_v_z_bot_ind; __pyx_t_15 = ((*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_20, __pyx_pybuffernd_z_vals.diminfo[0].strides)) - (*__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_z_vals.rcbuffer->pybuffer.buf, __pyx_t_21, __pyx_pybuffernd_z_vals.diminfo[0].strides))); if (unlikely(__pyx_t_15 == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "float division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[0]; __pyx_lineno = 80; __pyx_clineno = __LINE__; goto __pyx_L8_error;} } __pyx_v_z_fac = (__pyx_t_12 / __pyx_t_15); /* "_interpolate3d.pyx":83 * * # vertex values * if n_x_vals > 0 : # <<<<<<<<<<<<<< * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] */ __pyx_t_4 = ((__pyx_v_n_x_vals > 0) != 0); if (__pyx_t_4) { /* "_interpolate3d.pyx":84 * # vertex values * if n_x_vals > 0 : * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] # <<<<<<<<<<<<<< * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] */ __pyx_t_22 = __pyx_v_x_bot_ind; __pyx_t_23 = __pyx_v_y_bot_ind; __pyx_t_24 = __pyx_v_z_bot_ind; __pyx_v_v000 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_22, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_23, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_24, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":85 * if n_x_vals > 0 : * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] # <<<<<<<<<<<<<< * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] */ __pyx_t_25 = __pyx_v_x_bot_ind; __pyx_t_26 = __pyx_v_y_bot_ind; __pyx_t_27 = __pyx_v_z_top_ind; __pyx_v_v001 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_25, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_26, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_27, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":86 * v000 = vals[x_bot_ind,y_bot_ind,z_bot_ind] * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] # <<<<<<<<<<<<<< * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] */ __pyx_t_28 = __pyx_v_x_bot_ind; __pyx_t_29 = __pyx_v_y_top_ind; __pyx_t_30 = __pyx_v_z_bot_ind; __pyx_v_v010 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_28, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_29, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_30, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":87 * v001 = vals[x_bot_ind,y_bot_ind,z_top_ind] * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] # <<<<<<<<<<<<<< * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] */ __pyx_t_31 = __pyx_v_x_bot_ind; __pyx_t_32 = __pyx_v_y_top_ind; __pyx_t_33 = __pyx_v_z_top_ind; __pyx_v_v011 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_31, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_32, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_33, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":88 * v010 = vals[x_bot_ind,y_top_ind,z_bot_ind] * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] # <<<<<<<<<<<<<< * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] */ __pyx_t_34 = __pyx_v_x_top_ind; __pyx_t_35 = __pyx_v_y_bot_ind; __pyx_t_36 = __pyx_v_z_bot_ind; __pyx_v_v100 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_34, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_35, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_36, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":89 * v011 = vals[x_bot_ind,y_top_ind,z_top_ind] * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] # <<<<<<<<<<<<<< * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] * v111 = vals[x_top_ind,y_top_ind,z_top_ind] */ __pyx_t_37 = __pyx_v_x_top_ind; __pyx_t_38 = __pyx_v_y_bot_ind; __pyx_t_39 = __pyx_v_z_top_ind; __pyx_v_v101 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_37, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_38, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_39, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":90 * v100 = vals[x_top_ind,y_bot_ind,z_bot_ind] * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] # <<<<<<<<<<<<<< * v111 = vals[x_top_ind,y_top_ind,z_top_ind] * */ __pyx_t_40 = __pyx_v_x_top_ind; __pyx_t_41 = __pyx_v_y_top_ind; __pyx_t_42 = __pyx_v_z_bot_ind; __pyx_v_v110 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_40, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_41, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_42, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":91 * v101 = vals[x_top_ind,y_bot_ind,z_top_ind] * v110 = vals[x_top_ind,y_top_ind,z_bot_ind] * v111 = vals[x_top_ind,y_top_ind,z_top_ind] # <<<<<<<<<<<<<< * * v00 = v000*(1.0-x_fac) + v100*x_fac */ __pyx_t_43 = __pyx_v_x_top_ind; __pyx_t_44 = __pyx_v_y_top_ind; __pyx_t_45 = __pyx_v_z_top_ind; __pyx_v_v111 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_43, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_44, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_45, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":93 * v111 = vals[x_top_ind,y_top_ind,z_top_ind] * * v00 = v000*(1.0-x_fac) + v100*x_fac # <<<<<<<<<<<<<< * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac */ __pyx_v_v00 = ((__pyx_v_v000 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v100 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":94 * * v00 = v000*(1.0-x_fac) + v100*x_fac * v10 = v010*(1.0-x_fac) + v110*x_fac # <<<<<<<<<<<<<< * v01 = v001*(1.0-x_fac) + v101*x_fac * v11 = v011*(1.0-x_fac) + v111*x_fac */ __pyx_v_v10 = ((__pyx_v_v010 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v110 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":95 * v00 = v000*(1.0-x_fac) + v100*x_fac * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac # <<<<<<<<<<<<<< * v11 = v011*(1.0-x_fac) + v111*x_fac * */ __pyx_v_v01 = ((__pyx_v_v001 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v101 * __pyx_v_x_fac)); /* "_interpolate3d.pyx":96 * v10 = v010*(1.0-x_fac) + v110*x_fac * v01 = v001*(1.0-x_fac) + v101*x_fac * v11 = v011*(1.0-x_fac) + v111*x_fac # <<<<<<<<<<<<<< * * else : */ __pyx_v_v11 = ((__pyx_v_v011 * (1.0 - __pyx_v_x_fac)) + (__pyx_v_v111 * __pyx_v_x_fac)); goto __pyx_L22; } /*else*/ { /* "_interpolate3d.pyx":99 * * else : * v00 = vals[0, y_bot_ind, z_bot_ind] # <<<<<<<<<<<<<< * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] */ __pyx_t_46 = 0; __pyx_t_47 = __pyx_v_y_bot_ind; __pyx_t_48 = __pyx_v_z_bot_ind; __pyx_v_v00 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_46, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_47, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_48, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":100 * else : * v00 = vals[0, y_bot_ind, z_bot_ind] * v01 = vals[0, y_bot_ind, z_top_ind] # <<<<<<<<<<<<<< * v10 = vals[0, y_top_ind, z_bot_ind] * v11 = vals[0, y_top_ind, z_top_ind] */ __pyx_t_49 = 0; __pyx_t_50 = __pyx_v_y_bot_ind; __pyx_t_51 = __pyx_v_z_top_ind; __pyx_v_v01 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_49, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_50, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_51, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":101 * v00 = vals[0, y_bot_ind, z_bot_ind] * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] # <<<<<<<<<<<<<< * v11 = vals[0, y_top_ind, z_top_ind] * */ __pyx_t_52 = 0; __pyx_t_53 = __pyx_v_y_top_ind; __pyx_t_54 = __pyx_v_z_bot_ind; __pyx_v_v10 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_52, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_53, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_54, __pyx_pybuffernd_vals.diminfo[2].strides)); /* "_interpolate3d.pyx":102 * v01 = vals[0, y_bot_ind, z_top_ind] * v10 = vals[0, y_top_ind, z_bot_ind] * v11 = vals[0, y_top_ind, z_top_ind] # <<<<<<<<<<<<<< * * v0 = v00*(1.0-y_fac) + v10*y_fac */ __pyx_t_55 = 0; __pyx_t_56 = __pyx_v_y_top_ind; __pyx_t_57 = __pyx_v_z_top_ind; __pyx_v_v11 = (*__Pyx_BufPtrStrided3d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_vals.rcbuffer->pybuffer.buf, __pyx_t_55, __pyx_pybuffernd_vals.diminfo[0].strides, __pyx_t_56, __pyx_pybuffernd_vals.diminfo[1].strides, __pyx_t_57, __pyx_pybuffernd_vals.diminfo[2].strides)); } __pyx_L22:; /* "_interpolate3d.pyx":104 * v11 = vals[0, y_top_ind, z_top_ind] * * v0 = v00*(1.0-y_fac) + v10*y_fac # <<<<<<<<<<<<<< * v1 = v01*(1.0-y_fac) + v11*y_fac * */ __pyx_v_v0 = ((__pyx_v_v00 * (1.0 - __pyx_v_y_fac)) + (__pyx_v_v10 * __pyx_v_y_fac)); /* "_interpolate3d.pyx":105 * * v0 = v00*(1.0-y_fac) + v10*y_fac * v1 = v01*(1.0-y_fac) + v11*y_fac # <<<<<<<<<<<<<< * * result_array[i] = v0*(1-z_fac) + v1*z_fac */ __pyx_v_v1 = ((__pyx_v_v01 * (1.0 - __pyx_v_y_fac)) + (__pyx_v_v11 * __pyx_v_y_fac)); /* "_interpolate3d.pyx":107 * v1 = v01*(1.0-y_fac) + v11*y_fac * * result_array[i] = v0*(1-z_fac) + v1*z_fac # <<<<<<<<<<<<<< * * */ __pyx_t_58 = __pyx_v_i; *__Pyx_BufPtrStrided1d(__pyx_t_5numpy_float64_t *, __pyx_pybuffernd_result_array.rcbuffer->pybuffer.buf, __pyx_t_58, __pyx_pybuffernd_result_array.diminfo[0].strides) = ((__pyx_v_v0 * (1.0 - __pyx_v_z_fac)) + (__pyx_v_v1 * __pyx_v_z_fac)); goto __pyx_L24; __pyx_L8_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #ifdef _OPENMP #pragma omp flush(__pyx_parallel_exc_type) #endif /* _OPENMP */ if (!__pyx_parallel_exc_type) { __Pyx_ErrFetch(&__pyx_parallel_exc_type, &__pyx_parallel_exc_value, &__pyx_parallel_exc_tb); __pyx_parallel_filename = __pyx_filename; __pyx_parallel_lineno = __pyx_lineno; __pyx_parallel_clineno = __pyx_clineno; __Pyx_GOTREF(__pyx_parallel_exc_type); } #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_parallel_why = 4; goto __pyx_L23; __pyx_L23:; #ifdef _OPENMP #pragma omp critical(__pyx_parallel_lastprivates1) #endif /* _OPENMP */ { __pyx_parallel_temp0 = __pyx_v_y_fac; __pyx_parallel_temp1 = __pyx_v_z_fac; __pyx_parallel_temp2 = __pyx_v_v10; __pyx_parallel_temp3 = __pyx_v_v010; __pyx_parallel_temp4 = __pyx_v_z_bot_ind; __pyx_parallel_temp5 = __pyx_v_yi; __pyx_parallel_temp6 = __pyx_v_v1; __pyx_parallel_temp7 = __pyx_v_x_bot_ind; __pyx_parallel_temp8 = __pyx_v_v0; __pyx_parallel_temp9 = __pyx_v_x_top_ind; __pyx_parallel_temp10 = __pyx_v_xi; __pyx_parallel_temp11 = __pyx_v_v011; __pyx_parallel_temp12 = __pyx_v_v00; __pyx_parallel_temp13 = __pyx_v_v100; __pyx_parallel_temp14 = __pyx_v_z_top_ind; __pyx_parallel_temp15 = __pyx_v_v110; __pyx_parallel_temp16 = __pyx_v_y_bot_ind; __pyx_parallel_temp17 = __pyx_v_v01; __pyx_parallel_temp18 = __pyx_v_v101; __pyx_parallel_temp19 = __pyx_v_zi; __pyx_parallel_temp20 = __pyx_v_v111; __pyx_parallel_temp21 = __pyx_v_y_top_ind; __pyx_parallel_temp22 = __pyx_v_mid_ind; __pyx_parallel_temp23 = __pyx_v_v000; __pyx_parallel_temp24 = __pyx_v_v001; __pyx_parallel_temp25 = __pyx_v_i; __pyx_parallel_temp26 = __pyx_v_v11; __pyx_parallel_temp27 = __pyx_v_x_fac; } __pyx_L24:; #ifdef _OPENMP #pragma omp flush(__pyx_parallel_why) #endif /* _OPENMP */ } } #ifdef _OPENMP Py_END_ALLOW_THREADS #else { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif #endif /* _OPENMP */ /* Clean up any temporaries */ #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif #ifndef _OPENMP } #endif /* _OPENMP */ } } if (__pyx_parallel_exc_type) { /* This may have been overridden by a continue, break or return in another thread. Prefer the error. */ __pyx_parallel_why = 4; } if (__pyx_parallel_why) { __pyx_v_y_fac = __pyx_parallel_temp0; __pyx_v_z_fac = __pyx_parallel_temp1; __pyx_v_v10 = __pyx_parallel_temp2; __pyx_v_v010 = __pyx_parallel_temp3; __pyx_v_z_bot_ind = __pyx_parallel_temp4; __pyx_v_yi = __pyx_parallel_temp5; __pyx_v_v1 = __pyx_parallel_temp6; __pyx_v_x_bot_ind = __pyx_parallel_temp7; __pyx_v_v0 = __pyx_parallel_temp8; __pyx_v_x_top_ind = __pyx_parallel_temp9; __pyx_v_xi = __pyx_parallel_temp10; __pyx_v_v011 = __pyx_parallel_temp11; __pyx_v_v00 = __pyx_parallel_temp12; __pyx_v_v100 = __pyx_parallel_temp13; __pyx_v_z_top_ind = __pyx_parallel_temp14; __pyx_v_v110 = __pyx_parallel_temp15; __pyx_v_y_bot_ind = __pyx_parallel_temp16; __pyx_v_v01 = __pyx_parallel_temp17; __pyx_v_v101 = __pyx_parallel_temp18; __pyx_v_zi = __pyx_parallel_temp19; __pyx_v_v111 = __pyx_parallel_temp20; __pyx_v_y_top_ind = __pyx_parallel_temp21; __pyx_v_mid_ind = __pyx_parallel_temp22; __pyx_v_v000 = __pyx_parallel_temp23; __pyx_v_v001 = __pyx_parallel_temp24; __pyx_v_i = __pyx_parallel_temp25; __pyx_v_v11 = __pyx_parallel_temp26; __pyx_v_x_fac = __pyx_parallel_temp27; switch (__pyx_parallel_why) { case 3: goto __pyx_L3_return; case 4: { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_GIVEREF(__pyx_parallel_exc_type); __Pyx_ErrRestore(__pyx_parallel_exc_type, __pyx_parallel_exc_value, __pyx_parallel_exc_tb); __pyx_filename = __pyx_parallel_filename; __pyx_lineno = __pyx_parallel_lineno; __pyx_clineno = __pyx_parallel_clineno; #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } goto __pyx_L4_error; } } } #if ((defined(__APPLE__) || defined(__OSX__)) && (defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))))) #undef likely #undef unlikely #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif } /* "_interpolate3d.pyx":32 * cdef Py_ssize_t i * * for i in prange(n,nogil=True) : # <<<<<<<<<<<<<< * if n_x_vals > 0 : * xi = x[i] */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L3_return: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L0; } __pyx_L4_error: { #ifdef WITH_THREAD Py_BLOCK_THREADS #endif goto __pyx_L1_error; } __pyx_L5:; } } /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("_interpolate3d.interpolate3d", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_result_array.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_y_vals.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_z_vals.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "_interpolate3d.pyx":113 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef int bisect(np.float64_t x, int nval, np.float64_t [:] arr) nogil: # <<<<<<<<<<<<<< * cdef int mid, top, bot * top = nval - 1 */ static int __pyx_f_14_interpolate3d_bisect(__pyx_t_5numpy_float64_t __pyx_v_x, int __pyx_v_nval, __Pyx_memviewslice __pyx_v_arr) { int __pyx_v_mid; int __pyx_v_top; int __pyx_v_bot; int __pyx_r; int __pyx_t_1; int __pyx_t_2; /* "_interpolate3d.pyx":115 * cdef int bisect(np.float64_t x, int nval, np.float64_t [:] arr) nogil: * cdef int mid, top, bot * top = nval - 1 # <<<<<<<<<<<<<< * bot = 0 * */ __pyx_v_top = (__pyx_v_nval - 1); /* "_interpolate3d.pyx":116 * cdef int mid, top, bot * top = nval - 1 * bot = 0 # <<<<<<<<<<<<<< * * while(top > bot + 1) : */ __pyx_v_bot = 0; /* "_interpolate3d.pyx":118 * bot = 0 * * while(top > bot + 1) : # <<<<<<<<<<<<<< * mid = floor((top-bot)/2)+bot * if (x > arr[mid]) : */ while (1) { __pyx_t_1 = ((__pyx_v_top > (__pyx_v_bot + 1)) != 0); if (!__pyx_t_1) break; /* "_interpolate3d.pyx":119 * * while(top > bot + 1) : * mid = floor((top-bot)/2)+bot # <<<<<<<<<<<<<< * if (x > arr[mid]) : * bot = mid */ __pyx_v_mid = (floor(__Pyx_div_long((__pyx_v_top - __pyx_v_bot), 2)) + __pyx_v_bot); /* "_interpolate3d.pyx":120 * while(top > bot + 1) : * mid = floor((top-bot)/2)+bot * if (x > arr[mid]) : # <<<<<<<<<<<<<< * bot = mid * else : */ __pyx_t_2 = __pyx_v_mid; __pyx_t_1 = ((__pyx_v_x > (*((__pyx_t_5numpy_float64_t *) ( /* dim=0 */ (__pyx_v_arr.data + __pyx_t_2 * __pyx_v_arr.strides[0]) )))) != 0); if (__pyx_t_1) { /* "_interpolate3d.pyx":121 * mid = floor((top-bot)/2)+bot * if (x > arr[mid]) : * bot = mid # <<<<<<<<<<<<<< * else : * top = mid */ __pyx_v_bot = __pyx_v_mid; goto __pyx_L5; } /*else*/ { /* "_interpolate3d.pyx":123 * bot = mid * else : * top = mid # <<<<<<<<<<<<<< * return bot */ __pyx_v_top = __pyx_v_mid; } __pyx_L5:; } /* "_interpolate3d.pyx":124 * else : * top = mid * return bot # <<<<<<<<<<<<<< */ __pyx_r = __pyx_v_bot; goto __pyx_L0; /* "_interpolate3d.pyx":113 * @cython.boundscheck(False) * @cython.wraparound(False) * cdef int bisect(np.float64_t x, int nval, np.float64_t [:] arr) nogil: # <<<<<<<<<<<<<< * cdef int mid, top, bot * top = nval - 1 */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":203 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":206 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":207 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":209 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":211 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":212 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; goto __pyx_L4; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":214 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":216 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":217 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":220 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":221 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":224 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":225 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":226 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":229 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2))); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":230 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":231 * info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":232 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":233 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } goto __pyx_L11; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":235 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":236 * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":237 * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":238 * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":239 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":242 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef list stack */ __pyx_v_f = NULL; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":243 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef list stack * cdef int offset */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":247 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":249 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":251 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; goto __pyx_L14; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":254 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":256 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":257 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":258 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":259 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":260 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":277 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ switch (__pyx_v_t) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":261 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ case NPY_BYTE: __pyx_v_f = __pyx_k_b; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":262 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = __pyx_k_B; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":263 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = __pyx_k_h; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":264 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = __pyx_k_H; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":265 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = __pyx_k_i; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":266 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = __pyx_k_I; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":267 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = __pyx_k_l; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":268 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = __pyx_k_L; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":269 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = __pyx_k_q; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":270 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = __pyx_k_Q; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":271 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = __pyx_k_f; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":272 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = __pyx_k_d; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":273 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = __pyx_k_g; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":274 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = __pyx_k_Zf; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":275 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = __pyx_k_Zd; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":276 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = __pyx_k_Zg; break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":277 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = __pyx_k_O; break; default: /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":279 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 279; __pyx_clineno = __LINE__; goto __pyx_L1_error;} break; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":280 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":281 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":283 * return * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ __pyx_v_info->format = ((char *)malloc(255)); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":284 * else: * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":285 * info.format = <char*>stdlib.malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":286 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 286; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_7; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":289 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = '\x00'; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":197 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":291 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":292 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":293 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * stdlib.free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) */ free(__pyx_v_info->format); goto __pyx_L3; } __pyx_L3:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":294 * if PyArray_HASFIELDS(self): * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * stdlib.free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":295 * stdlib.free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * stdlib.free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ free(__pyx_v_info->strides); goto __pyx_L4; } __pyx_L4:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":291 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * stdlib.free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":771 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":772 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":771 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":775 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":774 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":778 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":777 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":781 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":780 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":784 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 784; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":783 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":786 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":793 * cdef int delta_offset * cdef tuple i * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":794 * cdef tuple i * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":797 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":798 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":799 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - <int>(new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":801 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 801; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":802 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":804 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":805 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; if (__pyx_t_6) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":806 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":816 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 816; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":817 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 120; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":818 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":819 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":821 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":823 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":824 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 824; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":825 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":826 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":829 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":830 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":831 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 104; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":832 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":833 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 105; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":834 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":835 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 108; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":836 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":837 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 113; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":838 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":839 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 102; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":840 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 100; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":841 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 103; goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":842 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 102; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":843 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 843; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 100; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":844 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 103; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":845 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 845; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":847 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[1]; __pyx_lineno = 847; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L15:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":848 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L13; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":852 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 852; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":797 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":853 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":786 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":969 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":971 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":972 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; goto __pyx_L3; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":974 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = <PyObject*>base * Py_XDECREF(arr.base) */ Py_INCREF(__pyx_v_base); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":975 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":976 * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":977 * baseptr = <PyObject*>base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":969 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":979 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":980 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":981 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return <object>arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; } /*else*/ { /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":983 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":979 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":116 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* Python wrapper */ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_shape = 0; Py_ssize_t __pyx_v_itemsize; PyObject *__pyx_v_format = 0; PyObject *__pyx_v_mode = 0; int __pyx_v_allocate_buffer; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0}; PyObject* values[5] = {0,0,0,0,0}; values[3] = ((PyObject *)__pyx_n_s_c); if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 3: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode); if (value) { values[3] = value; kw_args--; } } case 4: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer); if (value) { values[4] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_shape = ((PyObject*)values[0]); __pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_v_format = values[2]; __pyx_v_mode = values[3]; if (values[4]) { __pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 117; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { /* "View.MemoryView":117 * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, * mode="c", bint allocate_buffer=True): # <<<<<<<<<<<<<< * * cdef int idx */ __pyx_v_allocate_buffer = ((int)1); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 116; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer); /* "View.MemoryView":116 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) { int __pyx_v_idx; Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_dim; PyObject **__pyx_v_p; char __pyx_v_order; int __pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; char *__pyx_t_5; int __pyx_t_6; PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); __Pyx_INCREF(__pyx_v_format); /* "View.MemoryView":123 * cdef PyObject **p * * self.ndim = <int> len(shape) # <<<<<<<<<<<<<< * self.itemsize = itemsize * */ if (unlikely(__pyx_v_shape == Py_None)) { PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 123; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->ndim = ((int)__pyx_t_1); /* "View.MemoryView":124 * * self.ndim = <int> len(shape) * self.itemsize = itemsize # <<<<<<<<<<<<<< * * if not self.ndim: */ __pyx_v_self->itemsize = __pyx_v_itemsize; /* "View.MemoryView":126 * self.itemsize = itemsize * * if not self.ndim: # <<<<<<<<<<<<<< * raise ValueError("Empty shape tuple for cython.array") * */ __pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":127 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":129 * raise ValueError("Empty shape tuple for cython.array") * * if itemsize <= 0: # <<<<<<<<<<<<<< * raise ValueError("itemsize <= 0 for cython.array") * */ __pyx_t_2 = ((__pyx_v_itemsize <= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":130 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if isinstance(format, unicode): */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":132 * raise ValueError("itemsize <= 0 for cython.array") * * if isinstance(format, unicode): # <<<<<<<<<<<<<< * format = (<unicode>format).encode('ASCII') * self._format = format # keep a reference to the byte string */ __pyx_t_2 = PyUnicode_Check(__pyx_v_format); __pyx_t_4 = (__pyx_t_2 != 0); if (__pyx_t_4) { /* "View.MemoryView":133 * * if isinstance(format, unicode): * format = (<unicode>format).encode('ASCII') # <<<<<<<<<<<<<< * self._format = format # keep a reference to the byte string * self.format = self._format */ if (unlikely(__pyx_v_format == Py_None)) { PyErr_Format(PyExc_AttributeError, "'NoneType' object has no attribute '%s'", "encode"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_3 = PyUnicode_AsASCIIString(((PyObject*)__pyx_v_format)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3); __pyx_t_3 = 0; goto __pyx_L5; } __pyx_L5:; /* "View.MemoryView":134 * if isinstance(format, unicode): * format = (<unicode>format).encode('ASCII') * self._format = format # keep a reference to the byte string # <<<<<<<<<<<<<< * self.format = self._format * */ if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 134; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = __pyx_v_format; __Pyx_INCREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __Pyx_GOTREF(__pyx_v_self->_format); __Pyx_DECREF(__pyx_v_self->_format); __pyx_v_self->_format = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":135 * format = (<unicode>format).encode('ASCII') * self._format = format # keep a reference to the byte string * self.format = self._format # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_5) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 135; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_self->format = __pyx_t_5; /* "View.MemoryView":138 * * * self._shape = <Py_ssize_t *> PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) # <<<<<<<<<<<<<< * self._strides = self._shape + self.ndim * */ __pyx_v_self->_shape = ((Py_ssize_t *)PyMem_Malloc((((sizeof(Py_ssize_t)) * __pyx_v_self->ndim) * 2))); /* "View.MemoryView":139 * * self._shape = <Py_ssize_t *> PyMem_Malloc(sizeof(Py_ssize_t)*self.ndim*2) * self._strides = self._shape + self.ndim # <<<<<<<<<<<<<< * * if not self._shape: */ __pyx_v_self->_strides = (__pyx_v_self->_shape + __pyx_v_self->ndim); /* "View.MemoryView":141 * self._strides = self._shape + self.ndim * * if not self._shape: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate shape and strides.") * */ __pyx_t_4 = ((!(__pyx_v_self->_shape != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":142 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":145 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ __pyx_t_6 = 0; __pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0; for (;;) { if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_7); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_7 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif __pyx_t_8 = __Pyx_PyIndex_AsSsize_t(__pyx_t_7); if (unlikely((__pyx_t_8 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_v_dim = __pyx_t_8; __pyx_v_idx = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); /* "View.MemoryView":146 * * for idx, dim in enumerate(shape): * if dim <= 0: # <<<<<<<<<<<<<< * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim */ __pyx_t_4 = ((__pyx_v_dim <= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":147 * for idx, dim in enumerate(shape): * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<< * self._shape[idx] = dim * */ __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __pyx_t_9 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_10 = PyTuple_New(2); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_10, 1, __pyx_t_9); __Pyx_GIVEREF(__pyx_t_9); __pyx_t_7 = 0; __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __pyx_t_10 = PyTuple_New(1); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_10); PyTuple_SET_ITEM(__pyx_t_10, 0, __pyx_t_9); __Pyx_GIVEREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_10, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0; __Pyx_Raise(__pyx_t_9, 0, 0, 0); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":148 * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) * self._shape[idx] = dim # <<<<<<<<<<<<<< * * cdef char order */ (__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_v_dim; /* "View.MemoryView":145 * * * for idx, dim in enumerate(shape): # <<<<<<<<<<<<<< * if dim <= 0: * raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":151 * * cdef char order * if mode == 'fortran': # <<<<<<<<<<<<<< * order = b'F' * self.mode = u'fortran' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 151; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":152 * cdef char order * if mode == 'fortran': * order = b'F' # <<<<<<<<<<<<<< * self.mode = u'fortran' * elif mode == 'c': */ __pyx_v_order = 'F'; /* "View.MemoryView":153 * if mode == 'fortran': * order = b'F' * self.mode = u'fortran' # <<<<<<<<<<<<<< * elif mode == 'c': * order = b'C' */ __Pyx_INCREF(__pyx_n_u_fortran); __Pyx_GIVEREF(__pyx_n_u_fortran); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_fortran; goto __pyx_L10; } /* "View.MemoryView":154 * order = b'F' * self.mode = u'fortran' * elif mode == 'c': # <<<<<<<<<<<<<< * order = b'C' * self.mode = u'c' */ __pyx_t_4 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 154; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":155 * self.mode = u'fortran' * elif mode == 'c': * order = b'C' # <<<<<<<<<<<<<< * self.mode = u'c' * else: */ __pyx_v_order = 'C'; /* "View.MemoryView":156 * elif mode == 'c': * order = b'C' * self.mode = u'c' # <<<<<<<<<<<<<< * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) */ __Pyx_INCREF(__pyx_n_u_c); __Pyx_GIVEREF(__pyx_n_u_c); __Pyx_GOTREF(__pyx_v_self->mode); __Pyx_DECREF(__pyx_v_self->mode); __pyx_v_self->mode = __pyx_n_u_c; goto __pyx_L10; } /*else*/ { /* "View.MemoryView":158 * self.mode = u'c' * else: * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<< * * self.len = fill_contig_strides_array(self._shape, self._strides, */ __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 158; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L10:; /* "View.MemoryView":160 * raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) * * self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<< * itemsize, self.ndim, order) * */ __pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order); /* "View.MemoryView":163 * itemsize, self.ndim, order) * * self.free_data = allocate_buffer # <<<<<<<<<<<<<< * self.dtype_is_object = format == b'O' * if allocate_buffer: */ __pyx_v_self->free_data = __pyx_v_allocate_buffer; /* "View.MemoryView":164 * * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<< * if allocate_buffer: * */ __pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_4 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_self->dtype_is_object = __pyx_t_4; /* "View.MemoryView":165 * self.free_data = allocate_buffer * self.dtype_is_object = format == b'O' * if allocate_buffer: # <<<<<<<<<<<<<< * * */ __pyx_t_4 = (__pyx_v_allocate_buffer != 0); if (__pyx_t_4) { /* "View.MemoryView":168 * * * self.data = <char *>malloc(self.len) # <<<<<<<<<<<<<< * if not self.data: * raise MemoryError("unable to allocate array data.") */ __pyx_v_self->data = ((char *)malloc(__pyx_v_self->len)); /* "View.MemoryView":169 * * self.data = <char *>malloc(self.len) * if not self.data: # <<<<<<<<<<<<<< * raise MemoryError("unable to allocate array data.") * */ __pyx_t_4 = ((!(__pyx_v_self->data != 0)) != 0); if (__pyx_t_4) { /* "View.MemoryView":170 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":172 * raise MemoryError("unable to allocate array data.") * * if self.dtype_is_object: # <<<<<<<<<<<<<< * p = <PyObject **> self.data * for i in range(self.len / itemsize): */ __pyx_t_4 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_4) { /* "View.MemoryView":173 * * if self.dtype_is_object: * p = <PyObject **> self.data # <<<<<<<<<<<<<< * for i in range(self.len / itemsize): * p[i] = Py_None */ __pyx_v_p = ((PyObject **)__pyx_v_self->data); /* "View.MemoryView":174 * if self.dtype_is_object: * p = <PyObject **> self.data * for i in range(self.len / itemsize): # <<<<<<<<<<<<<< * p[i] = Py_None * Py_INCREF(Py_None) */ if (unlikely(__pyx_v_itemsize == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_t_1 = __Pyx_div_Py_ssize_t(__pyx_v_self->len, __pyx_v_itemsize); for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_1; __pyx_t_8+=1) { __pyx_v_i = __pyx_t_8; /* "View.MemoryView":175 * p = <PyObject **> self.data * for i in range(self.len / itemsize): * p[i] = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ (__pyx_v_p[__pyx_v_i]) = Py_None; /* "View.MemoryView":176 * for i in range(self.len / itemsize): * p[i] = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * @cname('getbuffer') */ Py_INCREF(Py_None); } goto __pyx_L13; } __pyx_L13:; goto __pyx_L11; } __pyx_L11:; /* "View.MemoryView":116 * cdef bint dtype_is_object * * def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<< * mode="c", bint allocate_buffer=True): * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_XDECREF(__pyx_t_10); __Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_format); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":179 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_bufmode; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; char *__pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; Py_ssize_t *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":180 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 # <<<<<<<<<<<<<< * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = -1; /* "View.MemoryView":181 * def __getbuffer__(self, Py_buffer *info, int flags): * cdef int bufmode = -1 * if self.mode == u"c": # <<<<<<<<<<<<<< * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": */ __pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":182 * cdef int bufmode = -1 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS */ __pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); goto __pyx_L3; } /* "View.MemoryView":183 * if self.mode == u"c": * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": # <<<<<<<<<<<<<< * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): */ __pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_u_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 183; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":184 * bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<< * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") */ __pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":185 * elif self.mode == u"fortran": * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): # <<<<<<<<<<<<<< * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data */ __pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":186 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":187 * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data # <<<<<<<<<<<<<< * info.len = self.len * info.ndim = self.ndim */ __pyx_t_4 = __pyx_v_self->data; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":188 * raise ValueError("Can only create a buffer that is contiguous in memory.") * info.buf = self.data * info.len = self.len # <<<<<<<<<<<<<< * info.ndim = self.ndim * info.shape = self._shape */ __pyx_t_5 = __pyx_v_self->len; __pyx_v_info->len = __pyx_t_5; /* "View.MemoryView":189 * info.buf = self.data * info.len = self.len * info.ndim = self.ndim # <<<<<<<<<<<<<< * info.shape = self._shape * info.strides = self._strides */ __pyx_t_6 = __pyx_v_self->ndim; __pyx_v_info->ndim = __pyx_t_6; /* "View.MemoryView":190 * info.len = self.len * info.ndim = self.ndim * info.shape = self._shape # <<<<<<<<<<<<<< * info.strides = self._strides * info.suboffsets = NULL */ __pyx_t_7 = __pyx_v_self->_shape; __pyx_v_info->shape = __pyx_t_7; /* "View.MemoryView":191 * info.ndim = self.ndim * info.shape = self._shape * info.strides = self._strides # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = self.itemsize */ __pyx_t_7 = __pyx_v_self->_strides; __pyx_v_info->strides = __pyx_t_7; /* "View.MemoryView":192 * info.shape = self._shape * info.strides = self._strides * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = self.itemsize * info.readonly = 0 */ __pyx_v_info->suboffsets = NULL; /* "View.MemoryView":193 * info.strides = self._strides * info.suboffsets = NULL * info.itemsize = self.itemsize # <<<<<<<<<<<<<< * info.readonly = 0 * */ __pyx_t_5 = __pyx_v_self->itemsize; __pyx_v_info->itemsize = __pyx_t_5; /* "View.MemoryView":194 * info.suboffsets = NULL * info.itemsize = self.itemsize * info.readonly = 0 # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->readonly = 0; /* "View.MemoryView":196 * info.readonly = 0 * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":197 * * if flags & PyBUF_FORMAT: * info.format = self.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_4 = __pyx_v_self->format; __pyx_v_info->format = __pyx_t_4; goto __pyx_L5; } /*else*/ { /* "View.MemoryView":199 * info.format = self.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.obj = self */ __pyx_v_info->format = NULL; } __pyx_L5:; /* "View.MemoryView":201 * info.format = NULL * * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":179 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * cdef int bufmode = -1 * if self.mode == u"c": */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":205 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* Python wrapper */ static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_array___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_array___pyx_pf_15View_dot_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":206 * * def __dealloc__(array self): * if self.callback_free_data != NULL: # <<<<<<<<<<<<<< * self.callback_free_data(self.data) * elif self.free_data: */ __pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":207 * def __dealloc__(array self): * if self.callback_free_data != NULL: * self.callback_free_data(self.data) # <<<<<<<<<<<<<< * elif self.free_data: * if self.dtype_is_object: */ __pyx_v_self->callback_free_data(__pyx_v_self->data); goto __pyx_L3; } /* "View.MemoryView":208 * if self.callback_free_data != NULL: * self.callback_free_data(self.data) * elif self.free_data: # <<<<<<<<<<<<<< * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, */ __pyx_t_1 = (__pyx_v_self->free_data != 0); if (__pyx_t_1) { /* "View.MemoryView":209 * self.callback_free_data(self.data) * elif self.free_data: * if self.dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) */ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":210 * elif self.free_data: * if self.dtype_is_object: * refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<< * self._strides, self.ndim, False) * free(self.data) */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0); goto __pyx_L4; } __pyx_L4:; /* "View.MemoryView":212 * refcount_objects_in_slice(self.data, self._shape, * self._strides, self.ndim, False) * free(self.data) # <<<<<<<<<<<<<< * PyMem_Free(self._shape) * */ free(__pyx_v_self->data); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":213 * self._strides, self.ndim, False) * free(self.data) * PyMem_Free(self._shape) # <<<<<<<<<<<<<< * * property memview: */ PyMem_Free(__pyx_v_self->_shape); /* "View.MemoryView":205 * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") * * def __dealloc__(array self): # <<<<<<<<<<<<<< * if self.callback_free_data != NULL: * self.callback_free_data(self.data) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":217 * property memview: * @cname('get_memview') * def __get__(self): # <<<<<<<<<<<<<< * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE */ /* Python wrapper */ static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/ static PyObject *get_memview(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) { int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":219 * def __get__(self): * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<< * return memoryview(self, flags, self.dtype_is_object) * */ __pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE); /* "View.MemoryView":220 * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE * return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":217 * property memview: * @cname('get_memview') * def __get__(self): # <<<<<<<<<<<<<< * * flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":223 * * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* Python wrapper */ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/ static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getattr__", 0); /* "View.MemoryView":224 * * def __getattr__(self, attr): * return getattr(self.memview, attr) # <<<<<<<<<<<<<< * * def __getitem__(self, item): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 224; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":223 * * * def __getattr__(self, attr): # <<<<<<<<<<<<<< * return getattr(self.memview, attr) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":226 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* Python wrapper */ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/ static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_array___pyx_pf_15View_dot_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":227 * * def __getitem__(self, item): * return self.memview[item] # <<<<<<<<<<<<<< * * def __setitem__(self, item, value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":226 * return getattr(self.memview, attr) * * def __getitem__(self, item): # <<<<<<<<<<<<<< * return self.memview[item] * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":229 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* Python wrapper */ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/ static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_array___pyx_pf_15View_dot_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); /* "View.MemoryView":230 * * def __setitem__(self, item, value): * self.memview[item] = value # <<<<<<<<<<<<<< * * */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":229 * return self.memview[item] * * def __setitem__(self, item, value): # <<<<<<<<<<<<<< * self.memview[item] = value * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":234 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) { struct __pyx_array_obj *__pyx_v_result = 0; struct __pyx_array_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("array_cwrapper", 0); /* "View.MemoryView":238 * cdef array result * * if buf == NULL: # <<<<<<<<<<<<<< * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: */ __pyx_t_1 = ((__pyx_v_buf == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":239 * * if buf == NULL: * result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<< * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_INCREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 239; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4); __pyx_t_4 = 0; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":241 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape); __Pyx_GIVEREF(__pyx_v_shape); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_4 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":242 * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) # <<<<<<<<<<<<<< * result.data = buf * */ if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":241 * result = array(shape, itemsize, format, mode.decode('ASCII')) * else: * result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<< * allocate_buffer=False) * result.data = buf */ __pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 241; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5); __pyx_t_5 = 0; /* "View.MemoryView":243 * result = array(shape, itemsize, format, mode.decode('ASCII'), * allocate_buffer=False) * result.data = buf # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->data = __pyx_v_buf; } __pyx_L3:; /* "View.MemoryView":245 * result.data = buf * * return result # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(((PyObject *)__pyx_r)); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":234 * * @cname("__pyx_array_new") * cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<< * char *mode, char *buf): * cdef array result */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":271 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* Python wrapper */ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_name = 0; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0}; PyObject* values[1] = {0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else if (PyTuple_GET_SIZE(__pyx_args) != 1) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); } __pyx_v_name = values[0]; } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 271; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__init__", 0); /* "View.MemoryView":272 * cdef object name * def __init__(self, name): * self.name = name # <<<<<<<<<<<<<< * def __repr__(self): * return self.name */ __Pyx_INCREF(__pyx_v_name); __Pyx_GIVEREF(__pyx_v_name); __Pyx_GOTREF(__pyx_v_self->name); __Pyx_DECREF(__pyx_v_self->name); __pyx_v_self->name = __pyx_v_name; /* "View.MemoryView":271 * cdef class Enum(object): * cdef object name * def __init__(self, name): # <<<<<<<<<<<<<< * self.name = name * def __repr__(self): */ /* function exit code */ __pyx_r = 0; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":273 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* Python wrapper */ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_MemviewEnum___pyx_pf_15View_dot_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":274 * self.name = name * def __repr__(self): * return self.name # <<<<<<<<<<<<<< * * cdef generic = Enum("<strided and direct or indirect>") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->name); __pyx_r = __pyx_v_self->name; goto __pyx_L0; /* "View.MemoryView":273 * def __init__(self, name): * self.name = name * def __repr__(self): # <<<<<<<<<<<<<< * return self.name * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":288 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) { Py_intptr_t __pyx_v_aligned_p; size_t __pyx_v_offset; void *__pyx_r; int __pyx_t_1; /* "View.MemoryView":290 * cdef void *align_pointer(void *memory, size_t alignment) nogil: * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory # <<<<<<<<<<<<<< * cdef size_t offset * */ __pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory); /* "View.MemoryView":294 * * with cython.cdivision(True): * offset = aligned_p % alignment # <<<<<<<<<<<<<< * * if offset > 0: */ __pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment); /* "View.MemoryView":296 * offset = aligned_p % alignment * * if offset > 0: # <<<<<<<<<<<<<< * aligned_p += alignment - offset * */ __pyx_t_1 = ((__pyx_v_offset > 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":297 * * if offset > 0: * aligned_p += alignment - offset # <<<<<<<<<<<<<< * * return <void *> aligned_p */ __pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset)); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":299 * aligned_p += alignment - offset * * return <void *> aligned_p # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview') */ __pyx_r = ((void *)__pyx_v_aligned_p); goto __pyx_L0; /* "View.MemoryView":288 * * @cname('__pyx_align_pointer') * cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<< * "Align pointer memory on a given boundary" * cdef Py_intptr_t aligned_p = <Py_intptr_t> memory */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":317 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* Python wrapper */ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyObject *__pyx_v_obj = 0; int __pyx_v_flags; int __pyx_v_dtype_is_object; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } case 2: if (kw_args > 0) { PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object); if (value) { values[2] = value; kw_args--; } } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } } else { switch (PyTuple_GET_SIZE(__pyx_args)) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[0] = PyTuple_GET_ITEM(__pyx_args, 0); break; default: goto __pyx_L5_argtuple_error; } } __pyx_v_obj = values[0]; __pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} if (values[2]) { __pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} } else { __pyx_v_dtype_is_object = ((int)0); } } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 317; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __pyx_L3_error:; __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return -1; __pyx_L4_argument_unpacking_done:; __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__cinit__", 0); /* "View.MemoryView":318 * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj # <<<<<<<<<<<<<< * self.flags = flags * if type(self) is memoryview or obj is not None: */ __Pyx_INCREF(__pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); __Pyx_GOTREF(__pyx_v_self->obj); __Pyx_DECREF(__pyx_v_self->obj); __pyx_v_self->obj = __pyx_v_obj; /* "View.MemoryView":319 * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): * self.obj = obj * self.flags = flags # <<<<<<<<<<<<<< * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) */ __pyx_v_self->flags = __pyx_v_flags; /* "View.MemoryView":320 * self.obj = obj * self.flags = flags * if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<< * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: */ __pyx_t_2 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type))); __pyx_t_3 = (__pyx_t_2 != 0); if (!__pyx_t_3) { } else { __pyx_t_1 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = (__pyx_v_obj != Py_None); __pyx_t_2 = (__pyx_t_3 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L4_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":321 * self.flags = flags * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<< * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None */ __pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 321; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":322 * if type(self) is memoryview or obj is not None: * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<< * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_t_1 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":323 * __Pyx_GetBuffer(obj, &self.view, flags) * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None; /* "View.MemoryView":324 * if <PyObject *> self.view.obj == NULL: * (<__pyx_buffer *> &self.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * self.lock = PyThread_allocate_lock() */ Py_INCREF(Py_None); goto __pyx_L6; } __pyx_L6:; goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":326 * Py_INCREF(Py_None) * * self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<< * if self.lock == NULL: * raise MemoryError */ __pyx_v_self->lock = PyThread_allocate_lock(); /* "View.MemoryView":327 * * self.lock = PyThread_allocate_lock() * if self.lock == NULL: # <<<<<<<<<<<<<< * raise MemoryError * */ __pyx_t_1 = ((__pyx_v_self->lock == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":328 * self.lock = PyThread_allocate_lock() * if self.lock == NULL: * raise MemoryError # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 328; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":330 * raise MemoryError * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * self.dtype_is_object = self.view.format == b'O' * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":331 * * if flags & PyBUF_FORMAT: * self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<< * else: * self.dtype_is_object = dtype_is_object */ __pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_1 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 331; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __pyx_v_self->dtype_is_object = __pyx_t_1; goto __pyx_L8; } /*else*/ { /* "View.MemoryView":333 * self.dtype_is_object = self.view.format == b'O' * else: * self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<< * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( */ __pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object; } __pyx_L8:; /* "View.MemoryView":335 * self.dtype_is_object = dtype_is_object * * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<< * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL */ __pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int)))); /* "View.MemoryView":337 * self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( * <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int)) * self.typeinfo = NULL # <<<<<<<<<<<<<< * * def __dealloc__(memoryview self): */ __pyx_v_self->typeinfo = NULL; /* "View.MemoryView":317 * cdef __Pyx_TypeInfo *typeinfo * * def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<< * self.obj = obj * self.flags = flags */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":339 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* Python wrapper */ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":340 * * def __dealloc__(memoryview self): * if self.obj is not None: # <<<<<<<<<<<<<< * __Pyx_ReleaseBuffer(&self.view) * */ __pyx_t_1 = (__pyx_v_self->obj != Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":341 * def __dealloc__(memoryview self): * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<< * * if self.lock != NULL: */ __Pyx_ReleaseBuffer((&__pyx_v_self->view)); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":343 * __Pyx_ReleaseBuffer(&self.view) * * if self.lock != NULL: # <<<<<<<<<<<<<< * PyThread_free_lock(self.lock) * */ __pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":344 * * if self.lock != NULL: * PyThread_free_lock(self.lock) # <<<<<<<<<<<<<< * * cdef char *get_item_pointer(memoryview self, object index) except NULL: */ PyThread_free_lock(__pyx_v_self->lock); goto __pyx_L4; } __pyx_L4:; /* "View.MemoryView":339 * self.typeinfo = NULL * * def __dealloc__(memoryview self): # <<<<<<<<<<<<<< * if self.obj is not None: * __Pyx_ReleaseBuffer(&self.view) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":346 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { Py_ssize_t __pyx_v_dim; char *__pyx_v_itemp; PyObject *__pyx_v_idx = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t __pyx_t_3; PyObject *(*__pyx_t_4)(PyObject *); PyObject *__pyx_t_5 = NULL; Py_ssize_t __pyx_t_6; char *__pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_item_pointer", 0); /* "View.MemoryView":348 * cdef char *get_item_pointer(memoryview self, object index) except NULL: * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf # <<<<<<<<<<<<<< * * for dim, idx in enumerate(index): */ __pyx_v_itemp = ((char *)__pyx_v_self->view.buf); /* "View.MemoryView":350 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ __pyx_t_1 = 0; if (likely(PyList_CheckExact(__pyx_v_index)) || PyTuple_CheckExact(__pyx_v_index)) { __pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0; __pyx_t_4 = NULL; } else { __pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext; if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_4)) { if (likely(PyList_CheckExact(__pyx_t_2))) { if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } } else { __pyx_t_5 = __pyx_t_4(__pyx_t_2); if (unlikely(!__pyx_t_5)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 350; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_5); } __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5); __pyx_t_5 = 0; __pyx_v_dim = __pyx_t_1; __pyx_t_1 = (__pyx_t_1 + 1); /* "View.MemoryView":351 * * for dim, idx in enumerate(index): * itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<< * * return itemp */ __pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 351; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_7; /* "View.MemoryView":350 * cdef char *itemp = <char *> self.view.buf * * for dim, idx in enumerate(index): # <<<<<<<<<<<<<< * itemp = pybuffer_index(&self.view, itemp, idx, dim) * */ } __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":353 * itemp = pybuffer_index(&self.view, itemp, idx, dim) * * return itemp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_itemp; goto __pyx_L0; /* "View.MemoryView":346 * PyThread_free_lock(self.lock) * * cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<< * cdef Py_ssize_t dim * cdef char *itemp = <char *> self.view.buf */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_idx); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":356 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* Python wrapper */ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/ static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_indices = NULL; char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; char *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__getitem__", 0); /* "View.MemoryView":357 * * def __getitem__(memoryview self, object index): * if index is Ellipsis: # <<<<<<<<<<<<<< * return self * */ __pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":358 * def __getitem__(memoryview self, object index): * if index is Ellipsis: * return self # <<<<<<<<<<<<<< * * have_slices, indices = _unellipsify(index, self.view.ndim) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_self)); __pyx_r = ((PyObject *)__pyx_v_self); goto __pyx_L0; } /* "View.MemoryView":360 * return self * * have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * cdef char *itemp */ __pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (likely(__pyx_t_3 != Py_None)) { PyObject* sequence = __pyx_t_3; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_4 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_5 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); #else __pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); #endif __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 360; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_have_slices = __pyx_t_4; __pyx_t_4 = 0; __pyx_v_indices = __pyx_t_5; __pyx_t_5 = 0; /* "View.MemoryView":363 * * cdef char *itemp * if have_slices: # <<<<<<<<<<<<<< * return memview_slice(self, indices) * else: */ __pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_2) { /* "View.MemoryView":364 * cdef char *itemp * if have_slices: * return memview_slice(self, indices) # <<<<<<<<<<<<<< * else: * itemp = self.get_item_pointer(indices) */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 364; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /*else*/ { /* "View.MemoryView":366 * return memview_slice(self, indices) * else: * itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<< * return self.convert_item_to_object(itemp) * */ __pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_6; /* "View.MemoryView":367 * else: * itemp = self.get_item_pointer(indices) * return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<< * * def __setitem__(memoryview self, object index, object value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 367; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":356 * * * def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<< * if index is Ellipsis: * return self */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_indices); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":369 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* Python wrapper */ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/ static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { PyObject *__pyx_v_have_slices = NULL; PyObject *__pyx_v_obj = NULL; int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__setitem__", 0); __Pyx_INCREF(__pyx_v_index); /* "View.MemoryView":370 * * def __setitem__(memoryview self, object index, object value): * have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<< * * if have_slices: */ __pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (likely(__pyx_t_1 != Py_None)) { PyObject* sequence = __pyx_t_1; #if CYTHON_COMPILING_IN_CPYTHON Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_2 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_3 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(__pyx_t_3); #else __pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } else { __Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_have_slices = __pyx_t_2; __pyx_t_2 = 0; __Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":372 * have_slices, index = _unellipsify(index, self.view.ndim) * * if have_slices: # <<<<<<<<<<<<<< * obj = self.is_slice(value) * if obj: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":373 * * if have_slices: * obj = self.is_slice(value) # <<<<<<<<<<<<<< * if obj: * self.setitem_slice_assignment(self[index], obj) */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_obj = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":374 * if have_slices: * obj = self.is_slice(value) * if obj: # <<<<<<<<<<<<<< * self.setitem_slice_assignment(self[index], obj) * else: */ __pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 374; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__pyx_t_4) { /* "View.MemoryView":375 * obj = self.is_slice(value) * if obj: * self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<< * else: * self.setitem_slice_assign_scalar(self[index], value) */ __pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 375; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L4; } /*else*/ { /* "View.MemoryView":377 * self.setitem_slice_assignment(self[index], obj) * else: * self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<< * else: * self.setitem_indexed(index, value) */ __pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __Pyx_GOTREF(__pyx_t_3); if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 377; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L4:; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":379 * self.setitem_slice_assign_scalar(self[index], value) * else: * self.setitem_indexed(index, value) # <<<<<<<<<<<<<< * * cdef is_slice(self, obj): */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; } __pyx_L3:; /* "View.MemoryView":369 * return self.convert_item_to_object(itemp) * * def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<< * have_slices, index = _unellipsify(index, self.view.ndim) * */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_XDECREF(__pyx_v_have_slices); __Pyx_XDECREF(__pyx_v_obj); __Pyx_XDECREF(__pyx_v_index); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":381 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; int __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_slice", 0); __Pyx_INCREF(__pyx_v_obj); /* "View.MemoryView":382 * * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): # <<<<<<<<<<<<<< * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type)); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":383 * cdef is_slice(self, obj): * if not isinstance(obj, memoryview): * try: # <<<<<<<<<<<<<< * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) */ { __Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); __Pyx_XGOTREF(__pyx_t_5); /*try:*/ { /* "View.MemoryView":384 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":385 * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) # <<<<<<<<<<<<<< * except TypeError: * return None */ __pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_7); /* "View.MemoryView":384 * if not isinstance(obj, memoryview): * try: * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<< * self.dtype_is_object) * except TypeError: */ __pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_8); __Pyx_INCREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj); __Pyx_GIVEREF(__pyx_v_obj); PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 384; __pyx_clineno = __LINE__; goto __pyx_L4_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7); __pyx_t_7 = 0; } __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; goto __pyx_L11_try_end; __pyx_L4_error:; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":386 * obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, * self.dtype_is_object) * except TypeError: # <<<<<<<<<<<<<< * return None * */ __pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError); if (__pyx_t_9) { __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 386; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_GOTREF(__pyx_t_8); __Pyx_GOTREF(__pyx_t_6); /* "View.MemoryView":387 * self.dtype_is_object) * except TypeError: * return None # <<<<<<<<<<<<<< * * return obj */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; goto __pyx_L7_except_return; } goto __pyx_L6_except_error; __pyx_L6_except_error:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L1_error; __pyx_L7_except_return:; __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_XGIVEREF(__pyx_t_5); __Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5); goto __pyx_L0; __pyx_L11_try_end:; } goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":389 * return None * * return obj # <<<<<<<<<<<<<< * * cdef setitem_slice_assignment(self, dst, src): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_obj); __pyx_r = __pyx_v_obj; goto __pyx_L0; /* "View.MemoryView":381 * self.setitem_indexed(index, value) * * cdef is_slice(self, obj): # <<<<<<<<<<<<<< * if not isinstance(obj, memoryview): * try: */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_obj); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":391 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) { __Pyx_memviewslice __pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_src_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assignment", 0); /* "View.MemoryView":395 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":396 * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<< * src.ndim, dst.ndim, self.dtype_is_object) * */ if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 396; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":397 * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<< * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 397; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":395 * cdef __Pyx_memviewslice src_slice * * memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<< * get_slice_from_memview(dst, &dst_slice)[0], * src.ndim, dst.ndim, self.dtype_is_object) */ __pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 395; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":391 * return obj * * cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice dst_slice * cdef __Pyx_memviewslice src_slice */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":399 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) { int __pyx_v_array[128]; void *__pyx_v_tmp; void *__pyx_v_item; __Pyx_memviewslice *__pyx_v_dst_slice; __Pyx_memviewslice __pyx_v_tmp_slice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_t_3; int __pyx_t_4; char const *__pyx_t_5; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0); /* "View.MemoryView":401 * cdef setitem_slice_assign_scalar(self, memoryview dst, value): * cdef int array[128] * cdef void *tmp = NULL # <<<<<<<<<<<<<< * cdef void *item * */ __pyx_v_tmp = NULL; /* "View.MemoryView":406 * cdef __Pyx_memviewslice *dst_slice * cdef __Pyx_memviewslice tmp_slice * dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<< * * if <size_t>self.view.itemsize > sizeof(array): */ __pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice)); /* "View.MemoryView":408 * dst_slice = get_slice_from_memview(dst, &tmp_slice) * * if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<< * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: */ __pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0); if (__pyx_t_1) { /* "View.MemoryView":409 * * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) # <<<<<<<<<<<<<< * if tmp == NULL: * raise MemoryError */ __pyx_v_tmp = PyMem_Malloc(__pyx_v_self->view.itemsize); /* "View.MemoryView":410 * if <size_t>self.view.itemsize > sizeof(array): * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: # <<<<<<<<<<<<<< * raise MemoryError * item = tmp */ __pyx_t_1 = ((__pyx_v_tmp == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":411 * tmp = PyMem_Malloc(self.view.itemsize) * if tmp == NULL: * raise MemoryError # <<<<<<<<<<<<<< * item = tmp * else: */ PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 411; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":412 * if tmp == NULL: * raise MemoryError * item = tmp # <<<<<<<<<<<<<< * else: * item = <void *> array */ __pyx_v_item = __pyx_v_tmp; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":414 * item = tmp * else: * item = <void *> array # <<<<<<<<<<<<<< * * try: */ __pyx_v_item = ((void *)__pyx_v_array); } __pyx_L3:; /* "View.MemoryView":416 * item = <void *> array * * try: # <<<<<<<<<<<<<< * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value */ /*try:*/ { /* "View.MemoryView":417 * * try: * if self.dtype_is_object: # <<<<<<<<<<<<<< * (<PyObject **> item)[0] = <PyObject *> value * else: */ __pyx_t_1 = (__pyx_v_self->dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":418 * try: * if self.dtype_is_object: * (<PyObject **> item)[0] = <PyObject *> value # <<<<<<<<<<<<<< * else: * self.assign_item_from_object(<char *> item, value) */ (((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value); goto __pyx_L8; } /*else*/ { /* "View.MemoryView":420 * (<PyObject **> item)[0] = <PyObject *> value * else: * self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 420; __pyx_clineno = __LINE__; goto __pyx_L6_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_L8:; /* "View.MemoryView":424 * * * if self.view.suboffsets != NULL: # <<<<<<<<<<<<<< * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":425 * * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<< * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, * item, self.dtype_is_object) */ __pyx_t_2 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 425; __pyx_clineno = __LINE__; goto __pyx_L6_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; goto __pyx_L9; } __pyx_L9:; /* "View.MemoryView":426 * if self.view.suboffsets != NULL: * assert_direct_dimensions(self.view.suboffsets, self.view.ndim) * slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<< * item, self.dtype_is_object) * finally: */ __pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object); } /* "View.MemoryView":429 * item, self.dtype_is_object) * finally: * PyMem_Free(tmp) # <<<<<<<<<<<<<< * * cdef setitem_indexed(self, index, value): */ /*finally:*/ { /*normal exit:*/{ PyMem_Free(__pyx_v_tmp); goto __pyx_L7; } /*exception exit:*/{ __pyx_L6_error:; __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; if (PY_MAJOR_VERSION >= 3) __Pyx_ExceptionSwap(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); if ((PY_MAJOR_VERSION < 3) || unlikely(__Pyx_GetException(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8) < 0)) __Pyx_ErrFetch(&__pyx_t_6, &__pyx_t_7, &__pyx_t_8); __Pyx_XGOTREF(__pyx_t_6); __Pyx_XGOTREF(__pyx_t_7); __Pyx_XGOTREF(__pyx_t_8); __Pyx_XGOTREF(__pyx_t_9); __Pyx_XGOTREF(__pyx_t_10); __Pyx_XGOTREF(__pyx_t_11); __pyx_t_3 = __pyx_lineno; __pyx_t_4 = __pyx_clineno; __pyx_t_5 = __pyx_filename; { PyMem_Free(__pyx_v_tmp); } if (PY_MAJOR_VERSION >= 3) { __Pyx_XGIVEREF(__pyx_t_9); __Pyx_XGIVEREF(__pyx_t_10); __Pyx_XGIVEREF(__pyx_t_11); __Pyx_ExceptionReset(__pyx_t_9, __pyx_t_10, __pyx_t_11); } __Pyx_XGIVEREF(__pyx_t_6); __Pyx_XGIVEREF(__pyx_t_7); __Pyx_XGIVEREF(__pyx_t_8); __Pyx_ErrRestore(__pyx_t_6, __pyx_t_7, __pyx_t_8); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_8 = 0; __pyx_t_9 = 0; __pyx_t_10 = 0; __pyx_t_11 = 0; __pyx_lineno = __pyx_t_3; __pyx_clineno = __pyx_t_4; __pyx_filename = __pyx_t_5; goto __pyx_L1_error; } __pyx_L7:; } /* "View.MemoryView":399 * src.ndim, dst.ndim, self.dtype_is_object) * * cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<< * cdef int array[128] * cdef void *tmp = NULL */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":431 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) { char *__pyx_v_itemp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations char *__pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("setitem_indexed", 0); /* "View.MemoryView":432 * * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<< * self.assign_item_from_object(itemp, value) * */ __pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 432; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_itemp = __pyx_t_1; /* "View.MemoryView":433 * cdef setitem_indexed(self, index, value): * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 433; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":431 * PyMem_Free(tmp) * * cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<< * cdef char *itemp = self.get_item_pointer(index) * self.assign_item_from_object(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":435 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_v_struct = NULL; PyObject *__pyx_v_bytesitem = 0; PyObject *__pyx_v_result = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; PyObject *__pyx_t_9 = NULL; size_t __pyx_t_10; int __pyx_t_11; int __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":438 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef bytes bytesitem * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 438; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":441 * cdef bytes bytesitem * * bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<< * try: * result = struct.unpack(self.view.format, bytesitem) */ __pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_bytesitem = ((PyObject*)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":442 * * bytesitem = itemp[:self.view.itemsize] * try: # <<<<<<<<<<<<<< * result = struct.unpack(self.view.format, bytesitem) * except struct.error: */ { __Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); __Pyx_XGOTREF(__pyx_t_4); /*try:*/ { /* "View.MemoryView":443 * bytesitem = itemp[:self.view.itemsize] * try: * result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<< * except struct.error: * raise ValueError("Unable to convert item to object") */ __pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = NULL; __pyx_t_8 = 0; if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_5))) { __pyx_t_7 = PyMethod_GET_SELF(__pyx_t_5); if (likely(__pyx_t_7)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_5); __Pyx_INCREF(__pyx_t_7); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_5, function); __pyx_t_8 = 1; } } __pyx_t_9 = PyTuple_New(2+__pyx_t_8); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_9); if (__pyx_t_7) { PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = NULL; } PyTuple_SET_ITEM(__pyx_t_9, 0+__pyx_t_8, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_6); __Pyx_INCREF(__pyx_v_bytesitem); PyTuple_SET_ITEM(__pyx_t_9, 1+__pyx_t_8, __pyx_v_bytesitem); __Pyx_GIVEREF(__pyx_v_bytesitem); __pyx_t_6 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_5, __pyx_t_9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 443; __pyx_clineno = __LINE__; goto __pyx_L3_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __pyx_v_result = __pyx_t_1; __pyx_t_1 = 0; } /*else:*/ { /* "View.MemoryView":447 * raise ValueError("Unable to convert item to object") * else: * if len(self.view.format) == 1: # <<<<<<<<<<<<<< * return result[0] * return result */ __pyx_t_10 = strlen(__pyx_v_self->view.format); __pyx_t_11 = ((__pyx_t_10 == 1) != 0); if (__pyx_t_11) { /* "View.MemoryView":448 * else: * if len(self.view.format) == 1: * return result[0] # <<<<<<<<<<<<<< * return result * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 1); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 448; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}; __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L6_except_return; } /* "View.MemoryView":449 * if len(self.view.format) == 1: * return result[0] * return result # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_result); __pyx_r = __pyx_v_result; goto __pyx_L6_except_return; } __pyx_L3_error:; __Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0; __Pyx_XDECREF(__pyx_t_9); __pyx_t_9 = 0; __Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":444 * try: * result = struct.unpack(self.view.format, bytesitem) * except struct.error: # <<<<<<<<<<<<<< * raise ValueError("Unable to convert item to object") * else: */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_12 = PyErr_ExceptionMatches(__pyx_t_1); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (__pyx_t_12) { __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_5, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 444; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_9); /* "View.MemoryView":445 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;} } goto __pyx_L5_except_error; __pyx_L5_except_error:; __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L1_error; __pyx_L6_except_return:; __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_XGIVEREF(__pyx_t_4); __Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4); goto __pyx_L0; } /* "View.MemoryView":435 * self.assign_item_from_object(itemp, value) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesitem); __Pyx_XDECREF(__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":451 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_v_struct = NULL; char __pyx_v_c; PyObject *__pyx_v_bytesvalue = 0; Py_ssize_t __pyx_v_i; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_t_3; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; Py_ssize_t __pyx_t_7; PyObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; char *__pyx_t_10; char *__pyx_t_11; char *__pyx_t_12; char *__pyx_t_13; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":454 * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" * import struct # <<<<<<<<<<<<<< * cdef char c * cdef bytes bytesvalue */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 454; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_v_struct = __pyx_t_1; __pyx_t_1 = 0; /* "View.MemoryView":459 * cdef Py_ssize_t i * * if isinstance(value, tuple): # <<<<<<<<<<<<<< * bytesvalue = struct.pack(self.view.format, *value) * else: */ __pyx_t_2 = PyTuple_Check(__pyx_v_value); __pyx_t_3 = (__pyx_t_2 != 0); if (__pyx_t_3) { /* "View.MemoryView":460 * * if isinstance(value, tuple): * bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<< * else: * bytesvalue = struct.pack(self.view.format, value) */ __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 460; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":462 * bytesvalue = struct.pack(self.view.format, *value) * else: * bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<< * * for i, c in enumerate(bytesvalue): */ __pyx_t_6 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __pyx_t_1 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_5 = NULL; __pyx_t_7 = 0; if (CYTHON_COMPILING_IN_CPYTHON && likely(PyMethod_Check(__pyx_t_6))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_6); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_6); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_6, function); __pyx_t_7 = 1; } } __pyx_t_8 = PyTuple_New(2+__pyx_t_7); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_8); if (__pyx_t_5) { PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; } PyTuple_SET_ITEM(__pyx_t_8, 0+__pyx_t_7, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __Pyx_INCREF(__pyx_v_value); PyTuple_SET_ITEM(__pyx_t_8, 1+__pyx_t_7, __pyx_v_value); __Pyx_GIVEREF(__pyx_v_value); __pyx_t_1 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_6, __pyx_t_8, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_bytesvalue = ((PyObject*)__pyx_t_4); __pyx_t_4 = 0; } __pyx_L3:; /* "View.MemoryView":464 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_7 = 0; if (unlikely(__pyx_v_bytesvalue == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 464; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __Pyx_INCREF(__pyx_v_bytesvalue); __pyx_t_9 = __pyx_v_bytesvalue; __pyx_t_11 = PyBytes_AS_STRING(__pyx_t_9); __pyx_t_12 = (__pyx_t_11 + PyBytes_GET_SIZE(__pyx_t_9)); for (__pyx_t_13 = __pyx_t_11; __pyx_t_13 < __pyx_t_12; __pyx_t_13++) { __pyx_t_10 = __pyx_t_13; __pyx_v_c = (__pyx_t_10[0]); /* "View.MemoryView":465 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ __pyx_v_i = __pyx_t_7; /* "View.MemoryView":464 * bytesvalue = struct.pack(self.view.format, value) * * for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<< * itemp[i] = c * */ __pyx_t_7 = (__pyx_t_7 + 1); /* "View.MemoryView":465 * * for i, c in enumerate(bytesvalue): * itemp[i] = c # <<<<<<<<<<<<<< * * @cname('getbuffer') */ (__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c; } __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; /* "View.MemoryView":451 * return result * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * """Only used if instantiated manually by the user, or if Cython doesn't * know how to convert the type""" */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_8); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_struct); __Pyx_XDECREF(__pyx_v_bytesvalue); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":468 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; Py_ssize_t *__pyx_t_2; char *__pyx_t_3; void *__pyx_t_4; int __pyx_t_5; Py_ssize_t __pyx_t_6; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "View.MemoryView":469 * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.shape = self.view.shape * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":470 * def __getbuffer__(self, Py_buffer *info, int flags): * if flags & PyBUF_STRIDES: * info.shape = self.view.shape # <<<<<<<<<<<<<< * else: * info.shape = NULL */ __pyx_t_2 = __pyx_v_self->view.shape; __pyx_v_info->shape = __pyx_t_2; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":472 * info.shape = self.view.shape * else: * info.shape = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_STRIDES: */ __pyx_v_info->shape = NULL; } __pyx_L3:; /* "View.MemoryView":474 * info.shape = NULL * * if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<< * info.strides = self.view.strides * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0); if (__pyx_t_1) { /* "View.MemoryView":475 * * if flags & PyBUF_STRIDES: * info.strides = self.view.strides # <<<<<<<<<<<<<< * else: * info.strides = NULL */ __pyx_t_2 = __pyx_v_self->view.strides; __pyx_v_info->strides = __pyx_t_2; goto __pyx_L4; } /*else*/ { /* "View.MemoryView":477 * info.strides = self.view.strides * else: * info.strides = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_INDIRECT: */ __pyx_v_info->strides = NULL; } __pyx_L4:; /* "View.MemoryView":479 * info.strides = NULL * * if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<< * info.suboffsets = self.view.suboffsets * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0); if (__pyx_t_1) { /* "View.MemoryView":480 * * if flags & PyBUF_INDIRECT: * info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<< * else: * info.suboffsets = NULL */ __pyx_t_2 = __pyx_v_self->view.suboffsets; __pyx_v_info->suboffsets = __pyx_t_2; goto __pyx_L5; } /*else*/ { /* "View.MemoryView":482 * info.suboffsets = self.view.suboffsets * else: * info.suboffsets = NULL # <<<<<<<<<<<<<< * * if flags & PyBUF_FORMAT: */ __pyx_v_info->suboffsets = NULL; } __pyx_L5:; /* "View.MemoryView":484 * info.suboffsets = NULL * * if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<< * info.format = self.view.format * else: */ __pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0); if (__pyx_t_1) { /* "View.MemoryView":485 * * if flags & PyBUF_FORMAT: * info.format = self.view.format # <<<<<<<<<<<<<< * else: * info.format = NULL */ __pyx_t_3 = __pyx_v_self->view.format; __pyx_v_info->format = __pyx_t_3; goto __pyx_L6; } /*else*/ { /* "View.MemoryView":487 * info.format = self.view.format * else: * info.format = NULL # <<<<<<<<<<<<<< * * info.buf = self.view.buf */ __pyx_v_info->format = NULL; } __pyx_L6:; /* "View.MemoryView":489 * info.format = NULL * * info.buf = self.view.buf # <<<<<<<<<<<<<< * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize */ __pyx_t_4 = __pyx_v_self->view.buf; __pyx_v_info->buf = __pyx_t_4; /* "View.MemoryView":490 * * info.buf = self.view.buf * info.ndim = self.view.ndim # <<<<<<<<<<<<<< * info.itemsize = self.view.itemsize * info.len = self.view.len */ __pyx_t_5 = __pyx_v_self->view.ndim; __pyx_v_info->ndim = __pyx_t_5; /* "View.MemoryView":491 * info.buf = self.view.buf * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize # <<<<<<<<<<<<<< * info.len = self.view.len * info.readonly = 0 */ __pyx_t_6 = __pyx_v_self->view.itemsize; __pyx_v_info->itemsize = __pyx_t_6; /* "View.MemoryView":492 * info.ndim = self.view.ndim * info.itemsize = self.view.itemsize * info.len = self.view.len # <<<<<<<<<<<<<< * info.readonly = 0 * info.obj = self */ __pyx_t_6 = __pyx_v_self->view.len; __pyx_v_info->len = __pyx_t_6; /* "View.MemoryView":493 * info.itemsize = self.view.itemsize * info.len = self.view.len * info.readonly = 0 # <<<<<<<<<<<<<< * info.obj = self * */ __pyx_v_info->readonly = 0; /* "View.MemoryView":494 * info.len = self.view.len * info.readonly = 0 * info.obj = self # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); /* "View.MemoryView":468 * * @cname('getbuffer') * def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<< * if flags & PyBUF_STRIDES: * info.shape = self.view.shape */ /* function exit code */ __pyx_r = 0; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":501 * property T: * @cname('__pyx_memoryview_transpose') * def __get__(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* Python wrapper */ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_t_2; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":502 * @cname('__pyx_memoryview_transpose') * def __get__(self): * cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<< * transpose_memslice(&result.from_slice) * return result */ __pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 502; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1); __pyx_t_1 = 0; /* "View.MemoryView":503 * def __get__(self): * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<< * return result * */ __pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 503; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":504 * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) * return result # <<<<<<<<<<<<<< * * property base: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":501 * property T: * @cname('__pyx_memoryview_transpose') * def __get__(self): # <<<<<<<<<<<<<< * cdef _memoryviewslice result = memoryview_copy(self) * transpose_memslice(&result.from_slice) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":508 * property base: * @cname('__pyx_memoryview__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.obj * */ /* Python wrapper */ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":509 * @cname('__pyx_memoryview__get__base') * def __get__(self): * return self.obj # <<<<<<<<<<<<<< * * property shape: */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->obj); __pyx_r = __pyx_v_self->obj; goto __pyx_L0; /* "View.MemoryView":508 * property base: * @cname('__pyx_memoryview__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.obj * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":513 * property shape: * @cname('__pyx_memoryview_get_shape') * def __get__(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_length; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":514 * @cname('__pyx_memoryview_get_shape') * def __get__(self): * return tuple([length for length in self.view.shape[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property strides: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_3 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_4 = __pyx_v_self->view.shape; __pyx_t_4 < __pyx_t_3; __pyx_t_4++) { __pyx_t_2 = __pyx_t_4; __pyx_v_length = (__pyx_t_2[0]); __pyx_t_5 = PyInt_FromSsize_t(__pyx_v_length); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 514; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":513 * property shape: * @cname('__pyx_memoryview_get_shape') * def __get__(self): # <<<<<<<<<<<<<< * return tuple([length for length in self.view.shape[:self.view.ndim]]) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":518 * property strides: * @cname('__pyx_memoryview_get_strides') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_stride; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":519 * @cname('__pyx_memoryview_get_strides') * def __get__(self): * if self.view.strides == NULL: # <<<<<<<<<<<<<< * * raise ValueError("Buffer view does not expose strides") */ __pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":521 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":523 * raise ValueError("Buffer view does not expose strides") * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property suboffsets: */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = (__pyx_v_self->view.strides + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.strides; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_v_stride = (__pyx_t_3[0]); __pyx_t_6 = PyInt_FromSsize_t(__pyx_v_stride); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_6))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __pyx_t_6 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 523; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_6; __pyx_t_6 = 0; goto __pyx_L0; /* "View.MemoryView":518 * property strides: * @cname('__pyx_memoryview_get_strides') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.strides == NULL: * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":527 * property suboffsets: * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; Py_ssize_t *__pyx_t_6; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":528 * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): * if self.view.suboffsets == NULL: # <<<<<<<<<<<<<< * return (-1,) * self.view.ndim * */ __pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":529 * def __get__(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_tuple__20, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":531 * return (-1,) * self.view.ndim * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) # <<<<<<<<<<<<<< * * property ndim: */ __Pyx_XDECREF(__pyx_r); __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_5 = (__pyx_v_self->view.suboffsets + __pyx_v_self->view.ndim); for (__pyx_t_6 = __pyx_v_self->view.suboffsets; __pyx_t_6 < __pyx_t_5; __pyx_t_6++) { __pyx_t_4 = __pyx_t_6; __pyx_v_suboffset = (__pyx_t_4[0]); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_suboffset); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); if (unlikely(__Pyx_ListComp_Append(__pyx_t_3, (PyObject*)__pyx_t_2))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } __pyx_t_2 = PyList_AsTuple(((PyObject*)__pyx_t_3)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":527 * property suboffsets: * @cname('__pyx_memoryview_get_suboffsets') * def __get__(self): # <<<<<<<<<<<<<< * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":535 * property ndim: * @cname('__pyx_memoryview_get_ndim') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":536 * @cname('__pyx_memoryview_get_ndim') * def __get__(self): * return self.view.ndim # <<<<<<<<<<<<<< * * property itemsize: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 536; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":535 * property ndim: * @cname('__pyx_memoryview_get_ndim') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.ndim * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":540 * property itemsize: * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":541 * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): * return self.view.itemsize # <<<<<<<<<<<<<< * * property nbytes: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 541; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":540 * property itemsize: * @cname('__pyx_memoryview_get_itemsize') * def __get__(self): # <<<<<<<<<<<<<< * return self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":545 * property nbytes: * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":546 * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): * return self.size * self.view.itemsize # <<<<<<<<<<<<<< * * property size: */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 546; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":545 * property nbytes: * @cname('__pyx_memoryview_get_nbytes') * def __get__(self): # <<<<<<<<<<<<<< * return self.size * self.view.itemsize * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":550 * property size: * @cname('__pyx_memoryview_get_size') * def __get__(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* Python wrapper */ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_v_result = NULL; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; Py_ssize_t *__pyx_t_3; Py_ssize_t *__pyx_t_4; Py_ssize_t *__pyx_t_5; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":551 * @cname('__pyx_memoryview_get_size') * def __get__(self): * if self._size is None: # <<<<<<<<<<<<<< * result = 1 * */ __pyx_t_1 = (__pyx_v_self->_size == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":552 * def __get__(self): * if self._size is None: * result = 1 # <<<<<<<<<<<<<< * * for length in self.view.shape[:self.view.ndim]: */ __Pyx_INCREF(__pyx_int_1); __pyx_v_result = __pyx_int_1; /* "View.MemoryView":554 * result = 1 * * for length in self.view.shape[:self.view.ndim]: # <<<<<<<<<<<<<< * result *= length * */ __pyx_t_4 = (__pyx_v_self->view.shape + __pyx_v_self->view.ndim); for (__pyx_t_5 = __pyx_v_self->view.shape; __pyx_t_5 < __pyx_t_4; __pyx_t_5++) { __pyx_t_3 = __pyx_t_5; __pyx_t_6 = PyInt_FromSsize_t((__pyx_t_3[0])); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_6); __pyx_t_6 = 0; /* "View.MemoryView":555 * * for length in self.view.shape[:self.view.ndim]: * result *= length # <<<<<<<<<<<<<< * * self._size = result */ __pyx_t_6 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 555; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF_SET(__pyx_v_result, __pyx_t_6); __pyx_t_6 = 0; } /* "View.MemoryView":557 * result *= length * * self._size = result # <<<<<<<<<<<<<< * * return self._size */ __Pyx_INCREF(__pyx_v_result); __Pyx_GIVEREF(__pyx_v_result); __Pyx_GOTREF(__pyx_v_self->_size); __Pyx_DECREF(__pyx_v_self->_size); __pyx_v_self->_size = __pyx_v_result; goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":559 * self._size = result * * return self._size # <<<<<<<<<<<<<< * * def __len__(self): */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->_size); __pyx_r = __pyx_v_self->_size; goto __pyx_L0; /* "View.MemoryView":550 * property size: * @cname('__pyx_memoryview_get_size') * def __get__(self): # <<<<<<<<<<<<<< * if self._size is None: * result = 1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":561 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* Python wrapper */ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/ static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__len__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static Py_ssize_t __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) { Py_ssize_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__len__", 0); /* "View.MemoryView":562 * * def __len__(self): * if self.view.ndim >= 1: # <<<<<<<<<<<<<< * return self.view.shape[0] * */ __pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":563 * def __len__(self): * if self.view.ndim >= 1: * return self.view.shape[0] # <<<<<<<<<<<<<< * * return 0 */ __pyx_r = (__pyx_v_self->view.shape[0]); goto __pyx_L0; } /* "View.MemoryView":565 * return self.view.shape[0] * * return 0 # <<<<<<<<<<<<<< * * def __repr__(self): */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":561 * return self._size * * def __len__(self): # <<<<<<<<<<<<<< * if self.view.ndim >= 1: * return self.view.shape[0] */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":567 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* Python wrapper */ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__repr__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__repr__", 0); /* "View.MemoryView":568 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":569 * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) # <<<<<<<<<<<<<< * * def __str__(self): */ __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_INCREF(((PyObject *)__pyx_v_self)); PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":568 * * def __repr__(self): * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<< * id(self)) * */ __pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_1 = 0; __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 568; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L0; /* "View.MemoryView":567 * return 0 * * def __repr__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, * id(self)) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":571 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* Python wrapper */ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__str__ (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("__str__", 0); /* "View.MemoryView":572 * * def __str__(self): * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 572; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":571 * id(self)) * * def __str__(self): # <<<<<<<<<<<<<< * return "<MemoryView of %r object>" % (self.base.__class__.__name__,) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":575 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_c_contig", 0); /* "View.MemoryView":578 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice, 'C', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":579 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<< * * def is_f_contig(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 579; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":575 * * * def is_c_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":581 * return slice_is_contig(mslice, 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* Python wrapper */ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice *__pyx_v_mslice; __Pyx_memviewslice __pyx_v_tmp; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("is_f_contig", 0); /* "View.MemoryView":584 * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<< * return slice_is_contig(mslice, 'F', self.view.ndim) * */ __pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp)); /* "View.MemoryView":585 * cdef __Pyx_memviewslice tmp * mslice = get_slice_from_memview(self, &tmp) * return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<< * * def copy(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 585; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":581 * return slice_is_contig(mslice, 'C', self.view.ndim) * * def is_f_contig(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice *mslice * cdef __Pyx_memviewslice tmp */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":587 * return slice_is_contig(mslice, 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_mslice; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy", 0); /* "View.MemoryView":589 * def copy(self): * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &mslice) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS)); /* "View.MemoryView":591 * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS * * slice_copy(self, &mslice) # <<<<<<<<<<<<<< * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice)); /* "View.MemoryView":592 * * slice_copy(self, &mslice) * mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_C_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 592; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_mslice = __pyx_t_1; /* "View.MemoryView":597 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<< * * def copy_fortran(self): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 597; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":587 * return slice_is_contig(mslice, 'F', self.view.ndim) * * def copy(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice mslice * cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":599 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* Python wrapper */ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/ static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0); __pyx_r = __pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_memoryview___pyx_pf_15View_dot_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) { __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; int __pyx_v_flags; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_memviewslice __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("copy_fortran", 0); /* "View.MemoryView":601 * def copy_fortran(self): * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<< * * slice_copy(self, &src) */ __pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS)); /* "View.MemoryView":603 * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS * * slice_copy(self, &src) # <<<<<<<<<<<<<< * dst = slice_copy_contig(&src, "fortran", self.view.ndim, * self.view.itemsize, */ __pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src)); /* "View.MemoryView":604 * * slice_copy(self, &src) * dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<< * self.view.itemsize, * flags|PyBUF_F_CONTIGUOUS, */ __pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 604; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_dst = __pyx_t_1; /* "View.MemoryView":609 * self.dtype_is_object) * * return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 609; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; /* "View.MemoryView":599 * return memoryview_copy_from_slice(self, &mslice) * * def copy_fortran(self): # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice src, dst * cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":613 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) { struct __pyx_memoryview_obj *__pyx_v_result = 0; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_cwrapper", 0); /* "View.MemoryView":614 * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<< * result.typeinfo = typeinfo * return result */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o); __Pyx_GIVEREF(__pyx_v_o); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 614; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":615 * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo # <<<<<<<<<<<<<< * return result * */ __pyx_v_result->typeinfo = __pyx_v_typeinfo; /* "View.MemoryView":616 * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_check') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":613 * * @cname('__pyx_memoryview_new') * cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<< * cdef memoryview result = memoryview(o, flags, dtype_is_object) * result.typeinfo = typeinfo */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":619 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("memoryview_check", 0); /* "View.MemoryView":620 * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): * return isinstance(o, memoryview) # <<<<<<<<<<<<<< * * cdef tuple _unellipsify(object index, int ndim): */ __pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type)); __pyx_r = __pyx_t_1; goto __pyx_L0; /* "View.MemoryView":619 * * @cname('__pyx_memoryview_check') * cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<< * return isinstance(o, memoryview) * */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":622 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) { PyObject *__pyx_v_tup = NULL; PyObject *__pyx_v_result = NULL; int __pyx_v_have_slices; int __pyx_v_seen_ellipsis; CYTHON_UNUSED PyObject *__pyx_v_idx = NULL; PyObject *__pyx_v_item = NULL; Py_ssize_t __pyx_v_nslices; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; Py_ssize_t __pyx_t_5; PyObject *(*__pyx_t_6)(PyObject *); PyObject *__pyx_t_7 = NULL; Py_ssize_t __pyx_t_8; int __pyx_t_9; int __pyx_t_10; PyObject *__pyx_t_11 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("_unellipsify", 0); /* "View.MemoryView":627 * full slices. * """ * if not isinstance(index, tuple): # <<<<<<<<<<<<<< * tup = (index,) * else: */ __pyx_t_1 = PyTuple_Check(__pyx_v_index); __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":628 * """ * if not isinstance(index, tuple): * tup = (index,) # <<<<<<<<<<<<<< * else: * tup = index */ __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 628; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_index); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index); __Pyx_GIVEREF(__pyx_v_index); __pyx_v_tup = __pyx_t_3; __pyx_t_3 = 0; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":630 * tup = (index,) * else: * tup = index # <<<<<<<<<<<<<< * * result = [] */ __Pyx_INCREF(__pyx_v_index); __pyx_v_tup = __pyx_v_index; } __pyx_L3:; /* "View.MemoryView":632 * tup = index * * result = [] # <<<<<<<<<<<<<< * have_slices = False * seen_ellipsis = False */ __pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 632; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_v_result = ((PyObject*)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":633 * * result = [] * have_slices = False # <<<<<<<<<<<<<< * seen_ellipsis = False * for idx, item in enumerate(tup): */ __pyx_v_have_slices = 0; /* "View.MemoryView":634 * result = [] * have_slices = False * seen_ellipsis = False # <<<<<<<<<<<<<< * for idx, item in enumerate(tup): * if item is Ellipsis: */ __pyx_v_seen_ellipsis = 0; /* "View.MemoryView":635 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ __Pyx_INCREF(__pyx_int_0); __pyx_t_3 = __pyx_int_0; if (likely(PyList_CheckExact(__pyx_v_tup)) || PyTuple_CheckExact(__pyx_v_tup)) { __pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0; __pyx_t_6 = NULL; } else { __pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext; if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_6)) { if (likely(PyList_CheckExact(__pyx_t_4))) { if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } } else { __pyx_t_7 = __pyx_t_6(__pyx_t_4); if (unlikely(!__pyx_t_7)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_7); } __Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7); __pyx_t_7 = 0; __Pyx_INCREF(__pyx_t_3); __Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3); __pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 635; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = __pyx_t_7; __pyx_t_7 = 0; /* "View.MemoryView":636 * seen_ellipsis = False * for idx, item in enumerate(tup): * if item is Ellipsis: # <<<<<<<<<<<<<< * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) */ __pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":637 * for idx, item in enumerate(tup): * if item is Ellipsis: * if not seen_ellipsis: # <<<<<<<<<<<<<< * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True */ __pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":638 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_7 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) { __Pyx_INCREF(__pyx_slice__21); PyList_SET_ITEM(__pyx_t_7, __pyx_temp, __pyx_slice__21); __Pyx_GIVEREF(__pyx_slice__21); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_7); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "View.MemoryView":639 * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) * seen_ellipsis = True # <<<<<<<<<<<<<< * else: * result.append(slice(None)) */ __pyx_v_seen_ellipsis = 1; goto __pyx_L7; } /*else*/ { /* "View.MemoryView":641 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_slice__22); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L7:; /* "View.MemoryView":642 * else: * result.append(slice(None)) * have_slices = True # <<<<<<<<<<<<<< * else: * if not isinstance(item, slice) and not PyIndex_Check(item): */ __pyx_v_have_slices = 1; goto __pyx_L6; } /*else*/ { /* "View.MemoryView":644 * have_slices = True * else: * if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<< * raise TypeError("Cannot index with type '%s'" % type(item)) * */ __pyx_t_2 = PySlice_Check(__pyx_v_item); __pyx_t_10 = ((!(__pyx_t_2 != 0)) != 0); if (__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = ((!(PyIndex_Check(__pyx_v_item) != 0)) != 0); __pyx_t_1 = __pyx_t_10; __pyx_L9_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":645 * else: * if not isinstance(item, slice) and not PyIndex_Check(item): * raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<< * * have_slices = have_slices or isinstance(item, slice) */ __pyx_t_7 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __pyx_t_11 = PyTuple_New(1); if (unlikely(!__pyx_t_11)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_11); PyTuple_SET_ITEM(__pyx_t_11, 0, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_11, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_11); __pyx_t_11 = 0; __Pyx_Raise(__pyx_t_7, 0, 0, 0); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 645; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":647 * raise TypeError("Cannot index with type '%s'" % type(item)) * * have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<< * result.append(item) * */ __pyx_t_10 = (__pyx_v_have_slices != 0); if (!__pyx_t_10) { } else { __pyx_t_1 = __pyx_t_10; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = PySlice_Check(__pyx_v_item); __pyx_t_2 = (__pyx_t_10 != 0); __pyx_t_1 = __pyx_t_2; __pyx_L11_bool_binop_done:; __pyx_v_have_slices = __pyx_t_1; /* "View.MemoryView":648 * * have_slices = have_slices or isinstance(item, slice) * result.append(item) # <<<<<<<<<<<<<< * * nslices = ndim - len(result) */ __pyx_t_9 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 648; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L6:; /* "View.MemoryView":635 * have_slices = False * seen_ellipsis = False * for idx, item in enumerate(tup): # <<<<<<<<<<<<<< * if item is Ellipsis: * if not seen_ellipsis: */ } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":650 * result.append(item) * * nslices = ndim - len(result) # <<<<<<<<<<<<<< * if nslices: * result.extend([slice(None)] * nslices) */ __pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 650; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5); /* "View.MemoryView":651 * * nslices = ndim - len(result) * if nslices: # <<<<<<<<<<<<<< * result.extend([slice(None)] * nslices) * */ __pyx_t_1 = (__pyx_v_nslices != 0); if (__pyx_t_1) { /* "View.MemoryView":652 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_t_3 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); { Py_ssize_t __pyx_temp; for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) { __Pyx_INCREF(__pyx_slice__23); PyList_SET_ITEM(__pyx_t_3, __pyx_temp, __pyx_slice__23); __Pyx_GIVEREF(__pyx_slice__23); } } __pyx_t_9 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_3); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L13; } __pyx_L13:; /* "View.MemoryView":654 * result.extend([slice(None)] * nslices) * * return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<< * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): */ __Pyx_XDECREF(__pyx_r); if (!__pyx_v_have_slices) { } else { __pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; goto __pyx_L14_bool_binop_done; } __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __pyx_t_4; __pyx_t_4 = 0; __pyx_L14_bool_binop_done:; __pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_7 = PyTuple_New(2); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 654; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_3 = 0; __pyx_t_4 = 0; __pyx_r = ((PyObject*)__pyx_t_7); __pyx_t_7 = 0; goto __pyx_L0; /* "View.MemoryView":622 * return isinstance(o, memoryview) * * cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<< * """ * Replace all ellipses with full slices and fill incomplete indices with */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_11); __Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_tup); __Pyx_XDECREF(__pyx_v_result); __Pyx_XDECREF(__pyx_v_idx); __Pyx_XDECREF(__pyx_v_item); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":656 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) { Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; Py_ssize_t *__pyx_t_2; Py_ssize_t *__pyx_t_3; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assert_direct_dimensions", 0); /* "View.MemoryView":657 * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") */ __pyx_t_2 = (__pyx_v_suboffsets + __pyx_v_ndim); for (__pyx_t_3 = __pyx_v_suboffsets; __pyx_t_3 < __pyx_t_2; __pyx_t_3++) { __pyx_t_1 = __pyx_t_3; __pyx_v_suboffset = (__pyx_t_1[0]); /* "View.MemoryView":658 * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * raise ValueError("Indirect dimensions not supported") * */ __pyx_t_4 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_4) { /* "View.MemoryView":659 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __Pyx_Raise(__pyx_t_5, 0, 0, 0); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } /* "View.MemoryView":656 * return have_slices or nslices, tuple(result) * * cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<< * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":666 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) { int __pyx_v_new_ndim; int __pyx_v_suboffset_dim; int __pyx_v_dim; __Pyx_memviewslice __pyx_v_src; __Pyx_memviewslice __pyx_v_dst; __Pyx_memviewslice *__pyx_v_p_src; struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0; __Pyx_memviewslice *__pyx_v_p_dst; int *__pyx_v_p_suboffset_dim; Py_ssize_t __pyx_v_start; Py_ssize_t __pyx_v_stop; Py_ssize_t __pyx_v_step; int __pyx_v_have_start; int __pyx_v_have_stop; int __pyx_v_have_step; PyObject *__pyx_v_index = NULL; struct __pyx_memoryview_obj *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; struct __pyx_memoryview_obj *__pyx_t_4; char *__pyx_t_5; int __pyx_t_6; Py_ssize_t __pyx_t_7; PyObject *(*__pyx_t_8)(PyObject *); PyObject *__pyx_t_9 = NULL; Py_ssize_t __pyx_t_10; int __pyx_t_11; Py_ssize_t __pyx_t_12; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memview_slice", 0); /* "View.MemoryView":667 * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): * cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<< * cdef bint negative_step * cdef __Pyx_memviewslice src, dst */ __pyx_v_new_ndim = 0; __pyx_v_suboffset_dim = -1; /* "View.MemoryView":674 * * * memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<< * * cdef _memoryviewslice memviewsliceobj */ memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst))); /* "View.MemoryView":678 * cdef _memoryviewslice memviewsliceobj * * assert memview.view.ndim > 0 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) { PyErr_SetNone(PyExc_AssertionError); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 678; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /* "View.MemoryView":680 * assert memview.view.ndim > 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":681 * * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview # <<<<<<<<<<<<<< * p_src = &memviewsliceobj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 681; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":682 * if isinstance(memview, _memoryviewslice): * memviewsliceobj = memview * p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, &src) */ __pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice); goto __pyx_L3; } /*else*/ { /* "View.MemoryView":684 * p_src = &memviewsliceobj.from_slice * else: * slice_copy(memview, &src) # <<<<<<<<<<<<<< * p_src = &src * */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src)); /* "View.MemoryView":685 * else: * slice_copy(memview, &src) * p_src = &src # <<<<<<<<<<<<<< * * */ __pyx_v_p_src = (&__pyx_v_src); } __pyx_L3:; /* "View.MemoryView":691 * * * dst.memview = p_src.memview # <<<<<<<<<<<<<< * dst.data = p_src.data * */ __pyx_t_4 = __pyx_v_p_src->memview; __pyx_v_dst.memview = __pyx_t_4; /* "View.MemoryView":692 * * dst.memview = p_src.memview * dst.data = p_src.data # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_v_p_src->data; __pyx_v_dst.data = __pyx_t_5; /* "View.MemoryView":697 * * * cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<< * cdef int *p_suboffset_dim = &suboffset_dim * cdef Py_ssize_t start, stop, step */ __pyx_v_p_dst = (&__pyx_v_dst); /* "View.MemoryView":698 * * cdef __Pyx_memviewslice *p_dst = &dst * cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<< * cdef Py_ssize_t start, stop, step * cdef bint have_start, have_stop, have_step */ __pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim); /* "View.MemoryView":702 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ __pyx_t_6 = 0; if (likely(PyList_CheckExact(__pyx_v_indices)) || PyTuple_CheckExact(__pyx_v_indices)) { __pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0; __pyx_t_8 = NULL; } else { __pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } for (;;) { if (likely(!__pyx_t_8)) { if (likely(PyList_CheckExact(__pyx_t_3))) { if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } else { if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break; #if CYTHON_COMPILING_IN_CPYTHON __pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #else __pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif } } else { __pyx_t_9 = __pyx_t_8(__pyx_t_3); if (unlikely(!__pyx_t_9)) { PyObject* exc_type = PyErr_Occurred(); if (exc_type) { if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear(); else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 702; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } break; } __Pyx_GOTREF(__pyx_t_9); } __Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9); __pyx_t_9 = 0; __pyx_v_dim = __pyx_t_6; __pyx_t_6 = (__pyx_t_6 + 1); /* "View.MemoryView":703 * * for dim, index in enumerate(indices): * if PyIndex_Check(index): # <<<<<<<<<<<<<< * slice_memviewslice( * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], */ __pyx_t_2 = (PyIndex_Check(__pyx_v_index) != 0); if (__pyx_t_2) { /* "View.MemoryView":707 * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, * index, 0, 0, # start, stop, step # <<<<<<<<<<<<<< * 0, 0, 0, # have_{start,stop,step} * False) */ __pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 707; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":704 * for dim, index in enumerate(indices): * if PyIndex_Check(index): * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 704; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L6; } /* "View.MemoryView":710 * 0, 0, 0, # have_{start,stop,step} * False) * elif index is None: # <<<<<<<<<<<<<< * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 */ __pyx_t_2 = (__pyx_v_index == Py_None); __pyx_t_1 = (__pyx_t_2 != 0); if (__pyx_t_1) { /* "View.MemoryView":711 * False) * elif index is None: * p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<< * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 */ (__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1; /* "View.MemoryView":712 * elif index is None: * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<< * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 */ (__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0; /* "View.MemoryView":713 * p_dst.shape[new_ndim] = 1 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<< * new_ndim += 1 * else: */ (__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1; /* "View.MemoryView":714 * p_dst.strides[new_ndim] = 0 * p_dst.suboffsets[new_ndim] = -1 * new_ndim += 1 # <<<<<<<<<<<<<< * else: * start = index.start or 0 */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); goto __pyx_L6; } /*else*/ { /* "View.MemoryView":716 * new_ndim += 1 * else: * start = index.start or 0 # <<<<<<<<<<<<<< * stop = index.stop or 0 * step = index.step or 0 */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L7_bool_binop_done; } __pyx_t_10 = 0; __pyx_L7_bool_binop_done:; __pyx_v_start = __pyx_t_10; /* "View.MemoryView":717 * else: * start = index.start or 0 * stop = index.stop or 0 # <<<<<<<<<<<<<< * step = index.step or 0 * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 717; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L9_bool_binop_done; } __pyx_t_10 = 0; __pyx_L9_bool_binop_done:; __pyx_v_stop = __pyx_t_10; /* "View.MemoryView":718 * start = index.start or 0 * stop = index.stop or 0 * step = index.step or 0 # <<<<<<<<<<<<<< * * have_start = index.start is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!__pyx_t_1) { __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; } else { __pyx_t_12 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_12 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 718; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_10 = __pyx_t_12; __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; goto __pyx_L11_bool_binop_done; } __pyx_t_10 = 0; __pyx_L11_bool_binop_done:; __pyx_v_step = __pyx_t_10; /* "View.MemoryView":720 * step = index.step or 0 * * have_start = index.start is not None # <<<<<<<<<<<<<< * have_stop = index.stop is not None * have_step = index.step is not None */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 720; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_start = __pyx_t_1; /* "View.MemoryView":721 * * have_start = index.start is not None * have_stop = index.stop is not None # <<<<<<<<<<<<<< * have_step = index.step is not None * */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 721; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_stop = __pyx_t_1; /* "View.MemoryView":722 * have_start = index.start is not None * have_stop = index.stop is not None * have_step = index.step is not None # <<<<<<<<<<<<<< * * slice_memviewslice( */ __pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 722; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_9); __pyx_t_1 = (__pyx_t_9 != Py_None); __Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0; __pyx_v_have_step = __pyx_t_1; /* "View.MemoryView":724 * have_step = index.step is not None * * slice_memviewslice( # <<<<<<<<<<<<<< * p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim], * dim, new_ndim, p_suboffset_dim, */ __pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 724; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":730 * have_start, have_stop, have_step, * True) * new_ndim += 1 # <<<<<<<<<<<<<< * * if isinstance(memview, _memoryviewslice): */ __pyx_v_new_ndim = (__pyx_v_new_ndim + 1); } __pyx_L6:; /* "View.MemoryView":702 * cdef bint have_start, have_stop, have_step * * for dim, index in enumerate(indices): # <<<<<<<<<<<<<< * if PyIndex_Check(index): * slice_memviewslice( */ } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":732 * new_ndim += 1 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":733 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":734 * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, # <<<<<<<<<<<<<< * memviewsliceobj.to_dtype_func, * memview.dtype_is_object) */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 734; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":735 * return memoryview_fromslice(dst, new_ndim, * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<< * memview.dtype_is_object) * else: */ if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 735; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":733 * * if isinstance(memview, _memoryviewslice): * return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<< * memviewsliceobj.to_object_func, * memviewsliceobj.to_dtype_func, */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /*else*/ { /* "View.MemoryView":738 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ __Pyx_XDECREF(((PyObject *)__pyx_r)); /* "View.MemoryView":739 * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); /* "View.MemoryView":738 * memview.dtype_is_object) * else: * return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<< * memview.dtype_is_object) * */ if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 738; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L0; } /* "View.MemoryView":666 * * @cname('__pyx_memview_slice') * cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<< * cdef int new_ndim = 0, suboffset_dim = -1, dim * cdef bint negative_step */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_9); __Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj); __Pyx_XDECREF(__pyx_v_index); __Pyx_XGIVEREF((PyObject *)__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":763 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) { Py_ssize_t __pyx_v_new_shape; int __pyx_v_negative_step; int __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":783 * cdef bint negative_step * * if not is_slice: # <<<<<<<<<<<<<< * * if start < 0: */ __pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_1) { /* "View.MemoryView":785 * if not is_slice: * * if start < 0: # <<<<<<<<<<<<<< * start += shape * if not 0 <= start < shape: */ __pyx_t_1 = ((__pyx_v_start < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":786 * * if start < 0: * start += shape # <<<<<<<<<<<<<< * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); goto __pyx_L4; } __pyx_L4:; /* "View.MemoryView":787 * if start < 0: * start += shape * if not 0 <= start < shape: # <<<<<<<<<<<<<< * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) * else: */ __pyx_t_1 = (0 <= __pyx_v_start); if (__pyx_t_1) { __pyx_t_1 = (__pyx_v_start < __pyx_v_shape); } __pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":788 * start += shape * if not 0 <= start < shape: * _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<< * else: * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":791 * else: * * negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<< * * if have_step and step == 0: */ __pyx_t_1 = ((__pyx_v_have_step != 0) != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L6_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step < 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L6_bool_binop_done:; __pyx_v_negative_step = __pyx_t_2; /* "View.MemoryView":793 * negative_step = have_step != 0 and step < 0 * * if have_step and step == 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) * */ __pyx_t_1 = (__pyx_v_have_step != 0); if (__pyx_t_1) { } else { __pyx_t_2 = __pyx_t_1; goto __pyx_L9_bool_binop_done; } __pyx_t_1 = ((__pyx_v_step == 0) != 0); __pyx_t_2 = __pyx_t_1; __pyx_L9_bool_binop_done:; if (__pyx_t_2) { /* "View.MemoryView":794 * * if have_step and step == 0: * _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; /* "View.MemoryView":797 * * * if have_start: # <<<<<<<<<<<<<< * if start < 0: * start += shape */ __pyx_t_2 = (__pyx_v_have_start != 0); if (__pyx_t_2) { /* "View.MemoryView":798 * * if have_start: * if start < 0: # <<<<<<<<<<<<<< * start += shape * if start < 0: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":799 * if have_start: * if start < 0: * start += shape # <<<<<<<<<<<<<< * if start < 0: * start = 0 */ __pyx_v_start = (__pyx_v_start + __pyx_v_shape); /* "View.MemoryView":800 * if start < 0: * start += shape * if start < 0: # <<<<<<<<<<<<<< * start = 0 * elif start >= shape: */ __pyx_t_2 = ((__pyx_v_start < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":801 * start += shape * if start < 0: * start = 0 # <<<<<<<<<<<<<< * elif start >= shape: * if negative_step: */ __pyx_v_start = 0; goto __pyx_L13; } __pyx_L13:; goto __pyx_L12; } /* "View.MemoryView":802 * if start < 0: * start = 0 * elif start >= shape: # <<<<<<<<<<<<<< * if negative_step: * start = shape - 1 */ __pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":803 * start = 0 * elif start >= shape: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":804 * elif start >= shape: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = shape */ __pyx_v_start = (__pyx_v_shape - 1); goto __pyx_L14; } /*else*/ { /* "View.MemoryView":806 * start = shape - 1 * else: * start = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_start = __pyx_v_shape; } __pyx_L14:; goto __pyx_L12; } __pyx_L12:; goto __pyx_L11; } /*else*/ { /* "View.MemoryView":808 * start = shape * else: * if negative_step: # <<<<<<<<<<<<<< * start = shape - 1 * else: */ __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":809 * else: * if negative_step: * start = shape - 1 # <<<<<<<<<<<<<< * else: * start = 0 */ __pyx_v_start = (__pyx_v_shape - 1); goto __pyx_L15; } /*else*/ { /* "View.MemoryView":811 * start = shape - 1 * else: * start = 0 # <<<<<<<<<<<<<< * * if have_stop: */ __pyx_v_start = 0; } __pyx_L15:; } __pyx_L11:; /* "View.MemoryView":813 * start = 0 * * if have_stop: # <<<<<<<<<<<<<< * if stop < 0: * stop += shape */ __pyx_t_2 = (__pyx_v_have_stop != 0); if (__pyx_t_2) { /* "View.MemoryView":814 * * if have_stop: * if stop < 0: # <<<<<<<<<<<<<< * stop += shape * if stop < 0: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":815 * if have_stop: * if stop < 0: * stop += shape # <<<<<<<<<<<<<< * if stop < 0: * stop = 0 */ __pyx_v_stop = (__pyx_v_stop + __pyx_v_shape); /* "View.MemoryView":816 * if stop < 0: * stop += shape * if stop < 0: # <<<<<<<<<<<<<< * stop = 0 * elif stop > shape: */ __pyx_t_2 = ((__pyx_v_stop < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":817 * stop += shape * if stop < 0: * stop = 0 # <<<<<<<<<<<<<< * elif stop > shape: * stop = shape */ __pyx_v_stop = 0; goto __pyx_L18; } __pyx_L18:; goto __pyx_L17; } /* "View.MemoryView":818 * if stop < 0: * stop = 0 * elif stop > shape: # <<<<<<<<<<<<<< * stop = shape * else: */ __pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":819 * stop = 0 * elif stop > shape: * stop = shape # <<<<<<<<<<<<<< * else: * if negative_step: */ __pyx_v_stop = __pyx_v_shape; goto __pyx_L17; } __pyx_L17:; goto __pyx_L16; } /*else*/ { /* "View.MemoryView":821 * stop = shape * else: * if negative_step: # <<<<<<<<<<<<<< * stop = -1 * else: */ __pyx_t_2 = (__pyx_v_negative_step != 0); if (__pyx_t_2) { /* "View.MemoryView":822 * else: * if negative_step: * stop = -1 # <<<<<<<<<<<<<< * else: * stop = shape */ __pyx_v_stop = -1; goto __pyx_L19; } /*else*/ { /* "View.MemoryView":824 * stop = -1 * else: * stop = shape # <<<<<<<<<<<<<< * * if not have_step: */ __pyx_v_stop = __pyx_v_shape; } __pyx_L19:; } __pyx_L16:; /* "View.MemoryView":826 * stop = shape * * if not have_step: # <<<<<<<<<<<<<< * step = 1 * */ __pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":827 * * if not have_step: * step = 1 # <<<<<<<<<<<<<< * * */ __pyx_v_step = 1; goto __pyx_L20; } __pyx_L20:; /* "View.MemoryView":831 * * with cython.cdivision(True): * new_shape = (stop - start) // step # <<<<<<<<<<<<<< * * if (stop - start) - step * new_shape: */ __pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step); /* "View.MemoryView":833 * new_shape = (stop - start) // step * * if (stop - start) - step * new_shape: # <<<<<<<<<<<<<< * new_shape += 1 * */ __pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0); if (__pyx_t_2) { /* "View.MemoryView":834 * * if (stop - start) - step * new_shape: * new_shape += 1 # <<<<<<<<<<<<<< * * if new_shape < 0: */ __pyx_v_new_shape = (__pyx_v_new_shape + 1); goto __pyx_L21; } __pyx_L21:; /* "View.MemoryView":836 * new_shape += 1 * * if new_shape < 0: # <<<<<<<<<<<<<< * new_shape = 0 * */ __pyx_t_2 = ((__pyx_v_new_shape < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":837 * * if new_shape < 0: * new_shape = 0 # <<<<<<<<<<<<<< * * */ __pyx_v_new_shape = 0; goto __pyx_L22; } __pyx_L22:; /* "View.MemoryView":840 * * * dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<< * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset */ (__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step); /* "View.MemoryView":841 * * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<< * dst.suboffsets[new_ndim] = suboffset * */ (__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape; /* "View.MemoryView":842 * dst.strides[new_ndim] = stride * step * dst.shape[new_ndim] = new_shape * dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<< * * */ (__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset; } __pyx_L3:; /* "View.MemoryView":845 * * * if suboffset_dim[0] < 0: # <<<<<<<<<<<<<< * dst.data += start * stride * else: */ __pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":846 * * if suboffset_dim[0] < 0: * dst.data += start * stride # <<<<<<<<<<<<<< * else: * dst.suboffsets[suboffset_dim[0]] += start * stride */ __pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride)); goto __pyx_L23; } /*else*/ { /* "View.MemoryView":848 * dst.data += start * stride * else: * dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<< * * if suboffset >= 0: */ __pyx_t_3 = (__pyx_v_suboffset_dim[0]); (__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride)); } __pyx_L23:; /* "View.MemoryView":850 * dst.suboffsets[suboffset_dim[0]] += start * stride * * if suboffset >= 0: # <<<<<<<<<<<<<< * if not is_slice: * if new_ndim == 0: */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":851 * * if suboffset >= 0: * if not is_slice: # <<<<<<<<<<<<<< * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset */ __pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":852 * if suboffset >= 0: * if not is_slice: * if new_ndim == 0: # <<<<<<<<<<<<<< * dst.data = (<char **> dst.data)[0] + suboffset * else: */ __pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":853 * if not is_slice: * if new_ndim == 0: * dst.data = (<char **> dst.data)[0] + suboffset # <<<<<<<<<<<<<< * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " */ __pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset); goto __pyx_L26; } /*else*/ { /* "View.MemoryView":855 * dst.data = (<char **> dst.data)[0] + suboffset * else: * _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<< * "must be indexed and not sliced", dim) * else: */ __pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 855; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L26:; goto __pyx_L25; } /*else*/ { /* "View.MemoryView":858 * "must be indexed and not sliced", dim) * else: * suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<< * * return 0 */ (__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim; } __pyx_L25:; goto __pyx_L24; } __pyx_L24:; /* "View.MemoryView":860 * suboffset_dim[0] = new_ndim * * return 0 # <<<<<<<<<<<<<< * * */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":763 * * @cname('__pyx_memoryview_slice_memviewslice') * cdef int slice_memviewslice( # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":866 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) { Py_ssize_t __pyx_v_shape; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_suboffset; Py_ssize_t __pyx_v_itemsize; char *__pyx_v_resultp; char *__pyx_r; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("pybuffer_index", 0); /* "View.MemoryView":868 * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<< * cdef Py_ssize_t itemsize = view.itemsize * cdef char *resultp */ __pyx_v_suboffset = -1; /* "View.MemoryView":869 * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 * cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<< * cdef char *resultp * */ __pyx_t_1 = __pyx_v_view->itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":872 * cdef char *resultp * * if view.ndim == 0: # <<<<<<<<<<<<<< * shape = view.len / itemsize * stride = itemsize */ __pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":873 * * if view.ndim == 0: * shape = view.len / itemsize # <<<<<<<<<<<<<< * stride = itemsize * else: */ if (unlikely(__pyx_v_itemsize == 0)) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[2]; __pyx_lineno = 873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif {__pyx_filename = __pyx_f[2]; __pyx_lineno = 873; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_v_shape = __Pyx_div_Py_ssize_t(__pyx_v_view->len, __pyx_v_itemsize); /* "View.MemoryView":874 * if view.ndim == 0: * shape = view.len / itemsize * stride = itemsize # <<<<<<<<<<<<<< * else: * shape = view.shape[dim] */ __pyx_v_stride = __pyx_v_itemsize; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":876 * stride = itemsize * else: * shape = view.shape[dim] # <<<<<<<<<<<<<< * stride = view.strides[dim] * if view.suboffsets != NULL: */ __pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]); /* "View.MemoryView":877 * else: * shape = view.shape[dim] * stride = view.strides[dim] # <<<<<<<<<<<<<< * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] */ __pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]); /* "View.MemoryView":878 * shape = view.shape[dim] * stride = view.strides[dim] * if view.suboffsets != NULL: # <<<<<<<<<<<<<< * suboffset = view.suboffsets[dim] * */ __pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0); if (__pyx_t_2) { /* "View.MemoryView":879 * stride = view.strides[dim] * if view.suboffsets != NULL: * suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<< * * if index < 0: */ __pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]); goto __pyx_L4; } __pyx_L4:; } __pyx_L3:; /* "View.MemoryView":881 * suboffset = view.suboffsets[dim] * * if index < 0: # <<<<<<<<<<<<<< * index += view.shape[dim] * if index < 0: */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":882 * * if index < 0: * index += view.shape[dim] # <<<<<<<<<<<<<< * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) */ __pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim])); /* "View.MemoryView":883 * if index < 0: * index += view.shape[dim] * if index < 0: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index < 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":884 * index += view.shape[dim] * if index < 0: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * if index >= shape: */ __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 884; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } goto __pyx_L5; } __pyx_L5:; /* "View.MemoryView":886 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * if index >= shape: # <<<<<<<<<<<<<< * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * */ __pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0); if (__pyx_t_2) { /* "View.MemoryView":887 * * if index >= shape: * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<< * * resultp = bufp + index * stride */ __pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 887; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":889 * raise IndexError("Out of bounds on buffer access (axis %d)" % dim) * * resultp = bufp + index * stride # <<<<<<<<<<<<<< * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset */ __pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride)); /* "View.MemoryView":890 * * resultp = bufp + index * stride * if suboffset >= 0: # <<<<<<<<<<<<<< * resultp = (<char **> resultp)[0] + suboffset * */ __pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":891 * resultp = bufp + index * stride * if suboffset >= 0: * resultp = (<char **> resultp)[0] + suboffset # <<<<<<<<<<<<<< * * return resultp */ __pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset); goto __pyx_L8; } __pyx_L8:; /* "View.MemoryView":893 * resultp = (<char **> resultp)[0] + suboffset * * return resultp # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_resultp; goto __pyx_L0; /* "View.MemoryView":866 * * @cname('__pyx_pybuffer_index') * cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<< * Py_ssize_t dim) except NULL: * cdef Py_ssize_t shape, stride, suboffset = -1 */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":899 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) { int __pyx_v_ndim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; int __pyx_v_i; int __pyx_v_j; int __pyx_r; int __pyx_t_1; Py_ssize_t *__pyx_t_2; long __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; int __pyx_t_6; int __pyx_t_7; int __pyx_t_8; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":900 * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: * cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<< * * cdef Py_ssize_t *shape = memslice.shape */ __pyx_t_1 = __pyx_v_memslice->memview->view.ndim; __pyx_v_ndim = __pyx_t_1; /* "View.MemoryView":902 * cdef int ndim = memslice.memview.view.ndim * * cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<< * cdef Py_ssize_t *strides = memslice.strides * */ __pyx_t_2 = __pyx_v_memslice->shape; __pyx_v_shape = __pyx_t_2; /* "View.MemoryView":903 * * cdef Py_ssize_t *shape = memslice.shape * cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<< * * */ __pyx_t_2 = __pyx_v_memslice->strides; __pyx_v_strides = __pyx_t_2; /* "View.MemoryView":907 * * cdef int i, j * for i in range(ndim / 2): # <<<<<<<<<<<<<< * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] */ __pyx_t_3 = __Pyx_div_long(__pyx_v_ndim, 2); for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":908 * cdef int i, j * for i in range(ndim / 2): * j = ndim - 1 - i # <<<<<<<<<<<<<< * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] */ __pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i); /* "View.MemoryView":909 * for i in range(ndim / 2): * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<< * shape[i], shape[j] = shape[j], shape[i] * */ __pyx_t_4 = (__pyx_v_strides[__pyx_v_j]); __pyx_t_5 = (__pyx_v_strides[__pyx_v_i]); (__pyx_v_strides[__pyx_v_i]) = __pyx_t_4; (__pyx_v_strides[__pyx_v_j]) = __pyx_t_5; /* "View.MemoryView":910 * j = ndim - 1 - i * strides[i], strides[j] = strides[j], strides[i] * shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<< * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: */ __pyx_t_5 = (__pyx_v_shape[__pyx_v_j]); __pyx_t_4 = (__pyx_v_shape[__pyx_v_i]); (__pyx_v_shape[__pyx_v_i]) = __pyx_t_5; (__pyx_v_shape[__pyx_v_j]) = __pyx_t_4; /* "View.MemoryView":912 * shape[i], shape[j] = shape[j], shape[i] * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<< * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * */ __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L6_bool_binop_done; } __pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L6_bool_binop_done:; if (__pyx_t_6) { /* "View.MemoryView":913 * * if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<< * * return 1 */ __pyx_t_8 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 913; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L5; } __pyx_L5:; } /* "View.MemoryView":915 * _err(ValueError, "Cannot transpose memoryview with indirect dimensions") * * return 1 # <<<<<<<<<<<<<< * * */ __pyx_r = 1; goto __pyx_L0; /* "View.MemoryView":899 * * @cname('__pyx_memslice_transpose') * cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<< * cdef int ndim = memslice.memview.view.ndim * */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = 0; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":932 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* Python wrapper */ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/ static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0); __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_memoryviewslice___pyx_pf_15View_dot_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__dealloc__", 0); /* "View.MemoryView":933 * * def __dealloc__(self): * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<< * * cdef convert_item_to_object(self, char *itemp): */ __PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1); /* "View.MemoryView":932 * cdef int (*to_dtype_func)(char *, object) except 0 * * def __dealloc__(self): # <<<<<<<<<<<<<< * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":935 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("convert_item_to_object", 0); /* "View.MemoryView":936 * * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: # <<<<<<<<<<<<<< * return self.to_object_func(itemp) * else: */ __pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":937 * cdef convert_item_to_object(self, char *itemp): * if self.to_object_func != NULL: * return self.to_object_func(itemp) # <<<<<<<<<<<<<< * else: * return memoryview.convert_item_to_object(self, itemp) */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 937; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /*else*/ { /* "View.MemoryView":939 * return self.to_object_func(itemp) * else: * return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<< * * cdef assign_item_from_object(self, char *itemp, object value): */ __Pyx_XDECREF(__pyx_r); __pyx_t_2 = __pyx_memoryview_convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 939; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_r = __pyx_t_2; __pyx_t_2 = 0; goto __pyx_L0; } /* "View.MemoryView":935 * __PYX_XDEC_MEMVIEW(&self.from_slice, 1) * * cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<< * if self.to_object_func != NULL: * return self.to_object_func(itemp) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":941 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("assign_item_from_object", 0); /* "View.MemoryView":942 * * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: # <<<<<<<<<<<<<< * self.to_dtype_func(itemp, value) * else: */ __pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":943 * cdef assign_item_from_object(self, char *itemp, object value): * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<< * else: * memoryview.assign_item_from_object(self, itemp, value) */ __pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 943; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } /*else*/ { /* "View.MemoryView":945 * self.to_dtype_func(itemp, value) * else: * memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<< * * property base: */ __pyx_t_3 = __pyx_memoryview_assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 945; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; } __pyx_L3:; /* "View.MemoryView":941 * return memoryview.convert_item_to_object(self, itemp) * * cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<< * if self.to_dtype_func != NULL: * self.to_dtype_func(itemp, value) */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":949 * property base: * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* Python wrapper */ static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/ static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) { PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__ (wrapper)", 0); __pyx_r = __pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_15View_dot_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__get__", 0); /* "View.MemoryView":950 * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): * return self.from_object # <<<<<<<<<<<<<< * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_v_self->from_object); __pyx_r = __pyx_v_self->from_object; goto __pyx_L0; /* "View.MemoryView":949 * property base: * @cname('__pyx_memoryviewslice__get__base') * def __get__(self): # <<<<<<<<<<<<<< * return self.from_object * */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":956 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) { struct __pyx_memoryviewslice_obj *__pyx_v_result = 0; Py_ssize_t __pyx_v_suboffset; PyObject *__pyx_v_length = NULL; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; __Pyx_TypeInfo *__pyx_t_4; Py_buffer __pyx_t_5; Py_ssize_t *__pyx_t_6; Py_ssize_t *__pyx_t_7; Py_ssize_t *__pyx_t_8; Py_ssize_t __pyx_t_9; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_fromslice", 0); /* "View.MemoryView":964 * cdef _memoryviewslice result * * if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<< * return None * */ __pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0); if (__pyx_t_1) { /* "View.MemoryView":965 * * if <PyObject *> memviewslice.memview == Py_None: * return None # <<<<<<<<<<<<<< * * */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; } /* "View.MemoryView":970 * * * result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<< * * result.from_slice = memviewslice */ __pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(Py_None); PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None); __Pyx_GIVEREF(Py_None); __Pyx_INCREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0); __Pyx_GIVEREF(__pyx_int_0); PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 970; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":972 * result = _memoryviewslice(None, 0, dtype_is_object) * * result.from_slice = memviewslice # <<<<<<<<<<<<<< * __PYX_INC_MEMVIEW(&memviewslice, 1) * */ __pyx_v_result->from_slice = __pyx_v_memviewslice; /* "View.MemoryView":973 * * result.from_slice = memviewslice * __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<< * * result.from_object = (<memoryview> memviewslice.memview).base */ __PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1); /* "View.MemoryView":975 * __PYX_INC_MEMVIEW(&memviewslice, 1) * * result.from_object = (<memoryview> memviewslice.memview).base # <<<<<<<<<<<<<< * result.typeinfo = memviewslice.memview.typeinfo * */ __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 975; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __Pyx_GOTREF(__pyx_v_result->from_object); __Pyx_DECREF(__pyx_v_result->from_object); __pyx_v_result->from_object = __pyx_t_2; __pyx_t_2 = 0; /* "View.MemoryView":976 * * result.from_object = (<memoryview> memviewslice.memview).base * result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<< * * result.view = memviewslice.memview.view */ __pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo; __pyx_v_result->__pyx_base.typeinfo = __pyx_t_4; /* "View.MemoryView":978 * result.typeinfo = memviewslice.memview.typeinfo * * result.view = memviewslice.memview.view # <<<<<<<<<<<<<< * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim */ __pyx_t_5 = __pyx_v_memviewslice.memview->view; __pyx_v_result->__pyx_base.view = __pyx_t_5; /* "View.MemoryView":979 * * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data # <<<<<<<<<<<<<< * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None */ __pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data); /* "View.MemoryView":980 * result.view = memviewslice.memview.view * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim # <<<<<<<<<<<<<< * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) */ __pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim; /* "View.MemoryView":981 * result.view.buf = <void *> memviewslice.data * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<< * Py_INCREF(Py_None) * */ ((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None; /* "View.MemoryView":982 * result.view.ndim = ndim * (<__pyx_buffer *> &result.view).obj = Py_None * Py_INCREF(Py_None) # <<<<<<<<<<<<<< * * result.flags = PyBUF_RECORDS */ Py_INCREF(Py_None); /* "View.MemoryView":984 * Py_INCREF(Py_None) * * result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<< * * result.view.shape = <Py_ssize_t *> result.from_slice.shape */ __pyx_v_result->__pyx_base.flags = PyBUF_RECORDS; /* "View.MemoryView":986 * result.flags = PyBUF_RECORDS * * result.view.shape = <Py_ssize_t *> result.from_slice.shape # <<<<<<<<<<<<<< * result.view.strides = <Py_ssize_t *> result.from_slice.strides * */ __pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape); /* "View.MemoryView":987 * * result.view.shape = <Py_ssize_t *> result.from_slice.shape * result.view.strides = <Py_ssize_t *> result.from_slice.strides # <<<<<<<<<<<<<< * * */ __pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides); /* "View.MemoryView":990 * * * result.view.suboffsets = NULL # <<<<<<<<<<<<<< * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: */ __pyx_v_result->__pyx_base.view.suboffsets = NULL; /* "View.MemoryView":991 * * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: # <<<<<<<<<<<<<< * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets */ __pyx_t_7 = (__pyx_v_result->from_slice.suboffsets + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->from_slice.suboffsets; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_v_suboffset = (__pyx_t_6[0]); /* "View.MemoryView":992 * result.view.suboffsets = NULL * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: # <<<<<<<<<<<<<< * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break */ __pyx_t_1 = ((__pyx_v_suboffset >= 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":993 * for suboffset in result.from_slice.suboffsets[:ndim]: * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets # <<<<<<<<<<<<<< * break * */ __pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets); /* "View.MemoryView":994 * if suboffset >= 0: * result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets * break # <<<<<<<<<<<<<< * * result.view.len = result.view.itemsize */ goto __pyx_L5_break; } } __pyx_L5_break:; /* "View.MemoryView":996 * break * * result.view.len = result.view.itemsize # <<<<<<<<<<<<<< * for length in result.view.shape[:ndim]: * result.view.len *= length */ __pyx_t_9 = __pyx_v_result->__pyx_base.view.itemsize; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; /* "View.MemoryView":997 * * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: # <<<<<<<<<<<<<< * result.view.len *= length * */ __pyx_t_7 = (__pyx_v_result->__pyx_base.view.shape + __pyx_v_ndim); for (__pyx_t_8 = __pyx_v_result->__pyx_base.view.shape; __pyx_t_8 < __pyx_t_7; __pyx_t_8++) { __pyx_t_6 = __pyx_t_8; __pyx_t_2 = PyInt_FromSsize_t((__pyx_t_6[0])); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 997; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_2); __pyx_t_2 = 0; /* "View.MemoryView":998 * result.view.len = result.view.itemsize * for length in result.view.shape[:ndim]: * result.view.len *= length # <<<<<<<<<<<<<< * * result.to_object_func = to_object_func */ __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_result->__pyx_base.view.len); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_t_2, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_9 = __Pyx_PyIndex_AsSsize_t(__pyx_t_3); if (unlikely((__pyx_t_9 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 998; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_v_result->__pyx_base.view.len = __pyx_t_9; } /* "View.MemoryView":1000 * result.view.len *= length * * result.to_object_func = to_object_func # <<<<<<<<<<<<<< * result.to_dtype_func = to_dtype_func * */ __pyx_v_result->to_object_func = __pyx_v_to_object_func; /* "View.MemoryView":1001 * * result.to_object_func = to_object_func * result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<< * * return result */ __pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func; /* "View.MemoryView":1003 * result.to_dtype_func = to_dtype_func * * return result # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_get_slice_from_memoryview') */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_result)); __pyx_r = ((PyObject *)__pyx_v_result); goto __pyx_L0; /* "View.MemoryView":956 * * @cname('__pyx_memoryview_fromslice') * cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<< * int ndim, * object (*to_object_func)(char *), */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_result); __Pyx_XDECREF(__pyx_v_length); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1006 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj */ static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) { struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0; __Pyx_memviewslice *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("get_slice_from_memview", 0); /* "View.MemoryView":1009 * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * obj = memview * return &obj.from_slice */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1010 * cdef _memoryviewslice obj * if isinstance(memview, _memoryviewslice): * obj = memview # <<<<<<<<<<<<<< * return &obj.from_slice * else: */ if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1010; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_t_3 = ((PyObject *)__pyx_v_memview); __Pyx_INCREF(__pyx_t_3); __pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":1011 * if isinstance(memview, _memoryviewslice): * obj = memview * return &obj.from_slice # <<<<<<<<<<<<<< * else: * slice_copy(memview, mslice) */ __pyx_r = (&__pyx_v_obj->from_slice); goto __pyx_L0; } /*else*/ { /* "View.MemoryView":1013 * return &obj.from_slice * else: * slice_copy(memview, mslice) # <<<<<<<<<<<<<< * return mslice * */ __pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice); /* "View.MemoryView":1014 * else: * slice_copy(memview, mslice) * return mslice # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_slice_copy') */ __pyx_r = __pyx_v_mslice; goto __pyx_L0; } /* "View.MemoryView":1006 * * @cname('__pyx_memoryview_get_slice_from_memoryview') * cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<< * __Pyx_memviewslice *mslice): * cdef _memoryviewslice obj */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_obj); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1017 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) { int __pyx_v_dim; Py_ssize_t *__pyx_v_shape; Py_ssize_t *__pyx_v_strides; Py_ssize_t *__pyx_v_suboffsets; __Pyx_RefNannyDeclarations Py_ssize_t *__pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; __Pyx_RefNannySetupContext("slice_copy", 0); /* "View.MemoryView":1021 * cdef (Py_ssize_t*) shape, strides, suboffsets * * shape = memview.view.shape # <<<<<<<<<<<<<< * strides = memview.view.strides * suboffsets = memview.view.suboffsets */ __pyx_t_1 = __pyx_v_memview->view.shape; __pyx_v_shape = __pyx_t_1; /* "View.MemoryView":1022 * * shape = memview.view.shape * strides = memview.view.strides # <<<<<<<<<<<<<< * suboffsets = memview.view.suboffsets * */ __pyx_t_1 = __pyx_v_memview->view.strides; __pyx_v_strides = __pyx_t_1; /* "View.MemoryView":1023 * shape = memview.view.shape * strides = memview.view.strides * suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<< * * dst.memview = <__pyx_memoryview *> memview */ __pyx_t_1 = __pyx_v_memview->view.suboffsets; __pyx_v_suboffsets = __pyx_t_1; /* "View.MemoryView":1025 * suboffsets = memview.view.suboffsets * * dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<< * dst.data = <char *> memview.view.buf * */ __pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview); /* "View.MemoryView":1026 * * dst.memview = <__pyx_memoryview *> memview * dst.data = <char *> memview.view.buf # <<<<<<<<<<<<<< * * for dim in range(memview.view.ndim): */ __pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf); /* "View.MemoryView":1028 * dst.data = <char *> memview.view.buf * * for dim in range(memview.view.ndim): # <<<<<<<<<<<<<< * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] */ __pyx_t_2 = __pyx_v_memview->view.ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_dim = __pyx_t_3; /* "View.MemoryView":1029 * * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<< * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 */ (__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]); /* "View.MemoryView":1030 * for dim in range(memview.view.ndim): * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<< * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 * */ (__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]); /* "View.MemoryView":1031 * dst.shape[dim] = shape[dim] * dst.strides[dim] = strides[dim] * dst.suboffsets[dim] = suboffsets[dim] if suboffsets else -1 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object') */ if ((__pyx_v_suboffsets != 0)) { __pyx_t_4 = (__pyx_v_suboffsets[__pyx_v_dim]); } else { __pyx_t_4 = -1; } (__pyx_v_dst->suboffsets[__pyx_v_dim]) = __pyx_t_4; } /* "View.MemoryView":1017 * * @cname('__pyx_memoryview_slice_copy') * cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<< * cdef int dim * cdef (Py_ssize_t*) shape, strides, suboffsets */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1034 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) { __Pyx_memviewslice __pyx_v_memviewslice; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy", 0); /* "View.MemoryView":1037 * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<< * return memoryview_copy_from_slice(memview, &memviewslice) * */ __pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice)); /* "View.MemoryView":1038 * cdef __Pyx_memviewslice memviewslice * slice_copy(memview, &memviewslice) * return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_object_from_slice') */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1038; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "View.MemoryView":1034 * * @cname('__pyx_memoryview_copy_object') * cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<< * "Create a new memoryview object" * cdef __Pyx_memviewslice memviewslice */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1041 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) { PyObject *(*__pyx_v_to_object_func)(char *); int (*__pyx_v_to_dtype_func)(char *, PyObject *); PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *(*__pyx_t_3)(char *); int (*__pyx_t_4)(char *, PyObject *); PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0); /* "View.MemoryView":1048 * cdef int (*to_dtype_func)(char *, object) except 0 * * if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<< * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func */ __pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type)); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "View.MemoryView":1049 * * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<< * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: */ __pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func; __pyx_v_to_object_func = __pyx_t_3; /* "View.MemoryView":1050 * if isinstance(memview, _memoryviewslice): * to_object_func = (<_memoryviewslice> memview).to_object_func * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<< * else: * to_object_func = NULL */ __pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func; __pyx_v_to_dtype_func = __pyx_t_4; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":1052 * to_dtype_func = (<_memoryviewslice> memview).to_dtype_func * else: * to_object_func = NULL # <<<<<<<<<<<<<< * to_dtype_func = NULL * */ __pyx_v_to_object_func = NULL; /* "View.MemoryView":1053 * else: * to_object_func = NULL * to_dtype_func = NULL # <<<<<<<<<<<<<< * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, */ __pyx_v_to_dtype_func = NULL; } __pyx_L3:; /* "View.MemoryView":1055 * to_dtype_func = NULL * * return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<< * to_object_func, to_dtype_func, * memview.dtype_is_object) */ __Pyx_XDECREF(__pyx_r); /* "View.MemoryView":1057 * return memoryview_fromslice(memviewslice[0], memview.view.ndim, * to_object_func, to_dtype_func, * memview.dtype_is_object) # <<<<<<<<<<<<<< * * */ __pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1055; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); __pyx_r = __pyx_t_5; __pyx_t_5 = 0; goto __pyx_L0; /* "View.MemoryView":1041 * * @cname('__pyx_memoryview_copy_object_from_slice') * cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<< * """ * Create a new memoryview object from a given memoryview object and slice. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "View.MemoryView":1063 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) { Py_ssize_t __pyx_r; int __pyx_t_1; /* "View.MemoryView":1064 * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: # <<<<<<<<<<<<<< * return -arg * else: */ __pyx_t_1 = ((__pyx_v_arg < 0) != 0); if (__pyx_t_1) { /* "View.MemoryView":1065 * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: * if arg < 0: * return -arg # <<<<<<<<<<<<<< * else: * return arg */ __pyx_r = (-__pyx_v_arg); goto __pyx_L0; } /*else*/ { /* "View.MemoryView":1067 * return -arg * else: * return arg # <<<<<<<<<<<<<< * * @cname('__pyx_get_best_slice_order') */ __pyx_r = __pyx_v_arg; goto __pyx_L0; } /* "View.MemoryView":1063 * * * cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<< * if arg < 0: * return -arg */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1070 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_c_stride; Py_ssize_t __pyx_v_f_stride; char __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1075 * """ * cdef int i * cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<< * cdef Py_ssize_t f_stride = 0 * */ __pyx_v_c_stride = 0; /* "View.MemoryView":1076 * cdef int i * cdef Py_ssize_t c_stride = 0 * cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_f_stride = 0; /* "View.MemoryView":1078 * cdef Py_ssize_t f_stride = 0 * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1079 * * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * c_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1080 * for i in range(ndim - 1, -1, -1): * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1081 * if mslice.shape[i] > 1: * c_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * for i in range(ndim): */ goto __pyx_L4_break; } } __pyx_L4_break:; /* "View.MemoryView":1083 * break * * for i in range(ndim): # <<<<<<<<<<<<<< * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] */ __pyx_t_1 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1084 * * for i in range(ndim): * if mslice.shape[i] > 1: # <<<<<<<<<<<<<< * f_stride = mslice.strides[i] * break */ __pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1085 * for i in range(ndim): * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] # <<<<<<<<<<<<<< * break * */ __pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1086 * if mslice.shape[i] > 1: * f_stride = mslice.strides[i] * break # <<<<<<<<<<<<<< * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): */ goto __pyx_L7_break; } } __pyx_L7_break:; /* "View.MemoryView":1088 * break * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<< * return 'C' * else: */ __pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1089 * * if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): * return 'C' # <<<<<<<<<<<<<< * else: * return 'F' */ __pyx_r = 'C'; goto __pyx_L0; } /*else*/ { /* "View.MemoryView":1091 * return 'C' * else: * return 'F' # <<<<<<<<<<<<<< * * @cython.cdivision(True) */ __pyx_r = 'F'; goto __pyx_L0; } /* "View.MemoryView":1070 * * @cname('__pyx_get_best_slice_order') * cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<< * """ * Figure out the best memory access order for a given slice. */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1094 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent; Py_ssize_t __pyx_v_dst_extent; Py_ssize_t __pyx_v_src_stride; Py_ssize_t __pyx_v_dst_stride; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; Py_ssize_t __pyx_t_4; Py_ssize_t __pyx_t_5; /* "View.MemoryView":1101 * * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] */ __pyx_v_src_extent = (__pyx_v_src_shape[0]); /* "View.MemoryView":1102 * cdef Py_ssize_t i * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] */ __pyx_v_dst_extent = (__pyx_v_dst_shape[0]); /* "View.MemoryView":1103 * cdef Py_ssize_t src_extent = src_shape[0] * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t dst_stride = dst_strides[0] * */ __pyx_v_src_stride = (__pyx_v_src_strides[0]); /* "View.MemoryView":1104 * cdef Py_ssize_t dst_extent = dst_shape[0] * cdef Py_ssize_t src_stride = src_strides[0] * cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_dst_stride = (__pyx_v_dst_strides[0]); /* "View.MemoryView":1106 * cdef Py_ssize_t dst_stride = dst_strides[0] * * if ndim == 1: # <<<<<<<<<<<<<< * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1107 * * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<< * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) */ __pyx_t_2 = ((__pyx_v_src_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } __pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L5_bool_binop_done; } /* "View.MemoryView":1108 * if ndim == 1: * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize * dst_extent) * else: */ __pyx_t_2 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize); if (__pyx_t_2) { __pyx_t_2 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride)); } __pyx_t_3 = (__pyx_t_2 != 0); __pyx_t_1 = __pyx_t_3; __pyx_L5_bool_binop_done:; if (__pyx_t_1) { /* "View.MemoryView":1109 * if (src_stride > 0 and dst_stride > 0 and * <size_t> src_stride == itemsize == <size_t> dst_stride): * memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent)); goto __pyx_L4; } /*else*/ { /* "View.MemoryView":1111 * memcpy(dst_data, src_data, itemsize * dst_extent) * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * memcpy(dst_data, src_data, itemsize) * src_data += src_stride */ __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1112 * else: * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<< * src_data += src_stride * dst_data += dst_stride */ memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize); /* "View.MemoryView":1113 * for i in range(dst_extent): * memcpy(dst_data, src_data, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * else: */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1114 * memcpy(dst_data, src_data, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * else: * for i in range(dst_extent): */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L4:; goto __pyx_L3; } /*else*/ { /* "View.MemoryView":1116 * dst_data += dst_stride * else: * for i in range(dst_extent): # <<<<<<<<<<<<<< * _copy_strided_to_strided(src_data, src_strides + 1, * dst_data, dst_strides + 1, */ __pyx_t_4 = __pyx_v_dst_extent; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1117 * else: * for i in range(dst_extent): * _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<< * dst_data, dst_strides + 1, * src_shape + 1, dst_shape + 1, */ _copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize); /* "View.MemoryView":1121 * src_shape + 1, dst_shape + 1, * ndim - 1, itemsize) * src_data += src_stride # <<<<<<<<<<<<<< * dst_data += dst_stride * */ __pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride); /* "View.MemoryView":1122 * ndim - 1, itemsize) * src_data += src_stride * dst_data += dst_stride # <<<<<<<<<<<<<< * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, */ __pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride); } } __pyx_L3:; /* "View.MemoryView":1094 * * @cython.cdivision(True) * cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<< * char *dst_data, Py_ssize_t *dst_strides, * Py_ssize_t *src_shape, Py_ssize_t *dst_shape, */ /* function exit code */ } /* "View.MemoryView":1124 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) { /* "View.MemoryView":1127 * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: * _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<< * src.shape, dst.shape, ndim, itemsize) * */ _copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1124 * dst_data += dst_stride * * cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *dst, * int ndim, size_t itemsize) nogil: */ /* function exit code */ } /* "View.MemoryView":1131 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i */ static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) { int __pyx_v_i; Py_ssize_t __pyx_v_size; Py_ssize_t __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1134 * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i * cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<< * * for i in range(ndim): */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_size = __pyx_t_1; /* "View.MemoryView":1136 * cdef Py_ssize_t size = src.memview.view.itemsize * * for i in range(ndim): # <<<<<<<<<<<<<< * size *= src.shape[i] * */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1137 * * for i in range(ndim): * size *= src.shape[i] # <<<<<<<<<<<<<< * * return size */ __pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i])); } /* "View.MemoryView":1139 * size *= src.shape[i] * * return size # <<<<<<<<<<<<<< * * @cname('__pyx_fill_contig_strides_array') */ __pyx_r = __pyx_v_size; goto __pyx_L0; /* "View.MemoryView":1131 * * @cname('__pyx_memoryview_slice_get_size') * cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<< * "Return the size of the memory occupied by the slice in number of bytes" * cdef int i */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1142 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) { int __pyx_v_idx; Py_ssize_t __pyx_r; int __pyx_t_1; int __pyx_t_2; int __pyx_t_3; /* "View.MemoryView":1151 * cdef int idx * * if order == 'F': # <<<<<<<<<<<<<< * for idx in range(ndim): * strides[idx] = stride */ __pyx_t_1 = ((__pyx_v_order == 'F') != 0); if (__pyx_t_1) { /* "View.MemoryView":1152 * * if order == 'F': * for idx in range(ndim): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ __pyx_t_2 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_idx = __pyx_t_3; /* "View.MemoryView":1153 * if order == 'F': * for idx in range(ndim): * strides[idx] = stride # <<<<<<<<<<<<<< * stride = stride * shape[idx] * else: */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1154 * for idx in range(ndim): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< * else: * for idx in range(ndim - 1, -1, -1): */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } goto __pyx_L3; } /*else*/ { /* "View.MemoryView":1156 * stride = stride * shape[idx] * else: * for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * strides[idx] = stride * stride = stride * shape[idx] */ for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) { __pyx_v_idx = __pyx_t_2; /* "View.MemoryView":1157 * else: * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride # <<<<<<<<<<<<<< * stride = stride * shape[idx] * */ (__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride; /* "View.MemoryView":1158 * for idx in range(ndim - 1, -1, -1): * strides[idx] = stride * stride = stride * shape[idx] # <<<<<<<<<<<<<< * * return stride */ __pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx])); } } __pyx_L3:; /* "View.MemoryView":1160 * stride = stride * shape[idx] * * return stride # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_data_to_temp') */ __pyx_r = __pyx_v_stride; goto __pyx_L0; /* "View.MemoryView":1142 * * @cname('__pyx_fill_contig_strides_array') * cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<< * Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride, * int ndim, char order) nogil: */ /* function exit code */ __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1163 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) { int __pyx_v_i; void *__pyx_v_result; size_t __pyx_v_itemsize; size_t __pyx_v_size; void *__pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; struct __pyx_memoryview_obj *__pyx_t_4; int __pyx_t_5; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1174 * cdef void *result * * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef size_t size = slice_get_size(src, ndim) * */ __pyx_t_1 = __pyx_v_src->memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1175 * * cdef size_t itemsize = src.memview.view.itemsize * cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<< * * result = malloc(size) */ __pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim); /* "View.MemoryView":1177 * cdef size_t size = slice_get_size(src, ndim) * * result = malloc(size) # <<<<<<<<<<<<<< * if not result: * _err(MemoryError, NULL) */ __pyx_v_result = malloc(__pyx_v_size); /* "View.MemoryView":1178 * * result = malloc(size) * if not result: # <<<<<<<<<<<<<< * _err(MemoryError, NULL) * */ __pyx_t_2 = ((!(__pyx_v_result != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1179 * result = malloc(size) * if not result: * _err(MemoryError, NULL) # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1179; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":1182 * * * tmpslice.data = <char *> result # <<<<<<<<<<<<<< * tmpslice.memview = src.memview * for i in range(ndim): */ __pyx_v_tmpslice->data = ((char *)__pyx_v_result); /* "View.MemoryView":1183 * * tmpslice.data = <char *> result * tmpslice.memview = src.memview # <<<<<<<<<<<<<< * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] */ __pyx_t_4 = __pyx_v_src->memview; __pyx_v_tmpslice->memview = __pyx_t_4; /* "View.MemoryView":1184 * tmpslice.data = <char *> result * tmpslice.memview = src.memview * for i in range(ndim): # <<<<<<<<<<<<<< * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1185 * tmpslice.memview = src.memview * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<< * tmpslice.suboffsets[i] = -1 * */ (__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]); /* "View.MemoryView":1186 * for i in range(ndim): * tmpslice.shape[i] = src.shape[i] * tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, */ (__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1; } /* "View.MemoryView":1188 * tmpslice.suboffsets[i] = -1 * * fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<< * ndim, order) * */ __pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order); /* "View.MemoryView":1192 * * * for i in range(ndim): # <<<<<<<<<<<<<< * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 */ __pyx_t_3 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "View.MemoryView":1193 * * for i in range(ndim): * if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<< * tmpslice.strides[i] = 0 * */ __pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1194 * for i in range(ndim): * if tmpslice.shape[i] == 1: * tmpslice.strides[i] = 0 # <<<<<<<<<<<<<< * * if slice_is_contig(src, order, ndim): */ (__pyx_v_tmpslice->strides[__pyx_v_i]) = 0; goto __pyx_L8; } __pyx_L8:; } /* "View.MemoryView":1196 * tmpslice.strides[i] = 0 * * if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<< * memcpy(result, src.data, size) * else: */ __pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1197 * * if slice_is_contig(src, order, ndim): * memcpy(result, src.data, size) # <<<<<<<<<<<<<< * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) */ memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size); goto __pyx_L9; } /*else*/ { /* "View.MemoryView":1199 * memcpy(result, src.data, size) * else: * copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<< * * return result */ copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize); } __pyx_L9:; /* "View.MemoryView":1201 * copy_strided_to_strided(src, tmpslice, ndim, itemsize) * * return result # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_result; goto __pyx_L0; /* "View.MemoryView":1163 * * @cname('__pyx_memoryview_copy_data_to_temp') * cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<< * __Pyx_memviewslice *tmpslice, * char order, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = NULL; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1206 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_extents", 0); /* "View.MemoryView":1209 * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % * (i, extent1, extent2)) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err_dim') */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1209; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1); __Pyx_GIVEREF(__pyx_t_1); PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_1 = 0; __pyx_t_2 = 0; __pyx_t_3 = 0; /* "View.MemoryView":1208 * cdef int _err_extents(int i, Py_ssize_t extent1, * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<< * (i, extent1, extent2)) * */ __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1208; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1206 * * @cname('__pyx_memoryview_err_extents') * cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<< * Py_ssize_t extent2) except -1 with gil: * raise ValueError("got differing extents in dimension %d (got %d and %d)" % */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1212 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err_dim", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1213 * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: * raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_err') */ __pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyUnicode_Format(__pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_INCREF(__pyx_v_error); __pyx_t_3 = __pyx_v_error; __pyx_t_2 = NULL; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_2 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_2)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_2); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); } } if (!__pyx_t_2) { __pyx_t_1 = __Pyx_PyObject_CallOneArg(__pyx_t_3, __pyx_t_4); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); } else { __pyx_t_5 = PyTuple_New(1+1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_2); __pyx_t_2 = NULL; PyTuple_SET_ITEM(__pyx_t_5, 0+1, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_1, 0, 0, 0); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1213; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1212 * * @cname('__pyx_memoryview_err_dim') * cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii') % dim) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1216 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) { int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("_err", 0); __Pyx_INCREF(__pyx_v_error); /* "View.MemoryView":1217 * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: # <<<<<<<<<<<<<< * raise error(msg.decode('ascii')) * else: */ __pyx_t_1 = ((__pyx_v_msg != NULL) != 0); if (__pyx_t_1) { /* "View.MemoryView":1218 * cdef int _err(object error, char *msg) except -1 with gil: * if msg != NULL: * raise error(msg.decode('ascii')) # <<<<<<<<<<<<<< * else: * raise error */ __pyx_t_3 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_INCREF(__pyx_v_error); __pyx_t_4 = __pyx_v_error; __pyx_t_5 = NULL; if (CYTHON_COMPILING_IN_CPYTHON && unlikely(PyMethod_Check(__pyx_t_4))) { __pyx_t_5 = PyMethod_GET_SELF(__pyx_t_4); if (likely(__pyx_t_5)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_4); __Pyx_INCREF(__pyx_t_5); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_4, function); } } if (!__pyx_t_5) { __pyx_t_2 = __Pyx_PyObject_CallOneArg(__pyx_t_4, __pyx_t_3); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_2); } else { __pyx_t_6 = PyTuple_New(1+1); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_5); __pyx_t_5 = NULL; PyTuple_SET_ITEM(__pyx_t_6, 0+1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_6, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; } __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /*else*/ { /* "View.MemoryView":1220 * raise error(msg.decode('ascii')) * else: * raise error # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_copy_contents') */ __Pyx_Raise(__pyx_v_error, 0, 0, 0); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } /* "View.MemoryView":1216 * * @cname('__pyx_memoryview_err') * cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<< * if msg != NULL: * raise error(msg.decode('ascii')) */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __Pyx_XDECREF(__pyx_v_error); __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif return __pyx_r; } /* "View.MemoryView":1223 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) { void *__pyx_v_tmpdata; size_t __pyx_v_itemsize; int __pyx_v_i; char __pyx_v_order; int __pyx_v_broadcasting; int __pyx_v_direct_copy; __Pyx_memviewslice __pyx_v_tmp; int __pyx_v_ndim; int __pyx_r; Py_ssize_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; int __pyx_t_4; int __pyx_t_5; void *__pyx_t_6; int __pyx_t_7; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; /* "View.MemoryView":1231 * Check for overlapping memory and verify the shapes. * """ * cdef void *tmpdata = NULL # <<<<<<<<<<<<<< * cdef size_t itemsize = src.memview.view.itemsize * cdef int i */ __pyx_v_tmpdata = NULL; /* "View.MemoryView":1232 * """ * cdef void *tmpdata = NULL * cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<< * cdef int i * cdef char order = get_best_order(&src, src_ndim) */ __pyx_t_1 = __pyx_v_src.memview->view.itemsize; __pyx_v_itemsize = __pyx_t_1; /* "View.MemoryView":1234 * cdef size_t itemsize = src.memview.view.itemsize * cdef int i * cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<< * cdef bint broadcasting = False * cdef bint direct_copy = False */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim); /* "View.MemoryView":1235 * cdef int i * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False # <<<<<<<<<<<<<< * cdef bint direct_copy = False * cdef __Pyx_memviewslice tmp */ __pyx_v_broadcasting = 0; /* "View.MemoryView":1236 * cdef char order = get_best_order(&src, src_ndim) * cdef bint broadcasting = False * cdef bint direct_copy = False # <<<<<<<<<<<<<< * cdef __Pyx_memviewslice tmp * */ __pyx_v_direct_copy = 0; /* "View.MemoryView":1239 * cdef __Pyx_memviewslice tmp * * if src_ndim < dst_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: */ __pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1240 * * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<< * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim); goto __pyx_L3; } /* "View.MemoryView":1241 * if src_ndim < dst_ndim: * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: # <<<<<<<<<<<<<< * broadcast_leading(&dst, dst_ndim, src_ndim) * */ __pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1242 * broadcast_leading(&src, src_ndim, dst_ndim) * elif dst_ndim < src_ndim: * broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<< * * cdef int ndim = max(src_ndim, dst_ndim) */ __pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":1244 * broadcast_leading(&dst, dst_ndim, src_ndim) * * cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<< * * for i in range(ndim): */ __pyx_t_3 = __pyx_v_dst_ndim; __pyx_t_4 = __pyx_v_src_ndim; if (((__pyx_t_3 > __pyx_t_4) != 0)) { __pyx_t_5 = __pyx_t_3; } else { __pyx_t_5 = __pyx_t_4; } __pyx_v_ndim = __pyx_t_5; /* "View.MemoryView":1246 * cdef int ndim = max(src_ndim, dst_ndim) * * for i in range(ndim): # <<<<<<<<<<<<<< * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: */ __pyx_t_5 = __pyx_v_ndim; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1247 * * for i in range(ndim): * if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<< * if src.shape[i] == 1: * broadcasting = True */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0); if (__pyx_t_2) { /* "View.MemoryView":1248 * for i in range(ndim): * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: # <<<<<<<<<<<<<< * broadcasting = True * src.strides[i] = 0 */ __pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0); if (__pyx_t_2) { /* "View.MemoryView":1249 * if src.shape[i] != dst.shape[i]: * if src.shape[i] == 1: * broadcasting = True # <<<<<<<<<<<<<< * src.strides[i] = 0 * else: */ __pyx_v_broadcasting = 1; /* "View.MemoryView":1250 * if src.shape[i] == 1: * broadcasting = True * src.strides[i] = 0 # <<<<<<<<<<<<<< * else: * _err_extents(i, dst.shape[i], src.shape[i]) */ (__pyx_v_src.strides[__pyx_v_i]) = 0; goto __pyx_L7; } /*else*/ { /* "View.MemoryView":1252 * src.strides[i] = 0 * else: * _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<< * * if src.suboffsets[i] >= 0: */ __pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1252; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } __pyx_L7:; goto __pyx_L6; } __pyx_L6:; /* "View.MemoryView":1254 * _err_extents(i, dst.shape[i], src.shape[i]) * * if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<< * _err_dim(ValueError, "Dimension %d is not direct", i) * */ __pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0); if (__pyx_t_2) { /* "View.MemoryView":1255 * * if src.suboffsets[i] >= 0: * _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<< * * if slices_overlap(&src, &dst, ndim, itemsize): */ __pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1255; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L8; } __pyx_L8:; } /* "View.MemoryView":1257 * _err_dim(ValueError, "Dimension %d is not direct", i) * * if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<< * * if not slice_is_contig(&src, order, ndim): */ __pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0); if (__pyx_t_2) { /* "View.MemoryView":1259 * if slices_overlap(&src, &dst, ndim, itemsize): * * if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<< * order = get_best_order(&dst, ndim) * */ __pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1260 * * if not slice_is_contig(&src, order, ndim): * order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<< * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) */ __pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim); goto __pyx_L10; } __pyx_L10:; /* "View.MemoryView":1262 * order = get_best_order(&dst, ndim) * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<< * src = tmp * */ __pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1262; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_v_tmpdata = __pyx_t_6; /* "View.MemoryView":1263 * * tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) * src = tmp # <<<<<<<<<<<<<< * * if not broadcasting: */ __pyx_v_src = __pyx_v_tmp; goto __pyx_L9; } __pyx_L9:; /* "View.MemoryView":1265 * src = tmp * * if not broadcasting: # <<<<<<<<<<<<<< * * */ __pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0); if (__pyx_t_2) { /* "View.MemoryView":1268 * * * if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): */ __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1269 * * if slice_is_contig(&src, 'C', ndim): * direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<< * elif slice_is_contig(&src, 'F', ndim): * direct_copy = slice_is_contig(&dst, 'F', ndim) */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim); goto __pyx_L12; } /* "View.MemoryView":1270 * if slice_is_contig(&src, 'C', ndim): * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<< * direct_copy = slice_is_contig(&dst, 'F', ndim) * */ __pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0); if (__pyx_t_2) { /* "View.MemoryView":1271 * direct_copy = slice_is_contig(&dst, 'C', ndim) * elif slice_is_contig(&src, 'F', ndim): * direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<< * * if direct_copy: */ __pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim); goto __pyx_L12; } __pyx_L12:; /* "View.MemoryView":1273 * direct_copy = slice_is_contig(&dst, 'F', ndim) * * if direct_copy: # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_2 = (__pyx_v_direct_copy != 0); if (__pyx_t_2) { /* "View.MemoryView":1275 * if direct_copy: * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1276 * * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) */ memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim)); /* "View.MemoryView":1277 * refcount_copying(&dst, dtype_is_object, ndim, False) * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * free(tmpdata) * return 0 */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1278 * memcpy(dst.data, src.data, slice_get_size(&src, ndim)) * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1279 * refcount_copying(&dst, dtype_is_object, ndim, True) * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * if order == 'F' == get_best_order(&dst, ndim): */ __pyx_r = 0; goto __pyx_L0; } goto __pyx_L11; } __pyx_L11:; /* "View.MemoryView":1281 * return 0 * * if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<< * * */ __pyx_t_2 = (__pyx_v_order == 'F'); if (__pyx_t_2) { __pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim)); } __pyx_t_7 = (__pyx_t_2 != 0); if (__pyx_t_7) { /* "View.MemoryView":1284 * * * transpose_memslice(&src) # <<<<<<<<<<<<<< * transpose_memslice(&dst) * */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1284; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":1285 * * transpose_memslice(&src) * transpose_memslice(&dst) # <<<<<<<<<<<<<< * * refcount_copying(&dst, dtype_is_object, ndim, False) */ __pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1285; __pyx_clineno = __LINE__; goto __pyx_L1_error;} goto __pyx_L14; } __pyx_L14:; /* "View.MemoryView":1287 * transpose_memslice(&dst) * * refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1288 * * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<< * refcount_copying(&dst, dtype_is_object, ndim, True) * */ copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize); /* "View.MemoryView":1289 * refcount_copying(&dst, dtype_is_object, ndim, False) * copy_strided_to_strided(&src, &dst, ndim, itemsize) * refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * free(tmpdata) */ __pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1291 * refcount_copying(&dst, dtype_is_object, ndim, True) * * free(tmpdata) # <<<<<<<<<<<<<< * return 0 * */ free(__pyx_v_tmpdata); /* "View.MemoryView":1292 * * free(tmpdata) * return 0 # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_broadcast_leading') */ __pyx_r = 0; goto __pyx_L0; /* "View.MemoryView":1223 * * @cname('__pyx_memoryview_copy_contents') * cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<< * __Pyx_memviewslice dst, * int src_ndim, int dst_ndim, */ /* function exit code */ __pyx_L1_error:; { #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } __pyx_r = -1; __pyx_L0:; return __pyx_r; } /* "View.MemoryView":1295 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim, int __pyx_v_ndim_other) { int __pyx_v_i; int __pyx_v_offset; int __pyx_t_1; int __pyx_t_2; /* "View.MemoryView":1299 * int ndim_other) nogil: * cdef int i * cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<< * * for i in range(ndim - 1, -1, -1): */ __pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim); /* "View.MemoryView":1301 * cdef int offset = ndim_other - ndim * * for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<< * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] */ for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) { __pyx_v_i = __pyx_t_1; /* "View.MemoryView":1302 * * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] # <<<<<<<<<<<<<< * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] */ (__pyx_v_mslice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->shape[__pyx_v_i]); /* "View.MemoryView":1303 * for i in range(ndim - 1, -1, -1): * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] # <<<<<<<<<<<<<< * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * */ (__pyx_v_mslice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->strides[__pyx_v_i]); /* "View.MemoryView":1304 * mslice.shape[i + offset] = mslice.shape[i] * mslice.strides[i + offset] = mslice.strides[i] * mslice.suboffsets[i + offset] = mslice.suboffsets[i] # <<<<<<<<<<<<<< * * for i in range(offset): */ (__pyx_v_mslice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_mslice->suboffsets[__pyx_v_i]); } /* "View.MemoryView":1306 * mslice.suboffsets[i + offset] = mslice.suboffsets[i] * * for i in range(offset): # <<<<<<<<<<<<<< * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] */ __pyx_t_1 = __pyx_v_offset; for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1307 * * for i in range(offset): * mslice.shape[i] = 1 # <<<<<<<<<<<<<< * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 */ (__pyx_v_mslice->shape[__pyx_v_i]) = 1; /* "View.MemoryView":1308 * for i in range(offset): * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] # <<<<<<<<<<<<<< * mslice.suboffsets[i] = -1 * */ (__pyx_v_mslice->strides[__pyx_v_i]) = (__pyx_v_mslice->strides[0]); /* "View.MemoryView":1309 * mslice.shape[i] = 1 * mslice.strides[i] = mslice.strides[0] * mslice.suboffsets[i] = -1 # <<<<<<<<<<<<<< * * */ (__pyx_v_mslice->suboffsets[__pyx_v_i]) = -1; } /* "View.MemoryView":1295 * * @cname('__pyx_memoryview_broadcast_leading') * cdef void broadcast_leading(__Pyx_memviewslice *mslice, # <<<<<<<<<<<<<< * int ndim, * int ndim_other) nogil: */ /* function exit code */ } /* "View.MemoryView":1317 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) { int __pyx_t_1; /* "View.MemoryView":1321 * * * if dtype_is_object: # <<<<<<<<<<<<<< * refcount_objects_in_slice_with_gil(dst.data, dst.shape, * dst.strides, ndim, inc) */ __pyx_t_1 = (__pyx_v_dtype_is_object != 0); if (__pyx_t_1) { /* "View.MemoryView":1322 * * if dtype_is_object: * refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<< * dst.strides, ndim, inc) * */ __pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc); goto __pyx_L3; } __pyx_L3:; /* "View.MemoryView":1317 * * @cname('__pyx_memoryview_refcount_copying') * cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<< * int ndim, bint inc) nogil: * */ /* function exit code */ } /* "View.MemoryView":1326 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { __Pyx_RefNannyDeclarations #ifdef WITH_THREAD PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); #endif __Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0); /* "View.MemoryView":1329 * Py_ssize_t *strides, int ndim, * bint inc) with gil: * refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<< * * @cname('__pyx_memoryview_refcount_objects_in_slice') */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc); /* "View.MemoryView":1326 * * @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil') * cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * bint inc) with gil: */ /* function exit code */ __Pyx_RefNannyFinishContext(); #ifdef WITH_THREAD PyGILState_Release(__pyx_gilstate_save); #endif } /* "View.MemoryView":1332 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; __Pyx_RefNannyDeclarations Py_ssize_t __pyx_t_1; Py_ssize_t __pyx_t_2; int __pyx_t_3; __Pyx_RefNannySetupContext("refcount_objects_in_slice", 0); /* "View.MemoryView":1336 * cdef Py_ssize_t i * * for i in range(shape[0]): # <<<<<<<<<<<<<< * if ndim == 1: * if inc: */ __pyx_t_1 = (__pyx_v_shape[0]); for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "View.MemoryView":1337 * * for i in range(shape[0]): * if ndim == 1: # <<<<<<<<<<<<<< * if inc: * Py_INCREF((<PyObject **> data)[0]) */ __pyx_t_3 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_3) { /* "View.MemoryView":1338 * for i in range(shape[0]): * if ndim == 1: * if inc: # <<<<<<<<<<<<<< * Py_INCREF((<PyObject **> data)[0]) * else: */ __pyx_t_3 = (__pyx_v_inc != 0); if (__pyx_t_3) { /* "View.MemoryView":1339 * if ndim == 1: * if inc: * Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * Py_DECREF((<PyObject **> data)[0]) */ Py_INCREF((((PyObject **)__pyx_v_data)[0])); goto __pyx_L6; } /*else*/ { /* "View.MemoryView":1341 * Py_INCREF((<PyObject **> data)[0]) * else: * Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<< * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, */ Py_DECREF((((PyObject **)__pyx_v_data)[0])); } __pyx_L6:; goto __pyx_L5; } /*else*/ { /* "View.MemoryView":1343 * Py_DECREF((<PyObject **> data)[0]) * else: * refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, inc) * */ __pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc); } __pyx_L5:; /* "View.MemoryView":1346 * ndim - 1, inc) * * data += strides[0] # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0])); } /* "View.MemoryView":1332 * * @cname('__pyx_memoryview_refcount_objects_in_slice') * cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, bint inc): * cdef Py_ssize_t i */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "View.MemoryView":1352 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) { /* "View.MemoryView":1355 * size_t itemsize, void *item, * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<< * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0); /* "View.MemoryView":1356 * bint dtype_is_object) nogil: * refcount_copying(dst, dtype_is_object, ndim, False) * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<< * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) */ __pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1358 * _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, * itemsize, item) * refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<< * * */ __pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1); /* "View.MemoryView":1352 * * @cname('__pyx_memoryview_slice_assign_scalar') * cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<< * size_t itemsize, void *item, * bint dtype_is_object) nogil: */ /* function exit code */ } /* "View.MemoryView":1362 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) { CYTHON_UNUSED Py_ssize_t __pyx_v_i; Py_ssize_t __pyx_v_stride; Py_ssize_t __pyx_v_extent; int __pyx_t_1; Py_ssize_t __pyx_t_2; Py_ssize_t __pyx_t_3; /* "View.MemoryView":1366 * size_t itemsize, void *item) nogil: * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<< * cdef Py_ssize_t extent = shape[0] * */ __pyx_v_stride = (__pyx_v_strides[0]); /* "View.MemoryView":1367 * cdef Py_ssize_t i * cdef Py_ssize_t stride = strides[0] * cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<< * * if ndim == 1: */ __pyx_v_extent = (__pyx_v_shape[0]); /* "View.MemoryView":1369 * cdef Py_ssize_t extent = shape[0] * * if ndim == 1: # <<<<<<<<<<<<<< * for i in range(extent): * memcpy(data, item, itemsize) */ __pyx_t_1 = ((__pyx_v_ndim == 1) != 0); if (__pyx_t_1) { /* "View.MemoryView":1370 * * if ndim == 1: * for i in range(extent): # <<<<<<<<<<<<<< * memcpy(data, item, itemsize) * data += stride */ __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1371 * if ndim == 1: * for i in range(extent): * memcpy(data, item, itemsize) # <<<<<<<<<<<<<< * data += stride * else: */ memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize); /* "View.MemoryView":1372 * for i in range(extent): * memcpy(data, item, itemsize) * data += stride # <<<<<<<<<<<<<< * else: * for i in range(extent): */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } goto __pyx_L3; } /*else*/ { /* "View.MemoryView":1374 * data += stride * else: * for i in range(extent): # <<<<<<<<<<<<<< * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) */ __pyx_t_2 = __pyx_v_extent; for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_i = __pyx_t_3; /* "View.MemoryView":1375 * else: * for i in range(extent): * _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<< * ndim - 1, itemsize, item) * data += stride */ __pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item); /* "View.MemoryView":1377 * _slice_assign_scalar(data, shape + 1, strides + 1, * ndim - 1, itemsize, item) * data += stride # <<<<<<<<<<<<<< * * */ __pyx_v_data = (__pyx_v_data + __pyx_v_stride); } } __pyx_L3:; /* "View.MemoryView":1362 * * @cname('__pyx_memoryview__slice_assign_scalar') * cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<< * Py_ssize_t *strides, int ndim, * size_t itemsize, void *item) nogil: */ /* function exit code */ } static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_array_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_array_obj *)o); p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None); p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None); if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_array(PyObject *o) { struct __pyx_array_obj *p = (struct __pyx_array_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_array___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->mode); Py_CLEAR(p->_format); (*Py_TYPE(o)->tp_free)(o); } static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_array___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) { PyObject *v = PyObject_GenericGetAttr(o, n); if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); v = __pyx_array___getattr__(o, n); } return v; } static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) { return get_memview(o); } static PyMethodDef __pyx_methods_array[] = { {"__getattr__", (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_array[] = { {(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_array = { 0, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_array, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_array = { 0, /*mp_length*/ __pyx_array___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_array, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_array = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_array_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_array = { PyVarObject_HEAD_INIT(0, 0) "_interpolate3d.array", /*tp_name*/ sizeof(struct __pyx_array_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_array, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #else 0, /*reserved*/ #endif 0, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_array, /*tp_as_sequence*/ &__pyx_tp_as_mapping_array, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ __pyx_tp_getattro_array, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_array, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/ 0, /*tp_doc*/ 0, /*tp_traverse*/ 0, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_array, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_array, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_array, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) { struct __pyx_MemviewEnum_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_MemviewEnum_obj *)o); p->name = Py_None; Py_INCREF(Py_None); return o; } static void __pyx_tp_dealloc_Enum(PyObject *o) { struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); Py_CLEAR(p->name); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) { int e; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; if (p->name) { e = (*v)(p->name, a); if (e) return e; } return 0; } static int __pyx_tp_clear_Enum(PyObject *o) { PyObject* tmp; struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o; tmp = ((PyObject*)p->name); p->name = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); return 0; } static PyMethodDef __pyx_methods_Enum[] = { {0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_MemviewEnum = { PyVarObject_HEAD_INIT(0, 0) "_interpolate3d.Enum", /*tp_name*/ sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_Enum, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #else 0, /*reserved*/ #endif __pyx_MemviewEnum___repr__, /*tp_repr*/ 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ 0, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_Enum, /*tp_traverse*/ __pyx_tp_clear_Enum, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_Enum, /*tp_methods*/ 0, /*tp_members*/ 0, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ __pyx_MemviewEnum___init__, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_Enum, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview; static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryview_obj *p; PyObject *o; if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) { o = (*t->tp_alloc)(t, 0); } else { o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0); } if (unlikely(!o)) return 0; p = ((struct __pyx_memoryview_obj *)o); p->__pyx_vtab = __pyx_vtabptr_memoryview; p->obj = Py_None; Py_INCREF(Py_None); p->_size = Py_None; Py_INCREF(Py_None); p->_array_interface = Py_None; Py_INCREF(Py_None); p->view.obj = NULL; if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) { Py_DECREF(o); o = 0; } return o; } static void __pyx_tp_dealloc_memoryview(PyObject *o) { struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryview___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->obj); Py_CLEAR(p->_size); Py_CLEAR(p->_array_interface); (*Py_TYPE(o)->tp_free)(o); } static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; if (p->obj) { e = (*v)(p->obj, a); if (e) return e; } if (p->_size) { e = (*v)(p->_size, a); if (e) return e; } if (p->_array_interface) { e = (*v)(p->_array_interface, a); if (e) return e; } if (p->view.obj) { e = (*v)(p->view.obj, a); if (e) return e; } return 0; } static int __pyx_tp_clear_memoryview(PyObject *o) { PyObject* tmp; struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o; tmp = ((PyObject*)p->obj); p->obj = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_size); p->_size = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); tmp = ((PyObject*)p->_array_interface); p->_array_interface = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); Py_CLEAR(p->view.obj); return 0; } static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) { PyObject *r; PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0; r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x); Py_DECREF(x); return r; } static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) { if (v) { return __pyx_memoryview___setitem__(o, i, v); } else { PyErr_Format(PyExc_NotImplementedError, "Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name); return -1; } } static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_transpose(o); } static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview__get__base(o); } static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_shape(o); } static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_strides(o); } static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_suboffsets(o); } static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_ndim(o); } static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_itemsize(o); } static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_nbytes(o); } static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryview_get_size(o); } static PyMethodDef __pyx_methods_memoryview[] = { {"is_c_contig", (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, 0}, {"is_f_contig", (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, 0}, {"copy", (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, 0}, {"copy_fortran", (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, 0}, {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets_memoryview[] = { {(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0}, {(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0}, {(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0}, {(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0}, {(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0}, {(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0}, {(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0}, {(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0}, {(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PySequenceMethods __pyx_tp_as_sequence_memoryview = { __pyx_memoryview___len__, /*sq_length*/ 0, /*sq_concat*/ 0, /*sq_repeat*/ __pyx_sq_item_memoryview, /*sq_item*/ 0, /*sq_slice*/ 0, /*sq_ass_item*/ 0, /*sq_ass_slice*/ 0, /*sq_contains*/ 0, /*sq_inplace_concat*/ 0, /*sq_inplace_repeat*/ }; static PyMappingMethods __pyx_tp_as_mapping_memoryview = { __pyx_memoryview___len__, /*mp_length*/ __pyx_memoryview___getitem__, /*mp_subscript*/ __pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/ }; static PyBufferProcs __pyx_tp_as_buffer_memoryview = { #if PY_MAJOR_VERSION < 3 0, /*bf_getreadbuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getwritebuffer*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getsegcount*/ #endif #if PY_MAJOR_VERSION < 3 0, /*bf_getcharbuffer*/ #endif __pyx_memoryview_getbuffer, /*bf_getbuffer*/ 0, /*bf_releasebuffer*/ }; static PyTypeObject __pyx_type___pyx_memoryview = { PyVarObject_HEAD_INIT(0, 0) "_interpolate3d.memoryview", /*tp_name*/ sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc_memoryview, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #else 0, /*reserved*/ #endif __pyx_memoryview___repr__, /*tp_repr*/ 0, /*tp_as_number*/ &__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/ &__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ __pyx_memoryview___str__, /*tp_str*/ 0, /*tp_getattro*/ 0, /*tp_setattro*/ &__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ 0, /*tp_doc*/ __pyx_tp_traverse_memoryview, /*tp_traverse*/ __pyx_tp_clear_memoryview, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods_memoryview, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets_memoryview, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new_memoryview, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice; static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) { struct __pyx_memoryviewslice_obj *p; PyObject *o = __pyx_tp_new_memoryview(t, a, k); if (unlikely(!o)) return 0; p = ((struct __pyx_memoryviewslice_obj *)o); p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice; p->from_object = Py_None; Py_INCREF(Py_None); p->from_slice.memview = NULL; return o; } static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) { struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; #if PY_VERSION_HEX >= 0x030400a1 if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) { if (PyObject_CallFinalizerFromDealloc(o)) return; } #endif PyObject_GC_UnTrack(o); { PyObject *etype, *eval, *etb; PyErr_Fetch(&etype, &eval, &etb); ++Py_REFCNT(o); __pyx_memoryviewslice___dealloc__(o); --Py_REFCNT(o); PyErr_Restore(etype, eval, etb); } Py_CLEAR(p->from_object); PyObject_GC_Track(o); __pyx_tp_dealloc_memoryview(o); } static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) { int e; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e; if (p->from_object) { e = (*v)(p->from_object, a); if (e) return e; } return 0; } static int __pyx_tp_clear__memoryviewslice(PyObject *o) { PyObject* tmp; struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o; __pyx_tp_clear_memoryview(o); tmp = ((PyObject*)p->from_object); p->from_object = Py_None; Py_INCREF(Py_None); Py_XDECREF(tmp); __PYX_XDEC_MEMVIEW(&p->from_slice, 1); return 0; } static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) { return __pyx_memoryviewslice__get__base(o); } static PyMethodDef __pyx_methods__memoryviewslice[] = { {0, 0, 0, 0} }; static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = { {(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0}, {0, 0, 0, 0, 0} }; static PyTypeObject __pyx_type___pyx_memoryviewslice = { PyVarObject_HEAD_INIT(0, 0) "_interpolate3d._memoryviewslice", /*tp_name*/ sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/ 0, /*tp_itemsize*/ __pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/ 0, /*tp_print*/ 0, /*tp_getattr*/ 0, /*tp_setattr*/ #if PY_MAJOR_VERSION < 3 0, /*tp_compare*/ #else 0, /*reserved*/ #endif #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___repr__, /*tp_repr*/ #else 0, /*tp_repr*/ #endif 0, /*tp_as_number*/ 0, /*tp_as_sequence*/ 0, /*tp_as_mapping*/ 0, /*tp_hash*/ 0, /*tp_call*/ #if CYTHON_COMPILING_IN_PYPY __pyx_memoryview___str__, /*tp_str*/ #else 0, /*tp_str*/ #endif 0, /*tp_getattro*/ 0, /*tp_setattro*/ 0, /*tp_as_buffer*/ Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/ "Internal class for passing memoryview slices to Python", /*tp_doc*/ __pyx_tp_traverse__memoryviewslice, /*tp_traverse*/ __pyx_tp_clear__memoryviewslice, /*tp_clear*/ 0, /*tp_richcompare*/ 0, /*tp_weaklistoffset*/ 0, /*tp_iter*/ 0, /*tp_iternext*/ __pyx_methods__memoryviewslice, /*tp_methods*/ 0, /*tp_members*/ __pyx_getsets__memoryviewslice, /*tp_getset*/ 0, /*tp_base*/ 0, /*tp_dict*/ 0, /*tp_descr_get*/ 0, /*tp_descr_set*/ 0, /*tp_dictoffset*/ 0, /*tp_init*/ 0, /*tp_alloc*/ __pyx_tp_new__memoryviewslice, /*tp_new*/ 0, /*tp_free*/ 0, /*tp_is_gc*/ 0, /*tp_bases*/ 0, /*tp_mro*/ 0, /*tp_cache*/ 0, /*tp_subclasses*/ 0, /*tp_weaklist*/ 0, /*tp_del*/ 0, /*tp_version_tag*/ #if PY_VERSION_HEX >= 0x030400a1 0, /*tp_finalize*/ #endif }; static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 static struct PyModuleDef __pyx_moduledef = { #if PY_VERSION_HEX < 0x03020000 { PyObject_HEAD_INIT(NULL) NULL, 0, NULL }, #else PyModuleDef_HEAD_INIT, #endif "_interpolate3d", 0, /* m_doc */ -1, /* m_size */ __pyx_methods /* m_methods */, NULL, /* m_reload */ NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_kp_s_, __pyx_k_, sizeof(__pyx_k_), 0, 0, 1, 0}, {&__pyx_n_s_AttributeError, __pyx_k_AttributeError, sizeof(__pyx_k_AttributeError), 0, 0, 1, 1}, {&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0}, {&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0}, {&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0}, {&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1}, {&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0}, {&__pyx_kp_s_Expected_at_least_d_arguments, __pyx_k_Expected_at_least_d_arguments, sizeof(__pyx_k_Expected_at_least_d_arguments), 0, 0, 1, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_kp_s_Function_call_with_ambiguous_arg, __pyx_k_Function_call_with_ambiguous_arg, sizeof(__pyx_k_Function_call_with_ambiguous_arg), 0, 0, 1, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1}, {&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0}, {&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0}, {&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0}, {&__pyx_kp_s_No_matching_signature_found, __pyx_k_No_matching_signature_found, sizeof(__pyx_k_No_matching_signature_found), 0, 0, 1, 0}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1}, {&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1}, {&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_kp_s__3, __pyx_k__3, sizeof(__pyx_k__3), 0, 0, 1, 0}, {&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1}, {&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1}, {&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1}, {&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1}, {&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_defaults, __pyx_k_defaults, sizeof(__pyx_k_defaults), 0, 0, 1, 1}, {&__pyx_n_s_double, __pyx_k_double, sizeof(__pyx_k_double), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1}, {&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1}, {&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1}, {&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1}, {&__pyx_n_s_float, __pyx_k_float, sizeof(__pyx_k_float), 0, 0, 1, 1}, {&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1}, {&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1}, {&__pyx_n_u_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 1, 0, 1}, {&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_interpolate3d, __pyx_k_interpolate3d, sizeof(__pyx_k_interpolate3d), 0, 0, 1, 1}, {&__pyx_n_s_interpolate3d_2, __pyx_k_interpolate3d_2, sizeof(__pyx_k_interpolate3d_2), 0, 0, 1, 1}, {&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1}, {&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0}, {&__pyx_n_s_kind, __pyx_k_kind, sizeof(__pyx_k_kind), 0, 0, 1, 1}, {&__pyx_n_s_kwargs, __pyx_k_kwargs, sizeof(__pyx_k_kwargs), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1}, {&__pyx_n_s_mid_ind, __pyx_k_mid_ind, sizeof(__pyx_k_mid_ind), 0, 0, 1, 1}, {&__pyx_kp_s_mnt_pact_ds381_seren3_src_analy, __pyx_k_mnt_pact_ds381_seren3_src_analy, sizeof(__pyx_k_mnt_pact_ds381_seren3_src_analy), 0, 0, 1, 0}, {&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1}, {&__pyx_n_s_n, __pyx_k_n, sizeof(__pyx_k_n), 0, 0, 1, 1}, {&__pyx_n_s_n_x_vals, __pyx_k_n_x_vals, sizeof(__pyx_k_n_x_vals), 0, 0, 1, 1}, {&__pyx_n_s_n_y_vals, __pyx_k_n_y_vals, sizeof(__pyx_k_n_y_vals), 0, 0, 1, 1}, {&__pyx_n_s_n_z_vals, __pyx_k_n_z_vals, sizeof(__pyx_k_n_z_vals), 0, 0, 1, 1}, {&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1}, {&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1}, {&__pyx_n_s_ndarray, __pyx_k_ndarray, sizeof(__pyx_k_ndarray), 0, 0, 1, 1}, {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, {&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1}, {&__pyx_n_s_ord, __pyx_k_ord, sizeof(__pyx_k_ord), 0, 0, 1, 1}, {&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1}, {&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1}, {&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_result_array, __pyx_k_result_array, sizeof(__pyx_k_result_array), 0, 0, 1, 1}, {&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1}, {&__pyx_n_s_signatures, __pyx_k_signatures, sizeof(__pyx_k_signatures), 0, 0, 1, 1}, {&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1}, {&__pyx_n_s_split, __pyx_k_split, sizeof(__pyx_k_split), 0, 0, 1, 1}, {&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1}, {&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1}, {&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1}, {&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0}, {&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0}, {&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1}, {&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1}, {&__pyx_n_s_sys, __pyx_k_sys, sizeof(__pyx_k_sys), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0}, {&__pyx_kp_s_unable_to_allocate_shape_and_str, __pyx_k_unable_to_allocate_shape_and_str, sizeof(__pyx_k_unable_to_allocate_shape_and_str), 0, 0, 1, 0}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1}, {&__pyx_n_s_v0, __pyx_k_v0, sizeof(__pyx_k_v0), 0, 0, 1, 1}, {&__pyx_n_s_v00, __pyx_k_v00, sizeof(__pyx_k_v00), 0, 0, 1, 1}, {&__pyx_n_s_v000, __pyx_k_v000, sizeof(__pyx_k_v000), 0, 0, 1, 1}, {&__pyx_n_s_v001, __pyx_k_v001, sizeof(__pyx_k_v001), 0, 0, 1, 1}, {&__pyx_n_s_v01, __pyx_k_v01, sizeof(__pyx_k_v01), 0, 0, 1, 1}, {&__pyx_n_s_v010, __pyx_k_v010, sizeof(__pyx_k_v010), 0, 0, 1, 1}, {&__pyx_n_s_v011, __pyx_k_v011, sizeof(__pyx_k_v011), 0, 0, 1, 1}, {&__pyx_n_s_v1, __pyx_k_v1, sizeof(__pyx_k_v1), 0, 0, 1, 1}, {&__pyx_n_s_v10, __pyx_k_v10, sizeof(__pyx_k_v10), 0, 0, 1, 1}, {&__pyx_n_s_v100, __pyx_k_v100, sizeof(__pyx_k_v100), 0, 0, 1, 1}, {&__pyx_n_s_v101, __pyx_k_v101, sizeof(__pyx_k_v101), 0, 0, 1, 1}, {&__pyx_n_s_v11, __pyx_k_v11, sizeof(__pyx_k_v11), 0, 0, 1, 1}, {&__pyx_n_s_v110, __pyx_k_v110, sizeof(__pyx_k_v110), 0, 0, 1, 1}, {&__pyx_n_s_v111, __pyx_k_v111, sizeof(__pyx_k_v111), 0, 0, 1, 1}, {&__pyx_n_s_vals, __pyx_k_vals, sizeof(__pyx_k_vals), 0, 0, 1, 1}, {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, {&__pyx_n_s_x_bot_ind, __pyx_k_x_bot_ind, sizeof(__pyx_k_x_bot_ind), 0, 0, 1, 1}, {&__pyx_n_s_x_fac, __pyx_k_x_fac, sizeof(__pyx_k_x_fac), 0, 0, 1, 1}, {&__pyx_n_s_x_top_ind, __pyx_k_x_top_ind, sizeof(__pyx_k_x_top_ind), 0, 0, 1, 1}, {&__pyx_n_s_x_vals, __pyx_k_x_vals, sizeof(__pyx_k_x_vals), 0, 0, 1, 1}, {&__pyx_n_s_xi, __pyx_k_xi, sizeof(__pyx_k_xi), 0, 0, 1, 1}, {&__pyx_n_s_y, __pyx_k_y, sizeof(__pyx_k_y), 0, 0, 1, 1}, {&__pyx_n_s_y_bot_ind, __pyx_k_y_bot_ind, sizeof(__pyx_k_y_bot_ind), 0, 0, 1, 1}, {&__pyx_n_s_y_fac, __pyx_k_y_fac, sizeof(__pyx_k_y_fac), 0, 0, 1, 1}, {&__pyx_n_s_y_top_ind, __pyx_k_y_top_ind, sizeof(__pyx_k_y_top_ind), 0, 0, 1, 1}, {&__pyx_n_s_y_vals, __pyx_k_y_vals, sizeof(__pyx_k_y_vals), 0, 0, 1, 1}, {&__pyx_n_s_yi, __pyx_k_yi, sizeof(__pyx_k_yi), 0, 0, 1, 1}, {&__pyx_n_s_z, __pyx_k_z, sizeof(__pyx_k_z), 0, 0, 1, 1}, {&__pyx_n_s_z_bot_ind, __pyx_k_z_bot_ind, sizeof(__pyx_k_z_bot_ind), 0, 0, 1, 1}, {&__pyx_n_s_z_fac, __pyx_k_z_fac, sizeof(__pyx_k_z_fac), 0, 0, 1, 1}, {&__pyx_n_s_z_top_ind, __pyx_k_z_top_ind, sizeof(__pyx_k_z_top_ind), 0, 0, 1, 1}, {&__pyx_n_s_z_vals, __pyx_k_z_vals, sizeof(__pyx_k_z_vals), 0, 0, 1, 1}, {&__pyx_n_s_zi, __pyx_k_zi, sizeof(__pyx_k_zi), 0, 0, 1, 1}, {&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_AttributeError = __Pyx_GetBuiltinName(__pyx_n_s_AttributeError); if (!__pyx_builtin_AttributeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_ord = __Pyx_GetBuiltinName(__pyx_n_s_ord); if (!__pyx_builtin_ord) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 231; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 569; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 788; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_s_); if (unlikely(!__pyx_tuple__2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_s__3); if (unlikely(!__pyx_tuple__4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":218 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 218; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":222 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 222; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":260 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 260; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":802 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 802; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":806 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 806; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); /* "../../../../lustre/scratch/astro/ds381/yt-x86_64/lib/python2.7/site-packages/Cython-0.22-py2.7-linux-x86_64.egg/Cython/Includes/numpy/__init__.pxd":826 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__12); __Pyx_GIVEREF(__pyx_tuple__12); /* "View.MemoryView":127 * * if not self.ndim: * raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<< * * if itemsize <= 0: */ __pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); /* "View.MemoryView":130 * * if itemsize <= 0: * raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<< * * if isinstance(format, unicode): */ __pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__14); __Pyx_GIVEREF(__pyx_tuple__14); /* "View.MemoryView":142 * * if not self._shape: * raise MemoryError("unable to allocate shape and strides.") # <<<<<<<<<<<<<< * * */ __pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_and_str); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 142; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); /* "View.MemoryView":170 * self.data = <char *>malloc(self.len) * if not self.data: * raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<< * * if self.dtype_is_object: */ __pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__16); __Pyx_GIVEREF(__pyx_tuple__16); /* "View.MemoryView":186 * bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS * if not (flags & bufmode): * raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<< * info.buf = self.data * info.len = self.len */ __pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 186; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__17); __Pyx_GIVEREF(__pyx_tuple__17); /* "View.MemoryView":445 * result = struct.unpack(self.view.format, bytesitem) * except struct.error: * raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<< * else: * if len(self.view.format) == 1: */ __pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 445; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__18); __Pyx_GIVEREF(__pyx_tuple__18); /* "View.MemoryView":521 * if self.view.strides == NULL: * * raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<< * * return tuple([stride for stride in self.view.strides[:self.view.ndim]]) */ __pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 521; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__19); __Pyx_GIVEREF(__pyx_tuple__19); /* "View.MemoryView":529 * def __get__(self): * if self.view.suboffsets == NULL: * return (-1,) * self.view.ndim # <<<<<<<<<<<<<< * * return tuple([suboffset for suboffset in self.view.suboffsets[:self.view.ndim]]) */ __pyx_tuple__20 = PyTuple_New(1); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__20); __Pyx_INCREF(__pyx_int_neg_1); PyTuple_SET_ITEM(__pyx_tuple__20, 0, __pyx_int_neg_1); __Pyx_GIVEREF(__pyx_int_neg_1); __Pyx_GIVEREF(__pyx_tuple__20); /* "View.MemoryView":638 * if item is Ellipsis: * if not seen_ellipsis: * result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<< * seen_ellipsis = True * else: */ __pyx_slice__21 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__21)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 638; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__21); __Pyx_GIVEREF(__pyx_slice__21); /* "View.MemoryView":641 * seen_ellipsis = True * else: * result.append(slice(None)) # <<<<<<<<<<<<<< * have_slices = True * else: */ __pyx_slice__22 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__22)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 641; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__22); __Pyx_GIVEREF(__pyx_slice__22); /* "View.MemoryView":652 * nslices = ndim - len(result) * if nslices: * result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<< * * return have_slices or nslices, tuple(result) */ __pyx_slice__23 = PySlice_New(Py_None, Py_None, Py_None); if (unlikely(!__pyx_slice__23)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 652; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_slice__23); __Pyx_GIVEREF(__pyx_slice__23); /* "View.MemoryView":659 * for suboffset in suboffsets[:ndim]: * if suboffset >= 0: * raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<< * * */ __pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 659; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__24); __Pyx_GIVEREF(__pyx_tuple__24); /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ __pyx_tuple__25 = PyTuple_Pack(40, __pyx_n_s_n, __pyx_n_s_x, __pyx_n_s_y, __pyx_n_s_z, __pyx_n_s_n_x_vals, __pyx_n_s_x_vals, __pyx_n_s_n_y_vals, __pyx_n_s_y_vals, __pyx_n_s_n_z_vals, __pyx_n_s_z_vals, __pyx_n_s_vals, __pyx_n_s_result_array, __pyx_n_s_x_top_ind, __pyx_n_s_x_bot_ind, __pyx_n_s_y_top_ind, __pyx_n_s_y_bot_ind, __pyx_n_s_z_top_ind, __pyx_n_s_z_bot_ind, __pyx_n_s_mid_ind, __pyx_n_s_x_fac, __pyx_n_s_y_fac, __pyx_n_s_z_fac, __pyx_n_s_v0, __pyx_n_s_v1, __pyx_n_s_v00, __pyx_n_s_v01, __pyx_n_s_v10, __pyx_n_s_v11, __pyx_n_s_v000, __pyx_n_s_v001, __pyx_n_s_v010, __pyx_n_s_v011, __pyx_n_s_v100, __pyx_n_s_v101, __pyx_n_s_v110, __pyx_n_s_v111, __pyx_n_s_xi, __pyx_n_s_yi, __pyx_n_s_zi, __pyx_n_s_i); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__25); __Pyx_GIVEREF(__pyx_tuple__25); __pyx_codeobj__26 = (PyObject*)__Pyx_PyCode_New(12, 0, 40, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__25, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_mnt_pact_ds381_seren3_src_analy, __pyx_n_s_interpolate3d, 14, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__26)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /* "View.MemoryView":276 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__27); __Pyx_GIVEREF(__pyx_tuple__27); /* "View.MemoryView":277 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_tuple__28 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__28); __Pyx_GIVEREF(__pyx_tuple__28); /* "View.MemoryView":278 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__29 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__29); __Pyx_GIVEREF(__pyx_tuple__29); /* "View.MemoryView":281 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_tuple__30 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__30); __Pyx_GIVEREF(__pyx_tuple__30); /* "View.MemoryView":282 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_tuple__31); __Pyx_GIVEREF(__pyx_tuple__31); __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { /* InitThreads.init */ #ifdef WITH_THREAD PyEval_InitThreads(); #endif if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_interpolate3d(void); /*proto*/ PyMODINIT_FUNC init_interpolate3d(void) #else PyMODINIT_FUNC PyInit__interpolate3d(void); /*proto*/ PyMODINIT_FUNC PyInit__interpolate3d(void) #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_lineno = 0; const char *__pyx_filename = NULL; int __pyx_clineno = 0; __Pyx_RefNannyDeclarations #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__interpolate3d(void)", 0); if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #ifdef __Pyx_CyFunction_USED if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("_interpolate3d", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; /*--- Initialize various global constants etc. ---*/ if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} #endif if (__pyx_module_is_main__interpolate3d) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}; } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} if (!PyDict_GetItemString(modules, "_interpolate3d")) { if (unlikely(PyDict_SetItemString(modules, "_interpolate3d", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} } } #endif /*--- Builtin init code ---*/ if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Constants init code ---*/ if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Global init code ---*/ generic = Py_None; Py_INCREF(Py_None); strided = Py_None; Py_INCREF(Py_None); indirect = Py_None; Py_INCREF(Py_None); contiguous = Py_None; Py_INCREF(Py_None); indirect_contiguous = Py_None; Py_INCREF(Py_None); /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 99; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_array.tp_print = 0; __pyx_array_type = &__pyx_type___pyx_array; if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 269; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_MemviewEnum.tp_print = 0; __pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum; __pyx_vtabptr_memoryview = &__pyx_vtable_memoryview; __pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer; __pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice; __pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment; __pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar; __pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed; __pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object; __pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object; if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_memoryview.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 302; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_memoryview_type = &__pyx_type___pyx_memoryview; __pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice; __pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview; __pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object; __pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object; __pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type; if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_type___pyx_memoryviewslice.tp_print = 0; if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 921; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice; /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 168; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 172; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 181; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;} /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ /* "_interpolate3d.pyx":3 * cimport numpy as np * cimport cython * import numpy as np # <<<<<<<<<<<<<< * import sys * */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 3; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "_interpolate3d.pyx":4 * cimport cython * import numpy as np * import sys # <<<<<<<<<<<<<< * * from cython cimport floating */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_sys, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_sys, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 4; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "_interpolate3d.pyx":14 * @cython.boundscheck(False) * @cython.wraparound(False) * def interpolate3d(int n, # <<<<<<<<<<<<<< * np.ndarray[floating,ndim=1] x, * np.ndarray[floating,ndim=1] y, */ __pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_14_interpolate3d_3interpolate3d, 0, __pyx_n_s_interpolate3d, NULL, __pyx_n_s_interpolate3d_2, __pyx_d, ((PyObject *)__pyx_codeobj__26)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_float, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_14_interpolate3d_5interpolate3d, 0, __pyx_n_s_interpolate3d, NULL, __pyx_n_s_interpolate3d_2, __pyx_d, ((PyObject *)__pyx_codeobj__26)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_double, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_mdef_14_interpolate3d_1interpolate3d, 0, __pyx_n_s_interpolate3d, NULL, __pyx_n_s_interpolate3d_2, __pyx_d, ((PyObject *)__pyx_codeobj__26)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_2); __Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple); ((__pyx_FusedFunctionObject *) __pyx_t_2)->__signatures__ = __pyx_t_1; __Pyx_GIVEREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_interpolate3d, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 14; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "_interpolate3d.pyx":1 * cimport numpy as np # <<<<<<<<<<<<<< * cimport cython * import numpy as np */ __pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":203 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * def __dealloc__(array self): */ __pyx_t_3 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 203; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; PyType_Modified(__pyx_array_type); /* "View.MemoryView":276 * return self.name * * cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<< * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") */ __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XGOTREF(generic); __Pyx_DECREF_SET(generic, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":277 * * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<< * cdef indirect = Enum("<strided and indirect>") * */ __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XGOTREF(strided); __Pyx_DECREF_SET(strided, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":278 * cdef generic = Enum("<strided and direct or indirect>") * cdef strided = Enum("<strided and direct>") # default * cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 278; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XGOTREF(indirect); __Pyx_DECREF_SET(indirect, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":281 * * * cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<< * cdef indirect_contiguous = Enum("<contiguous and indirect>") * */ __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 281; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XGOTREF(contiguous); __Pyx_DECREF_SET(contiguous, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":282 * * cdef contiguous = Enum("<contiguous and direct>") * cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); __Pyx_XGOTREF(indirect_contiguous); __Pyx_DECREF_SET(indirect_contiguous, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_3); __pyx_t_3 = 0; /* "View.MemoryView":496 * info.obj = self * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 496; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; PyType_Modified(__pyx_memoryview_type); /* "View.MemoryView":952 * return self.from_object * * __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<< * * */ __pyx_t_3 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_GOTREF(__pyx_t_3); if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_3) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;} __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; PyType_Modified(__pyx_memoryviewslice_type); /* "__pyxutil":2 * * cdef extern from *: # <<<<<<<<<<<<<< * void __pyx_PyErr_Clear "PyErr_Clear" () * __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_float(object) */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init _interpolate3d", __pyx_clineno, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init _interpolate3d"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if PY_MAJOR_VERSION < 3 return; #else return __pyx_m; #endif } /* --- Runtime support code --- */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); #else PyErr_GetExcInfo(type, value, tb); #endif } static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(type, value, tb); #endif } static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { PyObject *local_type, *local_value, *local_tb; #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_COMPILING_IN_CPYTHON tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) { #if CYTHON_COMPILING_IN_CPYTHON PyObject *tmp_type, *tmp_value, *tmp_tb; PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_Restore(type, value, tb); #endif } static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(type, value, tb); #endif } #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { if (PyObject_IsSubclass(instance_class, type)) { type = instance_class; } else { instance_class = NULL; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } #if PY_VERSION_HEX >= 0x03030000 if (cause) { #else if (cause && cause != Py_None) { #endif PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(tmp_type, tmp_value, tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = PyThreadState_GET(); PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) { int r; if (!j) return -1; r = PyObject_SetItem(o, j, v); Py_DECREF(j); return r; } static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v, int is_list, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o)); if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) { PyObject* old = PyList_GET_ITEM(o, n); Py_INCREF(v); PyList_SET_ITEM(o, n, v); Py_DECREF(old); return 1; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_ass_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (PyErr_ExceptionMatches(PyExc_OverflowError)) PyErr_Clear(); else return -1; } } return m->sq_ass_item(o, i, v); } } #else #if CYTHON_COMPILING_IN_PYPY if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) { #else if (is_list || PySequence_Check(o)) { #endif return PySequence_SetItem(o, i, v); } #endif return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v); } static CYTHON_INLINE int __Pyx_IterFinish(void) { #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); PyObject* exc_type = tstate->curexc_type; if (unlikely(exc_type)) { if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) { PyObject *exc_value, *exc_tb; exc_value = tstate->curexc_value; exc_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; Py_DECREF(exc_type); Py_XDECREF(exc_value); Py_XDECREF(exc_tb); return 0; } else { return -1; } } return 0; #else if (unlikely(PyErr_Occurred())) { if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) { PyErr_Clear(); return 0; } else { return -1; } } return 0; #endif } #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallMethO(PyObject *func, PyObject *arg) { PyObject *self, *result; PyCFunction cfunc; cfunc = PyCFunction_GET_FUNCTION(func); self = PyCFunction_GET_SELF(func); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = cfunc(self, arg); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_CallNoArg(PyObject *func) { #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_NOARGS)) { return __Pyx_PyObject_CallMethO(func, NULL); } } return __Pyx_PyObject_Call(func, __pyx_empty_tuple, NULL); } #endif #if CYTHON_COMPILING_IN_CPYTHON static PyObject* __Pyx__PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject *result; PyObject *args = PyTuple_New(1); if (unlikely(!args)) return NULL; Py_INCREF(arg); PyTuple_SET_ITEM(args, 0, arg); result = __Pyx_PyObject_Call(func, args, NULL); Py_DECREF(args); return result; } static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { #ifdef __Pyx_CyFunction_USED if (likely(PyCFunction_Check(func) || PyObject_TypeCheck(func, __pyx_CyFunctionType))) { #else if (likely(PyCFunction_Check(func))) { #endif if (likely(PyCFunction_GET_FLAGS(func) & METH_O)) { return __Pyx_PyObject_CallMethO(func, arg); } } return __Pyx__PyObject_CallOneArg(func, arg); } #else static CYTHON_INLINE PyObject* __Pyx_PyObject_CallOneArg(PyObject *func, PyObject *arg) { PyObject* args = PyTuple_Pack(1, arg); return (likely(args)) ? __Pyx_PyObject_Call(func, args, NULL) : NULL; } #endif static PyObject* __Pyx_PyObject_CallMethod0(PyObject* obj, PyObject* method_name) { PyObject *method, *result = NULL; method = __Pyx_PyObject_GetAttrStr(obj, method_name); if (unlikely(!method)) goto bad; #if CYTHON_COMPILING_IN_CPYTHON if (likely(PyMethod_Check(method))) { PyObject *self = PyMethod_GET_SELF(method); if (likely(self)) { PyObject *function = PyMethod_GET_FUNCTION(method); result = __Pyx_PyObject_CallOneArg(function, self); Py_DECREF(method); return result; } } #endif result = __Pyx_PyObject_CallNoArg(method); Py_DECREF(method); bad: return result; } static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) { if (unlikely(retval)) { Py_DECREF(retval); __Pyx_RaiseTooManyValuesError(expected); return -1; } else { return __Pyx_IterFinish(); } return 0; } static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } static void __Pyx_UnpackTupleError(PyObject *t, Py_ssize_t index) { if (t == Py_None) { __Pyx_RaiseNoneNotIterableError(); } else if (PyTuple_GET_SIZE(t) < index) { __Pyx_RaiseNeedMoreValuesError(PyTuple_GET_SIZE(t)); } else { __Pyx_RaiseTooManyValuesError(index); } } static CYTHON_INLINE int __Pyx_unpack_tuple2(PyObject* tuple, PyObject** pvalue1, PyObject** pvalue2, int is_tuple, int has_known_size, int decref_tuple) { Py_ssize_t index; PyObject *value1 = NULL, *value2 = NULL, *iter = NULL; if (!is_tuple && unlikely(!PyTuple_Check(tuple))) { iternextfunc iternext; iter = PyObject_GetIter(tuple); if (unlikely(!iter)) goto bad; if (decref_tuple) { Py_DECREF(tuple); tuple = NULL; } iternext = Py_TYPE(iter)->tp_iternext; value1 = iternext(iter); if (unlikely(!value1)) { index = 0; goto unpacking_failed; } value2 = iternext(iter); if (unlikely(!value2)) { index = 1; goto unpacking_failed; } if (!has_known_size && unlikely(__Pyx_IternextUnpackEndCheck(iternext(iter), 2))) goto bad; Py_DECREF(iter); } else { if (!has_known_size && unlikely(PyTuple_GET_SIZE(tuple) != 2)) { __Pyx_UnpackTupleError(tuple, 2); goto bad; } #if CYTHON_COMPILING_IN_PYPY value1 = PySequence_ITEM(tuple, 0); if (unlikely(!value1)) goto bad; value2 = PySequence_ITEM(tuple, 1); if (unlikely(!value2)) goto bad; #else value1 = PyTuple_GET_ITEM(tuple, 0); value2 = PyTuple_GET_ITEM(tuple, 1); Py_INCREF(value1); Py_INCREF(value2); #endif if (decref_tuple) { Py_DECREF(tuple); } } *pvalue1 = value1; *pvalue2 = value2; return 0; unpacking_failed: if (!has_known_size && __Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index); bad: Py_XDECREF(iter); Py_XDECREF(value1); Py_XDECREF(value2); if (decref_tuple) { Py_XDECREF(tuple); } return -1; } static CYTHON_INLINE PyObject* __Pyx_dict_iterator(PyObject* iterable, int is_dict, PyObject* method_name, Py_ssize_t* p_orig_length, int* p_source_is_dict) { is_dict = is_dict || likely(PyDict_CheckExact(iterable)); *p_source_is_dict = is_dict; #if !CYTHON_COMPILING_IN_PYPY if (is_dict) { *p_orig_length = PyDict_Size(iterable); Py_INCREF(iterable); return iterable; } #endif *p_orig_length = 0; if (method_name) { PyObject* iter; iterable = __Pyx_PyObject_CallMethod0(iterable, method_name); if (!iterable) return NULL; #if !CYTHON_COMPILING_IN_PYPY if (PyTuple_CheckExact(iterable) || PyList_CheckExact(iterable)) return iterable; #endif iter = PyObject_GetIter(iterable); Py_DECREF(iterable); return iter; } return PyObject_GetIter(iterable); } static CYTHON_INLINE int __Pyx_dict_iter_next(PyObject* iter_obj, Py_ssize_t orig_length, Py_ssize_t* ppos, PyObject** pkey, PyObject** pvalue, PyObject** pitem, int source_is_dict) { PyObject* next_item; #if !CYTHON_COMPILING_IN_PYPY if (source_is_dict) { PyObject *key, *value; if (unlikely(orig_length != PyDict_Size(iter_obj))) { PyErr_SetString(PyExc_RuntimeError, "dictionary changed size during iteration"); return -1; } if (unlikely(!PyDict_Next(iter_obj, ppos, &key, &value))) { return 0; } if (pitem) { PyObject* tuple = PyTuple_New(2); if (unlikely(!tuple)) { return -1; } Py_INCREF(key); Py_INCREF(value); PyTuple_SET_ITEM(tuple, 0, key); PyTuple_SET_ITEM(tuple, 1, value); *pitem = tuple; } else { if (pkey) { Py_INCREF(key); *pkey = key; } if (pvalue) { Py_INCREF(value); *pvalue = value; } } return 1; } else if (PyTuple_CheckExact(iter_obj)) { Py_ssize_t pos = *ppos; if (unlikely(pos >= PyTuple_GET_SIZE(iter_obj))) return 0; *ppos = pos + 1; next_item = PyTuple_GET_ITEM(iter_obj, pos); Py_INCREF(next_item); } else if (PyList_CheckExact(iter_obj)) { Py_ssize_t pos = *ppos; if (unlikely(pos >= PyList_GET_SIZE(iter_obj))) return 0; *ppos = pos + 1; next_item = PyList_GET_ITEM(iter_obj, pos); Py_INCREF(next_item); } else #endif { next_item = PyIter_Next(iter_obj); if (unlikely(!next_item)) { return __Pyx_IterFinish(); } } if (pitem) { *pitem = next_item; } else if (pkey && pvalue) { if (__Pyx_unpack_tuple2(next_item, pkey, pvalue, source_is_dict, source_is_dict, 1)) return -1; } else if (pkey) { *pkey = next_item; } else { *pvalue = next_item; } return 1; } static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) { PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); } static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (none_allowed && obj == Py_None) return 1; else if (exact) { if (likely(Py_TYPE(obj) == type)) return 1; #if PY_MAJOR_VERSION == 2 else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(PyObject_TypeCheck(obj, type))) return 1; } __Pyx_RaiseArgumentTypeInvalid(name, obj, type); return 0; } static CYTHON_INLINE int __Pyx_IsLittleEndian(void) { unsigned int n = 1; return *(unsigned char*)(&n) != 0; } static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static CYTHON_INLINE PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_IsLittleEndian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static CYTHON_INLINE int __Pyx_GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { if (obj == Py_None || obj == NULL) { __Pyx_ZeroBuffer(buf); return 0; } buf->buf = NULL; if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail; if (buf->ndim != nd) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned)buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_ZeroBuffer(buf); return -1; } static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (info->buf == NULL) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } static CYTHON_INLINE long __Pyx_div_long(long a, long b) { long q = a / b; long r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(PyObject_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else if (s1 == s2) { return (equals == Py_EQ); } else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) { const char *ps1, *ps2; Py_ssize_t length = PyBytes_GET_SIZE(s1); if (length != PyBytes_GET_SIZE(s2)) return (equals == Py_NE); ps1 = PyBytes_AS_STRING(s1); ps2 = PyBytes_AS_STRING(s2); if (ps1[0] != ps2[0]) { return (equals == Py_NE); } else if (length == 1) { return (equals == Py_EQ); } else { int result = memcmp(ps1, ps2, (size_t)length); return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) { return (equals == Py_NE); } else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) { return (equals == Py_NE); } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } #endif } static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) { #if CYTHON_COMPILING_IN_PYPY return PyObject_RichCompareBool(s1, s2, equals); #else #if PY_MAJOR_VERSION < 3 PyObject* owned_ref = NULL; #endif int s1_is_unicode, s2_is_unicode; if (s1 == s2) { goto return_eq; } s1_is_unicode = PyUnicode_CheckExact(s1); s2_is_unicode = PyUnicode_CheckExact(s2); #if PY_MAJOR_VERSION < 3 if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) { owned_ref = PyUnicode_FromObject(s2); if (unlikely(!owned_ref)) return -1; s2 = owned_ref; s2_is_unicode = 1; } else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) { owned_ref = PyUnicode_FromObject(s1); if (unlikely(!owned_ref)) return -1; s1 = owned_ref; s1_is_unicode = 1; } else if (((!s2_is_unicode) & (!s1_is_unicode))) { return __Pyx_PyBytes_Equals(s1, s2, equals); } #endif if (s1_is_unicode & s2_is_unicode) { Py_ssize_t length; int kind; void *data1, *data2; if (unlikely(__Pyx_PyUnicode_READY(s1) < 0) || unlikely(__Pyx_PyUnicode_READY(s2) < 0)) return -1; length = __Pyx_PyUnicode_GET_LENGTH(s1); if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) { goto return_ne; } kind = __Pyx_PyUnicode_KIND(s1); if (kind != __Pyx_PyUnicode_KIND(s2)) { goto return_ne; } data1 = __Pyx_PyUnicode_DATA(s1); data2 = __Pyx_PyUnicode_DATA(s2); if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) { goto return_ne; } else if (length == 1) { goto return_eq; } else { int result = memcmp(data1, data2, (size_t)(length * kind)); #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ) ? (result == 0) : (result != 0); } } else if ((s1 == Py_None) & s2_is_unicode) { goto return_ne; } else if ((s2 == Py_None) & s1_is_unicode) { goto return_ne; } else { int result; PyObject* py_result = PyObject_RichCompare(s1, s2, equals); if (!py_result) return -1; result = __Pyx_PyObject_IsTrue(py_result); Py_DECREF(py_result); return result; } return_eq: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_EQ); return_ne: #if PY_MAJOR_VERSION < 3 Py_XDECREF(owned_ref); #endif return (equals == Py_NE); #endif } static CYTHON_INLINE Py_ssize_t __Pyx_div_Py_ssize_t(Py_ssize_t a, Py_ssize_t b) { Py_ssize_t q = a / b; Py_ssize_t r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) { #if CYTHON_COMPILING_IN_CPYTHON #if PY_MAJOR_VERSION >= 3 if (likely(PyUnicode_Check(n))) #else if (likely(PyString_Check(n))) #endif return __Pyx_PyObject_GetAttrStr(o, n); #endif return PyObject_GetAttr(o, n); } static CYTHON_INLINE PyObject* __Pyx_decode_c_string( const char* cstring, Py_ssize_t start, Py_ssize_t stop, const char* encoding, const char* errors, PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) { Py_ssize_t length; if (unlikely((start < 0) | (stop < 0))) { length = strlen(cstring); if (start < 0) { start += length; if (start < 0) start = 0; } if (stop < 0) stop += length; } length = stop - start; if (unlikely(length <= 0)) return PyUnicode_FromUnicode(NULL, 0); cstring += start; if (decode_func) { return decode_func(cstring, length, errors); } else { return PyUnicode_Decode(cstring, length, encoding, errors); } } static CYTHON_INLINE void __Pyx_ExceptionSwap(PyObject **type, PyObject **value, PyObject **tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if CYTHON_COMPILING_IN_CPYTHON PyThreadState *tstate = PyThreadState_GET(); tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = *type; tstate->exc_value = *value; tstate->exc_traceback = *tb; #else PyErr_GetExcInfo(&tmp_type, &tmp_value, &tmp_tb); PyErr_SetExcInfo(*type, *value, *tb); #endif *type = tmp_type; *value = tmp_value; *tb = tmp_tb; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) { PyObject *r; if (!j) return NULL; r = PyObject_GetItem(o, j); Py_DECREF(j); return r; } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) { PyObject *r = PyList_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, i); Py_INCREF(r); return r; } return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); #else return PySequence_GetItem(o, i); #endif } static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i, int is_list, int wraparound, int boundscheck) { #if CYTHON_COMPILING_IN_CPYTHON if (is_list || PyList_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o); if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) { PyObject *r = PyList_GET_ITEM(o, n); Py_INCREF(r); return r; } } else if (PyTuple_CheckExact(o)) { Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o); if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) { PyObject *r = PyTuple_GET_ITEM(o, n); Py_INCREF(r); return r; } } else { PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence; if (likely(m && m->sq_item)) { if (wraparound && unlikely(i < 0) && likely(m->sq_length)) { Py_ssize_t l = m->sq_length(o); if (likely(l >= 0)) { i += l; } else { if (PyErr_ExceptionMatches(PyExc_OverflowError)) PyErr_Clear(); else return NULL; } } return m->sq_item(o, i); } } #else if (is_list || PySequence_Check(o)) { return PySequence_GetItem(o, i); } #endif return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i)); } static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) { PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname); } static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); if (full_traceback) { Py_XINCREF(old_exc); Py_XINCREF(old_val); Py_XINCREF(old_tb); __Pyx_ErrRestore(old_exc, old_val, old_tb); PyErr_PrintEx(1); } #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif __Pyx_ErrRestore(old_exc, old_val, old_tb); if (!ctx) { PyErr_WriteUnraisable(Py_None); } else { PyErr_WriteUnraisable(ctx); Py_DECREF(ctx); } } static int __Pyx_SetVtable(PyObject *dict, void *vtable) { #if PY_VERSION_HEX >= 0x02070000 PyObject *ob = PyCapsule_New(vtable, 0, 0); #else PyObject *ob = PyCObject_FromVoidPtr(vtable, 0); #endif if (!ob) goto bad; if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0) goto bad; Py_DECREF(ob); return 0; bad: Py_XDECREF(ob); return -1; } static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) { PyObject* fake_module; PyTypeObject* cached_type = NULL; fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI); if (!fake_module) return NULL; Py_INCREF(fake_module); cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name); if (cached_type) { if (!PyType_Check((PyObject*)cached_type)) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s is not a type object", type->tp_name); goto bad; } if (cached_type->tp_basicsize != type->tp_basicsize) { PyErr_Format(PyExc_TypeError, "Shared Cython type %.200s has the wrong size, try recompiling", type->tp_name); goto bad; } } else { if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad; PyErr_Clear(); if (PyType_Ready(type) < 0) goto bad; if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0) goto bad; Py_INCREF(type); cached_type = type; } done: Py_DECREF(fake_module); return cached_type; bad: Py_XDECREF(cached_type); cached_type = NULL; goto done; } static PyObject * __Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure) { if (unlikely(op->func_doc == NULL)) { if (op->func.m_ml->ml_doc) { #if PY_MAJOR_VERSION >= 3 op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc); #else op->func_doc = PyString_FromString(op->func.m_ml->ml_doc); #endif if (unlikely(op->func_doc == NULL)) return NULL; } else { Py_INCREF(Py_None); return Py_None; } } Py_INCREF(op->func_doc); return op->func_doc; } static int __Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value) { PyObject *tmp = op->func_doc; if (value == NULL) { value = Py_None; } Py_INCREF(value); op->func_doc = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op) { if (unlikely(op->func_name == NULL)) { #if PY_MAJOR_VERSION >= 3 op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name); #else op->func_name = PyString_InternFromString(op->func.m_ml->ml_name); #endif if (unlikely(op->func_name == NULL)) return NULL; } Py_INCREF(op->func_name); return op->func_name; } static int __Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) { #else if (unlikely(value == NULL || !PyString_Check(value))) { #endif PyErr_SetString(PyExc_TypeError, "__name__ must be set to a string object"); return -1; } tmp = op->func_name; Py_INCREF(value); op->func_name = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op) { Py_INCREF(op->func_qualname); return op->func_qualname; } static int __Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value) { PyObject *tmp; #if PY_MAJOR_VERSION >= 3 if (unlikely(value == NULL || !PyUnicode_Check(value))) { #else if (unlikely(value == NULL || !PyString_Check(value))) { #endif PyErr_SetString(PyExc_TypeError, "__qualname__ must be set to a string object"); return -1; } tmp = op->func_qualname; Py_INCREF(value); op->func_qualname = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure) { PyObject *self; self = m->func_closure; if (self == NULL) self = Py_None; Py_INCREF(self); return self; } static PyObject * __Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op) { if (unlikely(op->func_dict == NULL)) { op->func_dict = PyDict_New(); if (unlikely(op->func_dict == NULL)) return NULL; } Py_INCREF(op->func_dict); return op->func_dict; } static int __Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value) { PyObject *tmp; if (unlikely(value == NULL)) { PyErr_SetString(PyExc_TypeError, "function's dictionary may not be deleted"); return -1; } if (unlikely(!PyDict_Check(value))) { PyErr_SetString(PyExc_TypeError, "setting function's dictionary to a non-dict"); return -1; } tmp = op->func_dict; Py_INCREF(value); op->func_dict = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op) { Py_INCREF(op->func_globals); return op->func_globals; } static PyObject * __Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op) { Py_INCREF(Py_None); return Py_None; } static PyObject * __Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op) { PyObject* result = (op->func_code) ? op->func_code : Py_None; Py_INCREF(result); return result; } static int __Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) { PyObject *res = op->defaults_getter((PyObject *) op); if (unlikely(!res)) return -1; op->defaults_tuple = PyTuple_GET_ITEM(res, 0); Py_INCREF(op->defaults_tuple); op->defaults_kwdict = PyTuple_GET_ITEM(res, 1); Py_INCREF(op->defaults_kwdict); Py_DECREF(res); return 0; } static int __Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value) { PyObject* tmp; if (!value) { value = Py_None; } else if (value != Py_None && !PyTuple_Check(value)) { PyErr_SetString(PyExc_TypeError, "__defaults__ must be set to a tuple object"); return -1; } Py_INCREF(value); tmp = op->defaults_tuple; op->defaults_tuple = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op) { PyObject* result = op->defaults_tuple; if (unlikely(!result)) { if (op->defaults_getter) { if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; result = op->defaults_tuple; } else { result = Py_None; } } Py_INCREF(result); return result; } static int __Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value) { PyObject* tmp; if (!value) { value = Py_None; } else if (value != Py_None && !PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__kwdefaults__ must be set to a dict object"); return -1; } Py_INCREF(value); tmp = op->defaults_kwdict; op->defaults_kwdict = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op) { PyObject* result = op->defaults_kwdict; if (unlikely(!result)) { if (op->defaults_getter) { if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL; result = op->defaults_kwdict; } else { result = Py_None; } } Py_INCREF(result); return result; } static int __Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value) { PyObject* tmp; if (!value || value == Py_None) { value = NULL; } else if (!PyDict_Check(value)) { PyErr_SetString(PyExc_TypeError, "__annotations__ must be set to a dict object"); return -1; } Py_XINCREF(value); tmp = op->func_annotations; op->func_annotations = value; Py_XDECREF(tmp); return 0; } static PyObject * __Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op) { PyObject* result = op->func_annotations; if (unlikely(!result)) { result = PyDict_New(); if (unlikely(!result)) return NULL; op->func_annotations = result; } Py_INCREF(result); return result; } static PyGetSetDef __pyx_CyFunction_getsets[] = { {(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0}, {(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0}, {(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0}, {(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0}, {(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0}, {(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0}, {(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0}, {(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0}, {(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0}, {(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0}, {(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0}, {0, 0, 0, 0, 0} }; static PyMemberDef __pyx_CyFunction_members[] = { {(char *) "__module__", T_OBJECT, offsetof(__pyx_CyFunctionObject, func.m_module), PY_WRITE_RESTRICTED, 0}, {0, 0, 0, 0, 0} }; static PyObject * __Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromString(m->func.m_ml->ml_name); #else return PyString_FromString(m->func.m_ml->ml_name); #endif } static PyMethodDef __pyx_CyFunction_methods[] = { {"__reduce__", (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0}, {0, 0, 0, 0} }; #if PY_VERSION_HEX < 0x030500A0 #define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func_weakreflist) #else #define __Pyx_CyFunction_weakreflist(cyfunc) ((cyfunc)->func.m_weakreflist) #endif static PyObject *__Pyx_CyFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject* qualname, PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) { __pyx_CyFunctionObject *op = PyObject_GC_New(__pyx_CyFunctionObject, type); if (op == NULL) return NULL; op->flags = flags; __Pyx_CyFunction_weakreflist(op) = NULL; op->func.m_ml = ml; op->func.m_self = (PyObject *) op; Py_XINCREF(closure); op->func_closure = closure; Py_XINCREF(module); op->func.m_module = module; op->func_dict = NULL; op->func_name = NULL; Py_INCREF(qualname); op->func_qualname = qualname; op->func_doc = NULL; op->func_classobj = NULL; op->func_globals = globals; Py_INCREF(op->func_globals); Py_XINCREF(code); op->func_code = code; op->defaults_pyobjects = 0; op->defaults = NULL; op->defaults_tuple = NULL; op->defaults_kwdict = NULL; op->defaults_getter = NULL; op->func_annotations = NULL; PyObject_GC_Track(op); return (PyObject *) op; } static int __Pyx_CyFunction_clear(__pyx_CyFunctionObject *m) { Py_CLEAR(m->func_closure); Py_CLEAR(m->func.m_module); Py_CLEAR(m->func_dict); Py_CLEAR(m->func_name); Py_CLEAR(m->func_qualname); Py_CLEAR(m->func_doc); Py_CLEAR(m->func_globals); Py_CLEAR(m->func_code); Py_CLEAR(m->func_classobj); Py_CLEAR(m->defaults_tuple); Py_CLEAR(m->defaults_kwdict); Py_CLEAR(m->func_annotations); if (m->defaults) { PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); int i; for (i = 0; i < m->defaults_pyobjects; i++) Py_XDECREF(pydefaults[i]); PyMem_Free(m->defaults); m->defaults = NULL; } return 0; } static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m) { PyObject_GC_UnTrack(m); if (__Pyx_CyFunction_weakreflist(m) != NULL) PyObject_ClearWeakRefs((PyObject *) m); __Pyx_CyFunction_clear(m); PyObject_GC_Del(m); } static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg) { Py_VISIT(m->func_closure); Py_VISIT(m->func.m_module); Py_VISIT(m->func_dict); Py_VISIT(m->func_name); Py_VISIT(m->func_qualname); Py_VISIT(m->func_doc); Py_VISIT(m->func_globals); Py_VISIT(m->func_code); Py_VISIT(m->func_classobj); Py_VISIT(m->defaults_tuple); Py_VISIT(m->defaults_kwdict); if (m->defaults) { PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m); int i; for (i = 0; i < m->defaults_pyobjects; i++) Py_VISIT(pydefaults[i]); } return 0; } static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) { Py_INCREF(func); return func; } if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) { if (type == NULL) type = (PyObject *)(Py_TYPE(obj)); return __Pyx_PyMethod_New(func, type, (PyObject *)(Py_TYPE(type))); } if (obj == Py_None) obj = NULL; return __Pyx_PyMethod_New(func, obj, type); } static PyObject* __Pyx_CyFunction_repr(__pyx_CyFunctionObject *op) { #if PY_MAJOR_VERSION >= 3 return PyUnicode_FromFormat("<cyfunction %U at %p>", op->func_qualname, (void *)op); #else return PyString_FromFormat("<cyfunction %s at %p>", PyString_AsString(op->func_qualname), (void *)op); #endif } #if CYTHON_COMPILING_IN_PYPY static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyCFunctionObject* f = (PyCFunctionObject*)func; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); Py_ssize_t size; switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) { case METH_VARARGS: if (likely(kw == NULL) || PyDict_Size(kw) == 0) return (*meth)(self, arg); break; case METH_VARARGS | METH_KEYWORDS: return (*(PyCFunctionWithKeywords)meth)(self, arg, kw); case METH_NOARGS: if (likely(kw == NULL) || PyDict_Size(kw) == 0) { size = PyTuple_GET_SIZE(arg); if (size == 0) return (*meth)(self, NULL); PyErr_Format(PyExc_TypeError, "%.200s() takes no arguments (%" CYTHON_FORMAT_SSIZE_T "d given)", f->m_ml->ml_name, size); return NULL; } break; case METH_O: if (likely(kw == NULL) || PyDict_Size(kw) == 0) { size = PyTuple_GET_SIZE(arg); if (size == 1) return (*meth)(self, PyTuple_GET_ITEM(arg, 0)); PyErr_Format(PyExc_TypeError, "%.200s() takes exactly one argument (%" CYTHON_FORMAT_SSIZE_T "d given)", f->m_ml->ml_name, size); return NULL; } break; default: PyErr_SetString(PyExc_SystemError, "Bad call flags in " "__Pyx_CyFunction_Call. METH_OLDARGS is no " "longer supported!"); return NULL; } PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments", f->m_ml->ml_name); return NULL; } #else static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) { return PyCFunction_Call(func, arg, kw); } #endif static PyTypeObject __pyx_CyFunctionType_type = { PyVarObject_HEAD_INIT(0, 0) "cython_function_or_method", sizeof(__pyx_CyFunctionObject), 0, (destructor) __Pyx_CyFunction_dealloc, 0, 0, 0, #if PY_MAJOR_VERSION < 3 0, #else 0, #endif (reprfunc) __Pyx_CyFunction_repr, 0, 0, 0, 0, __Pyx_CyFunction_Call, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, 0, (traverseproc) __Pyx_CyFunction_traverse, (inquiry) __Pyx_CyFunction_clear, 0, #if PY_VERSION_HEX < 0x030500A0 offsetof(__pyx_CyFunctionObject, func_weakreflist), #else offsetof(PyCFunctionObject, m_weakreflist), #endif 0, 0, __pyx_CyFunction_methods, __pyx_CyFunction_members, __pyx_CyFunction_getsets, 0, 0, __Pyx_CyFunction_descr_get, 0, offsetof(__pyx_CyFunctionObject, func_dict), 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if PY_VERSION_HEX >= 0x030400a1 0, #endif }; static int __Pyx_CyFunction_init(void) { #if !CYTHON_COMPILING_IN_PYPY __pyx_CyFunctionType_type.tp_call = PyCFunction_Call; #endif __pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type); if (__pyx_CyFunctionType == NULL) { return -1; } return 0; } static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults = PyMem_Malloc(size); if (!m->defaults) return PyErr_NoMemory(); memset(m->defaults, 0, size); m->defaults_pyobjects = pyobjects; return m->defaults; } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_tuple = tuple; Py_INCREF(tuple); } static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->defaults_kwdict = dict; Py_INCREF(dict); } static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) { __pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func; m->func_annotations = dict; Py_INCREF(dict); } static PyObject * __pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject *qualname, PyObject *self, PyObject *module, PyObject *globals, PyObject *code) { __pyx_FusedFunctionObject *fusedfunc = (__pyx_FusedFunctionObject *) __Pyx_CyFunction_New(type, ml, flags, qualname, self, module, globals, code); if (!fusedfunc) return NULL; fusedfunc->__signatures__ = NULL; fusedfunc->type = NULL; fusedfunc->self = NULL; return (PyObject *) fusedfunc; } static void __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) { __pyx_FusedFunction_clear(self); __pyx_FusedFunctionType->tp_free((PyObject *) self); } static int __pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self, visitproc visit, void *arg) { Py_VISIT(self->self); Py_VISIT(self->type); Py_VISIT(self->__signatures__); return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg); } static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self) { Py_CLEAR(self->self); Py_CLEAR(self->type); Py_CLEAR(self->__signatures__); return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self); } static PyObject * __pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type) { __pyx_FusedFunctionObject *func, *meth; func = (__pyx_FusedFunctionObject *) self; if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) { Py_INCREF(self); return self; } if (obj == Py_None) obj = NULL; meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_NewEx( ((PyCFunctionObject *) func)->m_ml, ((__pyx_CyFunctionObject *) func)->flags, ((__pyx_CyFunctionObject *) func)->func_qualname, ((__pyx_CyFunctionObject *) func)->func_closure, ((PyCFunctionObject *) func)->m_module, ((__pyx_CyFunctionObject *) func)->func_globals, ((__pyx_CyFunctionObject *) func)->func_code); if (!meth) return NULL; Py_XINCREF(func->func.func_classobj); meth->func.func_classobj = func->func.func_classobj; Py_XINCREF(func->__signatures__); meth->__signatures__ = func->__signatures__; Py_XINCREF(type); meth->type = type; Py_XINCREF(func->func.defaults_tuple); meth->func.defaults_tuple = func->func.defaults_tuple; if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD) obj = type; Py_XINCREF(obj); meth->self = obj; return (PyObject *) meth; } static PyObject * _obj_to_str(PyObject *obj) { if (PyType_Check(obj)) return PyObject_GetAttr(obj, __pyx_n_s_name_2); else return PyObject_Str(obj); } static PyObject * __pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx) { PyObject *signature = NULL; PyObject *unbound_result_func; PyObject *result_func = NULL; if (self->__signatures__ == NULL) { PyErr_SetString(PyExc_TypeError, "Function is not fused"); return NULL; } if (PyTuple_Check(idx)) { PyObject *list = PyList_New(0); Py_ssize_t n = PyTuple_GET_SIZE(idx); PyObject *string = NULL; PyObject *sep = NULL; int i; if (!list) return NULL; for (i = 0; i < n; i++) { PyObject *item = PyTuple_GET_ITEM(idx, i); string = _obj_to_str(item); if (!string || PyList_Append(list, string) < 0) goto __pyx_err; Py_DECREF(string); } sep = PyUnicode_FromString("|"); if (sep) signature = PyUnicode_Join(sep, list); __pyx_err: ; Py_DECREF(list); Py_XDECREF(sep); } else { signature = _obj_to_str(idx); } if (!signature) return NULL; unbound_result_func = PyObject_GetItem(self->__signatures__, signature); if (unbound_result_func) { if (self->self || self->type) { __pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func; Py_CLEAR(unbound->func.func_classobj); Py_XINCREF(self->func.func_classobj); unbound->func.func_classobj = self->func.func_classobj; result_func = __pyx_FusedFunction_descr_get(unbound_result_func, self->self, self->type); } else { result_func = unbound_result_func; Py_INCREF(result_func); } } Py_DECREF(signature); Py_XDECREF(unbound_result_func); return result_func; } static PyObject * __pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw) { __pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func; PyObject *result; int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD && !((__pyx_FusedFunctionObject *) func)->__signatures__); if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) { Py_ssize_t argc; PyObject *new_args; PyObject *self; PyObject *m_self; argc = PyTuple_GET_SIZE(args); new_args = PyTuple_GetSlice(args, 1, argc); if (!new_args) return NULL; self = PyTuple_GetItem(args, 0); if (!self) return NULL; m_self = cyfunc->func.m_self; cyfunc->func.m_self = self; result = __Pyx_CyFunction_Call(func, new_args, kw); cyfunc->func.m_self = m_self; Py_DECREF(new_args); } else { result = __Pyx_CyFunction_Call(func, args, kw); } return result; } static PyObject * __pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw) { __pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func; Py_ssize_t argc = PyTuple_GET_SIZE(args); PyObject *new_args = NULL; __pyx_FusedFunctionObject *new_func = NULL; PyObject *result = NULL; PyObject *self = NULL; int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD; int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD; if (binding_func->self) { Py_ssize_t i; new_args = PyTuple_New(argc + 1); if (!new_args) return NULL; self = binding_func->self; Py_INCREF(self); PyTuple_SET_ITEM(new_args, 0, self); for (i = 0; i < argc; i++) { PyObject *item = PyTuple_GET_ITEM(args, i); Py_INCREF(item); PyTuple_SET_ITEM(new_args, i + 1, item); } args = new_args; } else if (binding_func->type) { if (argc < 1) { PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given."); return NULL; } self = PyTuple_GET_ITEM(args, 0); } if (self && !is_classmethod && !is_staticmethod && !PyObject_IsInstance(self, binding_func->type)) { PyErr_Format(PyExc_TypeError, "First argument should be of type %.200s, got %.200s.", ((PyTypeObject *) binding_func->type)->tp_name, self->ob_type->tp_name); goto __pyx_err; } if (binding_func->__signatures__) { PyObject *tup = PyTuple_Pack(4, binding_func->__signatures__, args, kw == NULL ? Py_None : kw, binding_func->func.defaults_tuple); if (!tup) goto __pyx_err; new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL); Py_DECREF(tup); if (!new_func) goto __pyx_err; Py_XINCREF(binding_func->func.func_classobj); Py_CLEAR(new_func->func.func_classobj); new_func->func.func_classobj = binding_func->func.func_classobj; func = (PyObject *) new_func; } result = __pyx_FusedFunction_callfunction(func, args, kw); __pyx_err: Py_XDECREF(new_args); Py_XDECREF((PyObject *) new_func); return result; } static PyMemberDef __pyx_FusedFunction_members[] = { {(char *) "__signatures__", T_OBJECT, offsetof(__pyx_FusedFunctionObject, __signatures__), READONLY, 0}, {0, 0, 0, 0, 0}, }; static PyMappingMethods __pyx_FusedFunction_mapping_methods = { 0, (binaryfunc) __pyx_FusedFunction_getitem, 0, }; static PyTypeObject __pyx_FusedFunctionType_type = { PyVarObject_HEAD_INIT(0, 0) "fused_cython_function", sizeof(__pyx_FusedFunctionObject), 0, (destructor) __pyx_FusedFunction_dealloc, 0, 0, 0, #if PY_MAJOR_VERSION < 3 0, #else 0, #endif 0, 0, 0, &__pyx_FusedFunction_mapping_methods, 0, (ternaryfunc) __pyx_FusedFunction_call, 0, 0, 0, 0, Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, 0, (traverseproc) __pyx_FusedFunction_traverse, (inquiry) __pyx_FusedFunction_clear, 0, 0, 0, 0, 0, __pyx_FusedFunction_members, __pyx_CyFunction_getsets, &__pyx_CyFunctionType_type, 0, __pyx_FusedFunction_descr_get, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, #if PY_VERSION_HEX >= 0x030400a1 0, #endif }; static int __pyx_FusedFunction_init(void) { __pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type); if (__pyx_FusedFunctionType == NULL) { return -1; } return 0; } static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = (start + end) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; py_code = __pyx_find_code_object(c_line ? c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? c_line : py_line, py_code); } py_frame = PyFrame_New( PyThreadState_GET(), /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; py_frame->f_lineno = py_line; PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } static int __Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview, int ndim, __Pyx_memviewslice *memviewslice, int memview_is_new_reference) { __Pyx_RefNannyDeclarations int i, retval=-1; Py_buffer *buf = &memview->view; __Pyx_RefNannySetupContext("init_memviewslice", 0); if (!buf) { PyErr_SetString(PyExc_ValueError, "buf is NULL."); goto fail; } else if (memviewslice->memview || memviewslice->data) { PyErr_SetString(PyExc_ValueError, "memviewslice is already initialized!"); goto fail; } if (buf->strides) { for (i = 0; i < ndim; i++) { memviewslice->strides[i] = buf->strides[i]; } } else { Py_ssize_t stride = buf->itemsize; for (i = ndim - 1; i >= 0; i--) { memviewslice->strides[i] = stride; stride *= buf->shape[i]; } } for (i = 0; i < ndim; i++) { memviewslice->shape[i] = buf->shape[i]; if (buf->suboffsets) { memviewslice->suboffsets[i] = buf->suboffsets[i]; } else { memviewslice->suboffsets[i] = -1; } } memviewslice->memview = memview; memviewslice->data = (char *)buf->buf; if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) { Py_INCREF(memview); } retval = 0; goto no_fail; fail: memviewslice->memview = 0; memviewslice->data = 0; retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) { va_list vargs; char msg[200]; va_start(vargs, fmt); #ifdef HAVE_STDARG_PROTOTYPES va_start(vargs, fmt); #else va_start(vargs); #endif vsnprintf(msg, 200, fmt, vargs); Py_FatalError(msg); va_end(vargs); } static CYTHON_INLINE int __pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)++; PyThread_release_lock(lock); return result; } static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count, PyThread_type_lock lock) { int result; PyThread_acquire_lock(lock, 1); result = (*acquisition_count)--; PyThread_release_lock(lock); return result; } static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int first_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview || (PyObject *) memview == Py_None) return; if (__pyx_get_slice_count(memview) < 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); first_time = __pyx_add_acquisition_count(memview) == 0; if (first_time) { if (have_gil) { Py_INCREF((PyObject *) memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_INCREF((PyObject *) memview); PyGILState_Release(_gilstate); } } } static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno) { int last_time; struct __pyx_memoryview_obj *memview = memslice->memview; if (!memview ) { return; } else if ((PyObject *) memview == Py_None) { memslice->memview = NULL; return; } if (__pyx_get_slice_count(memview) <= 0) __pyx_fatalerror("Acquisition count is %d (line %d)", __pyx_get_slice_count(memview), lineno); last_time = __pyx_sub_acquisition_count(memview) == 1; memslice->data = NULL; if (last_time) { if (have_gil) { Py_CLEAR(memslice->memview); } else { PyGILState_STATE _gilstate = PyGILState_Ensure(); Py_CLEAR(memslice->memview); PyGILState_Release(_gilstate); } } else { memslice->memview = NULL; } } static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b) { int i; if (!a || !b) return 0; if (a == b) return 1; if (a->size != b->size || a->typegroup != b->typegroup || a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) { if (a->typegroup == 'H' || b->typegroup == 'H') { return a->size == b->size; } else { return 0; } } if (a->ndim) { for (i = 0; i < a->ndim; i++) if (a->arraysize[i] != b->arraysize[i]) return 0; } if (a->typegroup == 'S') { if (a->flags != b->flags) return 0; if (a->fields || b->fields) { if (!(a->fields && b->fields)) return 0; for (i = 0; a->fields[i].type && b->fields[i].type; i++) { __Pyx_StructField *field_a = a->fields + i; __Pyx_StructField *field_b = b->fields + i; if (field_a->offset != field_b->offset || !__pyx_typeinfo_cmp(field_a->type, field_b->type)) return 0; } return !a->fields[i].type && !b->fields[i].type; } } return 1; } static int __pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec) { if (buf->shape[dim] <= 1) return 1; if (buf->strides) { if (spec & __Pyx_MEMVIEW_CONTIG) { if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) { if (buf->strides[dim] != sizeof(void *)) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly contiguous " "in dimension %d.", dim); goto fail; } } else if (buf->strides[dim] != buf->itemsize) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } if (spec & __Pyx_MEMVIEW_FOLLOW) { Py_ssize_t stride = buf->strides[dim]; if (stride < 0) stride = -stride; if (stride < buf->itemsize) { PyErr_SetString(PyExc_ValueError, "Buffer and memoryview are not contiguous " "in the same dimension."); goto fail; } } } else { if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not contiguous in " "dimension %d", dim); goto fail; } else if (spec & (__Pyx_MEMVIEW_PTR)) { PyErr_Format(PyExc_ValueError, "C-contiguous buffer is not indirect in " "dimension %d", dim); goto fail; } else if (buf->suboffsets) { PyErr_SetString(PyExc_ValueError, "Buffer exposes suboffsets but no strides"); goto fail; } } return 1; fail: return 0; } static int __pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec) { if (spec & __Pyx_MEMVIEW_DIRECT) { if (buf->suboffsets && buf->suboffsets[dim] >= 0) { PyErr_Format(PyExc_ValueError, "Buffer not compatible with direct access " "in dimension %d.", dim); goto fail; } } if (spec & __Pyx_MEMVIEW_PTR) { if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) { PyErr_Format(PyExc_ValueError, "Buffer is not indirectly accessible " "in dimension %d.", dim); goto fail; } } return 1; fail: return 0; } static int __pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag) { int i; if (c_or_f_flag & __Pyx_IS_F_CONTIG) { Py_ssize_t stride = 1; for (i = 0; i < ndim; i++) { if (stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1) { PyErr_SetString(PyExc_ValueError, "Buffer not fortran contiguous."); goto fail; } stride = stride * buf->shape[i]; } } else if (c_or_f_flag & __Pyx_IS_C_CONTIG) { Py_ssize_t stride = 1; for (i = ndim - 1; i >- 1; i--) { if (stride * buf->itemsize != buf->strides[i] && buf->shape[i] > 1) { PyErr_SetString(PyExc_ValueError, "Buffer not C contiguous."); goto fail; } stride = stride * buf->shape[i]; } } return 1; fail: return 0; } static int __Pyx_ValidateAndInit_memviewslice( int *axes_specs, int c_or_f_flag, int buf_flags, int ndim, __Pyx_TypeInfo *dtype, __Pyx_BufFmt_StackElem stack[], __Pyx_memviewslice *memviewslice, PyObject *original_obj) { struct __pyx_memoryview_obj *memview, *new_memview; __Pyx_RefNannyDeclarations Py_buffer *buf; int i, spec = 0, retval = -1; __Pyx_BufFmt_Context ctx; int from_memoryview = __pyx_memoryview_check(original_obj); __Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0); if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *) original_obj)->typeinfo)) { memview = (struct __pyx_memoryview_obj *) original_obj; new_memview = NULL; } else { memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( original_obj, buf_flags, 0, dtype); new_memview = memview; if (unlikely(!memview)) goto fail; } buf = &memview->view; if (buf->ndim != ndim) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", ndim, buf->ndim); goto fail; } if (new_memview) { __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if ((unsigned) buf->itemsize != dtype->size) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) " "does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } for (i = 0; i < ndim; i++) { spec = axes_specs[i]; if (!__pyx_check_strides(buf, i, ndim, spec)) goto fail; if (!__pyx_check_suboffsets(buf, i, ndim, spec)) goto fail; } if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag)) goto fail; if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice, new_memview != NULL) == -1)) { goto fail; } retval = 0; goto no_fail; fail: Py_XDECREF(new_memview); retval = -1; no_fail: __Pyx_RefNannyFinishContext(); return retval; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_float(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, PyBUF_RECORDS, 1, &__Pyx_TypeInfo_float, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_double(PyObject *obj) { __Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } }; __Pyx_BufFmt_StackElem stack[1]; int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) }; int retcode; if (obj == Py_None) { result.memview = (struct __pyx_memoryview_obj *) Py_None; return result; } retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0, PyBUF_RECORDS, 1, &__Pyx_TypeInfo_double, stack, &result, obj); if (unlikely(retcode == -1)) goto __pyx_fail; return result; __pyx_fail: result.memview = NULL; result.data = NULL; return result; } static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_VERSION_HEX < 0x03030000 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(1); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); #endif if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_VERSION_HEX < 0x03030000 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_VERSION_HEX < 0x03030000 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags); if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; } Py_DECREF(obj); view->obj = NULL; } #endif #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value) \ { \ func_type value = func_value; \ if (sizeof(target_type) < sizeof(func_type)) { \ if (unlikely(value != (func_type) (target_type) value)) { \ func_type zero = 0; \ if (is_unsigned && unlikely(value < zero)) \ goto raise_neg_overflow; \ else \ goto raise_overflow; \ } \ } \ return (target_type) value; \ } #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #endif #endif static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(int) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, +(((PyLongObject*)x)->ob_digit[0])); case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong(x)) } else if (sizeof(int) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(long) <= sizeof(unsigned long long)) { return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(long long)) { return PyLong_FromLongLong((long long) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) { const char neg_one = (char) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(char) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (char) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } if (sizeof(char) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(char) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(char, digit, +(((PyLongObject*)x)->ob_digit[0])); case -1: __PYX_VERIFY_RETURN_INT(char, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (sizeof(char) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong(x)) } else if (sizeof(char) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else char val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (char) -1; } } else { char val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (char) -1; val = __Pyx_PyInt_As_char(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to char"); return (char) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to char"); return (char) -1; } static CYTHON_INLINE int __Pyx_BytesContains(PyObject* bytes, char character) { const Py_ssize_t length = PyBytes_GET_SIZE(bytes); char* char_start = PyBytes_AS_STRING(bytes); char* pos; for (pos=char_start; pos < char_start+length; pos++) { if (character == pos[0]) return 1; } return 0; } #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(a, a); case 3: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, a); case 4: z = __Pyx_c_prodf(a, a); return __Pyx_c_prodf(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_absf(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double denom = b.real * b.real + b.imag * b.imag; z.real = (a.real * b.real + a.imag * b.imag) / denom; z.imag = (a.imag * b.real - a.real * b.imag) / denom; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(a, a); case 3: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, a); case 4: z = __Pyx_c_prod(a, a); return __Pyx_c_prod(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } r = a.real; theta = 0; } else { r = __Pyx_c_abs(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); } else if (sizeof(int) <= sizeof(unsigned long long)) { return PyLong_FromUnsignedLongLong((unsigned long long) value); } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(long long)) { return PyLong_FromLongLong((long long) value); } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs, char order, int ndim) { int i, index, step, start; Py_ssize_t itemsize = mvs->memview->view.itemsize; if (order == 'F') { step = 1; start = 0; } else { step = -1; start = ndim - 1; } for (i = 0; i < ndim; i++) { index = start + step * i; if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize) return 0; itemsize *= mvs->shape[index]; } return 1; } static void __pyx_get_array_memory_extents(__Pyx_memviewslice *slice, void **out_start, void **out_end, int ndim, size_t itemsize) { char *start, *end; int i; start = end = slice->data; for (i = 0; i < ndim; i++) { Py_ssize_t stride = slice->strides[i]; Py_ssize_t extent = slice->shape[i]; if (extent == 0) { *out_start = *out_end = start; return; } else { if (stride > 0) end += stride * (extent - 1); else start += stride * (extent - 1); } } *out_start = start; *out_end = end + itemsize; } static int __pyx_slices_overlap(__Pyx_memviewslice *slice1, __Pyx_memviewslice *slice2, int ndim, size_t itemsize) { void *start1, *end1, *start2, *end2; __pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize); __pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize); return (start1 < end2) && (start2 < end1); } static __Pyx_memviewslice __pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs, const char *mode, int ndim, size_t sizeof_dtype, int contig_flag, int dtype_is_object) { __Pyx_RefNannyDeclarations int i; __Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } }; struct __pyx_memoryview_obj *from_memview = from_mvs->memview; Py_buffer *buf = &from_memview->view; PyObject *shape_tuple = NULL; PyObject *temp_int = NULL; struct __pyx_array_obj *array_obj = NULL; struct __pyx_memoryview_obj *memview_obj = NULL; __Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0); for (i = 0; i < ndim; i++) { if (from_mvs->suboffsets[i] >= 0) { PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with " "indirect dimensions (axis %d)", i); goto fail; } } shape_tuple = PyTuple_New(ndim); if (unlikely(!shape_tuple)) { goto fail; } __Pyx_GOTREF(shape_tuple); for(i = 0; i < ndim; i++) { temp_int = PyInt_FromSsize_t(from_mvs->shape[i]); if(unlikely(!temp_int)) { goto fail; } else { PyTuple_SET_ITEM(shape_tuple, i, temp_int); temp_int = NULL; } } array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL); if (unlikely(!array_obj)) { goto fail; } __Pyx_GOTREF(array_obj); memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new( (PyObject *) array_obj, contig_flag, dtype_is_object, from_mvs->memview->typeinfo); if (unlikely(!memview_obj)) goto fail; if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0)) goto fail; if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim, dtype_is_object) < 0)) goto fail; goto no_fail; fail: __Pyx_XDECREF(new_mvs.memview); new_mvs.memview = NULL; new_mvs.data = NULL; no_fail: __Pyx_XDECREF(shape_tuple); __Pyx_XDECREF(temp_int); __Pyx_XDECREF(array_obj); __Pyx_RefNannyFinishContext(); return new_mvs; } static CYTHON_INLINE PyObject * __pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig) { PyObject *cobj; #if PY_VERSION_HEX >= 0x02070000 cobj = PyCapsule_New(p, sig, NULL); #else cobj = PyCObject_FromVoidPtr(p, NULL); #endif return cobj; } static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong(x)) } else if (sizeof(long) <= sizeof(unsigned long long)) { __PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong(x)) } } else { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(x)) { case 0: return 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, +(((PyLongObject*)x)->ob_digit[0])); case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, -(sdigit) ((PyLongObject*)x)->ob_digit[0]); } #endif #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong(x)) } else if (sizeof(long) <= sizeof(long long)) { __PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong(x)) } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_Int(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_Int(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility", module_name, class_name); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling", module_name, class_name); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { #if PY_VERSION_HEX < 0x03030000 char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; #else if (__Pyx_PyUnicode_READY(o) == -1) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (PyUnicode_IS_ASCII(o)) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif #endif } else #endif #if !CYTHON_COMPILING_IN_PYPY if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) { PyNumberMethods *m; const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (PyInt_Check(x) || PyLong_Check(x)) #else if (PyLong_Check(x)) #endif return Py_INCREF(x), x; m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = PyNumber_Int(x); } else if (m && m->nb_long) { name = "long"; res = PyNumber_Long(x); } #else if (m && m->nb_int) { name = "int"; res = PyNumber_Long(x); } #endif if (res) { #if PY_MAJOR_VERSION < 3 if (!PyInt_Check(res) && !PyLong_Check(res)) { #else if (!PyLong_Check(res)) { #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", name, name, Py_TYPE(res)->tp_name); Py_DECREF(res); return NULL; } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) return PyInt_AS_LONG(b); #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3 #if CYTHON_USE_PYLONG_INTERNALS switch (Py_SIZE(b)) { case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0]; case 0: return 0; case 1: return ((PyLongObject*)b)->ob_digit[0]; } #endif #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
oskar_mem_random_uniform.c
/* * Copyright (c) 2015-2017, The University of Oxford * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of the University of Oxford 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 "mem/oskar_mem.h" #include "mem/oskar_mem_random_uniform_cuda.h" #include "math/private_random_helpers.h" #include "utility/oskar_cl_utils.h" #include "utility/oskar_device_utils.h" #ifdef __cplusplus extern "C" { #endif void oskar_mem_random_uniform_f( const int num_elements, float* data, const unsigned int seed, const unsigned int counter1, const unsigned int counter2, const unsigned int counter3) { int i, i4, n1; n1 = num_elements / 4; #pragma omp parallel for private(i, i4) for (i = 0; i < n1; ++i) { OSKAR_R123_GENERATE_4(seed, i, counter1, counter2, counter3) /* Convert to uniform float. */ i4 = i * 4; data[i4] = oskar_int_to_range_0_to_1_f(u.i[0]); data[i4 + 1] = oskar_int_to_range_0_to_1_f(u.i[1]); data[i4 + 2] = oskar_int_to_range_0_to_1_f(u.i[2]); data[i4 + 3] = oskar_int_to_range_0_to_1_f(u.i[3]); } if (num_elements % 4) { OSKAR_R123_GENERATE_4(seed, n1, counter1, counter2, counter3) /* Convert to uniform float. */ i4 = n1 * 4; data[i4] = oskar_int_to_range_0_to_1_f(u.i[0]); if (i4 + 1 < num_elements) data[i4 + 1] = oskar_int_to_range_0_to_1_f(u.i[1]); if (i4 + 2 < num_elements) data[i4 + 2] = oskar_int_to_range_0_to_1_f(u.i[2]); if (i4 + 3 < num_elements) data[i4 + 3] = oskar_int_to_range_0_to_1_f(u.i[3]); } } void oskar_mem_random_uniform_d( const int num_elements, double* data, const unsigned int seed, const unsigned int counter1, const unsigned int counter2, const unsigned int counter3) { int i, i4, n1; n1 = num_elements / 4; #pragma omp parallel for private(i, i4) for (i = 0; i < n1; ++i) { OSKAR_R123_GENERATE_4(seed, i, counter1, counter2, counter3) /* Convert to uniform float. */ i4 = i * 4; data[i4] = oskar_int_to_range_0_to_1_d(u.i[0]); data[i4 + 1] = oskar_int_to_range_0_to_1_d(u.i[1]); data[i4 + 2] = oskar_int_to_range_0_to_1_d(u.i[2]); data[i4 + 3] = oskar_int_to_range_0_to_1_d(u.i[3]); } if (num_elements % 4) { OSKAR_R123_GENERATE_4(seed, n1, counter1, counter2, counter3) /* Convert to uniform float. */ i4 = n1 * 4; data[i4] = oskar_int_to_range_0_to_1_d(u.i[0]); if (i4 + 1 < num_elements) data[i4 + 1] = oskar_int_to_range_0_to_1_d(u.i[1]); if (i4 + 2 < num_elements) data[i4 + 2] = oskar_int_to_range_0_to_1_d(u.i[2]); if (i4 + 3 < num_elements) data[i4 + 3] = oskar_int_to_range_0_to_1_d(u.i[3]); } } void oskar_mem_random_uniform(oskar_Mem* data, unsigned int seed, unsigned int counter1, unsigned int counter2, unsigned int counter3, int* status) { int type, location; size_t num_elements; #ifdef OSKAR_HAVE_OPENCL cl_kernel k = 0; #endif /* Check if safe to proceed. */ if (*status) return; type = oskar_mem_precision(data); location = oskar_mem_location(data); num_elements = oskar_mem_length(data); if (oskar_mem_is_complex(data)) num_elements *= 2; if (oskar_mem_is_matrix(data)) num_elements *= 4; if (location == OSKAR_GPU) { #ifdef OSKAR_HAVE_CUDA if (type == OSKAR_SINGLE) oskar_mem_random_uniform_cuda_f((int)num_elements, oskar_mem_float(data, status), seed, counter1, counter2, counter3); else if (type == OSKAR_DOUBLE) oskar_mem_random_uniform_cuda_d((int)num_elements, oskar_mem_double(data, status), seed, counter1, counter2, counter3); oskar_device_check_error(status); #else *status = OSKAR_ERR_CUDA_NOT_AVAILABLE; #endif } else if (location == OSKAR_CPU) { if (type == OSKAR_SINGLE) oskar_mem_random_uniform_f((int)num_elements, oskar_mem_float(data, status), seed, counter1, counter2, counter3); else if (type == OSKAR_DOUBLE) oskar_mem_random_uniform_d((int)num_elements, oskar_mem_double(data, status), seed, counter1, counter2, counter3); } else if (location & OSKAR_CL) { #ifdef OSKAR_HAVE_OPENCL if (type == OSKAR_SINGLE) k = oskar_cl_kernel("mem_random_uniform_float"); else if (type == OSKAR_DOUBLE) k = oskar_cl_kernel("mem_random_uniform_double"); if (k) { cl_device_type dev_type; cl_event event; cl_int error, gpu; cl_uint n, s, c1, c2, c3; size_t global_size, local_size; /* Set kernel arguments. */ clGetDeviceInfo(oskar_cl_device_id(), CL_DEVICE_TYPE, sizeof(cl_device_type), &dev_type, NULL); gpu = dev_type & CL_DEVICE_TYPE_GPU; n = (cl_uint) num_elements; s = (cl_uint) seed; c1 = (cl_uint) counter1; c2 = (cl_uint) counter2; c3 = (cl_uint) counter3; error = clSetKernelArg(k, 0, sizeof(cl_uint), &n); error |= clSetKernelArg(k, 1, sizeof(cl_mem), oskar_mem_cl_buffer(data, status)); error |= clSetKernelArg(k, 2, sizeof(cl_uint), &s); error |= clSetKernelArg(k, 3, sizeof(cl_uint), &c1); error |= clSetKernelArg(k, 4, sizeof(cl_uint), &c2); error |= clSetKernelArg(k, 5, sizeof(cl_uint), &c3); if (*status) return; if (error != CL_SUCCESS) { *status = OSKAR_ERR_INVALID_ARGUMENT; return; } /* Launch kernel on current command queue. */ local_size = gpu ? 256 : 128; global_size = ((((num_elements + 3) / 4) + local_size - 1) / local_size) * local_size; error = clEnqueueNDRangeKernel(oskar_cl_command_queue(), k, 1, NULL, &global_size, &local_size, 0, NULL, &event); if (error != CL_SUCCESS) { *status = OSKAR_ERR_KERNEL_LAUNCH_FAILURE; return; } } else { *status = OSKAR_ERR_FUNCTION_NOT_AVAILABLE; } #else *status = OSKAR_ERR_OPENCL_NOT_AVAILABLE; #endif } else *status = OSKAR_ERR_BAD_LOCATION; } #ifdef __cplusplus } #endif
GB_unaryop__identity_int32_uint16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__identity_int32_uint16 // op(A') function: GB_tran__identity_int32_uint16 // C type: int32_t // A type: uint16_t // cast: int32_t cij = (int32_t) aij // unaryop: cij = aij #define GB_ATYPE \ uint16_t #define GB_CTYPE \ int32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ uint16_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = x ; // casting #define GB_CASTING(z, aij) \ int32_t z = (int32_t) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_IDENTITY || GxB_NO_INT32 || GxB_NO_UINT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__identity_int32_uint16 ( int32_t *Cx, // Cx and Ax may be aliased uint16_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__identity_int32_uint16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
Lamg.h
/* * Lamg.h * * Created on: Oct 20, 2015 * Author: Michael Wegner (michael.wegner@student.kit.edu) */ #ifndef NETWORKIT_CPP_NUMERICS_LAMG_LAMG_H_ #define NETWORKIT_CPP_NUMERICS_LAMG_LAMG_H_ #include <vector> #include "../LinearSolver.h" #include "MultiLevelSetup.h" #include "SolverLamg.h" #include "../GaussSeidelRelaxation.h" #include "../../algebraic/MatrixTools.h" #include "../../components/ParallelConnectedComponents.h" #include "omp.h" namespace NetworKit { /** * @ingroup numerics * Represents the interface to the Lean Algebraic Multigrid (LAMG) graph Laplacian linear solver * by Oren E. Livne and Achi Brandt. * @see Livne, Oren E., and Achi Brandt. "Lean algebraic multigrid (LAMG): Fast graph Laplacian linear solver." SIAM Journal on Scientific Computing 34.4 (2012): B499-B522. */ template<class Matrix> class Lamg : public LinearSolver<Matrix> { private: bool validSetup; GaussSeidelRelaxation<Matrix> smoother; MultiLevelSetup<Matrix> lamgSetup; Matrix laplacianMatrix; std::vector<LevelHierarchy<Matrix>> compHierarchies; std::vector<SolverLamg<Matrix>> compSolvers; std::vector<LAMGSolverStatus> compStati; std::vector<Vector> initialVectors; std::vector<Vector> rhsVectors; count numComponents; std::vector<std::vector<index>> components; std::vector<index> graph2Components; void initializeForOneComponent(); public: /** * Construct a solver with the given @a tolerance. The relative residual ||Ax-b||/||b|| will be less than or equal to * @a tolerance after the solver finished. * @param tolerance */ Lamg(const double tolerance = 1e-6) : LinearSolver<Matrix>(tolerance), validSetup(false), lamgSetup(smoother), numComponents(0) {} /** Default destructor */ ~Lamg() = default; /** * Compute the multigrid hierarchy for the given Laplacian matrix @a laplacianMatrix. * @param laplacianMatrix * @note This method also works for disconnected graphs. If you know that the graph is connected, * if is faster to use @ref setupConnected instead. */ void setup(const Matrix& laplacianMatrix); /** * Compute the multigrid hierarchy for te given Laplacian matrix @a laplacianMatrix. * @param laplacianMatrix * @note The graph has to be connected for this method to work. Otherwise the output is undefined. */ void setupConnected(const Matrix& laplacianMatrix); /** * Computes the @a result for the matrix currently setup and the right-hand side @a rhs. * The maximum spent time can be specified by @a maxConvergenceTime and the maximum number of iterations can be set * by @a maxIterations. * @param rhs * @param result * @param maxConvergenceTime * @param maxIterations * @return A @ref SolverStatus object which provides some statistics like the final absolute residual. */ SolverStatus solve(const Vector& rhs, Vector& result, count maxConvergenceTime = 5 * 60 * 1000, count maxIterations = std::numeric_limits<count>::max()); /** * Compute the @a results for the matrix currently setup and the right-hand sides @a rhs. * The maximum spent time for each system can be specified by @a maxConvergenceTime and the maximum number of iterations can be set * by @a maxIterations. * @param rhs * @param results * @param maxConvergenceTime * @param maxIterations */ void parallelSolve(const std::vector<Vector>& rhs, std::vector<Vector>& results, count maxConvergenceTime = 5 * 60 * 1000, count maxIterations = std::numeric_limits<count>::max()); }; template<class Matrix> void Lamg<Matrix>::initializeForOneComponent() { compHierarchies = std::vector<LevelHierarchy<Matrix>>(1); lamgSetup.setup(laplacianMatrix, compHierarchies[0]); compSolvers.clear(); compSolvers.push_back(SolverLamg<Matrix>(compHierarchies[0], smoother)); validSetup = true; } template<class Matrix> void Lamg<Matrix>::setupConnected(const Matrix& laplacianMatrix) { this->laplacianMatrix = laplacianMatrix; initializeForOneComponent(); numComponents = 1; } template<class Matrix> void Lamg<Matrix>::setup(const Matrix& laplacianMatrix) { this->laplacianMatrix = laplacianMatrix; Graph G = MatrixTools::matrixToGraph(laplacianMatrix); ParallelConnectedComponents con(G, false); con.run(); numComponents = con.numberOfComponents(); if (numComponents == 1) { initializeForOneComponent(); } else { graph2Components = std::vector<index>(G.numberOfNodes()); initialVectors = std::vector<Vector>(numComponents); rhsVectors = std::vector<Vector>(numComponents); components = std::vector<std::vector<index>>(numComponents); compHierarchies = std::vector<LevelHierarchy<Matrix>>(numComponents); compSolvers.clear(); compStati = std::vector<LAMGSolverStatus>(numComponents); // create solver for every component index compIdx = 0; for (auto component : con.getPartition().getSubsets()) { components[compIdx] = std::vector<index>(component.begin(), component.end()); std::vector<Triplet> triplets; index idx = 0; for (node u : components[compIdx]) { graph2Components[u] = idx; idx++; } for (node u : components[compIdx]) { G.forNeighborsOf(u, [&](node v, edgeweight w) { triplets.push_back({graph2Components[u], graph2Components[v], w}); }); } Matrix compMatrix(component.size(), component.size(), triplets); initialVectors[compIdx] = Vector(component.size()); rhsVectors[compIdx] = Vector(component.size()); lamgSetup.setup(compMatrix, compHierarchies[compIdx]); compSolvers.push_back(SolverLamg<Matrix>(compHierarchies[compIdx], smoother)); LAMGSolverStatus status; status.desiredResidualReduction = this->tolerance * component.size() / G.numberOfNodes(); compStati[compIdx] = status; compIdx++; } validSetup = true; } } template<class Matrix> SolverStatus Lamg<Matrix>::solve(const Vector& rhs, Vector& result, count maxConvergenceTime, count maxIterations) { if (!validSetup || result.getDimension() != laplacianMatrix.numberOfColumns() || rhs.getDimension() != laplacianMatrix.numberOfRows()) { throw std::runtime_error("No or wrong matrix is setup for given vectors."); } SolverStatus status; if (numComponents == 1) { LAMGSolverStatus stat; stat.desiredResidualReduction = this->tolerance * rhs.length() / (laplacianMatrix * result - rhs).length(); stat.maxIters = maxIterations; stat.maxConvergenceTime = maxConvergenceTime; compSolvers[0].solve(result, rhs, stat); status.residual = stat.residual; status.numIters = stat.numIters; status.converged = stat.converged; } else { // solve on every component count maxIters = 0; for (index i = 0; i < components.size(); ++i) { for (auto element : components[i]) { initialVectors[i][graph2Components[element]] = result[element]; rhsVectors[i][graph2Components[element]] = rhs[element]; } double resReduction = this->tolerance * rhsVectors[i].length() / (compHierarchies[i].at(0).getLaplacian() * initialVectors[i] - rhsVectors[i]).length(); compStati[i].desiredResidualReduction = resReduction * components[i].size() / laplacianMatrix.numberOfRows(); compStati[i].maxIters = maxIterations; compStati[i].maxConvergenceTime = maxConvergenceTime; compSolvers[i].solve(initialVectors[i], rhsVectors[i], compStati[i]); for (auto element : components[i]) { // write solution back to result result[element] = initialVectors[i][graph2Components[element]]; } maxIters = std::max(maxIters, compStati[i].numIters); } status.residual = (rhs - laplacianMatrix * result).length(); status.converged = status.residual <= this->tolerance; status.numIters = maxIters; } return status; } template<class Matrix> void Lamg<Matrix>::parallelSolve(const std::vector<Vector>& rhs, std::vector<Vector>& results, count maxConvergenceTime, count maxIterations) { if (numComponents == 1) { assert(rhs.size() == results.size()); const index numThreads = omp_get_max_threads(); if (compSolvers.size() != numThreads) { compSolvers.clear(); for (index i = 0; i < (index) numThreads; ++i) { compSolvers.push_back(SolverLamg<Matrix>(compHierarchies[0], smoother)); } } bool nested = omp_get_nested(); if (nested) omp_set_nested(false); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(rhs.size()); ++i) { index threadId = omp_get_thread_num(); LAMGSolverStatus stat; stat.desiredResidualReduction = this->tolerance * rhs[i].length() / (laplacianMatrix * results[i] - rhs[i]).length(); stat.maxIters = maxIterations; stat.maxConvergenceTime = maxConvergenceTime; compSolvers[threadId].solve(results[i], rhs[i], stat); } if (nested) omp_set_nested(true); } } } /* namespace NetworKit */ #endif /* NETWORKIT_CPP_NUMERICS_LAMG_LAMG_H_ */
ICP.h
/////////////////////////////////////////////////////////////////////////////// /// "Sparse Iterative Closest Point" /// by Sofien Bouaziz, Andrea Tagliasacchi, Mark Pauly /// Copyright (C) 2013 LGG, EPFL /// -- modified version -- /////////////////////////////////////////////////////////////////////////////// /// 1) This file contains different implementations of the ICP algorithm. /// 2) This code requires EIGEN and NANOFLANN. /// 3) If OPENMP is activated some part of the code will be parallelized. /// 4) This code is for now designed for 3D registration /// 5) Two main input types are Eigen::Matrix3Xd or Eigen::Map<Eigen::Matrix3Xd> /////////////////////////////////////////////////////////////////////////////// /// namespace nanoflann: NANOFLANN KD-tree adaptor for EIGEN /// namespace RigidMotionEstimator: functions to compute the rigid motion /// namespace SICP: sparse ICP implementation /// namespace ICP: reweighted ICP implementation /////////////////////////////////////////////////////////////////////////////// //Note for Online Surface Reconstruction: //The original implementation has been adapted slightly to conform to OSR data structures #ifndef ICP_H #define ICP_H #include <Eigen/Dense> #include <vector> #include "osr/INeighborQueryable.h" #include <nsessentials/util/TimedBlock.h> #include "osr/common.h" #include <iostream> /// Compute the rigid motion for point-to-point and point-to-plane distances namespace RigidMotionEstimator { template <typename Derived1, typename Derived2, typename Derived3> Eigen::Affine3f point_to_point(const Eigen::MatrixBase<Derived1>& X, const Eigen::MatrixBase<Derived2>& Y, const Eigen::MatrixBase<Derived3>& w, const Eigen::Affine3f& initialTransform) { /// Normalize weight vector Eigen::VectorXd w_normalized = w.template cast<double>()/(double)w.sum(); /// De-mean Eigen::Vector3d X_mean, Y_mean; for(int i=0; i<3; ++i) { X_mean(i) = (X.row(i).template cast<double>().array()*w_normalized.transpose().array()).sum(); Y_mean(i) = (Y.row(i).template cast<double>().array()*w_normalized.transpose().array()).sum(); } X_mean = initialTransform.cast<double>() * X_mean; /// Compute transformation Eigen::Affine3d transformation = initialTransform.cast<double>(); transformation.pretranslate(-X_mean.cast<double>()); Eigen::Matrix3d sigma; sigma.setConstant(0.0); for (int i = 0; i < X.cols(); ++i) { sigma += (initialTransform.template cast<double>() * X.col(i).template cast<double>() - X_mean) * (double)w_normalized.coeff(i) * (Y.col(i).template cast<double>() - Y_mean).transpose(); } Eigen::JacobiSVD<Eigen::Matrix3d> svd(sigma, Eigen::ComputeFullU | Eigen::ComputeFullV); Eigen::Affine3d rotation; rotation.setIdentity(); if(svd.matrixU().determinant()*svd.matrixV().determinant() < 0.0) { Eigen::Vector3d S = Eigen::Vector3d::Ones(); S(2) = -1.0; rotation.linear().noalias() = svd.matrixV()*S.asDiagonal()*svd.matrixU().transpose(); } else { rotation.linear().noalias() = svd.matrixV()*svd.matrixU().transpose(); } transformation = rotation * transformation; transformation.pretranslate(Y_mean); /// Return transform return transformation.cast<float>(); } /// @param Source (one 3D point per column) /// @param Target (one 3D point per column) template <typename Derived1, typename Derived2> inline Eigen::Affine3f point_to_point(const Eigen::MatrixBase<Derived1>& X, const Eigen::MatrixBase<Derived2>& Y, const Eigen::Affine3f& initialTransform) { return point_to_point(X, Y, Eigen::VectorXf::Ones(X.cols()), initialTransform); } /// @param Source (one 3D point per column) /// @param Target (one 3D point per column) /// @param Target normals (one 3D normal per column) /// @param Confidence weights /// @param Right hand side template <typename Derived1, typename Derived2, typename Derived3, typename Derived4, typename Derived5> Eigen::Affine3f point_to_plane(const Eigen::MatrixBase<Derived1>& X, const Eigen::MatrixBase<Derived2>& Y, const Eigen::MatrixBase<Derived3>& N, const Eigen::MatrixBase<Derived4>& w, const Eigen::MatrixBase<Derived5>& u, const Eigen::Affine3f& initialTransform) { typedef Eigen::Matrix<double, 6, 6> Matrix66; typedef Eigen::Matrix<double, 6, 1> Vector6; typedef Eigen::Block<Matrix66, 3, 3> Block33; /// Normalize weight vector Eigen::VectorXd w_normalized = w.template cast<double>()/(double)w.sum(); /// De-mean Eigen::Vector3d X_mean; for(int i=0; i<3; ++i) X_mean(i) = (X.row(i).template cast<double>().array()*w_normalized.transpose().array()).sum(); X_mean = initialTransform.cast<double>() * X_mean; Eigen::Affine3d transformation = initialTransform.cast<double>(); transformation.pretranslate(-X_mean); /// Prepare LHS and RHS Matrix66 LHS = Matrix66::Zero(); Vector6 RHS = Vector6::Zero(); Block33 TL = LHS.topLeftCorner<3,3>(); Block33 TR = LHS.topRightCorner<3,3>(); Block33 BR = LHS.bottomRightCorner<3,3>(); Eigen::MatrixXd C = Eigen::MatrixXd::Zero(3,X.cols()); #pragma omp parallel { #pragma omp for for(int i=0; i<X.cols(); i++) { C.col(i) = ((initialTransform * X.col(i)).template cast<double>() - X_mean).cross(N.col(i).template cast<double>()); } #pragma omp sections nowait { #pragma omp section for(int i=0; i<X.cols(); i++) TL.selfadjointView<Eigen::Upper>().rankUpdate(C.col(i), w(i)); #pragma omp section for(int i=0; i<X.cols(); i++) TR += (C.col(i) * N.col(i).template cast<double>().transpose())*w(i); #pragma omp section for(int i=0; i<X.cols(); i++) BR.selfadjointView<Eigen::Upper>().rankUpdate(N.col(i).template cast<double>(), w(i)); #pragma omp section for(int i=0; i<C.cols(); i++) { double dist_to_plane = -(((initialTransform * X.col(i)).template cast<double>() - Y.col(i).template cast<double>()).dot(N.col(i).template cast<double>()) - u(i)) * w(i); RHS.head<3>() += C.col(i)*dist_to_plane; RHS.tail<3>() += N.col(i).template cast<double>() * dist_to_plane; } } } LHS = LHS.selfadjointView<Eigen::Upper>(); /// Compute transformation Eigen::LDLT<Matrix66> ldlt(LHS); RHS = ldlt.solve(RHS); transformation = Eigen::AngleAxisd(RHS(0), Eigen::Vector3d::UnitX()) * Eigen::AngleAxisd(RHS(1), Eigen::Vector3d::UnitY()) * Eigen::AngleAxisd(RHS(2), Eigen::Vector3d::UnitZ()) * transformation; transformation.pretranslate(RHS.tail<3>()); transformation.pretranslate(X_mean); return transformation.cast<float>(); } /// @param Source (one 3D point per column) /// @param Target (one 3D point per column) /// @param Target normals (one 3D normal per column) /// @param Confidence weights template <typename Derived1, typename Derived2, typename Derived3, typename Derived4> inline Eigen::Affine3f point_to_plane(const Eigen::MatrixBase<Derived1>& X, const Eigen::MatrixBase<Derived2>& Yp, const Eigen::MatrixBase<Derived3>& Yn, const Eigen::MatrixBase<Derived4>& w, const Eigen::Affine3f& initialTransform) { return point_to_plane(X, Yp, Yn, w, Eigen::VectorXf::Zero(X.cols()), initialTransform); } } /////////////////////////////////////////////////////////////////////////////// /// ICP implementation using ADMM/ALM/Penalty method namespace SICP { struct Parameters { bool use_penalty = false; /// if use_penalty then penalty method else ADMM or ALM (see max_inner) float p = 1.0f; /// p norm float mu = 10.0f; /// penalty weight float alpha = 1.2f; /// penalty increase factor float max_mu = 1e5f; /// max penalty int max_icp = 100; /// max ICP iteration int max_outer = 100; /// max outer iteration int max_inner = 1; /// max inner iteration. If max_inner=1 then ADMM else ALM float stop = 1e-5f; /// stopping criteria bool print_icpn = false; /// (debug) print ICP iteration }; /// Shrinkage operator (Automatic loop unrolling using template) template<unsigned int I> inline float shrinkage(float mu, float n, float p, float s) { return shrinkage<I-1>(mu, n, p, 1.0f - (p/mu)*std::pow(n, p-2.0f)*std::pow(s, p-1.0f)); } template<> inline float shrinkage<0>(float, float, float, float s) {return s;} /// 3D Shrinkage for point-to-point template<unsigned int I> inline void shrink(Eigen::Matrix3Xf& dirField, float mu, float p) { float Ba = std::pow((2.0f/mu)*(1.0f-p), 1.0f/(2.0f-p)); float ha = Ba + (p/mu)*std::pow(Ba, p-1.0f); #pragma omp parallel for for(int i=0; i<dirField.cols(); ++i) { float n = dirField.col(i).norm(); float w = 0.0; if(n > ha) w = shrinkage<I>(mu, n, p, (Ba/n + 1.0f)/2.0f); dirField.col(i) *= w; } } /// 1D Shrinkage for point-to-plane template<unsigned int I> inline void shrink(Eigen::VectorXf& y, float mu, float p) { float Ba = std::pow((2.0/mu)*(1.0-p), 1.0/(2.0-p)); float ha = Ba + (p/mu)*std::pow(Ba, p-1.0); #pragma omp parallel for for(int i=0; i<y.rows(); ++i) { float n = std::abs(y(i)); float s = 0.0; if(n > ha) s = shrinkage<I>(mu, n, p, (Ba/n + 1.0)/2.0); y(i) *= s; } } /// Sparse ICP with point to point /// @param Source (one 3D point per column) /// @param Target (one 3D point per column) /// @param Parameters template <typename Index> inline Eigen::Affine3f point_to_point(const osr::Matrix3Xf& X, const osr::Matrix3Xf& N, const osr::IPointQueryable<Index>& Y, Parameters par = Parameters()) { /// Buffers Eigen::Matrix3Xf dirField = Eigen::Matrix3Xf::Zero(3, X.cols()); Eigen::Matrix3Xf Z = Eigen::Matrix3Xf::Zero(3, X.cols()); Eigen::Matrix3Xf C = Eigen::Matrix3Xf::Zero(3, X.cols()); Eigen::Affine3f transform = Eigen::Affine3f::Identity(); Eigen::Matrix3Xf Xo1 = X; Eigen::Matrix3Xf Xo2 = X; Eigen::VectorXf w = Eigen::VectorXf::Ones(X.cols()); /// ICP for (int icp = 0; icp<par.max_icp; ++icp) { if (par.print_icpn) std::cout << "Iteration #" << icp << "/" << par.max_icp << std::endl; /// Find closest point { nse::util::TimedBlock b("Finding correspondences .."); #pragma omp parallel for for (int i = 0; i < X.cols(); ++i) { Eigen::Vector3f px = transform * X.col(i); auto idx = Y.findClosestCompatiblePoint(px, transform.linear() * N.col(i)); if (Y.isIndexValid(idx)) { dirField.col(i) = Y.neighborP(idx); auto d = dirField.col(i) - px; auto ld = d.squaredNorm(); w(i) = 1; } else { dirField.col(i).setZero(); w(i) = 0; } } } //Compute rotation and translation double mu = par.mu; for (int outer = 0; outer<par.max_outer; ++outer) { double dual = 0.0; for (int inner = 0; inner<par.max_inner; ++inner) { //Z update (shrinkage) Z = transform * X - dirField + C / mu; shrink<3>(Z, mu, par.p); // Rotation and translation update Eigen::Matrix3Xf U = dirField + Z - C / mu; transform = RigidMotionEstimator::point_to_point(X, U, w, transform); // Stopping criteria dual = (transform * X - Xo1).colwise().norm().maxCoeff(); Xo1 = transform * X; if (dual < par.stop) break; } // C update (lagrange multipliers) Eigen::Matrix3Xf P = transform * X - dirField - Z; if (!par.use_penalty) C.noalias() += mu*P; // mu update (penalty) if (mu < par.max_mu) mu *= par.alpha; // Stopping criteria double primal = P.colwise().norm().maxCoeff(); if (primal < par.stop && dual < par.stop) break; } //transform = RigidMotionEstimator::point_to_point(X.V(), dirField, w, transform); /// Stopping criteria double stop = (transform * X - Xo2).colwise().norm().maxCoeff(); Xo2 = transform * X; if (stop < par.stop) break; } return transform; } /// Sparse ICP with point to plane /// @param Source (one 3D point per column) /// @param Target (one 3D point per column) /// @param Target normals (one 3D normal per column) /// @param Parameters template <typename Index> Eigen::Affine3f point_to_plane(const osr::Matrix3Xf& X, const osr::Matrix3Xf& N, const osr::IPointQueryable<Index>& Y, Parameters par = Parameters()) { /// Buffers Eigen::Matrix3Xf Qp = Eigen::Matrix3Xf::Zero(3, X.cols()); Eigen::Matrix3Xf Qn = Eigen::Matrix3Xf::Zero(3, X.cols()); Eigen::VectorXf Z = Eigen::VectorXf::Zero(X.cols()); Eigen::VectorXf C = Eigen::VectorXf::Zero(X.cols()); Eigen::Affine3f transform = Eigen::Affine3f::Identity(); Eigen::Matrix3Xf Xo1 = X; Eigen::Matrix3Xf Xo2 = X; Eigen::VectorXf w = Eigen::VectorXf::Ones(X.cols()); /// ICP for(int icp=0; icp<par.max_icp; ++icp) { if(par.print_icpn) std::cout << "Iteration #" << icp << "/" << par.max_icp << std::endl; /// Find closest point { nse::util::TimedBlock b("Finding correspondences .."); float sumWeight = 0; #pragma omp parallel for reduction(+ : sumWeight) for (int i = 0; i < X.cols(); ++i) { Eigen::Vector3f px = transform * X.col(i); auto idx = Y.findClosestCompatiblePoint(px, transform.linear() * N.col(i)); if (Y.isIndexValid(idx)) { Qp.col(i) = Y.neighborP(idx); Qn.col(i) = Y.neighborN(idx); w(i) = 1; sumWeight += w(i); } else { Qp.col(i).setZero(); Qn.col(i) = Eigen::Vector3f::UnitX(); w(i) = 0; } } if (sumWeight < 3) return transform; } /// Compute rotation and translation float mu = par.mu; for(int outer=0; outer<par.max_outer; ++outer) { float dual = 0.0; for(int inner=0; inner<par.max_inner; ++inner) { /// Z update (shrinkage) Eigen::Matrix3Xf transformedX = transform * X; Z = (Qn.array()*(transformedX - Qp).array()).colwise().sum().transpose()+C.array()/mu; shrink<3>(Z, mu, par.p); /// Rotation and translation update Eigen::VectorXf U = Z-C/mu; transform = RigidMotionEstimator::point_to_plane(X, Qp, Qn, w, U, transform); /// Stopping criteria dual = (transform * X - Xo1).colwise().norm().maxCoeff(); Xo1 = transform * X; if(dual < par.stop) break; } /// C update (lagrange multipliers) Eigen::VectorXf P = ((transform.linear() * Qn).array()*(transform * X - Qp).array()).colwise().sum().transpose()-Z.array(); if(!par.use_penalty) C.noalias() += mu*P; /// mu update (penalty) if(mu < par.max_mu) mu *= par.alpha; /// Stopping criteria float primal = P.array().abs().maxCoeff(); if(primal < par.stop && dual < par.stop) break; } /// Stopping criteria float stop = (transform * X - Xo2).colwise().norm().maxCoeff(); Xo2 = transform * X; if(stop < par.stop) break; } return transform; } } #endif
sort.mp.c
#include "../include/util.h" void sort(int *data, int size) { for(int i = 0, j = 0; i < size; i++) { int minor = INT_MAX; #pragma omp parallel for reduction(min:minor) for(j = i; j < size; j++) { minor = data[j]; j = j; } int aux = data[i]; data[i] = minor; data[j] = aux; for(int i = 0; i < 7; i++) printf("%d, ", data[i]); printf("%d.\n", data[7]); } } int main(int argc, char const *argv[]) { int data[] = { 8, 4, 5, 1, 7, 2, 6, 9 }; // 1, 2, 4, 5, 6, 7, 8, 9 sort(data, 8); return 0; }
5-64t.c
#include <stdio.h> #include <omp.h> int main() { int i; int sum=0; omp_set_num_threads(64); #pragma omp parallel for for (i=0; i<COUNT; i++) { sum = sum + i; printf("Thread number: %d Iteration: %d Local Sum: %d \n", omp_get_thread_num(), i, sum); } printf("\n All Threads Done – Final Global Sum: %d \n\n", sum); }
poly.c
/* poly.c - Polynomial (de)compression routines * * Copyright (c) 2015 Maurizio Tomasi * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "libpolycomp.h" #include <assert.h> #include <limits.h> #include <stdlib.h> #include <string.h> #include <gsl/gsl_block_double.h> #include <gsl/gsl_vector_double.h> #include <gsl/gsl_matrix_double.h> #include <gsl/gsl_multifit.h> #include <fftw3.h> #ifdef WITH_OPENMP #include <omp.h> #else static int omp_get_thread_num(void) { return 0; } static int omp_get_max_threads(void) { return 1; } #endif /**********************************************************************/ /** \defgroup poly Polynomial compression functions * * Polynomial compression relies on a simple idea, that is to divide * the input data stream into subsets of consecutive samples (called * "chunks"), and to approximate each chunk by means of a polynomial. * Such compression is inherently lossy, as the residuals of the * fitting procedure are usually discarded. If the polynomial used for * the fitting produces residuals that are too large, usually the * samples in the chunk are saved in uncompressed form. * * This idea has been widely applied in the literature. Libpolycomp * implements an improvement over it, because if the fit residuals are * too large, the library saves a chopped sequence of the Chebyshev * transform of the residuals. This allows to achieve better * compression ratios in those cases where polynomial fitting is not * always enough to keep compression errors below the desired * threshold. This kind of compression works quite well for smooth * data series, where changes between consecutive samples are well * described by slowly varying continuous functions. It is not * suitable if the signal contains noise, unless this noise is * significantly smaller than the signal and than the error threshold. * * Libpolycomp allows to avoid the usage of Chebyshev transforms. In * this case, if no polynomial of the desired degree are able to fit * the data with the given error threshold, the data for that chunk is * saved uncompressed. * * The typical workflow for applying polynomial compression is the * following: * * 1. Allocate a new \ref pcomp_polycomp_t object via a call to \ref * pcomp_init_polycomp. Such object contains the parameters to be * used for the compression, e.g., the size of each chunk, the * degree of the fitting polynomial, whether to apply or not the * Chebyshev transform to the residuals, etc. * * 2. Split the data into chunks and compress each of them using the * function \ref pcomp_compress_polycomp. * * 3. Convert the list of chunks into a byte sequence using \ref * pcomp_encode_chunks, typically with the purpose of saving it * into a file or sending it through a pipe/socket/etc. * * The decompression workflow is specular: * * 1. Process the byte sequence containing the compressed data using * \ref pcomp_decode_chunks. This will produce a list of chunks * that are still compressed. * * 2. Decompress the chunks using the function \ref * pcomp_decompress_polycomp. * * The compression functions described in this page use the \ref * pcomp_polycomp_t structure to determine which parameters to use for * the compression. The functions that allow to allocate/free/manage * this structure are the following: * * - \ref pcomp_init_polycomp and \ref pcomp_free_polycomp * - \ref pcomp_polycomp_samples_per_chunk * - \ref pcomp_polycomp_num_of_poly_coeffs * - \ref pcomp_polycomp_max_error * - \ref pcomp_polycomp_algorithm * - \ref pcomp_polycomp_period and \ref pcomp_polycomp_set_period * * It is possible to use a set of more low-level functions to use * polynomial compression. Refer to \ref poly_lowlevel for further * information. */ /** \defgroup poly_lowlevel Polynomial compression (low-level functions) */ /**********************************************************************/ static double integer_power(int x, int y) { double dbl_x = (double)x; if (y < 0) abort(); if (y == 0) return 1.0; else if (y == 1) return dbl_x; else { double result = dbl_x * dbl_x; int cur_power = 2; while (2 * cur_power < y) { result *= result; cur_power *= 2; } if (y > cur_power) result *= integer_power(x, y - cur_power); return result; } } /*********************************************************************** * Types and functions used for polynomial least-square fitting */ struct __pcomp_poly_fit_data_t { size_t num_of_samples; size_t num_of_coeffs; gsl_multifit_linear_workspace* workspace; gsl_matrix* matrix; gsl_vector* y; gsl_vector* c; gsl_matrix* cov_matrix; }; /** \ingroup polyfit * * \brief Allocate a new instance of the \ref pcomp_poly_fit_data_t * structure on the heap * * \param[in] num_of_samples Number of floating-point numbers that * must fit the polynomial * * \param[in] num_of_coeffs Number of coefficients of the * least-squares fitting polynomial \f$p(x)\f$. This is equal to * \f$\deg p(x) + 1\f$, where \f$\deg p(x)\f$ is the degree of the * polynomial. Thus, for a parabolic polynomial of the form \f$p(x) = * a x^2 + b x + c\f$, \a num_of_coeffs = 3. * * \returns A newly created instance of \ref pcomp_poly_fit_data_t * structure. This must be freed using \ref pcomp_free_poly_fit, once * it is no longer used. */ pcomp_poly_fit_data_t* pcomp_init_poly_fit(size_t num_of_samples, size_t num_of_coeffs) { size_t i, j; pcomp_poly_fit_data_t* poly_fit = malloc(sizeof(pcomp_poly_fit_data_t)); if (poly_fit == NULL) abort(); poly_fit->num_of_samples = num_of_samples; poly_fit->num_of_coeffs = num_of_coeffs; poly_fit->workspace = gsl_multifit_linear_alloc(num_of_samples, num_of_coeffs); poly_fit->matrix = gsl_matrix_alloc(num_of_samples, num_of_coeffs); poly_fit->y = gsl_vector_alloc(num_of_samples); poly_fit->c = gsl_vector_alloc(num_of_coeffs); poly_fit->cov_matrix = gsl_matrix_alloc(num_of_coeffs, num_of_coeffs); for (i = 0; i < num_of_samples; ++i) { for (j = 0; j < num_of_coeffs; ++j) { gsl_matrix_set(poly_fit->matrix, i, j, integer_power(i + 1, j)); } } return poly_fit; } /** \ingroup polyfit * * \brief Free an instance of the \ref pcomp_poly_fit_data_t that has * been allocated via a call to \ref pcomp_init_poly_fit. * * \param[in] poly_fit Pointer to the structure to be freed */ void pcomp_free_poly_fit(pcomp_poly_fit_data_t* poly_fit) { if (poly_fit == NULL) return; gsl_matrix_free(poly_fit->matrix); gsl_vector_free(poly_fit->y); gsl_vector_free(poly_fit->c); gsl_matrix_free(poly_fit->cov_matrix); gsl_multifit_linear_free(poly_fit->workspace); free(poly_fit); } /** \ingroup polyfit * * \brief Return the number of samples to be used in a polynomial fit * * \param[in] poly_fit Pointer to the structure detailing the fit * * \returns The number of samples that should be passed to a call to * \ref pcomp_run_poly_fit. */ size_t pcomp_poly_fit_num_of_samples(const pcomp_poly_fit_data_t* poly_fit) { if (poly_fit == NULL) abort(); return poly_fit->num_of_samples; } /** \ingroup polyfit * * \brief Return the number of coefficients of the least-squares * fitting polynomial * * \param[in] poly_fit Pointer to the structure detailing the fit * * \returns The number of coefficients for the fitting polynomial (one * plus the polynomial degree) */ size_t pcomp_poly_fit_num_of_coeffs(const pcomp_poly_fit_data_t* poly_fit) { if (poly_fit == NULL) abort(); return poly_fit->num_of_coeffs; } /** \ingroup polyfit * * \brief Calculates a polynomial least-squares fit. * * Compute a least-squares fit between the numbers \f$x_i\f$ (with * \f$i = 1 \ldots N\f$) and the polynomial \f$p(x)\f$ through the * points \f$(i, x_i)_{i=1}^N\f$. The coefficients of \f$p(x)\f$ are * saved in \a coeffs, from the least to the greatest degree. * * Here is an example of the usage of this function: * * \code{.c} * double points[] = { 1.0, 3.0, 5.0 }; * double coeffs[2]; * const size_t num_of_points = sizeof(points) / sizeof(points[0]); * const size_t num_of_coeffs = sizeof(coeffs) / sizeof(coeffs[0]); * pcomp_poly_fit_data_t* poly_fit; * * poly_fit = pcomp_init_poly_fit(num_of_points, num_of_coeffs); * pcomp_run_poly_fit(poly_fit, coeffs, points); * printf("The data are fitted by the polynomial y = %f + %f x\n", * coeffs[0], coeffs[1]); * \endcode * * \param[in] poly_fit Pointer to a \ref pcomp_poly_fit_data_t * structure, created using the \ref pcomp_init_poly_fit function. * * \param[out] coeffs Pointer to an array where the coefficients of * the polynomial will be stored on exit. The array must have room for * a number of elements greater or equal than the value returned by * \ref pcomp_poly_fit_num_of_coeffs. * * \param[in] points Array of numbers \f$x_i\f$ to use in the fit. The * number of elements considered in the fit is equal to the return * value of \ref pcomp_poly_fit_num_of_samples. * * \returns \ref PCOMP_STAT_SUCCESS if the fit was computed * successfully, \ref PCOMP_STAT_INVALID_FIT if the data are incorrect * (e.g., there are fewer samples than unknowns). */ int pcomp_run_poly_fit(pcomp_poly_fit_data_t* poly_fit, double* coeffs, const double* points) { size_t idx; double chisq; if (poly_fit == NULL || coeffs == NULL || points == NULL) abort(); for (idx = 0; idx < poly_fit->num_of_samples; ++idx) { gsl_vector_set(poly_fit->y, idx, points[idx]); } if (gsl_multifit_linear(poly_fit->matrix, poly_fit->y, poly_fit->c, poly_fit->cov_matrix, &chisq, poly_fit->workspace) != 0) { return PCOMP_STAT_INVALID_FIT; } for (idx = 0; idx < poly_fit->num_of_coeffs; ++idx) { coeffs[idx] = gsl_vector_get(poly_fit->c, idx); } return PCOMP_STAT_SUCCESS; } /*********************************************************************** * Types and functions used for computing Chebyshev transforms */ struct __pcomp_chebyshev_t { double* input; double* output; size_t num_of_samples; fftw_plan fftw_plan_ptr; pcomp_transform_direction_t dir; }; /** \ingroup cheby * * \brief Allocate a new instance of the \ref pcomp_chebyshev_t * structure on the heap * * Despite the fact that this function takes the parameter \a dir, the * function which actually computes the Chebyshev transform (\ref * pcomp_run_chebyshev) allow to specify the desired direction. The * purpose of having \a dir encoded in \ref pcomp_chebyshev_t is that * sometimes it is useful to keep it memorized in the structure * itself. * * \param[in] num_of_samples Number of floating-point numbers that * will be transformed * * \param[in] dir Direction of the transform (either forward or * backward). This is used to determine the normalization constant of * the transform: * - If computing a forward transform, the normalization is \f$1 / (N * - 1)\f$, with \f$N\f$ the number of samples. * - If computing a backward transform, the normalization is 1. * * \returns A newly created instance of \ref pcomp_poly_fit_data_t * structure. This must be freed using \ref pcomp_free_poly_fit, once * it is no longer used. */ pcomp_chebyshev_t* pcomp_init_chebyshev(size_t num_of_samples, pcomp_transform_direction_t dir) { pcomp_chebyshev_t* chebyshev = malloc(sizeof(pcomp_chebyshev_t)); if (chebyshev == NULL) abort(); chebyshev->input = fftw_alloc_real(num_of_samples); chebyshev->output = fftw_alloc_real(num_of_samples); chebyshev->num_of_samples = num_of_samples; chebyshev->fftw_plan_ptr = fftw_plan_r2r_1d( num_of_samples, chebyshev->input, chebyshev->output, FFTW_REDFT00, FFTW_ESTIMATE); chebyshev->dir = dir; return chebyshev; } /** \ingroup cheby * * \brief Free the memory allocated by a previous call to \ref * pcomp_init_chebyshev. * * \param[in] plan Pointer to the structure to be freed. */ void pcomp_free_chebyshev(pcomp_chebyshev_t* plan) { if (plan == NULL) return; if (plan->input != NULL) fftw_free(plan->input); if (plan->output != NULL) fftw_free(plan->output); if (plan->fftw_plan_ptr != NULL) fftw_destroy_plan(plan->fftw_plan_ptr); free(plan); } /** \ingroup cheby * * \brief Return the number of samples in a Chebyshev transform * * \param[in] plan Pointer to the Chebyshev plan. * * \returns The number of elements that are used in the Chebyshev * transform specified by \a plan. */ size_t pcomp_chebyshev_num_of_samples(const pcomp_chebyshev_t* plan) { if (plan == NULL) abort(); return plan->num_of_samples; } /** \ingroup cheby * * \brief Return the direction of a Chebyshev transform * * \param[in] plan Pointer to the Chebyshev plan. * * \returns A \ref pcomp_transform_direction_t value specifying the * normalization used for the Chebyshev transform specified by \a * plan. */ pcomp_transform_direction_t pcomp_chebyshev_direction(const pcomp_chebyshev_t* plan) { if (plan == NULL) abort(); return plan->dir; } static double chebyshev_normalization(pcomp_transform_direction_t dir, size_t num_of_samples) { if (dir == PCOMP_TD_DIRECT) return 1.0 / (((double)num_of_samples) - 1.0); else return 0.5; } /** \ingroup cheby * * \brief Compute a forward/backward Chebyshev discrete transform * * \code{.c} * #define NUM_OF_POINTS 3 * double points[NUM_OF_POINTS] = { 0.0, 1.0, 3.0 }; * double transform[NUM_OF_POINTS]; * pcomp_chebyshev_t* chebyshev; * size_t idx; * * chebyshev = pcomp_init_chebyshev(NUM_OF_POINTS, PCOMP_TD_DIRECT); * pcomp_run_chebyshev(chebyshev, PCOMP_TD_DIRECT, transform, points); * * puts("Transform:"); * for (idx = 0; idx < NUM_OF_POINTS; ++idx) { * printf("%f\t", transform[idx]); * } * puts(""); * \endcode * * \param[in] plan Pointer to a Chebyshev plan created by \ref * pcomp_init_chebyshev * * \param[in] dir Direction of the transform. This parameter overrides * the internal direction of \a plan (returned by \ref * pcomp_chebyshev_direction). * * \param[out] output Pointer to an array of \c double values that will * contain the Chebyshev transform of \a input. It must have room for * a number of elements at least equal to the return value of \ref * pcomp_num_of_samples. * * \param[in] input Array of \c double values to be transformed. The * function will use the first N elements, where N is the return value * of \ref pcomp_num_of_samples. * * \returns \ref PCOMP_STAT_SUCCESS when successful. */ int pcomp_run_chebyshev(pcomp_chebyshev_t* plan, pcomp_transform_direction_t dir, double* output, const double* input) { double norm; size_t idx; if (plan == NULL) abort(); if (input != NULL) { for (idx = 0; idx < plan->num_of_samples; ++idx) { plan->input[idx] = input[idx]; } } fftw_execute(plan->fftw_plan_ptr); norm = chebyshev_normalization(dir, plan->num_of_samples); for (idx = 0; idx < plan->num_of_samples; ++idx) { plan->output[idx] *= norm; } if (output != NULL && output != plan->output) { for (idx = 0; idx < plan->num_of_samples; ++idx) { output[idx] = plan->output[idx]; } } return PCOMP_STAT_SUCCESS; } /** \ingroup cheby * * \brief Return the input data used in the last call to \ref *pcomp_run_chebyshev * * If \ref pcomp_run_chebyshev was never called, the array returned by * this function contains garbage. * * \param[in] plan Pointer to a Chebyshev plan created by \ref * pcomp_init_chebyshev * * \return A pointer to the first element of the array of elements * used as input by the last call to \ref pcomp_run_chebyshev. */ const double* pcomp_chebyshev_input(const pcomp_chebyshev_t* plan) { if (plan == NULL) abort(); return plan->input; } /** \ingroup cheby * * \brief Return the output (Chebyshev transform) of the last call to *\ref pcomp_run_chebyshev * * If \ref pcomp_run_chebyshev was never called, the array returned by * this function contains garbage. * * \param[in] plan Pointer to a Chebyshev plan created by \ref * pcomp_init_chebyshev * * \return A pointer to the first element of the array of elements * containing the output of the last call to \ref pcomp_run_chebyshev. */ const double* pcomp_chebyshev_output(const pcomp_chebyshev_t* plan) { if (plan == NULL) abort(); return plan->output; } /*********************************************************************** * Types and functions used for applying the combined * fitting/Chebyshev transforms */ struct __pcomp_polycomp_t { size_t samples_per_chunk; pcomp_poly_fit_data_t* poly_fit; pcomp_chebyshev_t* chebyshev; pcomp_chebyshev_t* inv_chebyshev; double max_allowable_error; pcomp_polycomp_algorithm_t algorithm; double period; }; /** \ingroup poly * * \brief Allocate space for a \ref pcomp_polycomp_t structure * * \param[in] samples_per_chunk Number of samples in each chunk * * \param[in] num_of_coeffs Number of polynomial coefficients to use * * \param[in] max_allowable_error Upper bound for the compression * error (positive value) * * \param[in] algorithm Kind of compression algorithm to use * * \returns A pointer to the newly allocate \ref pcomp_polycomp_t * structure. This must be freed using \ref pcomp_free_polycomp, once * it is no longer used. */ pcomp_polycomp_t* pcomp_init_polycomp(pcomp_chunk_size_t samples_per_chunk, pcomp_poly_size_t num_of_coeffs, double max_allowable_error, pcomp_polycomp_algorithm_t algorithm) { pcomp_polycomp_t* params = malloc(sizeof(pcomp_polycomp_t)); if (params == NULL) abort(); params->samples_per_chunk = samples_per_chunk; params->poly_fit = pcomp_init_poly_fit(samples_per_chunk, num_of_coeffs); params->chebyshev = pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_DIRECT); params->inv_chebyshev = pcomp_init_chebyshev(samples_per_chunk, PCOMP_TD_INVERSE); params->max_allowable_error = max_allowable_error; params->algorithm = algorithm; params->period = 0.0; return params; } /** \ingroup poly * * \brief Free the memory allocated by \ref pcomp_init_polycomp for a * \ref pcomp_polycomp_t structure. * * \param[in] params Pointer to the structure to be freed */ void pcomp_free_polycomp(pcomp_polycomp_t* params) { if (params == NULL) return; pcomp_free_poly_fit(params->poly_fit); pcomp_free_chebyshev(params->chebyshev); pcomp_free_chebyshev(params->inv_chebyshev); free(params); } /** \ingroup poly * * \brief Return the number of samples per chunk * * This function returns the size of each chunk but the last one in * the input data for a polynomial compression. Such chunks contain a * set of consecutive values in the input array passed to routines as * \ref pcomp_compress_polycomp. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The number of samples in each chunk. */ pcomp_chunk_size_t pcomp_polycomp_samples_per_chunk(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->samples_per_chunk; } /** \ingroup poly * * \brief Return the number of coefficients for the fitting polynomial * used in the polynomial compression. * * The return value has the same meaning as the value returned by the * \ref pcomp_poly_fit_num_of_coeffs. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The number of coefficients of the fitting polynomial. */ pcomp_poly_size_t pcomp_polycomp_num_of_poly_coeffs(const pcomp_polycomp_t* params) { if (params == NULL || params->poly_fit == NULL) abort(); return params->poly_fit->num_of_coeffs; } /** \ingroup poly * * \brief Return the upper bound on the error of the polynomial *compression. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The maximum allowable error for the polynomial compression. */ double pcomp_polycomp_max_error(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->max_allowable_error; } /** \ingroup poly * * \brief Return the kind of algorithm used for a polynomial *compression. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The algorithm to be used by the compressor. */ pcomp_polycomp_algorithm_t pcomp_polycomp_algorithm(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->algorithm; } /** \ingroup poly_lowlevel * * \brief Return a pointer to a \ref pcomp_chebyshev_t structure * representing the forward Chebyshev transform. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The algorithm to be used by the compressor. */ pcomp_chebyshev_t* pcomp_polycomp_forward_cheby(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->chebyshev; } /** \ingroup poly_lowlevel * * \brief Return a pointer to a \ref pcomp_chebyshev_t structure * representing the forward Chebyshev transform. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The algorithm to be used by the compressor. */ pcomp_chebyshev_t* pcomp_polycomp_backward_cheby(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->inv_chebyshev; } /** \ingroup poly * * \brief Return the period of the input data, or a number * less than or equal to 0 if the data have no periodicity. * * See also \ref pcomp_polycomp_set_period. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \returns The periodicity. If zero or negative, no periodicity is * assumed in the data to be compressed. */ double pcomp_polycomp_period(const pcomp_polycomp_t* params) { if (params == NULL) abort(); return params->period; } /** \ingroup poly * * \brief Set the periodicity of the data to be compressed * * If \a period is a value greater than zero, this is assumed to be * the periodicity of the input data: the value \a x is therefore * assumed equivalent to \a x + \a period and to \a x - \a period. It * is typically a multiple of Pi = 3.14159... * * The polynomial compressor can improve the compression ratio for * data if they have some form of periodicity. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * containing the compression parameters * * \param[in] period The periodicity of the data, or a zero/negative * value if no periodicity should be assumed by the compressor. */ void pcomp_polycomp_set_period(pcomp_polycomp_t* params, double period) { if (params == NULL) abort(); params->period = period; } /*********************************************************************** * Evaluate the value of a polynomial at a point using Horner's formula */ static double eval_poly(double* coeffs, size_t num_of_coeffs, double x) { if (coeffs == NULL) abort(); if (num_of_coeffs >= 1) { int idx = num_of_coeffs - 1; double result = coeffs[idx]; if (num_of_coeffs == 1) return result; for (idx = num_of_coeffs - 2; idx >= 0; --idx) result = result * x + coeffs[idx]; return result; } else return 0.0; } /***********************************************************************/ /** \ingroup poly_lowlevel * * \brief Remove sudden jumps from \a input * * Assuming that the data in the array \a input have a periodicity * equal to \a period, the function copies them to \a output while * applying a positive/negative offset equal to a multiple of \a * period. * * It is ok for \a input and \a output to point to the same memory * location. * * \param[out] output Pointer to the array that will contain the * result. It must have room for at least \a num_of_samples values. * * \param[in] input Array of \a num_of_samples values to process. * * \param[in] num_of_samples Number of samples to process in \a input * * \param[in] period Periodicity of the data. If less or equal to * zero, \a input is copied verbatim to \a output. */ void pcomp_straighten(double* output, const double* input, size_t num_of_samples, double period) { size_t idx; if (input == NULL || output == NULL) abort(); if (period > 0) { double half_period = period * 0.5; double offset = 0.0; output[0] = input[0]; for (idx = 1; idx < num_of_samples; ++idx) { double diff_with_previous = input[idx] - input[idx - 1]; if (diff_with_previous > half_period) offset -= period; else if (diff_with_previous < -half_period) offset += period; output[idx] = input[idx] + offset; } } else { for (idx = 0; idx < num_of_samples; ++idx) output[idx] = input[idx]; } } /*********************************************************************** * Chunk initialization/destruction */ /* Information about a chunk of data compressed using the polynomial * compression */ struct __pcomp_polycomp_chunk_t { /* Number of samples in this chunk */ size_t num_of_samples; /* Is this chunk compressed using polynomial/Chebyshev * coefficients? */ int is_compressed; /* If the chunk is not compressed (is_compressed == 0), this * points to a buffer which holds "num_of_samples" uncompressed * samples */ double* uncompressed; /* Polynomial coefficients, from the lowest-order to the * highest-order */ size_t num_of_poly_coeffs; double* poly_coeffs; /* Chebyshev coefficients */ uint8_t* cheby_mask; size_t num_of_cheby_coeffs; /* This is always less than * num_of_samples, as the Chebyshev * series is chopped. */ double* cheby_coeffs; }; /** \ingroup poly_lowlevel * * \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object * * \param[in] num_of_samples Number of samples that the chunk will be * capable to hold. * * \return A pointer to the newly allocated object. Use \ref * pcomp_free_chunk to free the memory once is no longer needed. */ pcomp_polycomp_chunk_t* pcomp_init_chunk(pcomp_chunk_size_t num_of_samples) { pcomp_polycomp_chunk_t* chunk = malloc(sizeof(pcomp_polycomp_chunk_t)); if (chunk == NULL) abort(); chunk->num_of_samples = num_of_samples; chunk->is_compressed = 0; chunk->uncompressed = malloc(sizeof(double) * sizeof(chunk->num_of_samples)); chunk->num_of_poly_coeffs = 0; chunk->poly_coeffs = NULL; chunk->num_of_cheby_coeffs = 0; chunk->cheby_coeffs = NULL; chunk->cheby_mask = NULL; return chunk; } /** \ingroup poly_lowlevel * * \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object and * fill it with data in uncompressed form. * * \param[in] num_of_samples Number of samples that the chunk will be * capable to hold. * * \param[in] samples The (uncompressed) samples to copy into the * chunk. After the call, \a input is no longer needed and can be * freed without invalidating the pointer returned by the function. * * \return A pointer to the newly allocated object. Use \ref * pcomp_free_chunk to free the memory once is no longer needed. */ pcomp_polycomp_chunk_t* pcomp_init_uncompressed_chunk(pcomp_chunk_size_t num_of_samples, const double* samples) { pcomp_polycomp_chunk_t* chunk = malloc(sizeof(pcomp_polycomp_chunk_t)); const size_t num_of_bytes = sizeof(double) * num_of_samples; if (chunk == NULL) abort(); chunk->num_of_samples = num_of_samples; chunk->is_compressed = 0; chunk->uncompressed = malloc(num_of_bytes); if (chunk->uncompressed == NULL) abort(); memcpy(chunk->uncompressed, samples, num_of_bytes); chunk->num_of_poly_coeffs = 0; chunk->poly_coeffs = NULL; chunk->num_of_cheby_coeffs = 0; chunk->cheby_coeffs = NULL; chunk->cheby_mask = NULL; return chunk; } /** \ingroup poly_lowlevel * * \brief Allocate memory for a \ref pcomp_polycomp_chunk_t object and * fill it with data compressed using the polynomial compression * algorithm. * * \param[in] num_of_samples Number of samples that the chunk will be * capable to hold. * * \param[in] num_of_poly_coeffs Number of coefficients of the * interpolating polynomial. * * \param[in] poly_coeffs Pointer to the coefficients of the * interpolating polynomial. Their number must be equal to the * parameter \a num_of_poly_coeffs. * * \param[in] num_of_cheby_coeffs Number of nonzero Chebyshev * coefficients associated with the polynomial fit. This number is * always less than \a num_of_samples. Zero is allowed. * * \param[in] cheby_mask Bitmask representing the position of the * nonzero coefficients in \a cheby_coeffs within the full sequence. * (Use \ref pcomp_mask_get_bit and \ref pcomp_mask_set_bit to * read/write bits in the sequence.) * * \param[in] cheby_coeffs Array of nonzero Chebyshev coefficients. * Their number must be equal to \a num_of_cheby_coeffs. * * \return A pointer to the newly allocated object. Use \ref * pcomp_free_chunk to free the memory once is no longer needed. */ pcomp_polycomp_chunk_t* pcomp_init_compressed_chunk( pcomp_chunk_size_t num_of_samples, pcomp_poly_size_t num_of_poly_coeffs, const double* poly_coeffs, pcomp_chunk_size_t num_of_cheby_coeffs, const uint8_t* cheby_mask, const double* cheby_coeffs) { size_t size; pcomp_polycomp_chunk_t* chunk; if (num_of_samples == 0 || poly_coeffs == NULL) abort(); chunk = malloc(sizeof(pcomp_polycomp_chunk_t)); if (chunk == NULL) abort(); chunk->num_of_samples = num_of_samples; chunk->is_compressed = 1; chunk->uncompressed = NULL; chunk->num_of_poly_coeffs = num_of_poly_coeffs; size = num_of_poly_coeffs * sizeof(double); chunk->poly_coeffs = malloc(size); if (chunk->poly_coeffs == NULL) abort(); memcpy(chunk->poly_coeffs, poly_coeffs, size); chunk->num_of_cheby_coeffs = num_of_cheby_coeffs; if (num_of_cheby_coeffs > 0) { size = num_of_cheby_coeffs * sizeof(double); chunk->cheby_coeffs = malloc(size); if (chunk->cheby_coeffs == NULL) abort(); memcpy(chunk->cheby_coeffs, cheby_coeffs, size); size = pcomp_chunk_cheby_mask_size(num_of_samples) * sizeof(uint8_t); chunk->cheby_mask = malloc(size); if (chunk->cheby_mask == NULL) abort(); memcpy(chunk->cheby_mask, cheby_mask, size); } else { chunk->cheby_mask = NULL; chunk->cheby_coeffs = NULL; } return chunk; } /** \ingroup poly_lowlevel * * \brief Free memory associated with a \ref pcomp_poly_chunk_t * * This function releases the memory allocated by one of the following * functions: * - \ref pcomp_init_chunk * - \ref pcomp_init_uncompressed_chunk * - \ref pcomp_init_compressed_chunk * * \param[in] chunk Pointer to the object to be freed. */ void pcomp_free_chunk(pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) return; if (chunk->uncompressed != NULL) free(chunk->uncompressed); if (chunk->poly_coeffs != NULL) free(chunk->poly_coeffs); if (chunk->cheby_coeffs != NULL) free(chunk->cheby_coeffs); if (chunk->cheby_mask != NULL) free(chunk->cheby_mask); free(chunk); } /** \ingroup poly_lowlevel * * \brief Return the number of samples in a chunk * * \param[in] chunk Pointer to the chunk data * * \returns The number of samples */ pcomp_chunk_size_t pcomp_chunk_num_of_samples(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); return chunk->num_of_samples; } /** \ingroup poly_lowlevel * * \brief Return the number of bytes necessary to encode a chunk * * Refer to \ref pcomp_encode_chunks and \ref pcomp_decode_chunks for * further details. * * \param[in] chunk Pointer to the chunk data * * \returns The number of bytes */ size_t pcomp_chunk_num_of_bytes(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (chunk->is_compressed) { /* The size is calculated as follows: * - the "compressed" flag (int8_t) * - the number of samples (pcomp_chunk_size_t) * - the number N of polynomial coefficients (pcomp_poly_size_t) * - the size of the Chebyshev mask * - the number M of Chebyshev coefficients (pcomp_chunk_size_t) * - Nx8 bytes for the polynomial (only if M > 0) * - Mx8 bytes for the Chebyshev coefficients (only if M > 0) */ size_t result = sizeof(int8_t) + sizeof(pcomp_chunk_size_t) + sizeof(pcomp_poly_size_t) + (chunk->num_of_poly_coeffs) * sizeof(double) + sizeof(pcomp_chunk_size_t); if (chunk->num_of_cheby_coeffs > 0) { result += pcomp_chunk_cheby_mask_size(chunk->num_of_samples) + chunk->num_of_cheby_coeffs * sizeof(double); } return result; } else { /* The size is calculated as follows: * - 1 byte for the "uncompressed" flag * - 4 bytes for the number of samples * - Nx8 bytes for the samples */ return sizeof(int8_t) + sizeof(pcomp_chunk_size_t) + chunk->num_of_samples * sizeof(double); } } /** \ingroup poly_lowlevel * * \brief Return nonzero if the chunk holds data in uncompressed form. */ int pcomp_chunk_is_compressed(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); return chunk->is_compressed; } /** \ingroup poly_lowlevel * * \brief If the chunks contain uncompressed data, returns a pointer * to the first element. Otherwise, return \c NULL. */ const double* pcomp_chunk_uncompressed_data(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (chunk->is_compressed) return NULL; return chunk->uncompressed; } /** \ingroup poly_lowlevel * * \brief If the chunks contain compressed data, returns the number of * polynomial coefficients used in the compression. Otherwise, return * zero. */ pcomp_poly_size_t pcomp_chunk_num_of_poly_coeffs(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (!chunk->is_compressed) return 0; return chunk->num_of_poly_coeffs; } /** \ingroup poly_lowlevel * * \brief If the chunks contain compressed data, returns a pointer to * the first element of the array of coefficients of the interpolating * polynomial. Otherwise, return \c NULL. */ const double* pcomp_chunk_poly_coeffs(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (!chunk->is_compressed || chunk->num_of_poly_coeffs == 0) return NULL; return chunk->poly_coeffs; } /** \ingroup poly_lowlevel * * \brief If the chunks contain compressed data, returns the number of * nonzero Chebyshev coefficients held in the chunk. Otherwise, return * zero. */ pcomp_chunk_size_t pcomp_chunk_num_of_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (!chunk->is_compressed) return 0; return chunk->num_of_cheby_coeffs; } /** \ingroup poly_lowlevel * * \brief If the chunks contain compressed data, returns a pointer to * the first element of the Chebyshev transform of the fit residuals. * Otherwise, return \c NULL. */ const double* pcomp_chunk_cheby_coeffs(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); if (!chunk->is_compressed || chunk->num_of_cheby_coeffs == 0) return NULL; return chunk->cheby_coeffs; } /** \ingroup poly_lowlevel * * \brief Return the number of bytes required for the bitmask of * nonzero Chebyshev coefficients. * * The polynomial compression compresses Chebyshev transforms by * saving only those coefficients that are significantly different * from zero. In order to keep track of the position of such * coefficients in the full array, a bit mask is used. This function * determines how many bytes are required for such mask, which is * internally represented by Libpolycomp as an array of \c uint8_t * values. * * \param[in] chunk_size Number of samples in the chunk * * \returns The number of bytes (\c uint8_t values) required for the * mask. */ size_t pcomp_chunk_cheby_mask_size(pcomp_chunk_size_t chunk_size) { return chunk_size / CHAR_BIT + ((chunk_size % CHAR_BIT) > 0 ? 1 : 0); } /** \ingroup poly_lowlevel * * \brief Return a pointer to the bitmask of nonzero Chebyshev * coefficients for a chunk * * \param[in] chunk Pointer to the chunk * * \returns A pointer to the array of bytes which make up the mask. * Use \ref pcomp_mask_get_bit to access the values of each bit. */ const uint8_t* pcomp_chunk_cheby_mask(const pcomp_polycomp_chunk_t* chunk) { if (chunk == NULL) abort(); return chunk->cheby_mask; } /**********************************************************************/ /** \ingroup poly_lowlevel * * \brief Compute a polynomial fit of the data in \a input and a * Chebyshev transform of the residuals * * Note that this function *always* computes the Chebyshev transform * of the data, even if there is a perfect fit between the polynomial * and the input data. * * \param[in] params Pointer to a \ref pcomp_polycomp_t structure * initialized by \ref pcomp_init_polycomp. * * \param[out] coeffs Pointer to the array that on exit will hold the * coefficients of the best-fit polynomial. It must have enough room * for a number of elements equal to the return value of \ref * pcomp_polycomp_num_of_poly_coeffs. * * \param[out] cheby_residuals Pointer to an array that on exit will * contain the Chebyshev transform of the residuals of the fit. It can * be \c NULL; in any case, these numbers can be obtained by the use * of a call to \ref pcomp_polycomp_forward_cheby and \ref * pcomp_chebyshev_output. * * \param[in] input Pointer to the array of values to be transformed. * The number of values used is equal to the return value of the * function \ref pcomp_polycomp_samples_per_chunk. * * \param[out] max_residual Pointer to a variable that will hold the * maximum absolute value of the discrepancy between each sample in \a * input and the polynomial fit. It can be \c NULL. * * \returns If no errors occurred, \ref PCOMP_STAT_SUCCESS. Otherwise, * the function returns the code of the error. */ int pcomp_polyfit_and_chebyshev(pcomp_polycomp_t* params, double* coeffs, double* cheby_residuals, const double* input, double* max_residual) { size_t idx; int status; double running_max = -1.0; /* Negative stands for "uninitialized" */ status = pcomp_run_poly_fit(params->poly_fit, coeffs, input); if (status != PCOMP_STAT_SUCCESS) return status; for (idx = 0; idx < params->samples_per_chunk; ++idx) { double abs_residual; params->chebyshev->input[idx] = input[idx] - eval_poly(coeffs, params->poly_fit->num_of_coeffs, idx + 1.0); abs_residual = fabs(params->chebyshev->input[idx]); if (abs_residual > running_max || running_max < 0.0) running_max = abs_residual; } if (max_residual != NULL) *max_residual = running_max; if (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV) { status = pcomp_run_chebyshev( params->chebyshev, params->chebyshev->dir, NULL, NULL); if (cheby_residuals != NULL && cheby_residuals != params->chebyshev->output) { memcpy(cheby_residuals, params->chebyshev->output, sizeof(params->chebyshev->output[0]) * params->chebyshev->num_of_samples); } } return status; } /*********************************************************************** * Sort the array "positions" according to the absolute values of * "coeffs", in *descending* order. The function uses the merge sort * algorithm. */ static void sort_positions(pcomp_chunk_size_t positions[], const double coeffs[], size_t num) { size_t front, back; double pivot; pcomp_chunk_size_t temp; if (num < 2) return; pivot = fabs(coeffs[positions[num / 2]]); for (front = 0, back = num - 1;; front++, back--) { while (fabs(coeffs[positions[front]]) > pivot) { front++; } while (pivot > fabs(coeffs[positions[back]])) { if (back == 0) break; back--; } if (front >= back) break; temp = positions[front]; positions[front] = positions[back]; positions[back] = temp; } sort_positions(positions, coeffs, front); sort_positions(positions + front, coeffs, num - front); } /** \ingroup poly_lowlevel * * \brief Return the value of the bit at the position \a pos in the * bitmask \a mask. * * \param[in] mask Pointer to the first byte of the mask * * \param[in] pos Zero-based index of the bit in the mask * * \returns Either 0 or 1, depending on the value of the bit. */ int pcomp_mask_get_bit(const uint8_t* mask, size_t pos) { return (mask[pos / CHAR_BIT] & (1 << (pos % CHAR_BIT))) != 0; } /** \ingroup poly_lowlevel * * \brief Set the value of the bit at position \a pos in the bitmask \a * * \param[inout] mask The bitmask to modify * * \param[in] pos Zero-based index of the byte to set * * \param[in] value Value of the bit (either 0 or 1; any value * different from zero is treated as equal to 1) */ void pcomp_mask_set_bit(uint8_t* mask, size_t pos, int value) { if (value != 0) { mask[pos / CHAR_BIT] |= (1 << (pos % CHAR_BIT)); } else { mask[pos / CHAR_BIT] &= ~(((uint8_t)1) << (pos % CHAR_BIT)); } } static double compute_discrepancy(double a[], double b[], size_t num) { size_t idx; double err = 0.0; for (idx = 0; idx < num; ++idx) { double cur_err = fabs(a[idx] - b[idx]); if (cur_err > err) err = cur_err; } return err; } /** \ingroup poly_lowlevel * * \brief Find the smallest subset of Chebyshev coefficients that can * approximate a Chebyshev transform with an error less than \a * max_allowable_error. * * On exit, the bits in \a bitmask will be set to 1 in correspondence * of every Chebyshev coefficient that must be retained. The function * returns the number of Chebyshev coefficients to retain (i.e., the * number of bits in \a mask that have been set to 1). * * \param[in] chebyshev Pointer to a \ref pcomp_chebyshev_t structure * used to compute the forward Chebyshev transform (from the space of * the fit residuals to the Chebyshev space) * * \param[in] inv_chebyshev Pointer to a \ref pcomp_chebyshev_t * structure representing the inverse transform of \a chebyshev. * * \param[in] max_allowable_error The maximum allowed discrepancy for * the chopped Chebyshev, as measured in the space of the fit * residuals. * * \param[out] mask Bitmask that will contain the position of the * unchopped Chebyshev terms of the transform of the fit residuals. * Use \ref pcomp_mask_get_bit to access each element. * * \param[out] max_error If not \c NULL, it will be set to the maximum * error due to the chopping of the Chebyshev transform represented by * \a mask. * * \returns The number of bits equal to one in \a mask, i.e., the * number of unchopped Chebyshev coefficients. */ size_t pcomp_find_chebyshev_mask(pcomp_chebyshev_t* chebyshev, pcomp_chebyshev_t* inv_chebyshev, double max_allowable_error, uint8_t* mask, double* max_error) { size_t idx; size_t cur_coeff = 0; pcomp_chunk_size_t* positions; double err; if (chebyshev == NULL || inv_chebyshev == NULL || mask == NULL || chebyshev->num_of_samples != inv_chebyshev->num_of_samples) abort(); if (max_allowable_error <= 0.0) return 0; /* The "positions" array contains the indexes to the * chebyshev->output array, i.e., the list of Chebyshev * coefficients to sort in decreasing order. At the beginning each * entry is set to its own index: * * +---+---+---+-----+ * positions: | 0 | 1 | 2 | ... | * +---+---+---+-----+ * * After the call to "sort_positions", the "positions" array * contains the indexes to "chebyshev->output" ordered according * to the decreasing absolute value of the latters, e.g.: * * +---+---+---+-----+ * positions: | 7 | 2 | 5 | ... | * +---+---+---+-----+ */ positions = malloc(chebyshev->num_of_samples * sizeof(pcomp_chunk_size_t)); if (positions == NULL) abort(); for (idx = 0; idx < chebyshev->num_of_samples; ++idx) { positions[idx] = idx; } sort_positions(positions, chebyshev->output, chebyshev->num_of_samples); /* Start by setting all the coefficients to zero */ memset(&inv_chebyshev->input[0], 0, chebyshev->num_of_samples * sizeof(inv_chebyshev->input[0])); memset(&mask[0], 0, pcomp_chunk_cheby_mask_size(chebyshev->num_of_samples)); /* Add the coefficients one by one until the error is below * "max_allowable_error" */ cur_coeff = 0; while (cur_coeff < chebyshev->num_of_samples) { inv_chebyshev->input[positions[cur_coeff]] = chebyshev->output[positions[cur_coeff]]; pcomp_mask_set_bit(mask, positions[cur_coeff], 1); ++cur_coeff; pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL, NULL); err = compute_discrepancy(chebyshev->input, inv_chebyshev->output, chebyshev->num_of_samples); if (err < max_allowable_error) break; } free(positions); if (max_error != NULL) *max_error = err; return cur_coeff; } /* This function is used internally by "pcomp_run_polycomp_on_chunk" * and "pcomp_decompress_poly_chunk" to make sure there is no memory * leak on the chunk passed as argument. */ static void clear_chunk(pcomp_polycomp_chunk_t* chunk) { /* Leave chunk->uncompressed as it is, as it never changes */ chunk->num_of_poly_coeffs = 0; if (chunk->poly_coeffs != NULL) free(chunk->poly_coeffs); chunk->num_of_cheby_coeffs = 0; if (chunk->cheby_coeffs != NULL) free(chunk->cheby_coeffs); } /** \ingroup poly_lowlevel * * \brief Compress the first \a num_of_samples elements in \a input * and store them in \a chunk. * * The function determines if the data in \a input can be efficiently * compressed using polynomial compression with the parameters * described by \a params. If it is so, it stores the compressed data * in \a chunk. If the compression ratio is small or equal to one, or * if the compression error is too large, the function copies the data * in \a input into \a chunk in uncompressed format. * * The following example shows how to use this function together with * \ref pcomp_init_chunk: * * \code{.c} * double input[] = { 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, * 7.0, 8.0, 9.0, 11.0 }; * size_t input_size = sizeof(input) / sizeof(input[0]); * pcomp_polycomp_chunk_t* chunk; * pcomp_polycomp_t* polycomp; * double max_error; * size_t idx; * * polycomp = pcomp_init_polycomp(input_size, 2, 1.0e-5, * PCOMP_ALG_USE_CHEBYSHEV); * chunk = pcomp_init_chunk(input_size); * * pcomp_run_polycomp_on_chunk(polycomp, input, input_size, chunk, * &max_error); * \endcode * * \param[in] params Pointer to a \a pcomp_polycomp_t structure * (created using \ref pcomp_init_polycomp) which provides the * parameters of the compression. * * \param[in] input The sequence of numbers to compress. Their number * is equal to the parameter \a num_of_samples * * \param[in] num_of_samples Number of values in \a input to compress * * \param[inout] chunk The chunk that will contain the data, either in * compressed or uncompressed format. It must have already been * initialized via a call to \ref pcomp_init_chunk. * * \param[out] max_error On exit, the function writes the compression * error here. It can be \c NULL. * * \returns Either \ref PCOMP_STAT_SUCCESS (if no errors occurred), or * the error code. */ int pcomp_run_polycomp_on_chunk(pcomp_polycomp_t* params, const double* input, pcomp_chunk_size_t num_of_samples, pcomp_polycomp_chunk_t* chunk, double* max_error) { uint8_t* mask = NULL; double* coeffs = NULL; size_t cheby_coeffs_to_retain = 0; int apply_chebyshev = 1; double* buf = NULL; const double* straightened_input; if (chunk == NULL || input == NULL || params == NULL || params->poly_fit == NULL || params->chebyshev == NULL || params->inv_chebyshev == NULL) abort(); clear_chunk(chunk); if (num_of_samples != params->samples_per_chunk) return PCOMP_STAT_INVALID_BUFFER; if (params->period > 0.0) { buf = malloc(num_of_samples * sizeof(input[0])); if (buf == NULL) abort(); pcomp_straighten(buf, input, num_of_samples, params->period); straightened_input = buf; /* This preserve const-correctness */ } else { straightened_input = input; } if (num_of_samples <= params->poly_fit->num_of_coeffs) { /* The number of element is so small that is better to store * them uncompressed */ chunk->is_compressed = 0; } else { double max_residual; /* Compute the polynomial fit and the full Chebyshev * transform */ coeffs = malloc(sizeof(double) * params->poly_fit->num_of_coeffs); if (coeffs == NULL) abort(); pcomp_polyfit_and_chebyshev(params, coeffs, NULL, straightened_input, &max_residual); apply_chebyshev = (max_residual >= params->max_allowable_error) && (params->algorithm != PCOMP_ALG_NO_CHEBYSHEV); /* If the Chebyshev transform is needed, chop it as much as * possible */ if (apply_chebyshev) { mask = malloc(pcomp_chunk_cheby_mask_size(num_of_samples)); if (mask == NULL) abort(); cheby_coeffs_to_retain = pcomp_find_chebyshev_mask( params->chebyshev, params->inv_chebyshev, params->max_allowable_error, mask, max_error); chunk->is_compressed = (cheby_coeffs_to_retain + params->poly_fit->num_of_coeffs) < num_of_samples; if (!chunk->is_compressed) { free(mask); mask = NULL; } } else { /* Assume that num_of_samples > deg(p) + 1 */ chunk->is_compressed = (max_residual <= params->max_allowable_error); } } chunk->num_of_samples = num_of_samples; if (chunk->is_compressed) { size_t idx; chunk->num_of_poly_coeffs = params->poly_fit->num_of_coeffs; chunk->poly_coeffs = coeffs; if (apply_chebyshev) { size_t cheby_idx; chunk->num_of_cheby_coeffs = cheby_coeffs_to_retain; chunk->cheby_mask = mask; chunk->cheby_coeffs = malloc(sizeof(double) * cheby_coeffs_to_retain); if (chunk->cheby_coeffs == NULL) abort(); cheby_idx = 0; for (idx = 0; idx < params->chebyshev->num_of_samples; ++idx) { if (pcomp_mask_get_bit(mask, idx)) { chunk->cheby_coeffs[cheby_idx++] = params->chebyshev->output[idx]; } } } else { chunk->num_of_cheby_coeffs = 0; chunk->cheby_mask = NULL; chunk->cheby_coeffs = NULL; } } else { size_t idx; if (coeffs != NULL) free(coeffs); chunk->uncompressed = malloc(sizeof(double) * num_of_samples); if (chunk->uncompressed == NULL) abort(); for (idx = 0; idx < num_of_samples; ++idx) chunk->uncompressed[idx] = input[idx]; if (max_error != NULL) *max_error = 0.0; } if (buf != NULL) { free(buf); } return PCOMP_STAT_SUCCESS; } /** \ingroup poly_lowlevel * * \brief Decompress the data in a chunk * * This function performs the decompression of a chunk, and it is the * counterpart of \ref pcomp_run_polycomp_on_chunk. Here is an * example: * * \code{.c} * double* decompr; * pcomp_chebyshev_t* inv_chebyshev; * * // We assume that "chunk" has already been initialized somewhere * decompr = malloc(sizeof(double) * * pcomp_chunk_num_of_samples(chunk)); * * inv_chebyshev = pcomp_init_chebyshev(input_size, * PCOMP_TD_INVERSE); * pcomp_decompress_polycomp_chunk(decompr, chunk, inv_chebyshev); * \endcode * * \param[out] output Pointer to the array that will contain the * uncompressed data * * \param[in] chunk The chunk to decompress * * \param[in] inv_chebyshev Pointer to a \ref pcomp_chebyshev_t object * that performs the inverse Chebyshev transform. The function does * not allocate an object of this kind because in this way such * objects can be reused on subsequent calls to \ref * pcomp_decompress_polycomp_chunk. * * \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or * the error code. */ int pcomp_decompress_polycomp_chunk(double* output, const pcomp_polycomp_chunk_t* chunk, pcomp_chebyshev_t* inv_chebyshev) { if (output == NULL || chunk == NULL || inv_chebyshev == NULL) abort(); if (chunk->is_compressed) { size_t idx; /* Compute the values of the polynomial at the points 1, * 2, ... */ for (idx = 0; idx < chunk->num_of_samples; ++idx) { output[idx] = eval_poly(chunk->poly_coeffs, chunk->num_of_poly_coeffs, idx + 1); } /* If present, add the contribution of the Chebyshev * transform */ if (chunk->num_of_cheby_coeffs > 0) { size_t cur_cheby_idx = 0; if (chunk->cheby_coeffs == NULL) abort(); for (idx = 0; idx < chunk->num_of_samples; ++idx) { if (pcomp_mask_get_bit(chunk->cheby_mask, idx)) { if (cur_cheby_idx >= chunk->num_of_cheby_coeffs) { abort(); } inv_chebyshev->input[idx] = chunk->cheby_coeffs[cur_cheby_idx++]; } else { inv_chebyshev->input[idx] = 0.0; } } pcomp_run_chebyshev(inv_chebyshev, inv_chebyshev->dir, NULL, NULL); for (idx = 0; idx < chunk->num_of_samples; ++idx) { output[idx] += inv_chebyshev->output[idx]; } } } else { memcpy(output, chunk->uncompressed, sizeof(chunk->uncompressed[0]) * chunk->num_of_samples); } return PCOMP_STAT_SUCCESS; } /** \ingroup poly * * \brief Compress the array \a input_buf using polynomial compression * * This function compresses the first \a input_size elements of the * array \a input_buf using the polynomial compression scheme. The * output is an array of chunks saved in \a output_buf (the number of * elements of this array is saved in \a num_of_chunks). The \a params * variable specifies the parameters used by the compression * algorithm. * * Here is an example showing how to compress a sequence of numbers in * the variable \a input: * * \code{.c} * double input[] = { 1.0, 2.0, 3.0, 4.0, 3.0, 2.0, * 1.0, 2.0, 6.0, 7.0, 9.0 }; * size_t input_size = sizeof(input) / sizeof(input[0]); * double* decompr; * size_t decompr_size; * pcomp_polycomp_chunk_t** chunks; * size_t num_of_chunks; * pcomp_polycomp_t* params; * size_t idx; * * params = pcomp_init_polycomp(4, 2, 1.0e-5, PCOMP_ALG_USE_CHEBYSHEV); * pcomp_compress_polycomp(&chunks, &num_of_chunks, input, input_size, * params); * * // Print some information for each chunk * for(idx = 0; idx < num_of_chunks; ++idx) { * printf("Chunk %lu of %lu: %s\n", idx + 1, num_of_chunks, * pcomp_chunk_is_compressed(chunks[idx]) ? * "compressed" : "uncompressed"); * } * \endcode * * Once the sequence \a input_buf is compressed, the array of chunks * can either be analyzed (e.g., using a \c for loop as in the example * above) or encoded using the \ref pcomp_encode_chunks. Once the * variable \a output_buf is no longer used, it should be freed via a * call to \ref pcomp_free_chunks. * * \param[out] output_buf Pointer to a variable that will receive the * address of an array of \ref pcomp_polycomp_chunk_t variables * created by the function. Such array contains the whole set of data * in \a input in compressed format. The array can be freed via a call * to \ref pcomp_free_chunks. * * \param[out] num_of_chunks On output, the variable will contain the * number of chunks saved in \a output_buf. * * \param[in] input_buf Pointer to the array of numbers to compress. * * \param[in] input_size Number of elements in \a input_buf to * compress. * * \param[in] params Parameters used for the compression. The variable * must have been created via a call to \ref pcomp_init_polycomp. * * \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or * the error code. */ int pcomp_compress_polycomp(pcomp_polycomp_chunk_t** output_buf[], size_t* num_of_chunks, const double* input_buf, size_t input_size, const pcomp_polycomp_t* params) { size_t idx; pcomp_polycomp_t** chunk_params; pcomp_polycomp_t* last_chunk_params; size_t samples_in_last_chunk = 0; if (output_buf == NULL || num_of_chunks == NULL || input_buf == NULL || params == NULL || params->poly_fit == NULL) abort(); /* Calculate how many chunks we'll create */ *num_of_chunks = input_size / params->samples_per_chunk; samples_in_last_chunk = input_size % params->samples_per_chunk; if (samples_in_last_chunk != 0) ++(*num_of_chunks); *output_buf = malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks)); if (*output_buf == NULL) abort(); /* Allocate a pcomp_polycomp_t structure for each of the OpenMP * threads */ chunk_params = malloc(sizeof(pcomp_polycomp_t*) * omp_get_max_threads()); for (idx = 0; idx < omp_get_max_threads(); ++idx) { chunk_params[idx] = pcomp_init_polycomp( params->samples_per_chunk, params->poly_fit->num_of_coeffs, params->max_allowable_error, params->algorithm); } if (samples_in_last_chunk != 0) { /* This is going to be used by just *one* OpenMP process */ last_chunk_params = pcomp_init_polycomp( samples_in_last_chunk, params->poly_fit->num_of_coeffs, params->max_allowable_error, params->algorithm); } else { last_chunk_params = NULL; } #pragma omp parallel for for (idx = 0; idx < *num_of_chunks; ++idx) { const double* cur_input = input_buf + params->samples_per_chunk * idx; pcomp_polycomp_t* cur_params; size_t cur_chunk_size; if (idx + 1 < *num_of_chunks || last_chunk_params == NULL) { cur_params = chunk_params[omp_get_thread_num()]; cur_chunk_size = params->samples_per_chunk; } else { cur_params = last_chunk_params; cur_chunk_size = samples_in_last_chunk; } if (cur_params == NULL) abort(); (*output_buf)[idx] = pcomp_init_chunk(cur_chunk_size); pcomp_run_polycomp_on_chunk(cur_params, cur_input, cur_chunk_size, (*output_buf)[idx], NULL); } for (idx = 0; idx < omp_get_max_threads(); ++idx) pcomp_free_polycomp(chunk_params[idx]); free(chunk_params); pcomp_free_polycomp(last_chunk_params); return PCOMP_STAT_SUCCESS; } /** \ingroup poly * * \brief Compute the sum of the number of samples encoded in \a *chunk_array * * \param[in] chunk_array Array of \ref pcomp_polycomp_chunk_t * variables. Typically, such array is created via a call to \ref * pcomp_compress_polycomp. * * \param[in] num_of_chunks Number of elements in \a chunk_array * * \returns The overall number of samples encoded in the sequence of * chunks */ size_t pcomp_total_num_of_samples(pcomp_polycomp_chunk_t* const chunk_array[], size_t num_of_chunks) { size_t total = 0; size_t idx; if (chunk_array == NULL) abort(); for (idx = 0; idx < num_of_chunks; ++idx) { if (chunk_array[idx] == NULL) abort(); total += chunk_array[idx]->num_of_samples; } return total; } /** \ingroup poly * * \brief Decompress a sequence of chunks * * This function is the counterpart for \ref pcomp_compress_polycomp. * * \param[out] output_buf Pointer to the variable that will hold the * uncompressed data. It must have room for a number of elements at * least equal to the return value of \ref pcomp_total_num_of_samples. * * \param[in] chunk_array Array of chunks holding the data in * compressed format. * * \param[in] num_of_chunks Number of elements in the array \a * chunk_array. * * \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or * the error code. */ int pcomp_decompress_polycomp( double* output_buf, pcomp_polycomp_chunk_t* const chunk_array[], size_t num_of_chunks) { size_t idx; size_t* start_pos_list; pcomp_chebyshev_t** inv_cheby_list = NULL; pcomp_chebyshev_t* last_inv_cheby = NULL; if (output_buf == NULL || chunk_array == NULL || num_of_chunks == 0) abort(); /* Precompute the position in the output buffer where the * decompressed data from each chunk will be written: in this way, * we prevent data races in the parallel for loop below. */ start_pos_list = malloc(sizeof(size_t) * num_of_chunks); if (start_pos_list == NULL) abort(); start_pos_list[0] = 0; for (idx = 0; idx < num_of_chunks - 1; ++idx) { /* The algorithm heavy relies on the fact that *all the * chunks* but the last one have the same number of * elements! */ if (chunk_array[idx]->num_of_samples != chunk_array[0]->num_of_samples) abort(); start_pos_list[idx + 1] = start_pos_list[idx] + chunk_array[idx]->num_of_samples; } /* Since FFTW's plan allocation functions are not reentrant, we * must initialize them outside the parallel loop. */ inv_cheby_list = malloc(sizeof(pcomp_chebyshev_t*) * omp_get_max_threads()); if (inv_cheby_list == NULL) abort(); for (idx = 0; idx < omp_get_max_threads(); ++idx) { if (idx < num_of_chunks) { inv_cheby_list[idx] = pcomp_init_chebyshev( chunk_array[idx]->num_of_samples, PCOMP_TD_INVERSE); } else { inv_cheby_list[idx] = NULL; } } if (chunk_array[num_of_chunks - 1]->num_of_samples != chunk_array[0]->num_of_samples) { last_inv_cheby = pcomp_init_chebyshev( chunk_array[num_of_chunks - 1]->num_of_samples, PCOMP_TD_INVERSE); } else last_inv_cheby = NULL; #pragma omp parallel for for (idx = 0; idx < num_of_chunks; ++idx) { pcomp_chebyshev_t* cur_inv_cheby; if (chunk_array[idx] == NULL) abort(); if (idx + 1 < num_of_chunks || last_inv_cheby == NULL) { cur_inv_cheby = inv_cheby_list[omp_get_thread_num()]; } else { cur_inv_cheby = last_inv_cheby; } pcomp_decompress_polycomp_chunk( output_buf + start_pos_list[idx], chunk_array[idx], cur_inv_cheby); } free(start_pos_list); for (idx = 0; idx < omp_get_max_threads(); ++idx) { pcomp_free_chebyshev(inv_cheby_list[idx]); } free(inv_cheby_list); pcomp_free_chebyshev(last_inv_cheby); return PCOMP_STAT_SUCCESS; } /** \ingroup poly * * \brief Free an array of chunks * * \param[in] chunk_array An array of chunks. This variable must have * been allocated by a call to \ref pcomp_compress_polycomp. * * \param[in] num_of_chunks Number of elements in the array \a * chunk_array */ void pcomp_free_chunks(pcomp_polycomp_chunk_t* chunk_array[], size_t num_of_chunks) { size_t idx; if (chunk_array == NULL) return; for (idx = 0; idx < num_of_chunks; ++idx) { pcomp_free_chunk(chunk_array[idx]); } free(chunk_array); } /** \ingroup poly * * \brief Number of bytes required by \ref pcomp_encode_chunks * * This function computes the number of bytes required to encode the * array of chunks in the variable \a chunks. Unlike functions like * \ref pcomp_rle_bufsize, this function provides an exact estimate, * not an upper bound. * * \param[in] chunks Array of chunks to encode. This should have been * initialized via a call to \ref pcomp_compress_polycomp. * * \param[in] num_of_chunks Number of elements in \a chunks. * * \returns The number of bytes required for the output buffer used by * \ref pcomp_encode_chunks. */ size_t pcomp_chunks_num_of_bytes(pcomp_polycomp_chunk_t* const chunks[], size_t num_of_chunks) { size_t result = sizeof(size_t); /* Room for the number of chunks */ size_t idx; for (idx = 0; idx < num_of_chunks; ++idx) { result += pcomp_chunk_num_of_bytes(chunks[idx]); } return result; } /*********************************************************************** * Encode/decode a list of chunks into a raw stream of bytes (suitable * for I/O). */ #define SAVE_TO_PTR_AND_INCREMENT(buf, value, type) \ { \ *((type*)buf) = value; \ buf = ((type*)buf) + 1; \ } /** \ingroup poly * * \brief Encode a list of chunks into a sequence of raw bytes * * This function transforms an array of instances to \ref * pcomp_polycomp_chunk_t variables into a sequence of raw bytes, * suitable for I/O. It can be used together with \ref * pcomp_compress_polycomp to compress a dataset and save it into a * binary file. * * To decode byte sequences produced by this function, use \ref * pcomp_decode_chunks. * * \param[out] buf Pointer to a memory buffer that will receive the * result of the encoding. It must have room for a number of bytes (\c * uint8_t) at least equal to the return value of \ref * pcomp_chunks_num_of_bytes. * * \param[out] buf_size On exit, it will contain the number of bytes * actually written in \a buf. The latter number is equal to the value * returned by \ref pcomp_chunks_num_of_bytes. * * \param[in] chunk_array Array of chunks to encode * * \param[in] num_of_chunks Number of elements in the array \a * chunk_array. * * \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or * the error code. */ int pcomp_encode_chunks(void* buf, size_t* buf_size, pcomp_polycomp_chunk_t* const chunk_array[], size_t num_of_chunks) { void* buf_ptr = buf; size_t chunk_idx; uint64_t num_of_chunks_uint64 = (uint64_t)num_of_chunks; if (chunk_array == NULL || num_of_chunks == 0) abort(); SAVE_TO_PTR_AND_INCREMENT(buf_ptr, num_of_chunks_uint64, uint64_t); num_of_chunks = num_of_chunks_uint64; for (chunk_idx = 0; chunk_idx < num_of_chunks; ++chunk_idx) { const pcomp_polycomp_chunk_t* cur_chunk = chunk_array[chunk_idx]; size_t idx; /* Used for inner loops */ SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->is_compressed, uint8_t); SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->num_of_samples, pcomp_chunk_size_t); if (cur_chunk->is_compressed) { size_t cheby_mask_size = pcomp_chunk_cheby_mask_size( cur_chunk->num_of_samples); SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->num_of_poly_coeffs, pcomp_poly_size_t); for (idx = 0; idx < cur_chunk->num_of_poly_coeffs; idx++) { SAVE_TO_PTR_AND_INCREMENT( buf_ptr, cur_chunk->poly_coeffs[idx], double); } SAVE_TO_PTR_AND_INCREMENT(buf_ptr, cur_chunk->num_of_cheby_coeffs, pcomp_chunk_size_t); if (cur_chunk->num_of_cheby_coeffs > 0) { /* Mask */ for (idx = 0; idx < cheby_mask_size; ++idx) { SAVE_TO_PTR_AND_INCREMENT( buf_ptr, cur_chunk->cheby_mask[idx], uint8_t); } /* Chebyshev coefficients */ for (idx = 0; idx < cur_chunk->num_of_cheby_coeffs; idx++) { SAVE_TO_PTR_AND_INCREMENT( buf_ptr, cur_chunk->cheby_coeffs[idx], double); } } } else { for (idx = 0; idx < cur_chunk->num_of_samples; idx++) { SAVE_TO_PTR_AND_INCREMENT( buf_ptr, cur_chunk->uncompressed[idx], double); } } } *buf_size = ((uint8_t*)buf_ptr) - ((uint8_t*)buf); return PCOMP_STAT_SUCCESS; } #define READ_FROM_PTR_AND_INCREMENT(var, pointer, type) \ { \ var = *((type*)(pointer)); \ pointer = ((type*)(pointer)) + 1; \ } /** \ingroup poly * * \brief Decode a byte sequence created by \ref pcomp_encode_chunks * into an array of chunks. * * This function can be used to read from a binary file or a socket a * sequence of chunks encoded by \ref pcomp_encode_chunks. The * function allocates memory for an array of \ref * pcomp_polycomp_chunk_t structures and returns it in the variable \a * chunk_array. The latter variable must be freed using \ref * pcomp_free_chunks once it is no longer needed. * * This function is the counterpart for \ref pcomp_encode_chunks. * * \param[out] chunk_array Pointer to an array that will contain the * chunks decoded from \a buf. * * \param[out] num_of_chunks On exit, this variable will hold the * number of chunks saved in \a chunk_array. * * \param[in] Pointer to the byte sequence to decode. * * \returns Either \ref PCOMP_STAT_SUCCESS if no error occurred, or * the error code. */ int pcomp_decode_chunks(pcomp_polycomp_chunk_t** chunk_array[], size_t* num_of_chunks, const void* buf) { const void* cur_ptr = buf; size_t chunk_idx; double* poly_buf = NULL; size_t poly_buf_size = 0; double* cheby_buf = NULL; size_t cheby_buf_size = 0; uint8_t* cheby_mask_buf = NULL; size_t cheby_mask_buf_size = 0; double* uncompr_buf = NULL; size_t uncompr_buf_size = 0; uint64_t num_of_chunks_uint64; if (buf == NULL || chunk_array == NULL || num_of_chunks == NULL) abort(); READ_FROM_PTR_AND_INCREMENT(num_of_chunks_uint64, cur_ptr, uint64_t); *num_of_chunks = num_of_chunks_uint64; *chunk_array = malloc(sizeof(pcomp_polycomp_chunk_t*) * (*num_of_chunks)); if (*chunk_array == NULL) abort(); for (chunk_idx = 0; chunk_idx < *num_of_chunks; ++chunk_idx) { uint8_t is_compressed; size_t num_of_samples; size_t idx; /* Used for inner loops */ READ_FROM_PTR_AND_INCREMENT(is_compressed, cur_ptr, uint8_t); READ_FROM_PTR_AND_INCREMENT(num_of_samples, cur_ptr, pcomp_chunk_size_t); if (is_compressed) { size_t num_of_poly_coeffs; size_t num_of_cheby_coeffs; size_t cheby_mask_size = pcomp_chunk_cheby_mask_size(num_of_samples); READ_FROM_PTR_AND_INCREMENT(num_of_poly_coeffs, cur_ptr, pcomp_poly_size_t); if (num_of_poly_coeffs > poly_buf_size) { poly_buf_size = num_of_poly_coeffs; poly_buf = realloc(poly_buf, poly_buf_size * sizeof(double)); } for (idx = 0; idx < num_of_poly_coeffs; ++idx) { READ_FROM_PTR_AND_INCREMENT(poly_buf[idx], cur_ptr, double); } READ_FROM_PTR_AND_INCREMENT(num_of_cheby_coeffs, cur_ptr, pcomp_chunk_size_t); if (num_of_cheby_coeffs > 0) { if (cheby_mask_size > cheby_mask_buf_size) { cheby_mask_buf_size = cheby_mask_size; cheby_mask_buf = realloc(cheby_mask_buf, cheby_mask_buf_size * sizeof(uint8_t)); } for (idx = 0; idx < cheby_mask_size; ++idx) { READ_FROM_PTR_AND_INCREMENT(cheby_mask_buf[idx], cur_ptr, uint8_t); } if (num_of_cheby_coeffs > cheby_buf_size) { cheby_buf_size = num_of_cheby_coeffs; cheby_buf = realloc( cheby_buf, cheby_buf_size * sizeof(double)); } for (idx = 0; idx < num_of_cheby_coeffs; ++idx) { READ_FROM_PTR_AND_INCREMENT(cheby_buf[idx], cur_ptr, double); } } (*chunk_array)[chunk_idx] = pcomp_init_compressed_chunk( num_of_samples, num_of_poly_coeffs, poly_buf, num_of_cheby_coeffs, cheby_mask_buf, cheby_buf); } else { if (num_of_samples > uncompr_buf_size) { uncompr_buf_size = num_of_samples; uncompr_buf = realloc( uncompr_buf, uncompr_buf_size * sizeof(double)); } for (idx = 0; idx < num_of_samples; ++idx) { READ_FROM_PTR_AND_INCREMENT(uncompr_buf[idx], cur_ptr, double); } (*chunk_array)[chunk_idx] = pcomp_init_uncompressed_chunk( num_of_samples, uncompr_buf); } } if (poly_buf != NULL) free(poly_buf); if (cheby_buf != NULL) free(cheby_buf); if (uncompr_buf != NULL) free(uncompr_buf); return PCOMP_STAT_SUCCESS; }
pmv-OpenMP-b.c
#include <stdlib.h> #include <stdio.h> #include <time.h> //#define PRINT_ALL #define VECTOR_GLOBAL //#define VECTOR_DYNAMIC #ifdef VECTOR_GLOBAL #define MAX 1073741824 //=2^30 double v[MAX], m[MAX][MAX], r[MAX]; #endif int main(int argc,char** argv){ if (argc<2){ printf("Faltan nº componentes del vector \n"); exit(-1); } struct timespec cgt1,cgt2; double ncgt; //para tiempo de ejecución int i, j; unsigned int N = atoi(argv[1]); // Máximo N =2^32 -1=4294967295 (sizeof(unsigned int) = 4 B) #ifdef VECTOR_GLOBAL if (N>MAX) N=MAX; #endif #ifdef VECTOR_DYNAMIC double *v, **m, *r; v = (double*) malloc(N*sizeof(double)); // malloc necesita el tamaño en bytes m = (double**) malloc(N*sizeof(double*)); //si no hay espacio suficiente malloc devuelve NULL for (i=0; i<N; i++) m[i] = (double*) malloc(N*sizeof(double)); r = (double*) malloc(N*sizeof(double)); if ((v==NULL) || (m==NULL) || (r==NULL)) { printf("Error en la reserva de espacio para los vectores\n"); exit(-2); } #endif //Inicializar vector y matriz #pragma omp parallel for for (i=0; i<N; i++) { v[i] = N*0.1+ i*0.1; for (j=0; j<N; j++) m[i][j] = v[i]*0.1+j*0.1; } //Comprobamos la incialización #ifdef PRINT_ALL printf(" Vector:\n"); for (i=0; i<N; i++) { printf("\t%f", v[i]); } printf("\n\n Matriz: \n"); for (i=0; i<N; i++) { for (j=0; j<N; j++) printf("\t%f", m[i][j]); printf("\n\n"); } #endif clock_gettime(CLOCK_REALTIME,&cgt1); //Calcular el producto int sum_local; for (i=0; i<N; i++) { r[i] = 0; #pragma omp parallel { sum_local = 0; #pragma omp for for (j=0; j<N; j++) sum_local += m[i][j]*v[j]; #pragma omp atomic r[i] += sum_local; } } 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 del producto printf("\n Resultado:\n"); #ifdef PRINT_ALL for (i=0; i<N; i++) { printf("\t%f", r[i]); } printf("\n"); #else printf("Primer valor: %f \t Último valor: %f \n", r[0], r[N-1]); #endif printf("\n Tiempo de ejecución(s): %11.9f\n", ncgt); #ifdef VECTOR_DYNAMIC free(v); // libera el espacio reservado para v free(m); // libera el espacio reservado para m free(r); #endif return 0; }
simd_misc_messages.c
// RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=45 -verify=expected,omp45 %s -Wuninitialized // RUN: %clang_cc1 -fsyntax-only -fopenmp-simd -fopenmp-version=50 -verify=expected,omp50 %s -Wuninitialized void xxx(int argc) { int x; // expected-note {{initialize the variable 'x' to silence this warning}} #pragma omp simd for (int i = 0; i < 10; ++i) argc = x; // expected-warning {{variable 'x' is uninitialized when used here}} } // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd foo // expected-error@+1 {{unexpected OpenMP directive '#pragma omp simd'}} #pragma omp simd safelen(4) void test_no_clause() { int i; #pragma omp simd for (i = 0; i < 16; ++i) ; // expected-error@+2 {{statement after '#pragma omp simd' must be a for loop}} #pragma omp simd ++i; } void test_branch_protected_scope() { int i = 0; L1: ++i; int x[24]; #pragma omp simd for (i = 0; i < 16; ++i) { if (i == 5) goto L1; // expected-error {{use of undeclared label 'L1'}} else if (i == 6) return; // expected-error {{cannot return from OpenMP region}} else if (i == 7) goto L2; else if (i == 8) { L2: x[i]++; } } if (x[0] == 0) goto L2; // expected-error {{use of undeclared label 'L2'}} else if (x[1] == 1) goto L1; } void test_invalid_clause() { int i; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd foo bar for (i = 0; i < 16; ++i) ; } void test_non_identifiers() { int i, x; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd; for (i = 0; i < 16; ++i) ; // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd firstprivate(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd private(x); for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{extra tokens at the end of '#pragma omp simd' are ignored}} #pragma omp simd, private(x); for (i = 0; i < 16; ++i) ; } extern int foo(); void test_safelen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd safelen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd safelen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd safelen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd safelen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, ) for (i = 0; i < 16; ++i) ; // xxpected-error@+1 {{expected expression}} #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd safelen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd safelen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp simd safelen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp simd safelen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'safelen' clause must be a strictly positive integer value}} #pragma omp simd safelen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_simdlen() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd simdlen for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd simdlen() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd simdlen 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, ) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, , 4) for (i = 0; i < 16; ++i) ; #pragma omp simd simdlen(4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} #pragma omp simd simdlen(4, 8) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp simd simdlen(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp simd simdlen(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'simdlen' clause must be a strictly positive integer value}} #pragma omp simd simdlen(5 - 5) for (i = 0; i < 16; ++i) ; } void test_safelen_simdlen() { int i; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd simdlen(6) safelen(5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{the value of 'simdlen' parameter must be less than or equal to the value of the 'safelen' parameter}} #pragma omp simd safelen(5) simdlen(6) for (i = 0; i < 16; ++i) ; } void test_collapse() { int i; // expected-error@+1 {{expected '('}} #pragma omp simd collapse for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse( for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd collapse() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd collapse(, ) for (i = 0; i < 16; ++i) ; // expected-warning@+2 {{extra tokens at the end of '#pragma omp simd' are ignored}} // expected-error@+1 {{expected '('}} #pragma omp simd collapse 4) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, ) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // xxpected-error@+1 {{expected expression}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, , 4) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} #pragma omp simd collapse(4) for (int i1 = 0; i1 < 16; ++i1) for (int i2 = 0; i2 < 16; ++i2) for (int i3 = 0; i3 < 16; ++i3) for (int i4 = 0; i4 < 16; ++i4) foo(); // expected-error@+2 {{expected ')'}} // expected-note@+1 {{to match this '('}} expected-note@+1 {{as specified in 'collapse' clause}} #pragma omp simd collapse(4, 8) for (i = 0; i < 16; ++i) ; // expected-error {{expected 4 for loops after '#pragma omp simd', but found only 1}} // expected-error@+1 {{integer constant expression}} #pragma omp simd collapse(2.5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{integer constant expression}} #pragma omp simd collapse(foo()) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(-5) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument to 'collapse' clause must be a strictly positive integer value}} #pragma omp simd collapse(5 - 5) for (i = 0; i < 16; ++i) ; // expected-note@+2 2 {{defined as reduction}} #pragma omp parallel #pragma omp simd collapse(2) reduction(+ : i) for (i = 0; i < 16; ++i) // expected-error {{loop iteration variable in the associated loop of 'omp simd' directive may not be reduction, predetermined as lastprivate}} // expected-note@+1 {{variable with automatic storage duration is predetermined as private; perhaps you forget to enclose 'omp for' directive into a parallel or another task region?}} for (int j = 0; j < 16; ++j) // expected-error@+2 2 {{reduction variable must be shared}} // expected-error@+1 {{OpenMP constructs may not be nested inside a simd region}} #pragma omp for reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; #pragma omp parallel #pragma omp for for (i = 0; i < 16; ++i) for (int j = 0; j < 16; ++j) #pragma omp simd reduction(+ : i, j) for (int k = 0; k < 16; ++k) i += j; } void test_linear() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd linear(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd linear(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd linear(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd linear(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd linear(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd linear(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // expected-error@+1 {{expected expression}} #pragma omp simd linear(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd linear(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd linear(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be linear}} #pragma omp simd linear(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as private}} // expected-error@+1 {{private variable cannot be linear}} #pragma omp simd private(x) linear(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be private}} #pragma omp simd linear(x) private(x) for (i = 0; i < 16; ++i) ; // expected-warning@+1 {{zero linear step (x and other variables in clause should probably be const)}} #pragma omp simd linear(x, y : 0) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as linear}} // expected-error@+1 {{linear variable cannot be lastprivate}} #pragma omp simd linear(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as lastprivate}} // expected-error@+1 {{lastprivate variable cannot be linear}} #pragma omp simd lastprivate(x) linear(x) for (i = 0; i < 16; ++i) ; } void test_aligned() { int i; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(, for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected expression}} #pragma omp simd aligned(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd aligned(0) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; int *x, y, z[25]; // expected-note 4 {{'y' defined here}} #pragma omp simd aligned(x) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(z) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd aligned(x :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x :, ) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 1) for (i = 0; i < 16; ++i) ; #pragma omp simd aligned(x : 2 * 2) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd aligned(x : 1, y, z : 1) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) for (i = 0; i < 16; ++i) ; // expected-note@+2 {{defined as aligned}} // expected-error@+1 {{a variable cannot appear in more than one aligned clause}} #pragma omp simd aligned(x) aligned(z, x) for (i = 0; i < 16; ++i) ; // expected-note@+3 {{defined as aligned}} // expected-error@+2 {{a variable cannot appear in more than one aligned clause}} // expected-error@+1 2 {{argument of aligned clause should be array or pointer, not 'int'}} #pragma omp simd aligned(x, y, z) aligned(y, z) for (i = 0; i < 16; ++i) ; } void test_private() { int i; // expected-error@+2 {{expected expression}} // expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd private( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd private(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd private(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd private(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd private(x) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd private(x, y, z) for (i = 0; i < 16; ++i) { x = y * i + z; } } void test_firstprivate() { int i; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{unexpected OpenMP clause 'firstprivate' in directive '#pragma omp simd'}} // expected-error@+1 {{expected expression}} #pragma omp simd firstprivate( for (i = 0; i < 16; ++i) ; } void test_lastprivate() { int i; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected ')'}} expected-note@+2 {{to match this '('}} // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, for (i = 0; i < 16; ++i) ; // expected-error@+1 2 {{expected expression}} #pragma omp simd lastprivate(, ) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate() for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd lastprivate(int) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd lastprivate(0) for (i = 0; i < 16; ++i) ; int x, y, z; #pragma omp simd lastprivate(x) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y) for (i = 0; i < 16; ++i) ; #pragma omp simd lastprivate(x, y, z) for (i = 0; i < 16; ++i) ; } void test_reduction() { int i, x, y; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction( for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction() for (i = 0; i < 16; ++i) ; // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction( : x) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected identifier}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(, for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // expected-error@+2 {{expected expression}} // expected-warning@+1 {{missing ':' after reduction identifier - ignoring}} #pragma omp simd reduction(+ for (i = 0; i < 16; ++i) ; // expected-error@+3 {{expected ')'}} expected-note@+3 {{to match this '('}} // // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+: for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ :, y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected expression}} #pragma omp simd reduction(+ : x, + : y) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected identifier}} #pragma omp simd reduction(% : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(+ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(* : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(- : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(^ : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(&& : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(|| : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(max : x) for (i = 0; i < 16; ++i) ; #pragma omp simd reduction(min : x) for (i = 0; i < 16; ++i) ; struct X { int x; }; struct X X; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : X.x) for (i = 0; i < 16; ++i) ; // expected-error@+1 {{expected variable name}} #pragma omp simd reduction(+ : x + x) for (i = 0; i < 16; ++i) ; } void test_loop_messages() { float a[100], b[100], c[100]; // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (float fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } // expected-error@+2 {{variable must be of integer or pointer type}} #pragma omp simd for (double fi = 0; fi < 10.0; fi++) { c[(int)fi] = a[(int)fi] + b[(int)fi]; } } void linear_modifiers(int argc) { int f; #pragma omp simd linear(f) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(val(f)) for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(uval(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(ref(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; #pragma omp simd linear(foo(f)) // expected-error {{expected 'val' modifier}} for (int k = 0; k < argc; ++k) ++k; } void test_nontemporal() { int i; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal( for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 2 {{expected expression}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal(, for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 2 {{expected expression}} #pragma omp simd nontemporal(, ) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} #pragma omp simd nontemporal() for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected expression}} #pragma omp simd nontemporal(int) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} omp50-error@+1 {{expected variable name}} #pragma omp simd nontemporal(0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'x'}} #pragma omp simd nontemporal(x) for (i = 0; i < 16; ++i) ; // expected-error@+2 {{use of undeclared identifier 'x'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'y'}} #pragma omp simd nontemporal(x, y) for (i = 0; i < 16; ++i) ; // expected-error@+3 {{use of undeclared identifier 'x'}} // expected-error@+2 {{use of undeclared identifier 'y'}} // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{use of undeclared identifier 'z'}} #pragma omp simd nontemporal(x, y, z) for (i = 0; i < 16; ++i) ; int x, y; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} #pragma omp simd nontemporal(x :) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-error@+1 {{expected ')'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} #pragma omp simd nontemporal(x :, ) for (i = 0; i < 16; ++i) ; // omp50-note@+2 {{defined as nontemporal}} // omp45-error@+1 2 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} omp50-error@+1 {{a variable cannot appear in more than one nontemporal clause}} #pragma omp simd nontemporal(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd private(x) nontemporal(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd nontemporal(x) private(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} expected-note@+1 {{to match this '('}} expected-error@+1 {{expected ',' or ')' in 'nontemporal' clause}} expected-error@+1 {{expected ')'}} #pragma omp simd nontemporal(x, y : 0) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd nontemporal(x) lastprivate(x) for (i = 0; i < 16; ++i) ; // omp45-error@+1 {{unexpected OpenMP clause 'nontemporal' in directive '#pragma omp simd'}} #pragma omp simd lastprivate(x) nontemporal(x) for (i = 0; i < 16; ++i) ; #pragma omp simd order // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected '(' after 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order( // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(none // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} omp50-error {{expected 'concurrent' in OpenMP clause 'order'}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(concurrent // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int i = 0; i < 10; ++i) ; #pragma omp simd order(concurrent) // omp45-error {{unexpected OpenMP clause 'order' in directive '#pragma omp simd'}} for (int i = 0; i < 10; ++i) ; }
mandelAVXDD.c
#include <immintrin.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "mandelAVXDD.h" /* es können 4 DD auf einmal bearbeitet werden, d.h. in einem Register stehen 4 hi, im anderen die 4 lo */ DD4 DD4_mul(const DD4 pDD1, const DD4 pDD2) { const __m256d hi = pDD1.hi; const __m256d lo = pDD1.lo; const __m256d yhi = pDD2.hi; const __m256d ylo = pDD2.lo; __m256d t, tau, u, v, w; t = hi * yhi; /* Highest order double term. */ tau = _mm256_fmsub_pd(hi, yhi, t); v = hi * ylo; w = lo * yhi; tau += v + w; /* Add in other second-order terms. */ u = t + tau; const __m256d rlo = (t - u) + tau; return (DD4){u, rlo}; } DD4 DD4_mul_m256d(const DD4 pDD1, const __m256d pDouble4) { const __m256d hi = pDD1.hi; const __m256d lo = pDD1.lo; const __m256d yhi = pDouble4; __m256d t, tau, u, w; t = hi * yhi; /* Highest order double term. */ tau = _mm256_fmsub_pd(hi, yhi, t); w = lo * yhi; tau += w; /* Add in other second-order terms. */ u = t + tau; const __m256d rlo = (t - u) + tau; return (DD4){u, rlo}; } DD4 DD4_add(const DD4 pDD1, const DD4 pDD2) { const __m256d hi = pDD1.hi; const __m256d lo = pDD1.lo; const __m256d yhi = pDD2.hi; const __m256d ylo = pDD2.lo; __m256d z, q, zz, xh; z = hi + yhi; q = hi - z; zz = q + yhi + (hi - (q + z)) + lo + ylo; xh = z + zz; const __m256d rlo = z - xh + zz; return (DD4){xh, rlo}; } DD4 DD4_add__m256d(const DD4 pDD1, const __m256d y) { __m256d hi = pDD1.hi; __m256d lo = pDD1.lo; __m256d z, q, zz, xh; z = hi + y; q = hi - z; zz = q + y + (hi - (q + z)) + lo; xh = z + zz; const __m256d rlo = z - xh + zz; return (DD4){xh, rlo}; } DD4 DD4_sub(const DD4 pDD1,const DD4 pDD2) { return DD4_add(pDD1, (DD4){-pDD2.hi, -pDD2.lo}); } void checkCompilerOptimizationDD4() { DD4 y = (DD4){_mm256_set1_pd(2.9615004935834156e-03),_mm256_set1_pd(-1.8408960875370855e-20)}; DD4 erg = DD4_mul_m256d(y, _mm256_set1_pd(1.0120000000000000e+03)); if ( erg.lo[0]!=4.2085453253312943e-17) { printf("compiler break DD Logik -> please do not use -ffast-math or -funsafe-math-optimizations\n"); fflush(stdout); } } void mandel_avxdd( int32_t *iters, double *lastZrs, double *lastZis, double *distancesR, double *distancesI, const int32_t mode, const int32_t width, const int32_t height, const double xStartHi, const double xStartLo, const double yStartHi, const double yStartLo, const double juliaCrHi, const double juliaCrLo, const double juliaCiHi, const double juliaCiLo, const double xIncHi, const double xIncLo, const double yIncHi, const double yIncLo, const int32_t maxIterations, const double sqrEscapeRadius) { checkCompilerOptimizationDD4(); const __m256d mZero = _mm256_set1_pd(0); const __m256d mOne = _mm256_set1_pd(1); const __m256d mOneminus = _mm256_set1_pd(-1); const __m256d threshold = _mm256_set1_pd(sqrEscapeRadius); const DD4 xmin = (DD4){_mm256_set1_pd(xStartHi), _mm256_set1_pd(xStartLo)}; const DD4 ymin = (DD4){_mm256_set1_pd(yStartHi), _mm256_set1_pd(yStartLo)}; const DD4 xScale = (DD4){_mm256_set1_pd(xIncHi), _mm256_set1_pd(xIncLo)}; const DD4 yScale = (DD4){_mm256_set1_pd(yIncHi), _mm256_set1_pd(yIncLo)}; const DD4 juliaCr = (DD4){_mm256_set1_pd(juliaCrHi), _mm256_set1_pd(juliaCrLo)}; const DD4 juliaCi = (DD4){_mm256_set1_pd(juliaCiHi), _mm256_set1_pd(juliaCiLo)}; const DD4 zero = (DD4){mZero, mZero}; const DD4 one = (DD4){mOne, mZero}; const DD4 xInc = DD4_mul_m256d(xScale, _mm256_set1_pd(4)); #pragma omp parallel for schedule(dynamic, 1) for (int y = 0; y < height; y++) { // as long as the assignment loop is failing, we calc some pixels less to avoid writing outside array limits const DD4 tY = DD4_add(ymin,DD4_mul_m256d(yScale,_mm256_set1_pd(y))); const DD4 ci = mode == MODE_JULIA ? juliaCi : tY; DD4 tX = DD4_add(xmin,DD4_mul_m256d(xScale,_mm256_set_pd(3,2,1,0))); for (int x = 0; x < width; x += 4) { const DD4 cr = mode == MODE_JULIA ? juliaCr : tX; DD4 zr = tX; DD4 zi = tY; int32_t k = 0; // store the iterations __m256d mk = _mm256_set1_pd(k); // last Zr/Zi values -> make them accessible as float vector __m256d mlastZr = mZero; __m256d mlastZi = mZero; // distance DD4 dr = one; DD4 di = zero; __m256d lastDr = dr.hi; __m256d lastDi = di.hi; __m256d previousInsideMask = _mm256_set1_pd(0xFFFFFFFFFFFFFFFF); while (++k <= maxIterations) { /* Compute z1 from z0 */ const DD4 zr2 = DD4_mul(zr,zr); const DD4 zi2 = DD4_mul(zi,zi); const DD4 zr2zi2 = DD4_add(zr2,zi2); const __m256d insideMask = _mm256_cmp_pd(zr2zi2.hi, threshold, _CMP_LT_OS); // store last inside values of z // copy only if inside mask changes for the vector (xor previous and current const __m256d noticeZMask = _mm256_xor_pd(insideMask, previousInsideMask); mlastZr = _mm256_and_pd(noticeZMask, zr.hi) + mlastZr; mlastZi = _mm256_and_pd(noticeZMask, zi.hi) + mlastZi; if( mode == MODE_MANDEL_DISTANCE ) { lastDr = _mm256_and_pd(noticeZMask, dr.hi) + lastDr; lastDi = _mm256_and_pd(noticeZMask, di.hi) + lastDi; } previousInsideMask = insideMask; /* Early bailout? */ if (_mm256_testz_pd(insideMask, mOneminus)) { break; } /* Increment k for all vectors inside */ mk = _mm256_and_pd(insideMask, mOne) + mk; if ( mode == MODE_MANDEL_DISTANCE) { const DD4 zwergDr = DD4_sub(DD4_mul(zr,dr), DD4_mul(zi,di)); const DD4 zwergDi = DD4_add(DD4_mul(zr,di), DD4_mul(zi,dr)); dr = DD4_add(DD4_add(zwergDr,zwergDr), one); di = DD4_add(zwergDi,zwergDi); } const DD4 zrzi = DD4_mul(zr,zi); zi = DD4_add(DD4_add(zrzi,zrzi),ci); zr = DD4_add(DD4_sub(zr2,zi2),cr); } // convert counter to int and make it accessible via array index union { int32_t i[4]; __m128i m; } vCount; vCount.m = _mm256_cvtpd_epi32(mk); double tLastZrs[4]; double tLastZis[4]; _mm256_storeu_pd(tLastZrs, mlastZr); _mm256_storeu_pd(tLastZis, mlastZi); const int tIndex = x + y * width; for ( int i=0; i<4 && x+i<width; i++ ) { iters[tIndex+i] = vCount.i[i]; lastZrs[tIndex+i] = tLastZrs[i]; lastZis[tIndex+i] = tLastZis[i]; } if ( mode == MODE_MANDEL_DISTANCE) { double tLastDrs[4]; double tLastDis[4]; _mm256_storeu_pd(tLastDrs, lastDr); _mm256_storeu_pd(tLastDis, lastDi); for ( int i=0; i<4 && x+i<width; i++ ) { distancesR[tIndex+i] = tLastDrs[i]; distancesI[tIndex+i] = tLastDis[i]; } } tX = DD4_add(tX, xInc); } } }
3d7pt_var.c
/* * Order-1, 3D 7 point stencil with variable coefficients * Adapted from PLUTO and Pochoir test bench * * Tareq Malas */ #include <stdio.h> #include <stdlib.h> #include <sys/time.h> #ifdef LIKWID_PERFMON #include <likwid.h> #endif #include "print_utils.h" #define TESTS 2 #define MAX(a,b) ((a) > (b) ? a : b) #define MIN(a,b) ((a) < (b) ? a : b) /* Subtract the `struct timeval' values X and Y, * storing the result in RESULT. * * Return 1 if the difference is negative, otherwise 0. */ int timeval_subtract(struct timeval *result, struct timeval *x, struct timeval *y) { /* Perform the carry for the later subtraction by updating y. */ if (x->tv_usec < y->tv_usec) { int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1; y->tv_usec -= 1000000 * nsec; y->tv_sec += nsec; } if (x->tv_usec - y->tv_usec > 1000000) { int nsec = (x->tv_usec - y->tv_usec) / 1000000; y->tv_usec += 1000000 * nsec; y->tv_sec -= nsec; } /* Compute the time remaining to wait. * tv_usec is certainly positive. */ result->tv_sec = x->tv_sec - y->tv_sec; result->tv_usec = x->tv_usec - y->tv_usec; /* Return 1 if result is negative. */ return x->tv_sec < y->tv_sec; } int main(int argc, char *argv[]) { int t, i, j, k, m, test; int Nx, Ny, Nz, Nt; if (argc > 3) { Nx = atoi(argv[1])+2; Ny = atoi(argv[2])+2; Nz = atoi(argv[3])+2; } if (argc > 4) Nt = atoi(argv[4]); // allocate the arrays double ****A = (double ****) malloc(sizeof(double***)*2); for(m=0; m<2;m++){ A[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ A[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ A[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } double ****coef = (double ****) malloc(sizeof(double***)*7); for(m=0; m<7;m++){ coef[m] = (double ***) malloc(sizeof(double**)*Nz); for(i=0; i<Nz; i++){ coef[m][i] = (double**) malloc(sizeof(double*)*Ny); for(j=0;j<Ny;j++){ coef[m][i][j] = (double*) malloc(sizeof(double)*Nx); } } } // tile size information, including extra element to decide the list length int *tile_size = (int*) malloc(sizeof(int)); tile_size[0] = -1; // The list is modified here before source-to-source transformations tile_size = (int*) realloc((void *)tile_size, sizeof(int)*5); tile_size[0] = 32; tile_size[1] = 32; tile_size[2] = 4; tile_size[3] = 1024; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); } } } for (m=0; m<7; m++) { for (i=1; i<Nz; i++) { for (j=1; j<Ny; j++) { for (k=1; k<Nx; k++) { coef[m][i][j][k] = 1.0 * (rand() % BASE); } } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt-1; t++) { for (i = 1; i < Nz-1; i++) { for (j = 1; j < Ny-1; j++) { for (k = 1; k < Nx-1; k++) { A[(t+1)%2][i][j][k] = coef[0][i][j][k] * A[t%2][i ][j ][k ] + coef[1][i][j][k] * A[t%2][i-1][j ][k ] + coef[2][i][j][k] * A[t%2][i ][j-1][k ] + coef[3][i][j][k] * A[t%2][i ][j ][k-1] + coef[4][i][j][k] * A[t%2][i+1][j ][k ] + coef[5][i][j][k] * A[t%2][i ][j+1][k ] + coef[6][i][j][k] * A[t%2][i ][j ][k+1]; } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = min(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(1, "variable no-symmetry") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); } free(A[0][i]); free(A[1][i]); } free(A[0]); free(A[1]); for(m=0; m<7;m++){ for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(coef[m][i][j]); } free(coef[m][i]); } free(coef[m]); } return 0; }
fourier.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % FFFFF OOO U U RRRR IIIII EEEEE RRRR % % F O O U U R R I E R R % % FFF O O U U RRRR I EEE RRRR % % F O O U U R R I E R R % % F OOO UUU R R IIIII EEEEE R R % % % % % % MagickCore Discrete Fourier Transform Methods % % % % Software Design % % Sean Burke % % Fred Weinhaus % % Cristy % % July 2009 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/artifact.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/cache.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/fourier.h" #include "MagickCore/log.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/property.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/string-private.h" #include "MagickCore/thread-private.h" #if defined(MAGICKCORE_FFTW_DELEGATE) #if defined(MAGICKCORE_HAVE_COMPLEX_H) #include <complex.h> #endif #include <fftw3.h> #if !defined(MAGICKCORE_HAVE_CABS) #define cabs(z) (sqrt(z[0]*z[0]+z[1]*z[1])) #endif #if !defined(MAGICKCORE_HAVE_CARG) #define carg(z) (atan2(cimag(z),creal(z))) #endif #if !defined(MAGICKCORE_HAVE_CIMAG) #define cimag(z) (z[1]) #endif #if !defined(MAGICKCORE_HAVE_CREAL) #define creal(z) (z[0]) #endif #endif /* Typedef declarations. */ typedef struct _FourierInfo { PixelChannel channel; MagickBooleanType modulus; size_t width, height; ssize_t center; } FourierInfo; /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % C o m p l e x I m a g e s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ComplexImages() performs complex mathematics on an image sequence. % % The format of the ComplexImages method is: % % MagickBooleanType ComplexImages(Image *images,const ComplexOperator op, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o op: A complex operator. % % o exception: return any errors or warnings in this structure. % */ MagickExport Image *ComplexImages(const Image *images,const ComplexOperator op, ExceptionInfo *exception) { #define ComplexImageTag "Complex/Image" CacheView *Ai_view, *Ar_view, *Bi_view, *Br_view, *Ci_view, *Cr_view; const char *artifact; const Image *Ai_image, *Ar_image, *Bi_image, *Br_image; double snr; Image *Ci_image, *complex_images, *Cr_image, *image; MagickBooleanType status; MagickOffsetType progress; ssize_t y; assert(images != (Image *) NULL); assert(images->signature == MagickCoreSignature); if (images->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",images->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); if (images->next == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",images->filename); return((Image *) NULL); } image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) return((Image *) NULL); if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) { image=DestroyImageList(image); return(image); } image->depth=32UL; complex_images=NewImageList(); AppendImageToList(&complex_images,image); image=CloneImage(images,images->columns,images->rows,MagickTrue,exception); if (image == (Image *) NULL) { complex_images=DestroyImageList(complex_images); return(complex_images); } AppendImageToList(&complex_images,image); /* Apply complex mathematics to image pixels. */ artifact=GetImageArtifact(image,"complex:snr"); snr=0.0; if (artifact != (const char *) NULL) snr=StringToDouble(artifact,(char **) NULL); Ar_image=images; Ai_image=images->next; Br_image=images; Bi_image=images->next; if ((images->next->next != (Image *) NULL) && (images->next->next->next != (Image *) NULL)) { Br_image=images->next->next; Bi_image=images->next->next->next; } Cr_image=complex_images; Ci_image=complex_images->next; Ar_view=AcquireVirtualCacheView(Ar_image,exception); Ai_view=AcquireVirtualCacheView(Ai_image,exception); Br_view=AcquireVirtualCacheView(Br_image,exception); Bi_view=AcquireVirtualCacheView(Bi_image,exception); Cr_view=AcquireAuthenticCacheView(Cr_image,exception); Ci_view=AcquireAuthenticCacheView(Ci_image,exception); status=MagickTrue; progress=0; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static,4) shared(progress,status) \ magick_number_threads(images,complex_images,images->rows,1L) #endif for (y=0; y < (ssize_t) images->rows; y++) { register const Quantum *magick_restrict Ai, *magick_restrict Ar, *magick_restrict Bi, *magick_restrict Br; register Quantum *magick_restrict Ci, *magick_restrict Cr; register ssize_t x; if (status == MagickFalse) continue; Ar=GetCacheViewVirtualPixels(Ar_view,0,y,Ar_image->columns,1,exception); Ai=GetCacheViewVirtualPixels(Ai_view,0,y,Ai_image->columns,1,exception); Br=GetCacheViewVirtualPixels(Br_view,0,y,Br_image->columns,1,exception); Bi=GetCacheViewVirtualPixels(Bi_view,0,y,Bi_image->columns,1,exception); Cr=QueueCacheViewAuthenticPixels(Cr_view,0,y,Cr_image->columns,1,exception); Ci=QueueCacheViewAuthenticPixels(Ci_view,0,y,Ci_image->columns,1,exception); if ((Ar == (const Quantum *) NULL) || (Ai == (const Quantum *) NULL) || (Br == (const Quantum *) NULL) || (Bi == (const Quantum *) NULL) || (Cr == (Quantum *) NULL) || (Ci == (Quantum *) NULL)) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) images->columns; x++) { register ssize_t i; for (i=0; i < (ssize_t) GetPixelChannels(images); i++) { switch (op) { case AddComplexOperator: { Cr[i]=Ar[i]+Br[i]; Ci[i]=Ai[i]+Bi[i]; break; } case ConjugateComplexOperator: default: { Cr[i]=Ar[i]; Ci[i]=(-Bi[i]); break; } case DivideComplexOperator: { double gamma; gamma=PerceptibleReciprocal(Br[i]*Br[i]+Bi[i]*Bi[i]+snr); Cr[i]=gamma*(Ar[i]*Br[i]+Ai[i]*Bi[i]); Ci[i]=gamma*(Ai[i]*Br[i]-Ar[i]*Bi[i]); break; } case MagnitudePhaseComplexOperator: { Cr[i]=sqrt(Ar[i]*Ar[i]+Ai[i]*Ai[i]); Ci[i]=atan2(Ai[i],Ar[i])/(2.0*MagickPI)+0.5; break; } case MultiplyComplexOperator: { Cr[i]=QuantumScale*(Ar[i]*Br[i]-Ai[i]*Bi[i]); Ci[i]=QuantumScale*(Ai[i]*Br[i]+Ar[i]*Bi[i]); break; } case RealImaginaryComplexOperator: { Cr[i]=Ar[i]*cos(2.0*MagickPI*(Ai[i]-0.5)); Ci[i]=Ar[i]*sin(2.0*MagickPI*(Ai[i]-0.5)); break; } case SubtractComplexOperator: { Cr[i]=Ar[i]-Br[i]; Ci[i]=Ai[i]-Bi[i]; break; } } } Ar+=GetPixelChannels(Ar_image); Ai+=GetPixelChannels(Ai_image); Br+=GetPixelChannels(Br_image); Bi+=GetPixelChannels(Bi_image); Cr+=GetPixelChannels(Cr_image); Ci+=GetPixelChannels(Ci_image); } if (SyncCacheViewAuthenticPixels(Ci_view,exception) == MagickFalse) status=MagickFalse; if (SyncCacheViewAuthenticPixels(Cr_view,exception) == MagickFalse) status=MagickFalse; if (images->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ComplexImages) #endif proceed=SetImageProgress(images,ComplexImageTag,progress++, images->rows); if (proceed == MagickFalse) status=MagickFalse; } } Cr_view=DestroyCacheView(Cr_view); Ci_view=DestroyCacheView(Ci_view); Br_view=DestroyCacheView(Br_view); Bi_view=DestroyCacheView(Bi_view); Ar_view=DestroyCacheView(Ar_view); Ai_view=DestroyCacheView(Ai_view); if (status == MagickFalse) complex_images=DestroyImageList(complex_images); return(complex_images); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % F o r w a r d F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ForwardFourierTransformImage() implements the discrete Fourier transform % (DFT) of the image either as a magnitude / phase or real / imaginary image % pair. % % The format of the ForwadFourierTransformImage method is: % % Image *ForwardFourierTransformImage(const Image *image, % const MagickBooleanType modulus,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o modulus: if true, return as transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType RollFourier(const size_t width,const size_t height, const ssize_t x_offset,const ssize_t y_offset,double *roll_pixels) { double *source_pixels; MemoryInfo *source_info; register ssize_t i, x; ssize_t u, v, y; /* Move zero frequency (DC, average color) from (0,0) to (width/2,height/2). */ source_info=AcquireVirtualMemory(width,height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) return(MagickFalse); source_pixels=(double *) GetVirtualMemoryBlob(source_info); i=0L; for (y=0L; y < (ssize_t) height; y++) { if (y_offset < 0L) v=((y+y_offset) < 0L) ? y+y_offset+(ssize_t) height : y+y_offset; else v=((y+y_offset) > ((ssize_t) height-1L)) ? y+y_offset-(ssize_t) height : y+y_offset; for (x=0L; x < (ssize_t) width; x++) { if (x_offset < 0L) u=((x+x_offset) < 0L) ? x+x_offset+(ssize_t) width : x+x_offset; else u=((x+x_offset) > ((ssize_t) width-1L)) ? x+x_offset-(ssize_t) width : x+x_offset; source_pixels[v*width+u]=roll_pixels[i++]; } } (void) CopyMagickMemory(roll_pixels,source_pixels,height*width* sizeof(*source_pixels)); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType ForwardQuadrantSwap(const size_t width, const size_t height,double *source_pixels,double *forward_pixels) { MagickBooleanType status; register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; status=RollFourier((size_t) center,height,0L,(ssize_t) height/2L, source_pixels); if (status == MagickFalse) return(MagickFalse); for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[y*width+x+width/2L]=source_pixels[y*center+x]; for (y=1; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[(height-y)*width+width/2L-x-1L]= source_pixels[y*center+x+1L]; for (x=0L; x < (ssize_t) (width/2L); x++) forward_pixels[width/2L-x-1L]=source_pixels[x+1L]; return(MagickTrue); } static void CorrectPhaseLHS(const size_t width,const size_t height, double *fourier_pixels) { register ssize_t x; ssize_t y; for (y=0L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L); x++) fourier_pixels[y*width+x]*=(-1.0); } static MagickBooleanType ForwardFourier(const FourierInfo *fourier_info, Image *image,double *magnitude,double *phase,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *magnitude_pixels, *phase_pixels; Image *magnitude_image, *phase_image; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; register Quantum *q; register ssize_t x; ssize_t i, y; magnitude_image=GetFirstImageInList(image); phase_image=GetNextImageInList(image); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",image->filename); return(MagickFalse); } /* Create "Fourier Transform" image from constituent arrays. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); (void) ResetMagickMemory(magnitude_pixels,0,fourier_info->width* fourier_info->height*sizeof(*magnitude_pixels)); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); (void) ResetMagickMemory(phase_pixels,0,fourier_info->width* fourier_info->height*sizeof(*phase_pixels)); status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height, magnitude,magnitude_pixels); if (status != MagickFalse) status=ForwardQuadrantSwap(fourier_info->width,fourier_info->height,phase, phase_pixels); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]/=(2.0*MagickPI); phase_pixels[i]+=0.5; i++; } } magnitude_view=AcquireAuthenticCacheView(magnitude_image,exception); i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(magnitude_image,ClampToQuantum(QuantumRange* magnitude_pixels[i]),q); break; } } i++; q+=GetPixelChannels(magnitude_image); } status=SyncCacheViewAuthenticPixels(magnitude_view,exception); if (status == MagickFalse) break; } magnitude_view=DestroyCacheView(magnitude_view); i=0L; phase_view=AcquireAuthenticCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { q=GetCacheViewAuthenticPixels(phase_view,0L,y,fourier_info->width,1UL, exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BluePixelChannel: { SetPixelBlue(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case BlackPixelChannel: { SetPixelBlack(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } case AlphaPixelChannel: { SetPixelAlpha(phase_image,ClampToQuantum(QuantumRange* phase_pixels[i]),q); break; } } i++; q+=GetPixelChannels(phase_image); } status=SyncCacheViewAuthenticPixels(phase_view,exception); if (status == MagickFalse) break; } phase_view=DestroyCacheView(phase_view); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } static MagickBooleanType ForwardFourierTransform(FourierInfo *fourier_info, const Image *image,double *magnitude_pixels,double *phase_pixels, ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_complex *forward_pixels; fftw_plan fftw_r2c_plan; MemoryInfo *forward_info, *source_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Generate the forward Fourier transform. */ source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); ResetMagickMemory(source_pixels,0,fourier_info->width*fourier_info->height* sizeof(*source_pixels)); i=0L; image_view=AcquireVirtualCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(image_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { source_pixels[i]=QuantumScale*GetPixelRed(image,p); break; } case GreenPixelChannel: { source_pixels[i]=QuantumScale*GetPixelGreen(image,p); break; } case BluePixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlue(image,p); break; } case BlackPixelChannel: { source_pixels[i]=QuantumScale*GetPixelBlack(image,p); break; } case AlphaPixelChannel: { source_pixels[i]=QuantumScale*GetPixelAlpha(image,p); break; } } i++; p+=GetPixelChannels(image); } } image_view=DestroyCacheView(image_view); forward_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*forward_pixels)); if (forward_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); return(MagickFalse); } forward_pixels=(fftw_complex *) GetVirtualMemoryBlob(forward_info); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_ForwardFourierTransform) #endif fftw_r2c_plan=fftw_plan_dft_r2c_2d(fourier_info->width,fourier_info->height, source_pixels,forward_pixels,FFTW_ESTIMATE); fftw_execute_dft_r2c(fftw_r2c_plan,source_pixels,forward_pixels); fftw_destroy_plan(fftw_r2c_plan); source_info=(MemoryInfo *) RelinquishVirtualMemory(source_info); value=GetImageArtifact(image,"fourier:normalize"); if ((value == (const char *) NULL) || (LocaleCompare(value,"forward") == 0)) { double gamma; /* Normalize fourier transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) forward_pixels[i]*=gamma; #else forward_pixels[i][0]*=gamma; forward_pixels[i][1]*=gamma; #endif i++; } } /* Generate magnitude and phase (or real and imaginary). */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=cabs(forward_pixels[i]); phase_pixels[i]=carg(forward_pixels[i]); i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { magnitude_pixels[i]=creal(forward_pixels[i]); phase_pixels[i]=cimag(forward_pixels[i]); i++; } forward_info=(MemoryInfo *) RelinquishVirtualMemory(forward_info); return(MagickTrue); } static MagickBooleanType ForwardFourierTransformChannel(const Image *image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { double *magnitude_pixels, *phase_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *magnitude_info, *phase_info; fourier_info.width=image->columns; fourier_info.height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; magnitude_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*phase_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL)) { if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (magnitude_info == (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); status=ForwardFourierTransform(&fourier_info,image,magnitude_pixels, phase_pixels,exception); if (status != MagickFalse) status=ForwardFourier(&fourier_info,fourier_image,magnitude_pixels, phase_pixels,exception); phase_info=RelinquishVirtualMemory(phase_info); magnitude_info=RelinquishVirtualMemory(magnitude_info); return(status); } #endif MagickExport Image *ForwardFourierTransformImage(const Image *image, const MagickBooleanType modulus,ExceptionInfo *exception) { Image *fourier_image; fourier_image=NewImageList(); #if !defined(MAGICKCORE_FFTW_DELEGATE) (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", image->filename); #else { Image *magnitude_image; size_t height, width; width=image->columns; height=image->rows; if ((image->columns != image->rows) || ((image->columns % 2) != 0) || ((image->rows % 2) != 0)) { size_t extent=image->columns < image->rows ? image->rows : image->columns; width=(extent & 0x01) == 1 ? extent+1UL : extent; } height=width; magnitude_image=CloneImage(image,width,height,MagickTrue,exception); if (magnitude_image != (Image *) NULL) { Image *phase_image; magnitude_image->storage_class=DirectClass; magnitude_image->depth=32UL; phase_image=CloneImage(image,width,height,MagickTrue,exception); if (phase_image == (Image *) NULL) magnitude_image=DestroyImage(magnitude_image); else { MagickBooleanType is_gray, status; phase_image->storage_class=DirectClass; phase_image->depth=32UL; AppendImageToList(&fourier_image,magnitude_image); AppendImageToList(&fourier_image,phase_image); status=MagickTrue; is_gray=IsImageGray(image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=ForwardFourierTransformChannel(image, GrayPixelChannel,modulus,fourier_image,exception); else thread_status=ForwardFourierTransformChannel(image, RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=ForwardFourierTransformChannel(image, BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->colorspace == CMYKColorspace) thread_status=ForwardFourierTransformChannel(image, BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (image->alpha_trait != UndefinedPixelTrait) thread_status=ForwardFourierTransformChannel(image, AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImageList(fourier_image); fftw_cleanup(); } } } #endif return(fourier_image); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n v e r s e F o u r i e r T r a n s f o r m I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InverseFourierTransformImage() implements the inverse discrete Fourier % transform (DFT) of the image either as a magnitude / phase or real / % imaginary image pair. % % The format of the InverseFourierTransformImage method is: % % Image *InverseFourierTransformImage(const Image *magnitude_image, % const Image *phase_image,const MagickBooleanType modulus, % ExceptionInfo *exception) % % A description of each parameter follows: % % o magnitude_image: the magnitude or real image. % % o phase_image: the phase or imaginary image. % % o modulus: if true, return transform as a magnitude / phase pair % otherwise a real / imaginary image pair. % % o exception: return any errors or warnings in this structure. % */ #if defined(MAGICKCORE_FFTW_DELEGATE) static MagickBooleanType InverseQuadrantSwap(const size_t width, const size_t height,const double *source,double *destination) { register ssize_t x; ssize_t center, y; /* Swap quadrants. */ center=(ssize_t) (width/2L)+1L; for (y=1L; y < (ssize_t) height; y++) for (x=0L; x < (ssize_t) (width/2L+1L); x++) destination[(height-y)*center-x+width/2L]=source[y*width+x]; for (y=0L; y < (ssize_t) height; y++) destination[y*center]=source[y*width+width/2L]; for (x=0L; x < center; x++) destination[x]=source[center-x-1L]; return(RollFourier(center,height,0L,(ssize_t) height/-2L,destination)); } static MagickBooleanType InverseFourier(FourierInfo *fourier_info, const Image *magnitude_image,const Image *phase_image, fftw_complex *fourier_pixels,ExceptionInfo *exception) { CacheView *magnitude_view, *phase_view; double *inverse_pixels, *magnitude_pixels, *phase_pixels; MagickBooleanType status; MemoryInfo *inverse_info, *magnitude_info, *phase_info; register const Quantum *p; register ssize_t i, x; ssize_t y; /* Inverse fourier - read image and break down into a double array. */ magnitude_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*magnitude_pixels)); phase_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*phase_pixels)); inverse_info=AcquireVirtualMemory((size_t) fourier_info->width, (fourier_info->height/2+1)*sizeof(*inverse_pixels)); if ((magnitude_info == (MemoryInfo *) NULL) || (phase_info == (MemoryInfo *) NULL) || (inverse_info == (MemoryInfo *) NULL)) { if (magnitude_info != (MemoryInfo *) NULL) magnitude_info=RelinquishVirtualMemory(magnitude_info); if (phase_info != (MemoryInfo *) NULL) phase_info=RelinquishVirtualMemory(phase_info); if (inverse_info != (MemoryInfo *) NULL) inverse_info=RelinquishVirtualMemory(inverse_info); (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } magnitude_pixels=(double *) GetVirtualMemoryBlob(magnitude_info); phase_pixels=(double *) GetVirtualMemoryBlob(phase_info); inverse_pixels=(double *) GetVirtualMemoryBlob(inverse_info); i=0L; magnitude_view=AcquireVirtualCacheView(magnitude_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(magnitude_view,0L,y,fourier_info->width,1UL, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { magnitude_pixels[i]=QuantumScale*GetPixelRed(magnitude_image,p); break; } case GreenPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelGreen(magnitude_image,p); break; } case BluePixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlue(magnitude_image,p); break; } case BlackPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelBlack(magnitude_image,p); break; } case AlphaPixelChannel: { magnitude_pixels[i]=QuantumScale*GetPixelAlpha(magnitude_image,p); break; } } i++; p+=GetPixelChannels(magnitude_image); } } magnitude_view=DestroyCacheView(magnitude_view); status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, magnitude_pixels,inverse_pixels); (void) CopyMagickMemory(magnitude_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*magnitude_pixels)); i=0L; phase_view=AcquireVirtualCacheView(phase_image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { p=GetCacheViewVirtualPixels(phase_view,0,y,fourier_info->width,1, exception); if (p == (const Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { switch (fourier_info->channel) { case RedPixelChannel: default: { phase_pixels[i]=QuantumScale*GetPixelRed(phase_image,p); break; } case GreenPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelGreen(phase_image,p); break; } case BluePixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlue(phase_image,p); break; } case BlackPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelBlack(phase_image,p); break; } case AlphaPixelChannel: { phase_pixels[i]=QuantumScale*GetPixelAlpha(phase_image,p); break; } } i++; p+=GetPixelChannels(phase_image); } } if (fourier_info->modulus != MagickFalse) { i=0L; for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->width; x++) { phase_pixels[i]-=0.5; phase_pixels[i]*=(2.0*MagickPI); i++; } } phase_view=DestroyCacheView(phase_view); CorrectPhaseLHS(fourier_info->width,fourier_info->height,phase_pixels); if (status != MagickFalse) status=InverseQuadrantSwap(fourier_info->width,fourier_info->height, phase_pixels,inverse_pixels); (void) CopyMagickMemory(phase_pixels,inverse_pixels,fourier_info->height* fourier_info->center*sizeof(*phase_pixels)); inverse_info=RelinquishVirtualMemory(inverse_info); /* Merge two sets. */ i=0L; if (fourier_info->modulus != MagickFalse) for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]*cos(phase_pixels[i])+I* magnitude_pixels[i]*sin(phase_pixels[i]); #else fourier_pixels[i][0]=magnitude_pixels[i]*cos(phase_pixels[i]); fourier_pixels[i][1]=magnitude_pixels[i]*sin(phase_pixels[i]); #endif i++; } else for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]=magnitude_pixels[i]+I*phase_pixels[i]; #else fourier_pixels[i][0]=magnitude_pixels[i]; fourier_pixels[i][1]=phase_pixels[i]; #endif i++; } magnitude_info=RelinquishVirtualMemory(magnitude_info); phase_info=RelinquishVirtualMemory(phase_info); return(status); } static MagickBooleanType InverseFourierTransform(FourierInfo *fourier_info, fftw_complex *fourier_pixels,Image *image,ExceptionInfo *exception) { CacheView *image_view; const char *value; double *source_pixels; fftw_plan fftw_c2r_plan; MemoryInfo *source_info; register Quantum *q; register ssize_t i, x; ssize_t y; source_info=AcquireVirtualMemory((size_t) fourier_info->width, fourier_info->height*sizeof(*source_pixels)); if (source_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } source_pixels=(double *) GetVirtualMemoryBlob(source_info); value=GetImageArtifact(image,"fourier:normalize"); if (LocaleCompare(value,"inverse") == 0) { double gamma; /* Normalize inverse transform. */ i=0L; gamma=PerceptibleReciprocal((double) fourier_info->width* fourier_info->height); for (y=0L; y < (ssize_t) fourier_info->height; y++) for (x=0L; x < (ssize_t) fourier_info->center; x++) { #if defined(MAGICKCORE_HAVE_COMPLEX_H) fourier_pixels[i]*=gamma; #else fourier_pixels[i][0]*=gamma; fourier_pixels[i][1]*=gamma; #endif i++; } } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp critical (MagickCore_InverseFourierTransform) #endif fftw_c2r_plan=fftw_plan_dft_c2r_2d(fourier_info->width,fourier_info->height, fourier_pixels,source_pixels,FFTW_ESTIMATE); fftw_execute_dft_c2r(fftw_c2r_plan,fourier_pixels,source_pixels); fftw_destroy_plan(fftw_c2r_plan); i=0L; image_view=AcquireAuthenticCacheView(image,exception); for (y=0L; y < (ssize_t) fourier_info->height; y++) { if (y >= (ssize_t) image->rows) break; q=GetCacheViewAuthenticPixels(image_view,0L,y,fourier_info->width > image->columns ? image->columns : fourier_info->width,1UL,exception); if (q == (Quantum *) NULL) break; for (x=0L; x < (ssize_t) fourier_info->width; x++) { if (x < (ssize_t) image->columns) switch (fourier_info->channel) { case RedPixelChannel: default: { SetPixelRed(image,ClampToQuantum(QuantumRange*source_pixels[i]),q); break; } case GreenPixelChannel: { SetPixelGreen(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BluePixelChannel: { SetPixelBlue(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case BlackPixelChannel: { SetPixelBlack(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } case AlphaPixelChannel: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*source_pixels[i]), q); break; } } i++; q+=GetPixelChannels(image); } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) break; } image_view=DestroyCacheView(image_view); source_info=RelinquishVirtualMemory(source_info); return(MagickTrue); } static MagickBooleanType InverseFourierTransformChannel( const Image *magnitude_image,const Image *phase_image, const PixelChannel channel,const MagickBooleanType modulus, Image *fourier_image,ExceptionInfo *exception) { fftw_complex *inverse_pixels; FourierInfo fourier_info; MagickBooleanType status; MemoryInfo *inverse_info; fourier_info.width=magnitude_image->columns; fourier_info.height=magnitude_image->rows; if ((magnitude_image->columns != magnitude_image->rows) || ((magnitude_image->columns % 2) != 0) || ((magnitude_image->rows % 2) != 0)) { size_t extent=magnitude_image->columns < magnitude_image->rows ? magnitude_image->rows : magnitude_image->columns; fourier_info.width=(extent & 0x01) == 1 ? extent+1UL : extent; } fourier_info.height=fourier_info.width; fourier_info.center=(ssize_t) (fourier_info.width/2L)+1L; fourier_info.channel=channel; fourier_info.modulus=modulus; inverse_info=AcquireVirtualMemory((size_t) fourier_info.width, (fourier_info.height/2+1)*sizeof(*inverse_pixels)); if (inverse_info == (MemoryInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'", magnitude_image->filename); return(MagickFalse); } inverse_pixels=(fftw_complex *) GetVirtualMemoryBlob(inverse_info); status=InverseFourier(&fourier_info,magnitude_image,phase_image, inverse_pixels,exception); if (status != MagickFalse) status=InverseFourierTransform(&fourier_info,inverse_pixels,fourier_image, exception); inverse_info=RelinquishVirtualMemory(inverse_info); return(status); } #endif MagickExport Image *InverseFourierTransformImage(const Image *magnitude_image, const Image *phase_image,const MagickBooleanType modulus, ExceptionInfo *exception) { Image *fourier_image; assert(magnitude_image != (Image *) NULL); assert(magnitude_image->signature == MagickCoreSignature); if (magnitude_image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", magnitude_image->filename); if (phase_image == (Image *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ImageSequenceRequired","`%s'",magnitude_image->filename); return((Image *) NULL); } #if !defined(MAGICKCORE_FFTW_DELEGATE) fourier_image=(Image *) NULL; (void) modulus; (void) ThrowMagickException(exception,GetMagickModule(), MissingDelegateWarning,"DelegateLibrarySupportNotBuiltIn","`%s' (FFTW)", magnitude_image->filename); #else { fourier_image=CloneImage(magnitude_image,magnitude_image->columns, magnitude_image->rows,MagickTrue,exception); if (fourier_image != (Image *) NULL) { MagickBooleanType is_gray, status; status=MagickTrue; is_gray=IsImageGray(magnitude_image); if (is_gray != MagickFalse) is_gray=IsImageGray(phase_image); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel sections #endif { #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; if (is_gray != MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GrayPixelChannel,modulus,fourier_image,exception); else thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,RedPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,GreenPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (is_gray == MagickFalse) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BluePixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->colorspace == CMYKColorspace) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,BlackPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp section #endif { MagickBooleanType thread_status; thread_status=MagickTrue; if (magnitude_image->alpha_trait != UndefinedPixelTrait) thread_status=InverseFourierTransformChannel(magnitude_image, phase_image,AlphaPixelChannel,modulus,fourier_image,exception); if (thread_status == MagickFalse) status=thread_status; } } if (status == MagickFalse) fourier_image=DestroyImage(fourier_image); } fftw_cleanup(); } #endif return(fourier_image); }
oligo.c
/* * Copyright (c) 2014, Jason M. Wood <sandain@hotmail.com> * * 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 * 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. */ /** * Oligo categorizes sequence data based on oligonucleotide usage frequency. * * @file oligo.c * @mainpage Oligo * * Oligo categorizes sequence data based on oligonucleotide usage frequency. * * */ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <omp.h> #include "cluster.h" #include "fasta.h" #include "sequence.h" #include "tools.h" /** * @def DEBUG * The default debug level to use. Set to 1 to turn debugging output on. */ #define DEBUG 1 /** * @def DEFAULT_OLIGO_LENGTH * The default length oligo to use. This becomes very computationally * intensive with larger numbers. */ #define DEFAULT_OLIGO_LENGTH 4 /** * @def DEFAULT_FRAGMENT_LENGTH * The default length fragment to use. Smaller fragments retain less * fidelity. */ #define DEFAULT_FRAGMENT_LENGTH 5000 void generateOligonucleotides ( size_t oligoLength, char ** oligonucleotides, char * oligo, size_t index ); double * oligoFrequency ( Fasta * fasta, size_t numSequences, size_t numCombinations, size_t oligoLength, size_t fragmentLength ); /** * The main entry point for the Oligo program. * * @param argc The number of arguments passed to Oligo. * @param argv The array of arguments passed to Oligo. * @return The error level, 0 for no error. */ int main ( int argc, char * argv[] ) { size_t oligoLength; size_t fragmentLength; size_t numSequences; size_t numCombinations; size_t i; double * frequency; char ** ids; char * fastaFile; /* Grab the fasta file from the command line, or produce an error. */ if (argc < 2) { printf ("Error, fasta formatted sequence file not provided!\n"); return 1; } fastaFile = strdup (argv[1]); /* Grab the oligo length from the command line, or use the default value if not provided. */ if (argc >= 3) { oligoLength = atoi (argv[2]); } else { printf ( "Oligo length parameter not supplied, using default value of %d.\n", DEFAULT_OLIGO_LENGTH ); oligoLength = DEFAULT_OLIGO_LENGTH; } /* Grab the fragment length from the command line, or use the default value if not provided. */ if (argc >= 4) { fragmentLength = atoi (argv[3]); } else { printf ( "Fragment length parameter not supplied, using default value of %d.\n", DEFAULT_FRAGMENT_LENGTH ); fragmentLength = DEFAULT_FRAGMENT_LENGTH; } /* Load the fasta file. */ Fasta * fasta = newFasta (fastaFile); setMinimumLength (fasta, fragmentLength); numSequences = numberSequences (fasta); ids = getIdentifiers (fasta); // XXX Use the fasta object throughout. Requires the fasta object to be smarter. /* Determine the number of nucleotide combinations. */ numCombinations = power (4, oligoLength); /* Generate the oligonucleotide usage frequency matrix. */ printf ("Generating the oligo usage frequency matrix.\n"); frequency = oligoFrequency ( fasta, numSequences, numCombinations, oligoLength, fragmentLength ); /* Display the oligonucleotide usage frequency matrix if debug is on. */ if (DEBUG > 0) { size_t s, c; for (s = 0; s < numSequences; s ++) { printf ("%s: ", ids[s]); for (c = 0; c < numCombinations; c ++) { printf ("%.4f ", frequency[s + c * numCombinations]); } printf ("\n"); } } /* Run the Kmeans algorithm. */ printf ("Running the Kmeans algorithm.\n"); runKmeans (ids, numSequences, numCombinations, frequency, 10, DEBUG); /* Run the AIB algorithm. */ printf ("Running the AIB algorithm.\n"); runAIB (ids, numSequences, numCombinations, frequency, DEBUG); /* Free reserved memory. */ free (ids); freeFasta (fasta); free (frequency); return 0; } /** * Generate all of the nucleotide combinations for the given length using a * recursive method. * * @param oligoLength The length of oligonucleotides to generate. * @param oligonucleotides The final list of oligonucleotides generated. * @param oligo The oligo being generated via recursion. * @param index The index of oligonucleotides to store the resulting * oligonucleotide in. */ void generateOligonucleotides ( size_t oligoLength, char ** oligonucleotides, char * oligo, size_t index ) { char nucs[4] = {'a', 'c', 'g', 't'}; size_t i; size_t length = strlen(oligo); /* If oligo is not long enough, append the four nucleotides to oligo and recurse. If oligo is long enough, push the oligo onto the oligonucleotides array and return. */ if (oligoLength > length) { /* Make a local copy of the oligo. */ char buffer[oligoLength + 1]; strcpy (buffer, oligo); for (i = 0; i < 4; i ++) { buffer[length] = nucs[i]; buffer[length + 1] = '\0'; generateOligonucleotides ( oligoLength, oligonucleotides, buffer, index + i * pow(4, length) ); } } else { oligonucleotides[index] = strdup (oligo); } } /** * Calculate the oligo usage frequency for each sequence in a fasta file. * * @param fasta The fasta object. * @param numSequences The number of sequences. * @param oligoLength - The length of the oligos. * @param fragmentLength - The minimum length of sequences to use. * @param numCombinations - The number of possible oligo combinations. * @return The oligo frequency matrix generated. */ double * oligoFrequency ( Fasta * fasta, size_t numSequences, size_t numCombinations, size_t oligoLength, size_t fragmentLength ) { size_t i, j, k, l; size_t numSamples; size_t numOligos; size_t stepSize; double * frequency; char ** oligonucleotides; char * sample; char * oligo; int r; /* Initialize the random number generator. */ srand (time (NULL)); /* Initialize the frequency matrix. */ frequency = malloc (numSequences * numCombinations * sizeof (double)); for (i = 0; i < numSequences * numCombinations; i ++) { frequency[i] = 0.0; } /* Generate all of the nucleotide combinations. */ oligonucleotides = malloc (numCombinations * sizeof (char *)); generateOligonucleotides (oligoLength, oligonucleotides, "", 0); /* Calculate the number of oligonucleotides that will be tested. */ numOligos = floor (fragmentLength / oligoLength); /* #pragma omp parallel shared ( \ fasta, numSequences, oligoLength, numCombinations, frequency, \ oligonucleotides, numOligos \ ) #pragma omp for */ /* Count the number of times each oligonucleotide appears in a sequence. */ Sequence * seq; i = 0; while (nextSequence (fasta, &seq)) { size_t sequenceLength = getSequenceLength (seq); /* Take samples from the sequence, and average the nucleotide usage of the samples. */ numSamples = rint ( (1.5 * sequenceLength) / (1.0 * fragmentLength) ); stepSize = rint ( (sequenceLength - fragmentLength) / (1.0 * numSamples) ); for (j = 0; j < numSamples; j ++) { /* Take a random sample of a section of the sequence. */ r = rand() % stepSize + j * stepSize; sample = strndup (getSequence (seq) + r, fragmentLength); for (k = 0; k < numOligos; k ++) { /* Compare the oligo generated from the sequence with each possible oligo. */ oligo = strndup (sample + k * oligoLength, oligoLength); for (l = 0; l < numCombinations; l ++) { /* Increment the frequency counter if a match is found in the sequence. */ if (sequenceIsEqual (oligo, oligonucleotides[l])) { #pragma omp critical frequency[i * numCombinations + l] ++; } } free (oligo); } free (sample); } freeSequence (seq); i ++; } /* Normalize the frequency values based on the number of samples and length of the sequence. */ for (i = 0; i < numSequences; i ++) { for (j = 0; j < numCombinations; j ++) { frequency[i * numCombinations + j] /= numSamples * (fragmentLength - oligoLength + 1); } } /* Free the memory used by the oligonucleotides array. */ for (i = 0; i < numCombinations; i ++) { free (oligonucleotides[i]); } free (oligonucleotides); return frequency; }
omp_hello.c
#include <stdio.h> #include <omp.h> int main() { int nthreads, tid; #pragma omp parallel private(nthreads, tid) { tid = omp_get_thread_num(); printf("Hello, world! I am thread %d\n", tid); #pragma omp barrier if (tid == 0) { nthreads = omp_get_num_threads(); printf("Number of threads = %d\n", nthreads); } } return 0; }
closed_bug2.c
#include <stdio.h> #include "assert.h" #include <unistd.h> #define NZ 10 #define NA 9 #pragma omp declare target int colstat[NZ]; #pragma omp end declare target int main(){ colstat[0]=-1; #pragma omp target map(alloc:colstat[0:NZ]) { colstat[1] = 1111; } #pragma omp target map(alloc:colstat[:0]) { colstat[2] = 2222; } fprintf(stderr, "BEFORE colstat[0..2] %d %d %d \n", colstat[0], colstat[1], colstat[2]); #pragma omp target update from(colstat) fprintf(stderr, "AFTER colstat[0..2] %d %d %d \n", colstat[0], colstat[1], colstat[2]); if (colstat[1] == 1111 && colstat[2] == 2222) printf("Success\n"); else printf("Fail!\n"); return (colstat[1] == 1111 && colstat[2] == 2222) ? 0 : 1 ; }
critical-4.c
/* { dg-do compile } */ extern void bar(int); void foo1 (void) { #pragma omp critical #pragma omp critical(foo) #pragma omp critical(bar) bar (0); } void foo2 (void) { #pragma omp critical #pragma omp critical /* { dg-warning "with the same name" } */ bar (0); } void foo3 (void) { #pragma omp critical(foo) #pragma omp critical(foo) /* { dg-warning "with the same name" } */ bar (0); }
pixel.c
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % PPPP IIIII X X EEEEE L % % P P I X X E L % % PPPP I X EEE L % % P I X X E L % % P IIIII X X EEEEE LLLLL % % % % MagickCore Methods to Import/Export Pixels % % % % Software Design % % Cristy % % October 1998 % % % % % % Copyright @ 1999 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/property.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache-private.h" #include "MagickCore/color-private.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/draw.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/cache.h" #include "MagickCore/constitute.h" #include "MagickCore/delegate.h" #include "MagickCore/geometry.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/memory-private.h" #include "MagickCore/monitor.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/pixel-private.h" #include "MagickCore/quantum.h" #include "MagickCore/quantum-private.h" #include "MagickCore/resource_.h" #include "MagickCore/semaphore.h" #include "MagickCore/statistic.h" #include "MagickCore/stream.h" #include "MagickCore/string_.h" #include "MagickCore/transform.h" #include "MagickCore/utility.h" /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + A c q u i r e P i x e l C h a n n e l M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % AcquirePixelChannelMap() acquires a pixel component map. % % The format of the AcquirePixelChannelMap() method is: % % PixelChannelMap *AcquirePixelChannelMap(void) % */ MagickExport PixelChannelMap *AcquirePixelChannelMap(void) { PixelChannelMap *channel_map; ssize_t i; channel_map=(PixelChannelMap *) AcquireQuantumMemory(MaxPixelChannels, sizeof(*channel_map)); if (channel_map == (PixelChannelMap *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); (void) memset(channel_map,0,MaxPixelChannels*sizeof(*channel_map)); for (i=0; i < MaxPixelChannels; i++) channel_map[i].channel=(PixelChannel) i; return(channel_map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l C h a n n e l M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelChannelMap() clones a pixel component map. % % The format of the ClonePixelChannelMap() method is: % % PixelChannelMap *ClonePixelChannelMap(PixelChannelMap *channel_map) % % A description of each parameter follows: % % o channel_map: the pixel component map. % */ MagickExport PixelChannelMap *ClonePixelChannelMap(PixelChannelMap *channel_map) { PixelChannelMap *clone_map; assert(channel_map != (PixelChannelMap *) NULL); clone_map=AcquirePixelChannelMap(); if (clone_map == (PixelChannelMap *) NULL) return((PixelChannelMap *) NULL); (void) memcpy(clone_map,channel_map,MaxPixelChannels* sizeof(*channel_map)); return(clone_map); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C l o n e P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ClonePixelInfo() makes a duplicate of the given pixel info structure, or if % pixel info is NULL, a new one. % % The format of the ClonePixelInfo method is: % % PixelInfo *ClonePixelInfo(const PixelInfo *pixel) % % A description of each parameter follows: % % o pixel: the pixel info. % */ MagickExport PixelInfo *ClonePixelInfo(const PixelInfo *pixel) { PixelInfo *pixel_info; pixel_info=(PixelInfo *) AcquireMagickMemory(sizeof(*pixel_info)); if (pixel_info == (PixelInfo *) NULL) ThrowFatalException(ResourceLimitFatalError,"MemoryAllocationFailed"); *pixel_info=(*pixel); return(pixel_info); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + C o n f o r m P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ConformPixelInfo() ensures the pixel conforms with the colorspace and alpha % attribute of the image. % % The format of the ConformPixelInfo method is: % % void *ConformPixelInfo((Image *image,const PixelInfo *source, % PixelInfo *destination,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o source: the source pixel info. % % o destination: the destination pixel info. % % o exception: return any errors or warnings in this structure. % */ MagickExport void ConformPixelInfo(Image *image,const PixelInfo *source, PixelInfo *destination,ExceptionInfo *exception) { assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(destination != (const PixelInfo *) NULL); *destination=(*source); if (image->colorspace == CMYKColorspace) { if (IssRGBCompatibleColorspace(destination->colorspace) != MagickFalse) ConvertRGBToCMYK(destination); } else if (destination->colorspace == CMYKColorspace) { if (IssRGBCompatibleColorspace(image->colorspace) != MagickFalse) ConvertCMYKToRGB(destination); } if ((IsPixelInfoGray(&image->background_color) == MagickFalse) && (IsGrayColorspace(image->colorspace) != MagickFalse)) (void) TransformImageColorspace(image,sRGBColorspace,exception); if ((destination->alpha_trait != UndefinedPixelTrait) && (image->alpha_trait == UndefinedPixelTrait)) (void) SetImageAlpha(image,OpaqueAlpha,exception); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e P i x e l G a m m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodePixelGamma() applies the expansive power-law nonlinearity to the pixel. % % The format of the DecodePixelGamma method is: % % double DecodePixelGamma(const MagickRealType pixel) % % A description of each parameter follows: % % o pixel: the pixel. % */ static inline double DecodeGamma(const double x) { div_t quotient; double p, term[9]; int exponent; static const double coefficient[] = /* terms for x^(7/5), x=1.5 */ { 1.7917488588043277509, 0.82045614371976854984, 0.027694100686325412819, -0.00094244335181762134018, 0.000064355540911469709545, -5.7224404636060757485e-06, 5.8767669437311184313e-07, -6.6139920053589721168e-08, 7.9323242696227458163e-09 }; static const double powers_of_two[] = /* (2^x)^(7/5) */ { 1.0, 2.6390158215457883983, 6.9644045063689921093, 1.8379173679952558018e+01, 4.8502930128332728543e+01 }; /* Compute x^2.4 == x*x^(7/5) == pow(x,2.4). */ term[0]=1.0; term[1]=4.0*frexp(x,&exponent)-3.0; term[2]=2.0*term[1]*term[1]-term[0]; term[3]=2.0*term[1]*term[2]-term[1]; term[4]=2.0*term[1]*term[3]-term[2]; term[5]=2.0*term[1]*term[4]-term[3]; term[6]=2.0*term[1]*term[5]-term[4]; term[7]=2.0*term[1]*term[6]-term[5]; term[8]=2.0*term[1]*term[7]-term[6]; p=coefficient[0]*term[0]+coefficient[1]*term[1]+coefficient[2]*term[2]+ coefficient[3]*term[3]+coefficient[4]*term[4]+coefficient[5]*term[5]+ coefficient[6]*term[6]+coefficient[7]*term[7]+coefficient[8]*term[8]; quotient=div(exponent-1,5); if (quotient.rem < 0) { quotient.quot-=1; quotient.rem+=5; } return(x*ldexp(powers_of_two[quotient.rem]*p,7*quotient.quot)); } MagickExport MagickRealType DecodePixelGamma(const MagickRealType pixel) { if (pixel <= (0.0404482362771076*QuantumRange)) return(pixel/12.92f); return((MagickRealType) (QuantumRange*DecodeGamma((double) (QuantumScale* pixel+0.055)/1.055))); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + D e s t r o y P i x e l C h a n n e l M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DestroyPixelChannelMap() deallocates memory associated with the pixel % channel map. % % The format of the DestroyPixelChannelMap() method is: % % PixelChannelMap *DestroyPixelChannelMap(PixelChannelMap *channel_map) % % A description of each parameter follows: % % o channel_map: the pixel component map. % */ MagickExport PixelChannelMap *DestroyPixelChannelMap( PixelChannelMap *channel_map) { assert(channel_map != (PixelChannelMap *) NULL); channel_map=(PixelChannelMap *) RelinquishMagickMemory(channel_map); return((PixelChannelMap *) RelinquishMagickMemory(channel_map)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + E n c o d e P i x e l G a m m a % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodePixelGamma() cancels any nonlinearity in the pixel. % % The format of the EncodePixelGamma method is: % % MagickRealType EncodePixelGamma(const double MagickRealType) % % A description of each parameter follows: % % o pixel: the pixel. % */ static inline double EncodeGamma(const double x) { div_t quotient; double p, term[9]; int exponent; static const double coefficient[] = /* Chebychevi poly: x^(5/12), x=1.5 */ { 1.1758200232996901923, 0.16665763094889061230, -0.0083154894939042125035, 0.00075187976780420279038, -0.000083240178519391795367, 0.000010229209410070008679, -1.3400466409860246e-06, 1.8333422241635376682e-07, -2.5878596761348859722e-08 }; static const double powers_of_two[] = /* (2^N)^(5/12) */ { 1.0, 1.3348398541700343678, 1.7817974362806785482, 2.3784142300054420538, 3.1748021039363991669, 4.2378523774371812394, 5.6568542494923805819, 7.5509945014535482244, 1.0079368399158985525e1, 1.3454342644059433809e1, 1.7959392772949968275e1, 2.3972913230026907883e1 }; /* Compute x^(1/2.4) == x^(5/12) == pow(x,1.0/2.4). */ term[0]=1.0; term[1]=4.0*frexp(x,&exponent)-3.0; term[2]=2.0*term[1]*term[1]-term[0]; term[3]=2.0*term[1]*term[2]-term[1]; term[4]=2.0*term[1]*term[3]-term[2]; term[5]=2.0*term[1]*term[4]-term[3]; term[6]=2.0*term[1]*term[5]-term[4]; term[7]=2.0*term[1]*term[6]-term[5]; term[8]=2.0*term[1]*term[7]-term[6]; p=coefficient[0]*term[0]+coefficient[1]*term[1]+coefficient[2]*term[2]+ coefficient[3]*term[3]+coefficient[4]*term[4]+coefficient[5]*term[5]+ coefficient[6]*term[6]+coefficient[7]*term[7]+coefficient[8]*term[8]; quotient=div(exponent-1,12); if (quotient.rem < 0) { quotient.quot-=1; quotient.rem+=12; } return(ldexp(powers_of_two[quotient.rem]*p,5*quotient.quot)); } MagickExport MagickRealType EncodePixelGamma(const MagickRealType pixel) { if (pixel <= (0.0031306684425005883*QuantumRange)) return(12.92f*pixel); return((MagickRealType) QuantumRange*(1.055*EncodeGamma((double) QuantumScale* pixel)-0.055)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E x p o r t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ExportImagePixels() 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, Quantum, unsigned int, % unsigned long long, 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: % % ExportImagePixels(image,0,0,640,1,"RGB",CharPixel,pixels,exception); % % The format of the ExportImagePixels method is: % % MagickBooleanType ExportImagePixels(const Image *image,const ssize_t x, % const ssize_t y,const size_t width,const size_t height, % const char *map,const StorageType type,void *pixels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,width,height: 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 type: Define the data type of the pixels. Float and double types are % normalized to [0..1] otherwise [0..QuantumRange]. Choose from these % types: CharPixel (char *), DoublePixel (double *), FloatPixel (float *), % LongPixel (unsigned int *), LongLongPixel (unsigned long long *), % QuantumPixel (Quantum *), or ShortPixel (unsigned short *). % % 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. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ExportCharPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; ssize_t x; unsigned char *magick_restrict q; size_t length; ssize_t y; q=(unsigned char *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar((Quantum) 0); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(image,p))); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToChar(GetPixelRed(image,p)); *q++=ScaleQuantumToChar(GetPixelGreen(image,p)); *q++=ScaleQuantumToChar(GetPixelBlue(image,p)); *q++=ScaleQuantumToChar((Quantum) 0); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=ScaleQuantumToChar(GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=ScaleQuantumToChar(GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=ScaleQuantumToChar(GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=ScaleQuantumToChar(GetPixelAlpha(image,p)); break; } case OpacityQuantum: { *q=ScaleQuantumToChar(GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=ScaleQuantumToChar(GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=ScaleQuantumToChar(ClampToQuantum(GetPixelIntensity(image,p))); break; } default: break; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportDoublePixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; double *magick_restrict q; ssize_t x; size_t length; ssize_t y; q=(double *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelBlue(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelBlue(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelRed(image,p)); *q++=(double) (QuantumScale*GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelBlue(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelRed(image,p)); *q++=0.0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelIntensity(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelRed(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelRed(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelBlue(image,p)); *q++=(double) (QuantumScale*GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(double) (QuantumScale*GetPixelRed(image,p)); *q++=(double) (QuantumScale*GetPixelGreen(image,p)); *q++=(double) (QuantumScale*GetPixelBlue(image,p)); *q++=0.0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=(double) (QuantumScale*GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=(double) (QuantumScale*GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=(double) (QuantumScale*GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=(double) (QuantumScale*GetPixelAlpha(image,p)); break; } case OpacityQuantum: { *q=(double) (QuantumScale*GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=(double) (QuantumScale* GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=(double) (QuantumScale*GetPixelIntensity(image,p)); break; } default: *q=0; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportFloatPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; float *magick_restrict q; ssize_t x; size_t length; ssize_t y; q=(float *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelBlue(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelBlue(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelRed(image,p)); *q++=(float) (QuantumScale*GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelBlue(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelRed(image,p)); *q++=0.0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelIntensity(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelRed(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelRed(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelBlue(image,p)); *q++=(float) (QuantumScale*GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=(float) (QuantumScale*GetPixelRed(image,p)); *q++=(float) (QuantumScale*GetPixelGreen(image,p)); *q++=(float) (QuantumScale*GetPixelBlue(image,p)); *q++=0.0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=(float) (QuantumScale*GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=(float) (QuantumScale*GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=(float) (QuantumScale*GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=(float) (QuantumScale*((Quantum) (GetPixelAlpha(image,p)))); break; } case OpacityQuantum: { *q=(float) (QuantumScale*GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=(float) (QuantumScale* GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=(float) (QuantumScale*GetPixelIntensity(image,p)); break; } default: *q=0; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportLongPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; ssize_t x; unsigned int *magick_restrict q; size_t length; ssize_t y; q=(unsigned int *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLong(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelRed(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(ClampToQuantum(GetPixelIntensity(image,p))); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLong(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLong(GetPixelBlue(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=ScaleQuantumToLong(GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=ScaleQuantumToLong(GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=ScaleQuantumToLong(GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=ScaleQuantumToLong(GetPixelAlpha(image,p)); break; } case OpacityQuantum: { *q=ScaleQuantumToLong(GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=ScaleQuantumToLong(GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=ScaleQuantumToLong(ClampToQuantum(GetPixelIntensity(image,p))); break; } default: break; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportLongLongPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; ssize_t x; MagickSizeType *magick_restrict q; size_t length; ssize_t y; q=(MagickSizeType *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLongLong(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(ClampToQuantum( GetPixelIntensity(image,p))); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); *q++=ScaleQuantumToLongLong(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToLongLong(GetPixelRed(image,p)); *q++=ScaleQuantumToLongLong(GetPixelGreen(image,p)); *q++=ScaleQuantumToLongLong(GetPixelBlue(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=ScaleQuantumToLongLong(GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=ScaleQuantumToLongLong(GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=ScaleQuantumToLongLong(GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=ScaleQuantumToLongLong(GetPixelAlpha(image,p)); break; } case OpacityQuantum: { *q=ScaleQuantumToLongLong(GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=ScaleQuantumToLongLong(GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=ScaleQuantumToLongLong(ClampToQuantum( GetPixelIntensity(image,p))); break; } default: break; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportQuantumPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; q=(Quantum *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelBlue(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelRed(image,p); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelBlue(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelRed(image,p); *q++=(Quantum) (GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelBlue(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelRed(image,p); *q++=(Quantum) 0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ClampToQuantum(GetPixelIntensity(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelRed(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelBlue(image,p); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelRed(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelBlue(image,p); *q++=(Quantum) (GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=GetPixelRed(image,p); *q++=GetPixelGreen(image,p); *q++=GetPixelBlue(image,p); *q++=(Quantum) 0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=(Quantum) 0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=GetPixelRed(image,p); break; } case GreenQuantum: case MagentaQuantum: { *q=GetPixelGreen(image,p); break; } case BlueQuantum: case YellowQuantum: { *q=GetPixelBlue(image,p); break; } case AlphaQuantum: { *q=GetPixelAlpha(image,p); break; } case OpacityQuantum: { *q=GetPixelAlpha(image,p); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=GetPixelBlack(image,p); break; } case IndexQuantum: { *q=ClampToQuantum(GetPixelIntensity(image,p)); break; } default: { *q=(Quantum) 0; break; } } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ExportShortPixel(const Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; ssize_t x; unsigned short *magick_restrict q; size_t length; ssize_t y; q=(unsigned short *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelRed(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(ClampToQuantum(GetPixelIntensity(image,p))); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=ScaleQuantumToShort(GetPixelAlpha(image,p)); p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { *q++=ScaleQuantumToShort(GetPixelRed(image,p)); *q++=ScaleQuantumToShort(GetPixelGreen(image,p)); *q++=ScaleQuantumToShort(GetPixelBlue(image,p)); *q++=0; p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { p=GetVirtualPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (p == (const Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { *q=0; switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { *q=ScaleQuantumToShort(GetPixelRed(image,p)); break; } case GreenQuantum: case MagentaQuantum: { *q=ScaleQuantumToShort(GetPixelGreen(image,p)); break; } case BlueQuantum: case YellowQuantum: { *q=ScaleQuantumToShort(GetPixelBlue(image,p)); break; } case AlphaQuantum: { *q=ScaleQuantumToShort(GetPixelAlpha(image,p)); break; } case OpacityQuantum: { *q=ScaleQuantumToShort(GetPixelAlpha(image,p)); break; } case BlackQuantum: { if (image->colorspace == CMYKColorspace) *q=ScaleQuantumToShort(GetPixelBlack(image,p)); break; } case IndexQuantum: { *q=ScaleQuantumToShort(ClampToQuantum(GetPixelIntensity(image,p))); break; } default: break; } q++; } p+=GetPixelChannels(image); } } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } MagickExport MagickBooleanType ExportImagePixels(const Image *image, const ssize_t x,const ssize_t y,const size_t width,const size_t height, const char *map,const StorageType type,void *pixels,ExceptionInfo *exception) { MagickBooleanType status; QuantumType *quantum_map; RectangleInfo roi; ssize_t i; size_t length; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=strlen(map); quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map)); if (quantum_map == (QuantumType *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(MagickFalse); } for (i=0; i < (ssize_t) length; i++) { switch (map[i]) { case 'A': case 'a': { quantum_map[i]=AlphaQuantum; break; } case 'B': case 'b': { quantum_map[i]=BlueQuantum; break; } case 'C': case 'c': { quantum_map[i]=CyanQuantum; if (image->colorspace == CMYKColorspace) break; quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",map); return(MagickFalse); } case 'g': case 'G': { quantum_map[i]=GreenQuantum; break; } case 'I': case 'i': { quantum_map[i]=IndexQuantum; break; } case 'K': case 'k': { quantum_map[i]=BlackQuantum; if (image->colorspace == CMYKColorspace) break; quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",map); return(MagickFalse); } case 'M': case 'm': { quantum_map[i]=MagentaQuantum; if (image->colorspace == CMYKColorspace) break; quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",map); return(MagickFalse); } case 'o': case 'O': { quantum_map[i]=OpacityQuantum; break; } case 'P': case 'p': { quantum_map[i]=UndefinedQuantum; break; } case 'R': case 'r': { quantum_map[i]=RedQuantum; break; } case 'Y': case 'y': { quantum_map[i]=YellowQuantum; if (image->colorspace == CMYKColorspace) break; quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),ImageError, "ColorSeparatedImageRequired","`%s'",map); return(MagickFalse); } default: { quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnrecognizedPixelMap","`%s'",map); return(MagickFalse); } } } roi.width=width; roi.height=height; roi.x=x; roi.y=y; switch (type) { case CharPixel: { status=ExportCharPixel(image,&roi,map,quantum_map,pixels,exception); break; } case DoublePixel: { status=ExportDoublePixel(image,&roi,map,quantum_map,pixels,exception); break; } case FloatPixel: { status=ExportFloatPixel(image,&roi,map,quantum_map,pixels,exception); break; } case LongPixel: { status=ExportLongPixel(image,&roi,map,quantum_map,pixels,exception); break; } case LongLongPixel: { status=ExportLongLongPixel(image,&roi,map,quantum_map,pixels,exception); break; } case QuantumPixel: { status=ExportQuantumPixel(image,&roi,map,quantum_map,pixels,exception); break; } case ShortPixel: { status=ExportShortPixel(image,&roi,map,quantum_map,pixels,exception); break; } default: { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnrecognizedPixelMap","`%s'",map); status=MagickFalse; } } quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelInfo() initializes the PixelInfo structure. % % The format of the GetPixelInfo method is: % % GetPixelInfo(const Image *image,PixelInfo *pixel) % % A description of each parameter follows: % % o image: the image. (optional - may be NULL) % % o pixel: Specifies a pointer to a PixelInfo structure. % */ MagickExport void GetPixelInfo(const Image *image,PixelInfo *pixel) { (void) memset(pixel,0,sizeof(*pixel)); pixel->storage_class=DirectClass; pixel->colorspace=sRGBColorspace; pixel->depth=MAGICKCORE_QUANTUM_DEPTH; pixel->alpha_trait=UndefinedPixelTrait; pixel->alpha=(double) OpaqueAlpha; if (image == (const Image *) NULL) return; pixel->storage_class=image->storage_class; pixel->colorspace=image->colorspace; pixel->alpha_trait=image->alpha_trait; pixel->depth=image->depth; pixel->fuzz=image->fuzz; } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l I n d o I n t e n s i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelInfoIntensity() returns a single sample intensity value from the red, % green, and blue components of a pixel based on the selected method: % % Rec601Luma 0.298839R' + 0.586811G' + 0.114350B' % Rec601Luminance 0.298839R + 0.586811G + 0.114350B % Rec709Luma 0.212656R' + 0.715158G' + 0.072186B' % Rec709Luminance 0.212656R + 0.715158G + 0.072186B % Brightness max(R', G', B') % Lightness (min(R', G', B') + max(R', G', B')) / 2.0 % % MS (R^2 + G^2 + B^2) / 3.0 % RMS sqrt((R^2 + G^2 + B^2) / 3.0 % Average (R + G + B') / 3.0 % % The format of the GetPixelInfoIntensity method is: % % MagickRealType GetPixelInfoIntensity(const Image *image, % const Quantum *pixel) % % A description of each parameter follows: % % o image: the image. % % o pixel: Specifies a pointer to a Quantum structure. % */ MagickExport MagickRealType GetPixelInfoIntensity( const Image *magick_restrict image,const PixelInfo *magick_restrict pixel) { MagickRealType blue, green, red, intensity; PixelIntensityMethod method; method=Rec709LumaPixelIntensityMethod; if (image != (const Image *) NULL) method=image->intensity; red=pixel->red; green=pixel->green; blue=pixel->blue; switch (method) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+blue*blue)/ (3.0*QuantumRange)); break; } case Rec601LumaPixelIntensityMethod: { if (pixel->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if (pixel->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if (pixel->colorspace == RGBColorspace) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if (pixel->colorspace == sRGBColorspace) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+blue*blue)/ sqrt(3.0)); break; } } return(intensity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % G e t P i x e l I n t e n s i t y % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % GetPixelIntensity() returns a single sample intensity value from the red, % green, and blue components of a pixel based on the selected method: % % Rec601Luma 0.298839R' + 0.586811G' + 0.114350B' % Rec601Luminance 0.298839R + 0.586811G + 0.114350B % Rec709Luma 0.212656R' + 0.715158G' + 0.072186B' % Rec709Luminance 0.212656R + 0.715158G + 0.072186B % Brightness max(R', G', B') % Lightness (min(R', G', B') + max(R', G', B')) / 2.0 % % MS (R^2 + G^2 + B^2) / 3.0 % RMS sqrt((R^2 + G^2 + B^2) / 3.0 % Average (R + G + B') / 3.0 % % The format of the GetPixelIntensity method is: % % MagickRealType GetPixelIntensity(const Image *image, % const Quantum *pixel) % % A description of each parameter follows: % % o image: the image. % % o pixel: Specifies a pointer to a Quantum structure. % */ MagickExport MagickRealType GetPixelIntensity( const Image *magick_restrict image,const Quantum *magick_restrict pixel) { MagickRealType blue, green, red, intensity; red=(MagickRealType) GetPixelRed(image,pixel); if (image->number_channels == 1) return(red); green=(MagickRealType) GetPixelGreen(image,pixel); blue=(MagickRealType) GetPixelBlue(image,pixel); switch (image->intensity) { case AveragePixelIntensityMethod: { intensity=(red+green+blue)/3.0; break; } case BrightnessPixelIntensityMethod: { intensity=MagickMax(MagickMax(red,green),blue); break; } case LightnessPixelIntensityMethod: { intensity=(MagickMin(MagickMin(red,green),blue)+ MagickMax(MagickMax(red,green),blue))/2.0; break; } case MSPixelIntensityMethod: { intensity=(MagickRealType) (((double) red*red+green*green+blue*blue)/ (3.0*QuantumRange)); break; } case Rec601LumaPixelIntensityMethod: { if ((image->colorspace == RGBColorspace) || (image->colorspace == LinearGRAYColorspace)) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec601LuminancePixelIntensityMethod: { if ((image->colorspace == sRGBColorspace) || (image->colorspace == GRAYColorspace)) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.298839*red+0.586811*green+0.114350*blue; break; } case Rec709LumaPixelIntensityMethod: default: { if ((image->colorspace == RGBColorspace) || (image->colorspace == LinearGRAYColorspace)) { red=EncodePixelGamma(red); green=EncodePixelGamma(green); blue=EncodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case Rec709LuminancePixelIntensityMethod: { if ((image->colorspace == sRGBColorspace) || (image->colorspace == GRAYColorspace)) { red=DecodePixelGamma(red); green=DecodePixelGamma(green); blue=DecodePixelGamma(blue); } intensity=0.212656*red+0.715158*green+0.072186*blue; break; } case RMSPixelIntensityMethod: { intensity=(MagickRealType) (sqrt((double) red*red+green*green+blue*blue)/ sqrt(3.0)); break; } } return(intensity); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I m p o r t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ImportImagePixels() accepts pixel data and stores in the image at the % location you specify. The method returns MagickTrue on success otherwise % MagickFalse if an error is encountered. The pixel data can be either char, % Quantum, short int, unsigned int, unsigned long long, 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: % % ImportImagePixels(image,0,0,640,1,"RGB",CharPixel,pixels); % % The format of the ImportImagePixels method is: % % MagickBooleanType ImportImagePixels(Image *image,const ssize_t x, % const ssize_t y,const size_t width,const size_t height, % const char *map,const StorageType type,const void *pixels, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o x,y,width,height: 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 type: Define the data type of the pixels. Float and double types are % normalized to [0..1] otherwise [0..QuantumRange]. Choose from these % types: CharPixel (char *), DoublePixel (double *), FloatPixel (float *), % LongPixel (unsigned int *), LongLongPixel (unsigned long long *), % QuantumPixel (Quantum *), or ShortPixel (unsigned short *). % % 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. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType ImportCharPixel(Image *image,const RectangleInfo *roi, const char *magick_restrict map,const QuantumType *quantum_map, const void *pixels,ExceptionInfo *exception) { const unsigned char *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const unsigned char *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRO") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelRed(image,ScaleCharToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBO") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); SetPixelAlpha(image,ScaleCharToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleCharToQuantum(*p++),q); SetPixelGreen(image,ScaleCharToQuantum(*p++),q); SetPixelBlue(image,ScaleCharToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ScaleCharToQuantum(*p),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ScaleCharToQuantum(*p),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ScaleCharToQuantum(*p),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ScaleCharToQuantum(*p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ScaleCharToQuantum(*p),q); break; } case BlackQuantum: { SetPixelBlack(image,ScaleCharToQuantum(*p),q); break; } case IndexQuantum: { SetPixelGray(image,ScaleCharToQuantum(*p),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportDoublePixel(Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception) { const double *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const double *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case BlackQuantum: { SetPixelBlack(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case IndexQuantum: { SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportFloatPixel(Image *image,const RectangleInfo *roi, const char *magick_restrict map,const QuantumType *quantum_map, const void *pixels,ExceptionInfo *exception) { const float *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const float *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); p++; SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case BlackQuantum: { SetPixelBlack(image,ClampToQuantum(QuantumRange*(*p)),q); break; } case IndexQuantum: { SetPixelGray(image,ClampToQuantum(QuantumRange*(*p)),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportLongPixel(Image *image,const RectangleInfo *roi, const char *magick_restrict map,const QuantumType *quantum_map, const void *pixels,ExceptionInfo *exception) { const unsigned int *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const unsigned int *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongToQuantum(*p++),q); SetPixelAlpha(image,ScaleLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ScaleLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongToQuantum(*p++),q); SetPixelAlpha(image,ScaleLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ScaleLongToQuantum(*p),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ScaleLongToQuantum(*p),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ScaleLongToQuantum(*p),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ScaleLongToQuantum(*p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ScaleLongToQuantum(*p),q); break; } case BlackQuantum: { SetPixelBlack(image,ScaleLongToQuantum(*p),q); break; } case IndexQuantum: { SetPixelGray(image,ScaleLongToQuantum(*p),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportLongLongPixel(Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception) { const MagickSizeType *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const MagickSizeType *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); SetPixelAlpha(image,ScaleLongLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ScaleLongLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); SetPixelAlpha(image,ScaleLongLongToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleLongLongToQuantum(*p++),q); SetPixelGreen(image,ScaleLongLongToQuantum(*p++),q); SetPixelBlue(image,ScaleLongLongToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ScaleLongLongToQuantum(*p),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ScaleLongLongToQuantum(*p),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ScaleLongLongToQuantum(*p),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ScaleLongLongToQuantum(*p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ScaleLongLongToQuantum(*p),q); break; } case BlackQuantum: { SetPixelBlack(image,ScaleLongLongToQuantum(*p),q); break; } case IndexQuantum: { SetPixelGray(image,ScaleLongLongToQuantum(*p),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportQuantumPixel(Image *image, const RectangleInfo *roi,const char *magick_restrict map, const QuantumType *quantum_map,const void *pixels,ExceptionInfo *exception) { const Quantum *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const Quantum *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelRed(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelRed(image,*p++,q); SetPixelAlpha(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelRed(image,*p++,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); SetPixelAlpha(image,*p++,q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,*p++,q); SetPixelGreen(image,*p++,q); SetPixelBlue(image,*p++,q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,*p,q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,*p,q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,*p,q); break; } case AlphaQuantum: { SetPixelAlpha(image,*p,q); break; } case OpacityQuantum: { SetPixelAlpha(image,*p,q); break; } case BlackQuantum: { SetPixelBlack(image,*p,q); break; } case IndexQuantum: { SetPixelGray(image,*p,q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } static MagickBooleanType ImportShortPixel(Image *image,const RectangleInfo *roi, const char *magick_restrict map,const QuantumType *quantum_map, const void *pixels,ExceptionInfo *exception) { const unsigned short *magick_restrict p; Quantum *magick_restrict q; ssize_t x; size_t length; ssize_t y; p=(const unsigned short *) pixels; if (LocaleCompare(map,"BGR") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelRed(image,ScaleShortToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelRed(image,ScaleShortToQuantum(*p++),q); SetPixelAlpha(image,ScaleShortToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"BGRP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelBlue(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelRed(image,ScaleShortToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"I") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelGray(image,ScaleShortToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGB") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelBlue(image,ScaleShortToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBA") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelBlue(image,ScaleShortToQuantum(*p++),q); SetPixelAlpha(image,ScaleShortToQuantum(*p++),q); q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } if (LocaleCompare(map,"RGBP") == 0) { for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { SetPixelRed(image,ScaleShortToQuantum(*p++),q); SetPixelGreen(image,ScaleShortToQuantum(*p++),q); SetPixelBlue(image,ScaleShortToQuantum(*p++),q); p++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } length=strlen(map); for (y=0; y < (ssize_t) roi->height; y++) { q=GetAuthenticPixels(image,roi->x,roi->y+y,roi->width,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) roi->width; x++) { ssize_t i; for (i=0; i < (ssize_t) length; i++) { switch (quantum_map[i]) { case RedQuantum: case CyanQuantum: { SetPixelRed(image,ScaleShortToQuantum(*p),q); break; } case GreenQuantum: case MagentaQuantum: { SetPixelGreen(image,ScaleShortToQuantum(*p),q); break; } case BlueQuantum: case YellowQuantum: { SetPixelBlue(image,ScaleShortToQuantum(*p),q); break; } case AlphaQuantum: { SetPixelAlpha(image,ScaleShortToQuantum(*p),q); break; } case OpacityQuantum: { SetPixelAlpha(image,ScaleShortToQuantum(*p),q); break; } case BlackQuantum: { SetPixelBlack(image,ScaleShortToQuantum(*p),q); break; } case IndexQuantum: { SetPixelGray(image,ScaleShortToQuantum(*p),q); break; } default: break; } p++; } q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; } return(y < (ssize_t) roi->height ? MagickFalse : MagickTrue); } MagickExport MagickBooleanType ImportImagePixels(Image *image,const ssize_t x, const ssize_t y,const size_t width,const size_t height,const char *map, const StorageType type,const void *pixels,ExceptionInfo *exception) { MagickBooleanType status; QuantumType *quantum_map; RectangleInfo roi; ssize_t i; size_t length; /* Allocate image structure. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); length=strlen(map); quantum_map=(QuantumType *) AcquireQuantumMemory(length,sizeof(*quantum_map)); if (quantum_map == (QuantumType *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); for (i=0; i < (ssize_t) length; i++) { switch (map[i]) { case 'a': case 'A': { quantum_map[i]=AlphaQuantum; image->alpha_trait=BlendPixelTrait; break; } case 'B': case 'b': { quantum_map[i]=BlueQuantum; break; } case 'C': case 'c': { quantum_map[i]=CyanQuantum; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } case 'g': case 'G': { quantum_map[i]=GreenQuantum; break; } case 'K': case 'k': { quantum_map[i]=BlackQuantum; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } case 'I': case 'i': { quantum_map[i]=IndexQuantum; (void) SetImageColorspace(image,GRAYColorspace,exception); break; } case 'm': case 'M': { quantum_map[i]=MagentaQuantum; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } case 'O': case 'o': { quantum_map[i]=OpacityQuantum; image->alpha_trait=BlendPixelTrait; break; } case 'P': case 'p': { quantum_map[i]=UndefinedQuantum; break; } case 'R': case 'r': { quantum_map[i]=RedQuantum; break; } case 'Y': case 'y': { quantum_map[i]=YellowQuantum; (void) SetImageColorspace(image,CMYKColorspace,exception); break; } default: { quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnrecognizedPixelMap","`%s'",map); return(MagickFalse); } } } if (SetImageStorageClass(image,DirectClass,exception) == MagickFalse) return(MagickFalse); /* Transfer the pixels from the pixel data to the image. */ roi.width=width; roi.height=height; roi.x=x; roi.y=y; switch (type) { case CharPixel: { status=ImportCharPixel(image,&roi,map,quantum_map,pixels,exception); break; } case DoublePixel: { status=ImportDoublePixel(image,&roi,map,quantum_map,pixels,exception); break; } case FloatPixel: { status=ImportFloatPixel(image,&roi,map,quantum_map,pixels,exception); break; } case LongPixel: { status=ImportLongPixel(image,&roi,map,quantum_map,pixels,exception); break; } case LongLongPixel: { status=ImportLongLongPixel(image,&roi,map,quantum_map,pixels,exception); break; } case QuantumPixel: { status=ImportQuantumPixel(image,&roi,map,quantum_map,pixels,exception); break; } case ShortPixel: { status=ImportShortPixel(image,&roi,map,quantum_map,pixels,exception); break; } default: { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "UnrecognizedStorageType","`%d'",type); status=MagickFalse; } } quantum_map=(QuantumType *) RelinquishMagickMemory(quantum_map); return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I n i t i a l i z e P i x e l C h a n n e l M a p % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InitializePixelChannelMap() defines the standard pixel component map. % % The format of the InitializePixelChannelMap() method is: % % void InitializePixelChannelMap(Image *image) % % A description of each parameter follows: % % o image: the image. % */ MagickExport void InitializePixelChannelMap(Image *image) { PixelTrait trait; ssize_t n; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); (void) memset(image->channel_map,0,MaxPixelChannels* sizeof(*image->channel_map)); trait=UpdatePixelTrait; if (image->alpha_trait != UndefinedPixelTrait) trait=(PixelTrait) (trait | BlendPixelTrait); n=0; if ((image->colorspace == LinearGRAYColorspace) || (image->colorspace == GRAYColorspace)) { SetPixelChannelAttributes(image,BluePixelChannel,trait,n); SetPixelChannelAttributes(image,GreenPixelChannel,trait,n); SetPixelChannelAttributes(image,RedPixelChannel,trait,n++); } else { SetPixelChannelAttributes(image,RedPixelChannel,trait,n++); SetPixelChannelAttributes(image,GreenPixelChannel,trait,n++); SetPixelChannelAttributes(image,BluePixelChannel,trait,n++); } if (image->colorspace == CMYKColorspace) SetPixelChannelAttributes(image,BlackPixelChannel,trait,n++); if (image->alpha_trait != UndefinedPixelTrait) SetPixelChannelAttributes(image,AlphaPixelChannel,CopyPixelTrait,n++); if (image->storage_class == PseudoClass) SetPixelChannelAttributes(image,IndexPixelChannel,CopyPixelTrait,n++); if ((image->channels & ReadMaskChannel) != 0) SetPixelChannelAttributes(image,ReadMaskPixelChannel,CopyPixelTrait,n++); if ((image->channels & WriteMaskChannel) != 0) SetPixelChannelAttributes(image,WriteMaskPixelChannel,CopyPixelTrait,n++); if ((image->channels & CompositeMaskChannel) != 0) SetPixelChannelAttributes(image,CompositeMaskPixelChannel,CopyPixelTrait, n++); if (image->number_meta_channels > 0) { PixelChannel meta_channel; ssize_t i; meta_channel=StartMetaPixelChannel; for (i=0; i < (ssize_t) image->number_meta_channels; i++) { assert(meta_channel < MaxPixelChannels); SetPixelChannelAttributes(image,meta_channel,UpdatePixelTrait,n); meta_channel=(PixelChannel) (meta_channel+1); n++; } } assert(n < MaxPixelChannels); image->number_channels=(size_t) n; (void) SetPixelChannelMask(image,image->channel_mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t e P i x e l C h a n n e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolatePixelChannel() applies a pixel interpolation method between a % floating point coordinate and the pixels surrounding that coordinate. No % pixel area resampling, or scaling of the result is performed. % % Interpolation is restricted to just the specified channel. % % The format of the InterpolatePixelChannel method is: % % MagickBooleanType InterpolatePixelChannel( % const Image *magick_restrict image,const CacheView *image_view, % const PixelChannel channel,const PixelInterpolateMethod method, % const double x,const double y,double *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o image_view: the image view. % % o channel: the pixel channel to interpolate. % % o method: the pixel color interpolation method. % % o x,y: A double representing the current (x,y) position of the pixel. % % o pixel: return the interpolated pixel here. % % o exception: return any errors or warnings in this structure. % */ static inline void CatromWeights(const double x,double (*weights)[4]) { double alpha, beta, gamma; /* Nicolas Robidoux' 10 flops (4* + 5- + 1+) refactoring of the computation of the standard four 1D Catmull-Rom weights. The sampling location is assumed between the second and third input pixel locations, and x is the position relative to the second input pixel location. Formulas originally derived for the VIPS (Virtual Image Processing System) library. */ alpha=(double) 1.0-x; beta=(double) (-0.5)*x*alpha; (*weights)[0]=alpha*beta; (*weights)[3]=x*beta; /* The following computation of the inner weights from the outer ones work for all Keys cubics. */ gamma=(*weights)[3]-(*weights)[0]; (*weights)[1]=alpha-(*weights)[0]+gamma; (*weights)[2]=x-(*weights)[3]-gamma; } static inline void SplineWeights(const double x,double (*weights)[4]) { double alpha, beta; /* Nicolas Robidoux' 12 flops (6* + 5- + 1+) refactoring of the computation of the standard four 1D cubic B-spline smoothing weights. The sampling location is assumed between the second and third input pixel locations, and x is the position relative to the second input pixel location. */ alpha=(double) 1.0-x; (*weights)[3]=(double) (1.0/6.0)*x*x*x; (*weights)[0]=(double) (1.0/6.0)*alpha*alpha*alpha; beta=(*weights)[3]-(*weights)[0]; (*weights)[1]=alpha-(*weights)[0]+beta; (*weights)[2]=x-(*weights)[3]-beta; } static inline double MeshInterpolate(const PointInfo *delta,const double p, const double x,const double y) { return(delta->x*x+delta->y*y+(1.0-delta->x-delta->y)*p); } MagickExport MagickBooleanType InterpolatePixelChannel( const Image *magick_restrict image,const CacheView_ *image_view, const PixelChannel channel,const PixelInterpolateMethod method, const double x,const double y,double *pixel,ExceptionInfo *exception) { double alpha[16], gamma, pixels[16]; MagickBooleanType status; PixelInterpolateMethod interpolate; PixelTrait traits; const Quantum *magick_restrict p; ssize_t i; ssize_t x_offset, y_offset; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image_view != (CacheView *) NULL); status=MagickTrue; *pixel=0.0; traits=GetPixelChannelTraits(image,channel); x_offset=CastDoubleToLong(floor(x)); y_offset=CastDoubleToLong(floor(y)); interpolate=method; if (interpolate == UndefinedInterpolatePixel) interpolate=image->interpolate; switch (interpolate) { case AverageInterpolatePixel: /* nearest 4 neighbours */ case Average9InterpolatePixel: /* nearest 9 neighbours */ case Average16InterpolatePixel: /* nearest 16 neighbours */ { ssize_t count; count=2; /* size of the area to average - default nearest 4 */ if (interpolate == Average9InterpolatePixel) { count=3; x_offset=CastDoubleToLong(floor(x+0.5)-1.0); y_offset=CastDoubleToLong(floor(y+0.5)-1.0); } else if (interpolate == Average16InterpolatePixel) { count=4; x_offset--; y_offset--; } p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,(size_t) count, (size_t) count,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } count*=count; /* Number of pixels to average */ if ((traits & BlendPixelTrait) == 0) for (i=0; i < (ssize_t) count; i++) { alpha[i]=1.0; pixels[i]=(double) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < (ssize_t) count; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } for (i=0; i < (ssize_t) count; i++) { gamma=PerceptibleReciprocal(alpha[i])/count; *pixel+=gamma*pixels[i]; } break; } case BilinearInterpolatePixel: default: { PointInfo delta, epsilon; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((traits & BlendPixelTrait) == 0) for (i=0; i < 4; i++) { alpha[i]=1.0; pixels[i]=(double) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < 4; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } delta.x=x-x_offset; delta.y=y-y_offset; epsilon.x=1.0-delta.x; epsilon.y=1.0-delta.y; gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y* (epsilon.x*alpha[2]+delta.x*alpha[3]))); gamma=PerceptibleReciprocal(gamma); *pixel=gamma*(epsilon.y*(epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y* (epsilon.x*pixels[2]+delta.x*pixels[3])); break; } case BlendInterpolatePixel: { p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((traits & BlendPixelTrait) == 0) for (i=0; i < 4; i++) { alpha[i]=1.0; pixels[i]=(MagickRealType) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < 4; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } gamma=1.0; /* number of pixels blended together (its variable) */ for (i=0; i <= 1L; i++) { if ((y-y_offset) >= 0.75) { alpha[i]=alpha[i+2]; /* take right pixels */ pixels[i]=pixels[i+2]; } else if ((y-y_offset) > 0.25) { gamma=2.0; /* blend both pixels in row */ alpha[i]+=alpha[i+2]; /* add up alpha weights */ pixels[i]+=pixels[i+2]; } } if ((x-x_offset) >= 0.75) { alpha[0]=alpha[1]; /* take bottom row blend */ pixels[0]=pixels[1]; } else if ((x-x_offset) > 0.25) { gamma*=2.0; /* blend both rows */ alpha[0]+=alpha[1]; /* add up alpha weights */ pixels[0]+=pixels[1]; } if (channel != AlphaPixelChannel) gamma=PerceptibleReciprocal(alpha[0]); /* (color) 1/alpha_weights */ else gamma=PerceptibleReciprocal(gamma); /* (alpha) 1/number_of_pixels */ *pixel=gamma*pixels[0]; break; } case CatromInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((traits & BlendPixelTrait) == 0) for (i=0; i < 16; i++) { alpha[i]=1.0; pixels[i]=(double) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < 16; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } CatromWeights((double) (x-x_offset),&cx); CatromWeights((double) (y-y_offset),&cy); gamma=(channel == AlphaPixelChannel ? (double) 1.0 : PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]* alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]* alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]* alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+ cx[2]*alpha[14]+cx[3]*alpha[15]))); *pixel=gamma*(cy[0]*(cx[0]*pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+ cx[3]*pixels[3])+cy[1]*(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]* pixels[6]+cx[3]*pixels[7])+cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+ cx[2]*pixels[10]+cx[3]*pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]* pixels[13]+cx[2]*pixels[14]+cx[3]*pixels[15])); break; } case IntegerInterpolatePixel: { p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } *pixel=(double) GetPixelChannel(image,channel,p); break; } case NearestInterpolatePixel: { x_offset=CastDoubleToLong(floor(x+0.5)); y_offset=CastDoubleToLong(floor(y+0.5)); p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } *pixel=(double) GetPixelChannel(image,channel,p); break; } case MeshInterpolatePixel: { PointInfo delta, luminance; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((traits & BlendPixelTrait) == 0) for (i=0; i < 4; i++) { alpha[i]=1.0; pixels[i]=(double) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < 4; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } delta.x=x-x_offset; delta.y=y-y_offset; luminance.x=GetPixelLuma(image,p)-(double) GetPixelLuma(image,p+3*GetPixelChannels(image)); luminance.y=GetPixelLuma(image,p+GetPixelChannels(image))-(double) GetPixelLuma(image,p+2*GetPixelChannels(image)); if (fabs((double) luminance.x) < fabs((double) luminance.y)) { /* Diagonal 0-3 NW-SE. */ if (delta.x <= delta.y) { /* Bottom-left triangle (pixel: 2, diagonal: 0-3). */ delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]); gamma=PerceptibleReciprocal(gamma); *pixel=gamma*MeshInterpolate(&delta,pixels[2],pixels[3], pixels[0]); } else { /* Top-right triangle (pixel: 1, diagonal: 0-3). */ delta.x=1.0-delta.x; gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]); gamma=PerceptibleReciprocal(gamma); *pixel=gamma*MeshInterpolate(&delta,pixels[1],pixels[0], pixels[3]); } } else { /* Diagonal 1-2 NE-SW. */ if (delta.x <= (1.0-delta.y)) { /* Top-left triangle (pixel: 0, diagonal: 1-2). */ gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]); gamma=PerceptibleReciprocal(gamma); *pixel=gamma*MeshInterpolate(&delta,pixels[0],pixels[1], pixels[2]); } else { /* Bottom-right triangle (pixel: 3, diagonal: 1-2). */ delta.x=1.0-delta.x; delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]); gamma=PerceptibleReciprocal(gamma); *pixel=gamma*MeshInterpolate(&delta,pixels[3],pixels[2], pixels[1]); } } break; } case SplineInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } if ((traits & BlendPixelTrait) == 0) for (i=0; i < 16; i++) { alpha[i]=1.0; pixels[i]=(double) p[i*GetPixelChannels(image)+channel]; } else for (i=0; i < 16; i++) { alpha[i]=QuantumScale*GetPixelAlpha(image,p+i* GetPixelChannels(image)); pixels[i]=alpha[i]*p[i*GetPixelChannels(image)+channel]; } SplineWeights((double) (x-x_offset),&cx); SplineWeights((double) (y-y_offset),&cy); gamma=(channel == AlphaPixelChannel ? (double) 1.0 : PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]* alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]* alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]* alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+ cx[2]*alpha[14]+cx[3]*alpha[15]))); *pixel=gamma*(cy[0]*(cx[0]*pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+ cx[3]*pixels[3])+cy[1]*(cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]* pixels[6]+cx[3]*pixels[7])+cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+ cx[2]*pixels[10]+cx[3]*pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]* pixels[13]+cx[2]*pixels[14]+cx[3]*pixels[15])); break; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t e P i x e l C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolatePixelChannels() applies a pixel interpolation method between a % floating point coordinate and the pixels surrounding that coordinate. No % pixel area resampling, or scaling of the result is performed. % % Interpolation is restricted to just the current channel setting of the % destination image into which the color is to be stored % % The format of the InterpolatePixelChannels method is: % % MagickBooleanType InterpolatePixelChannels( % const Image *magick_restrict source,const CacheView *source_view, % const Image *magick_restrict destination, % const PixelInterpolateMethod method,const double x,const double y, % Quantum *pixel,ExceptionInfo *exception) % % A description of each parameter follows: % % o source: the source. % % o source_view: the source view. % % o destination: the destination image, for the interpolated color % % o method: the pixel color interpolation method. % % o x,y: A double representing the current (x,y) position of the pixel. % % o pixel: return the interpolated pixel here. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType InterpolatePixelChannels( const Image *magick_restrict source,const CacheView_ *source_view, const Image *magick_restrict destination,const PixelInterpolateMethod method, const double x,const double y,Quantum *pixel,ExceptionInfo *exception) { MagickBooleanType status; double alpha[16], gamma, pixels[16]; const Quantum *magick_restrict p; ssize_t i; ssize_t x_offset, y_offset; PixelInterpolateMethod interpolate; assert(source != (Image *) NULL); assert(source->signature == MagickCoreSignature); assert(source_view != (CacheView *) NULL); status=MagickTrue; x_offset=CastDoubleToLong(floor(x)); y_offset=CastDoubleToLong(floor(y)); interpolate=method; if (interpolate == UndefinedInterpolatePixel) interpolate=source->interpolate; switch (interpolate) { case AverageInterpolatePixel: /* nearest 4 neighbours */ case Average9InterpolatePixel: /* nearest 9 neighbours */ case Average16InterpolatePixel: /* nearest 16 neighbours */ { ssize_t count; count=2; /* size of the area to average - default nearest 4 */ if (interpolate == Average9InterpolatePixel) { count=3; x_offset=CastDoubleToLong(floor(x+0.5)-1.0); y_offset=CastDoubleToLong(floor(y+0.5)-1.0); } else if (interpolate == Average16InterpolatePixel) { count=4; x_offset--; y_offset--; } p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,(size_t) count, (size_t) count,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } count*=count; /* Number of pixels to average */ for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { double sum; ssize_t j; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; for (j=0; j < (ssize_t) count; j++) pixels[j]=(double) p[j*GetPixelChannels(source)+i]; sum=0.0; if ((traits & BlendPixelTrait) == 0) { for (j=0; j < (ssize_t) count; j++) sum+=pixels[j]; sum/=count; SetPixelChannel(destination,channel,ClampToQuantum(sum),pixel); continue; } for (j=0; j < (ssize_t) count; j++) { alpha[j]=QuantumScale*GetPixelAlpha(source,p+j* GetPixelChannels(source)); pixels[j]*=alpha[j]; gamma=PerceptibleReciprocal(alpha[j]); sum+=gamma*pixels[j]; } sum/=count; SetPixelChannel(destination,channel,ClampToQuantum(sum),pixel); } break; } case BilinearInterpolatePixel: default: { p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PointInfo delta, epsilon; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; delta.x=x-x_offset; delta.y=y-y_offset; epsilon.x=1.0-delta.x; epsilon.y=1.0-delta.y; pixels[0]=(double) p[i]; pixels[1]=(double) p[GetPixelChannels(source)+i]; pixels[2]=(double) p[2*GetPixelChannels(source)+i]; pixels[3]=(double) p[3*GetPixelChannels(source)+i]; if ((traits & BlendPixelTrait) == 0) { gamma=((epsilon.y*(epsilon.x+delta.x)+delta.y*(epsilon.x+delta.x))); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma*(epsilon.y* (epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y*(epsilon.x* pixels[2]+delta.x*pixels[3]))),pixel); continue; } alpha[0]=QuantumScale*GetPixelAlpha(source,p); alpha[1]=QuantumScale*GetPixelAlpha(source,p+GetPixelChannels(source)); alpha[2]=QuantumScale*GetPixelAlpha(source,p+2* GetPixelChannels(source)); alpha[3]=QuantumScale*GetPixelAlpha(source,p+3* GetPixelChannels(source)); pixels[0]*=alpha[0]; pixels[1]*=alpha[1]; pixels[2]*=alpha[2]; pixels[3]*=alpha[3]; gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y* (epsilon.x*alpha[2]+delta.x*alpha[3]))); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma*(epsilon.y* (epsilon.x*pixels[0]+delta.x*pixels[1])+delta.y*(epsilon.x*pixels[2]+ delta.x*pixels[3]))),pixel); } break; } case BlendInterpolatePixel: { p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { ssize_t j; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; if (source->alpha_trait != BlendPixelTrait) for (j=0; j < 4; j++) { alpha[j]=1.0; pixels[j]=(double) p[j*GetPixelChannels(source)+i]; } else for (j=0; j < 4; j++) { alpha[j]=QuantumScale*GetPixelAlpha(source,p+j* GetPixelChannels(source)); pixels[j]=(double) p[j*GetPixelChannels(source)+i]; if (channel != AlphaPixelChannel) pixels[j]*=alpha[j]; } gamma=1.0; /* number of pixels blended together (its variable) */ for (j=0; j <= 1L; j++) { if ((y-y_offset) >= 0.75) { alpha[j]=alpha[j+2]; /* take right pixels */ pixels[j]=pixels[j+2]; } else if ((y-y_offset) > 0.25) { gamma=2.0; /* blend both pixels in row */ alpha[j]+=alpha[j+2]; /* add up alpha weights */ pixels[j]+=pixels[j+2]; } } if ((x-x_offset) >= 0.75) { alpha[0]=alpha[1]; /* take bottom row blend */ pixels[0]=pixels[1]; } else if ((x-x_offset) > 0.25) { gamma*=2.0; /* blend both rows */ alpha[0]+=alpha[1]; /* add up alpha weights */ pixels[0]+=pixels[1]; } if (channel != AlphaPixelChannel) gamma=PerceptibleReciprocal(alpha[0]); /* (color) 1/alpha_weights */ else gamma=PerceptibleReciprocal(gamma); /* (alpha) 1/number_of_pixels */ SetPixelChannel(destination,channel,ClampToQuantum(gamma*pixels[0]), pixel); } break; } case CatromInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(source_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { ssize_t j; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) for (j=0; j < 16; j++) { alpha[j]=1.0; pixels[j]=(double) p[j*GetPixelChannels(source)+i]; } else for (j=0; j < 16; j++) { alpha[j]=QuantumScale*GetPixelAlpha(source,p+j* GetPixelChannels(source)); pixels[j]=alpha[j]*p[j*GetPixelChannels(source)+i]; } CatromWeights((double) (x-x_offset),&cx); CatromWeights((double) (y-y_offset),&cy); gamma=((traits & BlendPixelTrait) ? (double) (1.0) : PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]* alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]* alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]* alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+ cx[2]*alpha[14]+cx[3]*alpha[15]))); SetPixelChannel(destination,channel,ClampToQuantum(gamma*(cy[0]*(cx[0]* pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+cx[3]*pixels[3])+cy[1]* (cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*pixels[6]+cx[3]*pixels[7])+ cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+cx[2]*pixels[10]+cx[3]* pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*pixels[13]+cx[2]* pixels[14]+cx[3]*pixels[15]))),pixel); } break; } case IntegerInterpolatePixel: { p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; SetPixelChannel(destination,channel,p[i],pixel); } break; } case NearestInterpolatePixel: { x_offset=CastDoubleToLong(floor(x+0.5)); y_offset=CastDoubleToLong(floor(y+0.5)); p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; SetPixelChannel(destination,channel,p[i],pixel); } break; } case MeshInterpolatePixel: { p=GetCacheViewVirtualPixels(source_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { PointInfo delta, luminance; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; pixels[0]=(double) p[i]; pixels[1]=(double) p[GetPixelChannels(source)+i]; pixels[2]=(double) p[2*GetPixelChannels(source)+i]; pixels[3]=(double) p[3*GetPixelChannels(source)+i]; if ((traits & BlendPixelTrait) == 0) { alpha[0]=1.0; alpha[1]=1.0; alpha[2]=1.0; alpha[3]=1.0; } else { alpha[0]=QuantumScale*GetPixelAlpha(source,p); alpha[1]=QuantumScale*GetPixelAlpha(source,p+ GetPixelChannels(source)); alpha[2]=QuantumScale*GetPixelAlpha(source,p+2* GetPixelChannels(source)); alpha[3]=QuantumScale*GetPixelAlpha(source,p+3* GetPixelChannels(source)); } delta.x=x-x_offset; delta.y=y-y_offset; luminance.x=fabs((double) (GetPixelLuma(source,p)- GetPixelLuma(source,p+3*GetPixelChannels(source)))); luminance.y=fabs((double) (GetPixelLuma(source,p+ GetPixelChannels(source))-GetPixelLuma(source,p+2* GetPixelChannels(source)))); if (luminance.x < luminance.y) { /* Diagonal 0-3 NW-SE. */ if (delta.x <= delta.y) { /* Bottom-left triangle (pixel: 2, diagonal: 0-3). */ delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma* MeshInterpolate(&delta,pixels[2],pixels[3],pixels[0])),pixel); } else { /* Top-right triangle (pixel: 1, diagonal: 0-3). */ delta.x=1.0-delta.x; gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma* MeshInterpolate(&delta,pixels[1],pixels[0],pixels[3])),pixel); } } else { /* Diagonal 1-2 NE-SW. */ if (delta.x <= (1.0-delta.y)) { /* Top-left triangle (pixel: 0, diagonal: 1-2). */ gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma* MeshInterpolate(&delta,pixels[0],pixels[1],pixels[2])),pixel); } else { /* Bottom-right triangle (pixel: 3, diagonal: 1-2). */ delta.x=1.0-delta.x; delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]); gamma=PerceptibleReciprocal(gamma); SetPixelChannel(destination,channel,ClampToQuantum(gamma* MeshInterpolate(&delta,pixels[3],pixels[2],pixels[1])),pixel); } } } break; } case SplineInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(source_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < (ssize_t) GetPixelChannels(source); i++) { ssize_t j; PixelChannel channel = GetPixelChannelChannel(source,i); PixelTrait traits = GetPixelChannelTraits(source,channel); PixelTrait destination_traits=GetPixelChannelTraits(destination, channel); if ((traits == UndefinedPixelTrait) || (destination_traits == UndefinedPixelTrait)) continue; if ((traits & BlendPixelTrait) == 0) for (j=0; j < 16; j++) { alpha[j]=1.0; pixels[j]=(double) p[j*GetPixelChannels(source)+i]; } else for (j=0; j < 16; j++) { alpha[j]=QuantumScale*GetPixelAlpha(source,p+j* GetPixelChannels(source)); pixels[j]=alpha[j]*p[j*GetPixelChannels(source)+i]; } SplineWeights((double) (x-x_offset),&cx); SplineWeights((double) (y-y_offset),&cy); gamma=((traits & BlendPixelTrait) ? (double) (1.0) : PerceptibleReciprocal(cy[0]*(cx[0]*alpha[0]+cx[1]*alpha[1]+cx[2]* alpha[2]+cx[3]*alpha[3])+cy[1]*(cx[0]*alpha[4]+cx[1]*alpha[5]+cx[2]* alpha[6]+cx[3]*alpha[7])+cy[2]*(cx[0]*alpha[8]+cx[1]*alpha[9]+cx[2]* alpha[10]+cx[3]*alpha[11])+cy[3]*(cx[0]*alpha[12]+cx[1]*alpha[13]+ cx[2]*alpha[14]+cx[3]*alpha[15]))); SetPixelChannel(destination,channel,ClampToQuantum(gamma*(cy[0]*(cx[0]* pixels[0]+cx[1]*pixels[1]+cx[2]*pixels[2]+cx[3]*pixels[3])+cy[1]* (cx[0]*pixels[4]+cx[1]*pixels[5]+cx[2]*pixels[6]+cx[3]*pixels[7])+ cy[2]*(cx[0]*pixels[8]+cx[1]*pixels[9]+cx[2]*pixels[10]+cx[3]* pixels[11])+cy[3]*(cx[0]*pixels[12]+cx[1]*pixels[13]+cx[2]* pixels[14]+cx[3]*pixels[15]))),pixel); } break; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I n t e r p o l a t e P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % InterpolatePixelInfo() applies a pixel interpolation method between a % floating point coordinate and the pixels surrounding that coordinate. No % pixel area resampling, or scaling of the result is performed. % % Interpolation is restricted to just RGBKA channels. % % The format of the InterpolatePixelInfo method is: % % MagickBooleanType InterpolatePixelInfo(const Image *image, % const CacheView *image_view,const PixelInterpolateMethod method, % const double x,const double y,PixelInfo *pixel, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o image_view: the image view. % % o method: the pixel color interpolation method. % % o x,y: A double representing the current (x,y) position of the pixel. % % o pixel: return the interpolated pixel here. % % o exception: return any errors or warnings in this structure. % */ static inline void AlphaBlendPixelInfo(const Image *image, const Quantum *pixel,PixelInfo *pixel_info,double *alpha) { if (image->alpha_trait == UndefinedPixelTrait) { *alpha=1.0; pixel_info->red=(double) GetPixelRed(image,pixel); pixel_info->green=(double) GetPixelGreen(image,pixel); pixel_info->blue=(double) GetPixelBlue(image,pixel); pixel_info->black=0.0; if (image->colorspace == CMYKColorspace) pixel_info->black=(double) GetPixelBlack(image,pixel); pixel_info->alpha=(double) GetPixelAlpha(image,pixel); return; } *alpha=QuantumScale*GetPixelAlpha(image,pixel); pixel_info->red=(*alpha*GetPixelRed(image,pixel)); pixel_info->green=(*alpha*GetPixelGreen(image,pixel)); pixel_info->blue=(*alpha*GetPixelBlue(image,pixel)); pixel_info->black=0.0; if (image->colorspace == CMYKColorspace) pixel_info->black=(*alpha*GetPixelBlack(image,pixel)); pixel_info->alpha=(double) GetPixelAlpha(image,pixel); } MagickExport MagickBooleanType InterpolatePixelInfo(const Image *image, const CacheView_ *image_view,const PixelInterpolateMethod method, const double x,const double y,PixelInfo *pixel,ExceptionInfo *exception) { MagickBooleanType status; double alpha[16], gamma; PixelInfo pixels[16]; const Quantum *p; ssize_t i; ssize_t x_offset, y_offset; PixelInterpolateMethod interpolate; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(image_view != (CacheView *) NULL); status=MagickTrue; x_offset=CastDoubleToLong(floor(x)); y_offset=CastDoubleToLong(floor(y)); interpolate=method; if (interpolate == UndefinedInterpolatePixel) interpolate=image->interpolate; GetPixelInfoPixel(image,(const Quantum *) NULL,pixel); (void) memset(&pixels,0,sizeof(pixels)); switch (interpolate) { case AverageInterpolatePixel: /* nearest 4 neighbours */ case Average9InterpolatePixel: /* nearest 9 neighbours */ case Average16InterpolatePixel: /* nearest 16 neighbours */ { ssize_t count; count=2; /* size of the area to average - default nearest 4 */ if (interpolate == Average9InterpolatePixel) { count=3; x_offset=CastDoubleToLong(floor(x+0.5)-1.0); y_offset=CastDoubleToLong(floor(y+0.5)-1.0); } else if (interpolate == Average16InterpolatePixel) { count=4; x_offset--; y_offset--; } p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,(size_t) count, (size_t) count,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } count*=count; /* number of pixels - square of size */ for (i=0; i < (ssize_t) count; i++) { AlphaBlendPixelInfo(image,p,pixels,alpha); gamma=PerceptibleReciprocal(alpha[0]); pixel->red+=gamma*pixels[0].red; pixel->green+=gamma*pixels[0].green; pixel->blue+=gamma*pixels[0].blue; pixel->black+=gamma*pixels[0].black; pixel->alpha+=pixels[0].alpha; p += GetPixelChannels(image); } gamma=1.0/count; /* average weighting of each pixel in area */ pixel->red*=gamma; pixel->green*=gamma; pixel->blue*=gamma; pixel->black*=gamma; pixel->alpha*=gamma; break; } case BackgroundInterpolatePixel: { *pixel=image->background_color; /* Copy PixelInfo Structure */ break; } case BilinearInterpolatePixel: default: { PointInfo delta, epsilon; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < 4L; i++) AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i); delta.x=x-x_offset; delta.y=y-y_offset; epsilon.x=1.0-delta.x; epsilon.y=1.0-delta.y; gamma=((epsilon.y*(epsilon.x*alpha[0]+delta.x*alpha[1])+delta.y* (epsilon.x*alpha[2]+delta.x*alpha[3]))); gamma=PerceptibleReciprocal(gamma); pixel->red=gamma*(epsilon.y*(epsilon.x*pixels[0].red+delta.x* pixels[1].red)+delta.y*(epsilon.x*pixels[2].red+delta.x*pixels[3].red)); pixel->green=gamma*(epsilon.y*(epsilon.x*pixels[0].green+delta.x* pixels[1].green)+delta.y*(epsilon.x*pixels[2].green+delta.x* pixels[3].green)); pixel->blue=gamma*(epsilon.y*(epsilon.x*pixels[0].blue+delta.x* pixels[1].blue)+delta.y*(epsilon.x*pixels[2].blue+delta.x* pixels[3].blue)); if (image->colorspace == CMYKColorspace) pixel->black=gamma*(epsilon.y*(epsilon.x*pixels[0].black+delta.x* pixels[1].black)+delta.y*(epsilon.x*pixels[2].black+delta.x* pixels[3].black)); gamma=((epsilon.y*(epsilon.x+delta.x)+delta.y*(epsilon.x+delta.x))); gamma=PerceptibleReciprocal(gamma); pixel->alpha=gamma*(epsilon.y*(epsilon.x*pixels[0].alpha+delta.x* pixels[1].alpha)+delta.y*(epsilon.x*pixels[2].alpha+delta.x* pixels[3].alpha)); break; } case BlendInterpolatePixel: { p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < 4L; i++) { GetPixelInfoPixel(image,p+i*GetPixelChannels(image),pixels+i); AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i); } gamma=1.0; /* number of pixels blended together (its variable) */ for (i=0; i <= 1L; i++) { if ((y-y_offset) >= 0.75) { alpha[i]=alpha[i+2]; /* take right pixels */ pixels[i]=pixels[i+2]; } else if ((y-y_offset) > 0.25) { gamma=2.0; /* blend both pixels in row */ alpha[i]+=alpha[i+2]; /* add up alpha weights */ pixels[i].red+=pixels[i+2].red; pixels[i].green+=pixels[i+2].green; pixels[i].blue+=pixels[i+2].blue; pixels[i].black+=pixels[i+2].black; pixels[i].alpha+=pixels[i+2].alpha; } } if ((x-x_offset) >= 0.75) { alpha[0]=alpha[1]; pixels[0]=pixels[1]; } else if ((x-x_offset) > 0.25) { gamma*=2.0; /* blend both rows */ alpha[0]+= alpha[1]; /* add up alpha weights */ pixels[0].red+=pixels[1].red; pixels[0].green+=pixels[1].green; pixels[0].blue+=pixels[1].blue; pixels[0].black+=pixels[1].black; pixels[0].alpha+=pixels[1].alpha; } gamma=1.0/gamma; alpha[0]=PerceptibleReciprocal(alpha[0]); pixel->red=alpha[0]*pixels[0].red; pixel->green=alpha[0]*pixels[0].green; /* divide by sum of alpha */ pixel->blue=alpha[0]*pixels[0].blue; pixel->black=alpha[0]*pixels[0].black; pixel->alpha=gamma*pixels[0].alpha; /* divide by number of pixels */ break; } case CatromInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < 16L; i++) AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i); CatromWeights((double) (x-x_offset),&cx); CatromWeights((double) (y-y_offset),&cy); pixel->red=(cy[0]*(cx[0]*pixels[0].red+cx[1]*pixels[1].red+cx[2]* pixels[2].red+cx[3]*pixels[3].red)+cy[1]*(cx[0]*pixels[4].red+cx[1]* pixels[5].red+cx[2]*pixels[6].red+cx[3]*pixels[7].red)+cy[2]*(cx[0]* pixels[8].red+cx[1]*pixels[9].red+cx[2]*pixels[10].red+cx[3]* pixels[11].red)+cy[3]*(cx[0]*pixels[12].red+cx[1]*pixels[13].red+cx[2]* pixels[14].red+cx[3]*pixels[15].red)); pixel->green=(cy[0]*(cx[0]*pixels[0].green+cx[1]*pixels[1].green+cx[2]* pixels[2].green+cx[3]*pixels[3].green)+cy[1]*(cx[0]*pixels[4].green+ cx[1]*pixels[5].green+cx[2]*pixels[6].green+cx[3]*pixels[7].green)+ cy[2]*(cx[0]*pixels[8].green+cx[1]*pixels[9].green+cx[2]* pixels[10].green+cx[3]*pixels[11].green)+cy[3]*(cx[0]* pixels[12].green+cx[1]*pixels[13].green+cx[2]*pixels[14].green+cx[3]* pixels[15].green)); pixel->blue=(cy[0]*(cx[0]*pixels[0].blue+cx[1]*pixels[1].blue+cx[2]* pixels[2].blue+cx[3]*pixels[3].blue)+cy[1]*(cx[0]*pixels[4].blue+cx[1]* pixels[5].blue+cx[2]*pixels[6].blue+cx[3]*pixels[7].blue)+cy[2]*(cx[0]* pixels[8].blue+cx[1]*pixels[9].blue+cx[2]*pixels[10].blue+cx[3]* pixels[11].blue)+cy[3]*(cx[0]*pixels[12].blue+cx[1]*pixels[13].blue+ cx[2]*pixels[14].blue+cx[3]*pixels[15].blue)); if (image->colorspace == CMYKColorspace) pixel->black=(cy[0]*(cx[0]*pixels[0].black+cx[1]*pixels[1].black+cx[2]* pixels[2].black+cx[3]*pixels[3].black)+cy[1]*(cx[0]*pixels[4].black+ cx[1]*pixels[5].black+cx[2]*pixels[6].black+cx[3]*pixels[7].black)+ cy[2]*(cx[0]*pixels[8].black+cx[1]*pixels[9].black+cx[2]* pixels[10].black+cx[3]*pixels[11].black)+cy[3]*(cx[0]* pixels[12].black+cx[1]*pixels[13].black+cx[2]*pixels[14].black+cx[3]* pixels[15].black)); pixel->alpha=(cy[0]*(cx[0]*pixels[0].alpha+cx[1]*pixels[1].alpha+cx[2]* pixels[2].alpha+cx[3]*pixels[3].alpha)+cy[1]*(cx[0]*pixels[4].alpha+ cx[1]*pixels[5].alpha+cx[2]*pixels[6].alpha+cx[3]*pixels[7].alpha)+ cy[2]*(cx[0]*pixels[8].alpha+cx[1]*pixels[9].alpha+cx[2]* pixels[10].alpha+cx[3]*pixels[11].alpha)+cy[3]*(cx[0]*pixels[12].alpha+ cx[1]*pixels[13].alpha+cx[2]*pixels[14].alpha+cx[3]*pixels[15].alpha)); break; } case IntegerInterpolatePixel: { p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } GetPixelInfoPixel(image,p,pixel); break; } case MeshInterpolatePixel: { PointInfo delta, luminance; p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,2,2,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } delta.x=x-x_offset; delta.y=y-y_offset; luminance.x=GetPixelLuma(image,p)-(double) GetPixelLuma(image,p+3*GetPixelChannels(image)); luminance.y=GetPixelLuma(image,p+GetPixelChannels(image))-(double) GetPixelLuma(image,p+2*GetPixelChannels(image)); AlphaBlendPixelInfo(image,p,pixels+0,alpha+0); AlphaBlendPixelInfo(image,p+GetPixelChannels(image),pixels+1,alpha+1); AlphaBlendPixelInfo(image,p+2*GetPixelChannels(image),pixels+2,alpha+2); AlphaBlendPixelInfo(image,p+3*GetPixelChannels(image),pixels+3,alpha+3); if (fabs((double) luminance.x) < fabs((double) luminance.y)) { /* Diagonal 0-3 NW-SE. */ if (delta.x <= delta.y) { /* Bottom-left triangle (pixel: 2, diagonal: 0-3). */ delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[2],alpha[3],alpha[0]); gamma=PerceptibleReciprocal(gamma); pixel->red=gamma*MeshInterpolate(&delta,pixels[2].red, pixels[3].red,pixels[0].red); pixel->green=gamma*MeshInterpolate(&delta,pixels[2].green, pixels[3].green,pixels[0].green); pixel->blue=gamma*MeshInterpolate(&delta,pixels[2].blue, pixels[3].blue,pixels[0].blue); if (image->colorspace == CMYKColorspace) pixel->black=gamma*MeshInterpolate(&delta,pixels[2].black, pixels[3].black,pixels[0].black); gamma=MeshInterpolate(&delta,1.0,1.0,1.0); pixel->alpha=gamma*MeshInterpolate(&delta,pixels[2].alpha, pixels[3].alpha,pixels[0].alpha); } else { /* Top-right triangle (pixel:1 , diagonal: 0-3). */ delta.x=1.0-delta.x; gamma=MeshInterpolate(&delta,alpha[1],alpha[0],alpha[3]); gamma=PerceptibleReciprocal(gamma); pixel->red=gamma*MeshInterpolate(&delta,pixels[1].red, pixels[0].red,pixels[3].red); pixel->green=gamma*MeshInterpolate(&delta,pixels[1].green, pixels[0].green,pixels[3].green); pixel->blue=gamma*MeshInterpolate(&delta,pixels[1].blue, pixels[0].blue,pixels[3].blue); if (image->colorspace == CMYKColorspace) pixel->black=gamma*MeshInterpolate(&delta,pixels[1].black, pixels[0].black,pixels[3].black); gamma=MeshInterpolate(&delta,1.0,1.0,1.0); pixel->alpha=gamma*MeshInterpolate(&delta,pixels[1].alpha, pixels[0].alpha,pixels[3].alpha); } } else { /* Diagonal 1-2 NE-SW. */ if (delta.x <= (1.0-delta.y)) { /* Top-left triangle (pixel: 0, diagonal: 1-2). */ gamma=MeshInterpolate(&delta,alpha[0],alpha[1],alpha[2]); gamma=PerceptibleReciprocal(gamma); pixel->red=gamma*MeshInterpolate(&delta,pixels[0].red, pixels[1].red,pixels[2].red); pixel->green=gamma*MeshInterpolate(&delta,pixels[0].green, pixels[1].green,pixels[2].green); pixel->blue=gamma*MeshInterpolate(&delta,pixels[0].blue, pixels[1].blue,pixels[2].blue); if (image->colorspace == CMYKColorspace) pixel->black=gamma*MeshInterpolate(&delta,pixels[0].black, pixels[1].black,pixels[2].black); gamma=MeshInterpolate(&delta,1.0,1.0,1.0); pixel->alpha=gamma*MeshInterpolate(&delta,pixels[0].alpha, pixels[1].alpha,pixels[2].alpha); } else { /* Bottom-right triangle (pixel: 3, diagonal: 1-2). */ delta.x=1.0-delta.x; delta.y=1.0-delta.y; gamma=MeshInterpolate(&delta,alpha[3],alpha[2],alpha[1]); gamma=PerceptibleReciprocal(gamma); pixel->red=gamma*MeshInterpolate(&delta,pixels[3].red, pixels[2].red,pixels[1].red); pixel->green=gamma*MeshInterpolate(&delta,pixels[3].green, pixels[2].green,pixels[1].green); pixel->blue=gamma*MeshInterpolate(&delta,pixels[3].blue, pixels[2].blue,pixels[1].blue); if (image->colorspace == CMYKColorspace) pixel->black=gamma*MeshInterpolate(&delta,pixels[3].black, pixels[2].black,pixels[1].black); gamma=MeshInterpolate(&delta,1.0,1.0,1.0); pixel->alpha=gamma*MeshInterpolate(&delta,pixels[3].alpha, pixels[2].alpha,pixels[1].alpha); } } break; } case NearestInterpolatePixel: { x_offset=CastDoubleToLong(floor(x+0.5)); y_offset=CastDoubleToLong(floor(y+0.5)); p=GetCacheViewVirtualPixels(image_view,x_offset,y_offset,1,1,exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } GetPixelInfoPixel(image,p,pixel); break; } case SplineInterpolatePixel: { double cx[4], cy[4]; p=GetCacheViewVirtualPixels(image_view,x_offset-1,y_offset-1,4,4, exception); if (p == (const Quantum *) NULL) { status=MagickFalse; break; } for (i=0; i < 16L; i++) AlphaBlendPixelInfo(image,p+i*GetPixelChannels(image),pixels+i,alpha+i); SplineWeights((double) (x-x_offset),&cx); SplineWeights((double) (y-y_offset),&cy); pixel->red=(cy[0]*(cx[0]*pixels[0].red+cx[1]*pixels[1].red+cx[2]* pixels[2].red+cx[3]*pixels[3].red)+cy[1]*(cx[0]*pixels[4].red+cx[1]* pixels[5].red+cx[2]*pixels[6].red+cx[3]*pixels[7].red)+cy[2]*(cx[0]* pixels[8].red+cx[1]*pixels[9].red+cx[2]*pixels[10].red+cx[3]* pixels[11].red)+cy[3]*(cx[0]*pixels[12].red+cx[1]*pixels[13].red+cx[2]* pixels[14].red+cx[3]*pixels[15].red)); pixel->green=(cy[0]*(cx[0]*pixels[0].green+cx[1]*pixels[1].green+cx[2]* pixels[2].green+cx[3]*pixels[3].green)+cy[1]*(cx[0]*pixels[4].green+ cx[1]*pixels[5].green+cx[2]*pixels[6].green+cx[3]*pixels[7].green)+ cy[2]*(cx[0]*pixels[8].green+cx[1]*pixels[9].green+cx[2]* pixels[10].green+cx[3]*pixels[11].green)+cy[3]*(cx[0]*pixels[12].green+ cx[1]*pixels[13].green+cx[2]*pixels[14].green+cx[3]*pixels[15].green)); pixel->blue=(cy[0]*(cx[0]*pixels[0].blue+cx[1]*pixels[1].blue+cx[2]* pixels[2].blue+cx[3]*pixels[3].blue)+cy[1]*(cx[0]*pixels[4].blue+cx[1]* pixels[5].blue+cx[2]*pixels[6].blue+cx[3]*pixels[7].blue)+cy[2]*(cx[0]* pixels[8].blue+cx[1]*pixels[9].blue+cx[2]*pixels[10].blue+cx[3]* pixels[11].blue)+cy[3]*(cx[0]*pixels[12].blue+cx[1]*pixels[13].blue+ cx[2]*pixels[14].blue+cx[3]*pixels[15].blue)); if (image->colorspace == CMYKColorspace) pixel->black=(cy[0]*(cx[0]*pixels[0].black+cx[1]*pixels[1].black+cx[2]* pixels[2].black+cx[3]*pixels[3].black)+cy[1]*(cx[0]*pixels[4].black+ cx[1]*pixels[5].black+cx[2]*pixels[6].black+cx[3]*pixels[7].black)+ cy[2]*(cx[0]*pixels[8].black+cx[1]*pixels[9].black+cx[2]* pixels[10].black+cx[3]*pixels[11].black)+cy[3]*(cx[0]* pixels[12].black+cx[1]*pixels[13].black+cx[2]*pixels[14].black+cx[3]* pixels[15].black)); pixel->alpha=(cy[0]*(cx[0]*pixels[0].alpha+cx[1]*pixels[1].alpha+cx[2]* pixels[2].alpha+cx[3]*pixels[3].alpha)+cy[1]*(cx[0]*pixels[4].alpha+ cx[1]*pixels[5].alpha+cx[2]*pixels[6].alpha+cx[3]*pixels[7].alpha)+ cy[2]*(cx[0]*pixels[8].alpha+cx[1]*pixels[9].alpha+cx[2]* pixels[10].alpha+cx[3]*pixels[11].alpha)+cy[3]*(cx[0]*pixels[12].alpha+ cx[1]*pixels[13].alpha+cx[2]*pixels[14].alpha+cx[3]*pixels[15].alpha)); break; } } return(status); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s F u z z y E q u i v a l e n c e P i x e l % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsFuzzyEquivalencePixel() returns MagickTrue if the distance between two % pixels is less than the specified distance in a linear three (or four) % dimensional color space. % % The format of the IsFuzzyEquivalencePixel method is: % % void IsFuzzyEquivalencePixel(const Image *source,const Quantum *p, % const Image *destination,const Quantum *q) % % A description of each parameter follows: % % o source: the source image. % % o p: Pixel p. % % o destination: the destination image. % % o q: Pixel q. % */ MagickExport MagickBooleanType IsFuzzyEquivalencePixel(const Image *source, const Quantum *p,const Image *destination,const Quantum *q) { double distance, fuzz, pixel, scale; fuzz=GetFuzzyColorDistance(source,destination); scale=1.0; distance=0.0; if ((source->alpha_trait != UndefinedPixelTrait) || (destination->alpha_trait != UndefinedPixelTrait)) { /* Transparencies are involved - set alpha distance. */ pixel=GetPixelAlpha(source,p)-(double) GetPixelAlpha(destination,q); distance=pixel*pixel; if (distance > fuzz) return(MagickFalse); /* Generate a alpha scaling factor to generate a 4D cone on colorspace. Note that if one color is transparent, distance has no color component. */ if (source->alpha_trait != UndefinedPixelTrait) scale*=QuantumScale*GetPixelAlpha(source,p); if (destination->alpha_trait != UndefinedPixelTrait) scale*=QuantumScale*GetPixelAlpha(destination,q); if (scale <= MagickEpsilon) return(MagickTrue); } /* RGB or CMY color cube. */ distance*=3.0; /* rescale appropriately */ fuzz*=3.0; pixel=GetPixelRed(source,p)-(double) GetPixelRed(destination,q); if (IsHueCompatibleColorspace(source->colorspace) != MagickFalse) { /* Compute an arc distance for hue. It should be a vector angle of 'S'/'W' length with 'L'/'B' forming appropriate cones. */ if (fabs((double) pixel) > (QuantumRange/2)) pixel-=QuantumRange; pixel*=2.0; } distance+=scale*pixel*pixel; if (distance > fuzz) return(MagickFalse); pixel=GetPixelGreen(source,p)-(double) GetPixelGreen(destination,q); distance+=scale*pixel*pixel; if (distance > fuzz) return(MagickFalse); pixel=GetPixelBlue(source,p)-(double) GetPixelBlue(destination,q); distance+=scale*pixel*pixel; if (distance > fuzz) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + I s F u z z y E q u i v a l e n c e P i x e l I n f o % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsFuzzyEquivalencePixelInfo() returns true if the distance between two % colors is less than the specified distance in a linear three (or four) % dimensional color space. % % This implements the equivalent of: % fuzz < sqrt(color_distance^2 * u.a*v.a + alpha_distance^2) % % Which produces a multi-dimensional cone for that colorspace along the % transparency vector. % % For example for an RGB: % color_distance^2 = ( (u.r-v.r)^2 + (u.g-v.g)^2 + (u.b-v.b)^2 ) / 3 % % See https://imagemagick.org/Usage/bugs/fuzz_distance/ % % Hue colorspace distances need more work. Hue is not a distance, it is an % angle! % % A check that q is in the same color space as p should be made and the % appropriate mapping made. -- Anthony Thyssen 8 December 2010 % % The format of the IsFuzzyEquivalencePixelInfo method is: % % MagickBooleanType IsFuzzyEquivalencePixelInfo(const PixelInfo *p, % const PixelInfo *q) % % A description of each parameter follows: % % o p: Pixel p. % % o q: Pixel q. % */ MagickExport MagickBooleanType IsFuzzyEquivalencePixelInfo(const PixelInfo *p, const PixelInfo *q) { double fuzz, pixel; double scale, distance; fuzz=(double) MagickMax(MagickMax(p->fuzz,q->fuzz),(MagickRealType) MagickSQ1_2); fuzz*=fuzz; scale=1.0; distance=0.0; if ((p->alpha_trait != UndefinedPixelTrait) || (q->alpha_trait != UndefinedPixelTrait)) { /* Transparencies are involved - set alpha distance. */ pixel=(p->alpha_trait != UndefinedPixelTrait ? p->alpha : OpaqueAlpha)- (q->alpha_trait != UndefinedPixelTrait ? q->alpha : OpaqueAlpha); distance=pixel*pixel; if (distance > fuzz) return(MagickFalse); /* Generate a alpha scaling factor to generate a 4D cone on colorspace. If one color is transparent, distance has no color component. */ if (p->alpha_trait != UndefinedPixelTrait) scale=(QuantumScale*p->alpha); if (q->alpha_trait != UndefinedPixelTrait) scale*=(QuantumScale*q->alpha); if (scale <= MagickEpsilon ) return(MagickTrue); } /* CMYK create a CMY cube with a multi-dimensional cone toward black. */ if (p->colorspace == CMYKColorspace) { pixel=p->black-q->black; distance+=pixel*pixel*scale; if (distance > fuzz) return(MagickFalse); scale*=(double) (QuantumScale*(QuantumRange-p->black)); scale*=(double) (QuantumScale*(QuantumRange-q->black)); } /* RGB or CMY color cube. */ distance*=3.0; /* rescale appropriately */ fuzz*=3.0; pixel=p->red-q->red; if (IsHueCompatibleColorspace(p->colorspace) != MagickFalse) { /* This calculates a arc distance for hue-- it should be a vector angle of 'S'/'W' length with 'L'/'B' forming appropriate cones. In other words this is a hack - Anthony. */ if (fabs((double) pixel) > (QuantumRange/2)) pixel-=QuantumRange; pixel*=2.0; } distance+=pixel*pixel*scale; if (distance > fuzz) return(MagickFalse); pixel=p->green-q->green; distance+=pixel*pixel*scale; if (distance > fuzz) return(MagickFalse); pixel=p->blue-q->blue; distance+=pixel*pixel*scale; if (distance > fuzz) return(MagickFalse); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l C h a n n e l M a s k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelChannelMask() sets the pixel channel map from the specified channel % mask. % % The format of the SetPixelChannelMask method is: % % ChannelType SetPixelChannelMask(Image *image, % const ChannelType channel_mask) % % A description of each parameter follows: % % o image: the image. % % o channel_mask: the channel mask. % */ static void LogPixelChannels(const Image *image) { ssize_t i; (void) LogMagickEvent(PixelEvent,GetMagickModule(),"%s[%08x]", image->filename,image->channel_mask); for (i=0; i < (ssize_t) image->number_channels; i++) { char channel_name[MagickPathExtent], traits[MagickPathExtent]; const char *name; PixelChannel channel; channel=GetPixelChannelChannel(image,i); switch (channel) { case RedPixelChannel: { name="red"; if (image->colorspace == CMYKColorspace) name="cyan"; if ((image->colorspace == LinearGRAYColorspace) || (image->colorspace == GRAYColorspace)) name="gray"; break; } case GreenPixelChannel: { name="green"; if (image->colorspace == CMYKColorspace) name="magenta"; break; } case BluePixelChannel: { name="blue"; if (image->colorspace == CMYKColorspace) name="yellow"; break; } case BlackPixelChannel: { name="black"; if (image->storage_class == PseudoClass) name="index"; break; } case IndexPixelChannel: { name="index"; break; } case AlphaPixelChannel: { name="alpha"; break; } case ReadMaskPixelChannel: { name="read-mask"; break; } case WriteMaskPixelChannel: { name="write-mask"; break; } case CompositeMaskPixelChannel: { name="composite-mask"; break; } case MetaPixelChannel: { name="meta"; break; } default: name="undefined"; } if (image->colorspace == UndefinedColorspace) { (void) FormatLocaleString(channel_name,MagickPathExtent,"%.20g", (double) channel); name=(const char *) channel_name; } *traits='\0'; if ((GetPixelChannelTraits(image,channel) & UpdatePixelTrait) != 0) (void) ConcatenateMagickString(traits,"update,",MagickPathExtent); if ((GetPixelChannelTraits(image,channel) & BlendPixelTrait) != 0) (void) ConcatenateMagickString(traits,"blend,",MagickPathExtent); if ((GetPixelChannelTraits(image,channel) & CopyPixelTrait) != 0) (void) ConcatenateMagickString(traits,"copy,",MagickPathExtent); if (*traits == '\0') (void) ConcatenateMagickString(traits,"undefined,",MagickPathExtent); traits[strlen(traits)-1]='\0'; (void) LogMagickEvent(PixelEvent,GetMagickModule()," %.20g: %s (%s)", (double) i,name,traits); } } MagickExport ChannelType SetPixelChannelMask(Image *image, const ChannelType channel_mask) { #define GetChannelBit(mask,bit) (((size_t) (mask) >> (size_t) (bit)) & 0x01) ChannelType mask; ssize_t i; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(PixelEvent,GetMagickModule(),"%s[%08x]", image->filename,channel_mask); mask=image->channel_mask; image->channel_mask=channel_mask; for (i=0; i < (ssize_t) GetPixelChannels(image); i++) { PixelChannel channel = GetPixelChannelChannel(image,i); if (GetChannelBit(channel_mask,channel) == 0) { SetPixelChannelTraits(image,channel,CopyPixelTrait); continue; } if (channel == AlphaPixelChannel) { if ((image->alpha_trait & CopyPixelTrait) != 0) { SetPixelChannelTraits(image,channel,CopyPixelTrait); continue; } SetPixelChannelTraits(image,channel,UpdatePixelTrait); continue; } if (image->alpha_trait != UndefinedPixelTrait) { SetPixelChannelTraits(image,channel,(const PixelTrait) (UpdatePixelTrait | BlendPixelTrait)); continue; } SetPixelChannelTraits(image,channel,UpdatePixelTrait); } if (image->storage_class == PseudoClass) SetPixelChannelTraits(image,IndexPixelChannel,CopyPixelTrait); if ((image->channels & ReadMaskChannel) != 0) SetPixelChannelTraits(image,ReadMaskPixelChannel,CopyPixelTrait); if ((image->channels & WriteMaskChannel) != 0) SetPixelChannelTraits(image,WriteMaskPixelChannel,CopyPixelTrait); if ((image->channels & CompositeMaskChannel) != 0) SetPixelChannelTraits(image,CompositeMaskPixelChannel,CopyPixelTrait); if (image->debug != MagickFalse) LogPixelChannels(image); return(mask); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S e t P i x e l M e t a C h a n n e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SetPixelMetaChannels() sets the image meta channels. % % The format of the SetPixelMetaChannels method is: % % MagickBooleanType SetPixelMetaChannels(Image *image, % const size_t number_meta_channels,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o number_meta_channels: the number of meta channels. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SetPixelMetaChannels(Image *image, const size_t number_meta_channels,ExceptionInfo *exception) { image->number_meta_channels=MagickMin(number_meta_channels,MaxPixelChannels -(size_t) StartMetaPixelChannel); InitializePixelChannelMap(image); return(SyncImagePixelCache(image,exception)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % S o r t I m a g e P i x e l s % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % SortImagePixels() sorts pixels within each scanline in ascending order of % intensity. % % The format of the SortImagePixels method is: % % MagickBooleanType SortImagePixels(Image *image,ExceptionInfo *exception) % % A description of each parameter follows: % % o image: the image. % % o exception: return any errors or warnings in this structure. % */ MagickExport MagickBooleanType SortImagePixels(Image *image, ExceptionInfo *exception) { #define SolarizeImageTag "Solarize/Image" CacheView *image_view; MagickBooleanType status; MagickOffsetType progress; ssize_t y; /* Sort image pixels. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); status=MagickTrue; progress=0; image_view=AcquireAuthenticCacheView(image,exception); #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp parallel for schedule(static) shared(progress,status) \ magick_number_threads(image,image,image->rows,1) #endif for (y=0; y < (ssize_t) image->rows; y++) { Quantum *magick_restrict q; ssize_t x; if (status == MagickFalse) continue; q=GetCacheViewAuthenticPixels(image_view,0,y,image->columns,1,exception); if (q == (Quantum *) NULL) { status=MagickFalse; continue; } for (x=0; x < (ssize_t) image->columns-1; x++) { MagickRealType current, previous; ssize_t j; previous=GetPixelIntensity(image,q); for (j=0; j < (ssize_t) (image->columns-x-1); j++) { current=GetPixelIntensity(image,q+(j+1)*GetPixelChannels(image)); if (previous > current) { Quantum pixel[MaxPixelChannels]; /* Swap adjacent pixels. */ (void) memcpy(pixel,q+j*GetPixelChannels(image), GetPixelChannels(image)*sizeof(Quantum)); (void) memcpy(q+j*GetPixelChannels(image),q+(j+1)* GetPixelChannels(image),GetPixelChannels(image)*sizeof(Quantum)); (void) memcpy(q+(j+1)*GetPixelChannels(image),pixel, GetPixelChannels(image)*sizeof(Quantum)); } else previous=current; } } if (SyncCacheViewAuthenticPixels(image_view,exception) == MagickFalse) status=MagickFalse; if (image->progress_monitor != (MagickProgressMonitor) NULL) { MagickBooleanType proceed; #if defined(MAGICKCORE_OPENMP_SUPPORT) #pragma omp atomic #endif progress++; proceed=SetImageProgress(image,SolarizeImageTag,progress,image->rows); if (proceed == MagickFalse) status=MagickFalse; } } image_view=DestroyCacheView(image_view); return(status); }
5796.c
// this source is derived from CHILL AST originally from file '/uufs/chpc.utah.edu/common/home/u1142914/lib/ytopt_vinu/polybench/polybench-code/stencils/heat-3d/kernel.c' as parsed by frontend compiler rose void kernel_heat_3d(int tsteps, int n, double A[200 + 0][200 + 0][200 + 0], double B[200 + 0][200 + 0][200 + 0]) { int t12; int t10; int t8; int t6; int t4; int t2; for (t2 = 1; t2 <= 1000; t2 += 1) { #pragma omp parallel for private(t4,t6,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 16) for (t6 = t4; t6 <= (t4 + 15 < n - 2 ? t4 + 15 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 32) for (t10 = t8; t10 <= (t8 + 31 < n - 2 ? t8 + 31 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) B[t6][t10][t12] = 0.125 * (A[t6 + 1][t10][t12] - 2 * A[t6][t10][t12] + A[t6 - 1][t10][t12]) + 0.125 * (A[t6][t10 + 1][t12] - 2 * A[t6][t10][t12] + A[t6][t10 - 1][t12]) + 0.125 * (A[t6][t10][t12 + 1] - 2 * A[t6][t10][t12] + A[t6][t10][t12 - 1]) + A[t6][t10][t12]; #pragma omp parallel for private(t4,t6,t8,t10,t12,t14) for (t4 = 1; t4 <= n - 2; t4 += 16) for (t6 = t4; t6 <= (t4 + 15 < n - 2 ? t4 + 15 : n - 2); t6 += 1) for (t8 = 1; t8 <= n - 2; t8 += 32) for (t10 = t8; t10 <= (t8 + 31 < n - 2 ? t8 + 31 : n - 2); t10 += 1) for (t12 = 1; t12 <= n - 2; t12 += 1) A[t6][t10][t12] = 0.125 * (B[t6 + 1][t10][t12] - 2 * B[t6][t10][t12] + B[t6 - 1][t10][t12]) + 0.125 * (B[t6][t10 + 1][t12] - 2 * B[t6][t10][t12] + B[t6][t10 - 1][t12]) + 0.125 * (B[t6][t10][t12 + 1] - 2 * B[t6][t10][t12] + B[t6][t10][t12 - 1]) + B[t6][t10][t12]; } }
GB_binop__pair_uint32.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__pair_uint32) // A.*B function (eWiseMult): GB (_AemultB) // A.*B function (eWiseMult): GB (_AemultB_02__pair_uint32) // A.*B function (eWiseMult): GB (_AemultB_03__pair_uint32) // A.*B function (eWiseMult): GB (_AemultB_bitmap__pair_uint32) // A*D function (colscale): GB (_AxD__pair_uint32) // D*A function (rowscale): GB (_DxB__pair_uint32) // C+=B function (dense accum): GB (_Cdense_accumB__pair_uint32) // C+=b function (dense accum): GB (_Cdense_accumb__pair_uint32) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__pair_uint32) // C=scalar+B GB ((none)) // C=scalar+B' GB ((none)) // C=A+scalar GB ((none)) // C=A'+scalar GB ((none)) // C type: uint32_t // A type: uint32_t // B,b type: uint32_t // BinaryOp: cij = 1 #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) \ ; // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ ; // 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) \ 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 = 1 ; // 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_PAIR || GxB_NO_UINT32 || GxB_NO_PAIR_UINT32) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_ewise3_noaccum__pair_uint32) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__pair_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__pair_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__pair_uint32) ( GrB_Matrix C, const GrB_Matrix A, bool A_is_pattern, const GrB_Matrix D, bool D_is_pattern, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_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__pair_uint32) ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint32_t *restrict Cx = (uint32_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__pair_uint32) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; #include "GB_add_template.c" GB_FREE_WORK ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C = A.*B or C<M> = A.*B //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_01__pair_uint32) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_01_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__pair_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_03__pair_uint32) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_03_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__pair_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 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 < anz ; p++) { if (!GBB (Bb, p)) continue ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( 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 ; ; ; Cx [p] = 1 ; } return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( 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 } #endif //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ #if 0 // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ ; ; \ Cx [pC] = 1 ; \ } GrB_Info GB ((none)) ( 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 #endif
example_07-ArrayOfStructs-CellLinkedList-innerOmp-SIMD.c
/* * SPDX-License-Identifier: BSD-3-Clause * * example_07-ArrayOfStructs-CellLinkedList-innerOmp-SIMD.c : * Example of SPH Density Calculation using * fast neighbor search the main density loop via * Cell Linked List method, Array of Structs (AoS) * data layout, OpenMP parallelization at the * chunk level, SIMD directives in the kernel * and in the main loop. * * (C) Copyright 2021 José Hugo Elsas * Author: José Hugo Elsas <jhelsas@gmail.com> * * Command Line Options: * -runs <int> : Set the number of repetitions (runs) for * calculating the density. The value of * the density is based on the last * iteration. * Default value: 1 * -run_seed <int>: Flag to set an alternative seed use for * for the PRNG. Instead of feeding seed * to the PRNG directly, it feeds * seed + iteration, as to generate different * configurations for each iteration. * Default value: 0 - (possible 0/1) * -seed <int>: Set the seed to use for the SPH particles * uniform position generation in the box * Default value: 123123123 * * -N <int>: Set the number of SPH particles to be used * Default value: 1e5 = 100,000 * -h <float>: Set the value of the smoothing kernel * parameter h, which corresponds to half * of the support of the kernel. * Default value: 0.05 * * -Nx <int>: Set the number of Cells in the X direction * Default value: 10 * -Ny <int>: Set the number of Cells in the Y direction * Default value: 10 * -Nz <int>: Set the number of Cells in the Z direction * Default value: 10 * * -Xmin <float>: Set the lower bound in the X direction for * the Cell Linked List box * Default value: 0.0 * -Ymin <float>: Set the lower bound in the Y direction for * the Cell Linked List box * Default value: 0.0 * -Ymin <float>: Set the lower bound in the Z direction for * the Cell Linked List box * Default value: 0.0 * * -Xmax <float>: Set the lower bound in the X direction for * the Cell Linked List box * Default value: 1.0 * -Ymax <float>: Set the lower bound in the Y direction for * the Cell Linked List box * Default value: 1.0 * -Zmax <float>: Set the lower bound in the Z direction for * the Cell Linked List box * Default value: 1.0 */ #include <math.h> #include <ctype.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <limits.h> #include <unistd.h> #include <stdbool.h> #include <sys/time.h> #include <inttypes.h> #include <omp.h> #include <gsl/gsl_math.h> #include <gsl/gsl_rng.h> #include <gsl/gsl_randist.h> #include <gsl/gsl_heapsort.h> #include "sph_data_types.h" #include "sph_linked_list.h" #include "sph_utils.h" #ifndef M_PI #define M_PI (3.14159265358979323846) #endif #define COMPUTE_BLOCKS 4 int main_loop(int run, bool run_seed, int64_t N, double h, long int seed, void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times); int compute_density_3d_chunk(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, SPHparticle *lsph); int compute_density_3d_cll_innerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box); double w_bspline_3d_constant(double h); #pragma omp declare simd double w_bspline_3d_simd(double q); int main(int argc, char **argv){ bool run_seed = false; // By default the behavior is is to use the same seed int runs = 1,err; // it only runs once long int seed = 123123123; // The default seed is 123123123 int64_t N = 100000; // The default number of particles is N = 1e5 = 100,000 double h=0.05; // The default kernel smoothing length is h = 0.05 linkedListBox *box; // Uninitialized Box containing the cells for the cell linked list method SPHparticle *lsph; // Uninitialized array of SPH particles box = (linkedListBox*)malloc(1*sizeof(linkedListBox)); // Create a box representing the entire 3d domain // allow for command line customization of the run arg_parse(argc,argv,&N,&h,&seed,&runs,&run_seed,box); // Parse the command line options // line arguments and override default values lsph = (SPHparticle*)malloc(N*sizeof(SPHparticle)); void *swap_arr = malloc(N*sizeof(double)); double times[runs*COMPUTE_BLOCKS]; for(int run=0;run<runs;run+=1) main_loop(run,run_seed,N,h,seed,swap_arr,box,lsph,times); bool is_cll = true; const char *prefix = "ex07,cll,AoS,innerOmp,SIMD"; print_time_stats(prefix,is_cll,N,h,seed,runs,lsph,box,times); print_sph_particles_density(prefix,is_cll,N,h,seed,runs,lsph,box); free(lsph); safe_free_box(box); free(swap_arr); return 0; } /* * Function main_loop: * Runs the main loop of the program, including the particle array generation, * density calculation and the timings annotations. * * Arguments: * run <int> : index (or value) or the present iteration * run_seed <bool> : boolean defining whether to use run index for seed or not * N <int> : Number of SPH particles to be used in the run * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * seed <long int> : seed for GSL PRNG generator to generate particle positions * box <linkedListBox> : Box of linked list cells, encapsulating the 3d domain * lsph <SPHparticle> : Array (pointer) of SPH particles to be updated * times <double> : Array to store the computation timings to be updated * Returns: * 0 : error code returned * lsph <SPHparticle> : SPH particle array is updated in the rho field by reference * times <double> : Times is updated by reference */ int main_loop(int run, bool run_seed, int64_t N, double h, long int seed, void *swap_arr, linkedListBox *box, SPHparticle *lsph, double *times) { int err; if(run_seed) err = gen_unif_rdn_pos_box(N,seed+run,box,lsph); else err = gen_unif_rdn_pos_box(N,seed,box,lsph); if(err) fprintf(stderr,"error in gen_unif_rdn_pos\n"); // ------------------------------------------------------ // double t0,t1,t2,t3,t4; t0 = omp_get_wtime(); err = compute_hash_MC3D(N,lsph,box); // Compute Morton Z 3D hash based on the if(err) // cell index for each of the X, Y and Z fprintf(stderr,"error in compute_hash_MC3D\n"); // directions, in which a given particle reside t1 = omp_get_wtime(); qsort(lsph,N,sizeof(SPHparticle),compare_SPHparticle); // Sort Particle Array according to hash, therefore // implicitly creating a cell of particles of same hash t2 = omp_get_wtime(); err = setup_interval_hashtables(N,lsph,box); // Annotate the begining and end of each cell if(err) // As to have a quick way to retrieve a cell fprintf(stderr,"error in setup_interval_hashtables\n"); // given its hash . t3 = omp_get_wtime(); err = compute_density_3d_cll_innerOmp(N,h,lsph,box); // Compute the density of the particles based if(err) // on the cell linked list method for fast fprintf(stderr,"error in compute_density_3d_innerOmp\n"); // neighbor search. t4 = omp_get_wtime(); // --------------------------------------------------------- // times[COMPUTE_BLOCKS*run+0] = t1-t0; // Time for compute morton Z 3d hash times[COMPUTE_BLOCKS*run+1] = t2-t1; // Time for sorting the particles times[COMPUTE_BLOCKS*run+2] = t3-t2; // Time for setting up the interval hash tables times[COMPUTE_BLOCKS*run+3] = t4-t3; // Time for computing the SPH particle densities return 0; } /* * Function compute_density_3d_cll_innerOmp: * Computes the SPH density from the particles using cell linked list, * with parallelization at the level of the outer-most loop of the chunk * contribution calculation and vectorization in the inner-most loop. * * Arguments: * N <int> : Number of SPH particles to be used in the run * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * lsph <SPHparticle> : Array (pointer) of SPH particles to be updated * Returns: * 0 : error code returned * lsph <SPHparticle> : SPH particle array is updated in the rho field by reference */ int compute_density_3d_cll_innerOmp(int N, double h, SPHparticle *lsph, linkedListBox *box){ khiter_t kbegin,kend; int64_t node_hash=-1,node_begin=0, node_end=0; // Start initializing the node indexes on the array int64_t nb_begin= 0, nb_end = 0; // initialize the neighbor indexes int64_t nblist[(2*box->width+1)*(2*box->width+1)*(2*box->width+1)]; // prepare a list of potential neighbor hashes for (kbegin = kh_begin(box->hbegin); kbegin != kh_end(box->hbegin); kbegin++){ // Iterate over each receiver cell begin index if (kh_exist(box->hbegin, kbegin)){ // verify if that given iterator actually exists kend = kh_get(1, box->hend, kh_key(box->hbegin, kbegin)); // Then get the end of the receiver cell iterator node_hash = kh_key(box->hbegin, kbegin); // Then get the hash corresponding to it node_begin = kh_value(box->hbegin, kbegin); // Get the receiver cell begin index in the array node_end = kh_value(box->hend, kend); // Get the receiver cell end index in the array for(int64_t ii=node_begin;ii<node_end;ii+=1) // iterate over the receiver cell particles lsph[ii].rho = 0.0; // and initialize its densities to zero neighbour_hash_3d(node_hash,nblist,box->width,box); // then find the hashes of its neighbors for(int j=0;j<(2*box->width+1)*(2*box->width+1)*(2*box->width+1);j+=1){ // and the iterate over them if(nblist[j]>=0){ // if a given neighbor actually has particles nb_begin = kh_value(box->hbegin, kh_get(0, box->hbegin, nblist[j]) ); // then get the contributing cell begin index nb_end = kh_value(box->hend , kh_get(1, box->hend , nblist[j]) ); // and get the contributing cell end index compute_density_3d_chunk(node_begin,node_end,nb_begin,nb_end,h,lsph); // and compute the density contribution from } // the contributing cell to the receiver cell } } } return 0; } /* * Function compute_density_3d_chunk: * Computes the SPH density contribution for a pair of cells, from nb_ indexes * to the node_ indexes. The computation is performed in parallel at the * level of the node_ index, the outer-most, but with vectorization in * the inner-most loop. * * Arguments: * node_begin <int> : Begin index of the receiver cell * node_end <int> : End index of the receiver cell * nb_begin <int> : Begin index of the sender (neighbor) cell * nb_end <int> : End index of the sender (neighbor) cell * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * lsph <SPHparticle*> : Array (pointer) of SPH particles to be updated * Returns: * 0 : error code returned * lsph <SPHparticle*> : SPH particle array is updated in the rho field by reference */ int compute_density_3d_chunk(int64_t node_begin, int64_t node_end, int64_t nb_begin, int64_t nb_end,double h, SPHparticle *lsph) { const double inv_h = 1./h; const double kernel_constant = w_bspline_3d_constant(h); #pragma omp parallel for // Execute the outer loop in parallel for(int64_t ii=node_begin;ii<node_end;ii+=1){ // Iterate over the ii index of the chunk double xii = lsph[ii].r.x; // Load the X component of the ii particle position double yii = lsph[ii].r.y; // Load the Y component of the ii particle position double zii = lsph[ii].r.z; // Load the Z component of the ii particle position double rhoii = 0.0; // Initialize the chunk contribution to density #pragma omp simd // Hint at the compiler to vectorize for(int64_t jj=nb_begin;jj<nb_end;jj+=1){ // Iterate over the each other particle in jj loop double q = 0.; // Initialize the distance double xij = xii-lsph[jj].r.x; // Load and subtract jj particle's X position component double yij = yii-lsph[jj].r.y; // Load and subtract jj particle's Y position component double zij = zii-lsph[jj].r.z; // Load and subtract jj particle's Z position component q += xij*xij; // Add the jj contribution to the ii distance in X q += yij*yij; // Add the jj contribution to the ii distance in Y q += zij*zij; // Add the jj contribution to the ii distance in Z q = sqrt(q)*inv_h; // Sqrt to compute the distance rhoii += lsph[jj].nu*w_bspline_3d_simd(q); // Add up the contribution from the jj particle } // to the intermediary density and then lsph[ii].rho += kernel_constant*rhoii; // add the intermediary density to the full density } return 0; } /* * Function w_bspline_3d_constant: * Returns the 3d normalization constant for the cubic b-spline SPH smoothing kernel * * Arguments: * h <double> : Smoothing Length for the Smoothing Kernel w_bspline * Returns: * 3d bspline normalization density <double> */ double w_bspline_3d_constant(double h){ return 3./(2.*M_PI*h*h*h); // 3d normalization value for the b-spline kernel } /* * Function w_bspline_3d_simd: * Returns the un-normalized value of the cubic b-spline SPH smoothing kernel * * Arguments: * q <double> : Distance between particles normalized by the smoothing length h * Returns: * wq <double> : Unnormalized value of the kernel * * Observation: * Why not else if(q<2.)? * Because if you use "else if", the compiler refuses to vectorize, * This results in a large slowdown, as of 2.5x slower for example_04 */ #pragma omp declare simd double w_bspline_3d_simd(double q){ double wq=0; double wq1 = (0.6666666666666666 - q*q + 0.5*q*q*q); // The first polynomial of the spline double wq2 = 0.16666666666666666*(2.-q)*(2.-q)*(2.-q); // The second polynomial of the spline if(q<2.) // If the distance is below 2 wq = wq2; // Use the 2nd polynomial for the spline if(q<1.) // If the distance is below 1 wq = wq1; // Use the 1st polynomial for the spline return wq; // return which ever value corresponds to the distance }
GB_binop__bget_uint8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2022, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCUDA_DEV #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__bget_uint8) // A.*B function (eWiseMult): GB (_AemultB_08__bget_uint8) // A.*B function (eWiseMult): GB (_AemultB_02__bget_uint8) // A.*B function (eWiseMult): GB (_AemultB_04__bget_uint8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__bget_uint8) // A*D function (colscale): GB ((none)) // D*A function (rowscale): GB ((none)) // C+=B function (dense accum): GB (_Cdense_accumB__bget_uint8) // C+=b function (dense accum): GB (_Cdense_accumb__bget_uint8) // C+=A+B function (dense ewise3): GB ((none)) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__bget_uint8) // C=scalar+B GB (_bind1st__bget_uint8) // C=scalar+B' GB (_bind1st_tran__bget_uint8) // C=A+scalar GB (_bind2nd__bget_uint8) // C=A'+scalar GB (_bind2nd_tran__bget_uint8) // C type: uint8_t // A type: uint8_t // A pattern? 0 // B type: uint8_t // B pattern? 0 // BinaryOp: cij = GB_BITGET (aij, bij, uint8_t, 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_BITGET (x, y, uint8_t, 8) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 1 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_BGET || GxB_NO_UINT8 || GxB_NO_BGET_UINT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ #if 0 // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } #endif //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__bget_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__bget_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__bget_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 //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ #if 0 GrB_Info GB ((none)) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else uint8_t *restrict Cx = (uint8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } #endif //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__bget_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__bget_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__bget_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__bget_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__bget_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__bget_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_BITGET (x, bij, uint8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__bget_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_BITGET (aij, y, uint8_t, 8) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ uint8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_BITGET (x, aij, uint8_t, 8) ; \ } GrB_Info GB (_bind1st_tran__bget_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_BITGET (aij, y, uint8_t, 8) ; \ } GrB_Info GB (_bind2nd_tran__bget_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
matrix_op-inl.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2015 by Contributors * \file matrix_op-inl.h * \brief Function definition of matrix related operators */ #ifndef MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_ #define MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_ #include <mxnet/operator_util.h> #include <vector> #include <string> #include <algorithm> #include <utility> #include <type_traits> #include "../mshadow_op.h" #include "../elemwise_op_common.h" #include "../channel_op_common.h" #include "../mxnet_op.h" #include "broadcast_reduce_op.h" #include "./init_op.h" #include "../../common/static_array.h" #include "./slice-inl.h" #if MXNET_USE_CUDA #include <thrust/device_vector.h> #endif #ifdef __CUDACC__ #include "./pseudo2DTranspose_op-inl.cuh" #endif namespace mxnet { namespace op { struct ReshapeParam : public dmlc::Parameter<ReshapeParam> { mxnet::TShape target_shape; bool keep_highest; mxnet::Tuple<int> shape; bool reverse; DMLC_DECLARE_PARAMETER(ReshapeParam) { DMLC_DECLARE_FIELD(shape) .set_default(mxnet::Tuple<int>()) .describe("The target shape"); DMLC_DECLARE_FIELD(reverse) .set_default(false) .describe("If true then the special values are inferred from right to left"); DMLC_DECLARE_FIELD(target_shape) .set_default(mxnet::TShape(0, -1)) .describe("(Deprecated! Use ``shape`` instead.) " "Target new shape. One and only one dim can be 0, " "in which case it will be inferred from the rest of dims"); DMLC_DECLARE_FIELD(keep_highest).set_default(false) .describe("(Deprecated! Use ``shape`` instead.) Whether keep the highest dim unchanged." "If set to true, then the first dim in target_shape is ignored," "and always fixed as input"); } bool operator==(const ReshapeParam &other) const { return this->target_shape == other.target_shape && this->keep_highest == other.keep_highest && this->shape == other.shape && this->reverse == other.reverse; } }; template<typename IType> inline mxnet::TShape InferReshapeShape(const mxnet::Tuple<IType>& shape, const mxnet::TShape& dshape, bool reverse) { std::vector<IType> dshape_vec; std::vector<IType> param_shape_vec(shape.begin(), shape.end()); for (int i = 0; i < dshape.ndim(); ++i) { dshape_vec.push_back(dshape[i]); } std::vector<IType> tmp; size_t src_idx = 0; int inf_idx = -1; if (reverse) { std::reverse(dshape_vec.begin(), dshape_vec.end()); std::reverse(param_shape_vec.begin(), param_shape_vec.end()); } auto dshape_len = dshape_vec.size(); auto params_len = param_shape_vec.size(); for (size_t i = 0; i < params_len; ++i) { IType proposed_dim = param_shape_vec[i]; if (proposed_dim == 0) { // keep same CHECK_LT(src_idx, dshape_len); tmp.push_back(dshape_vec[src_idx++]); } else if (proposed_dim == -1) { // infer CHECK_LT(inf_idx, 0) << "One and only one dim can be inferred"; inf_idx = i; tmp.push_back(1); src_idx++; } else if (proposed_dim == -2) { // copy all remaining dims from source while (src_idx < dshape_len) { const int dn = dshape_vec[src_idx++]; tmp.push_back(dn); } } else if (proposed_dim == -3) { // merge two dims from source CHECK_LT(src_idx, dshape_len-1); const int d1 = dshape_vec[src_idx++]; const int d2 = dshape_vec[src_idx++]; if (!mxnet::dim_size_is_known(d1) || !mxnet::dim_size_is_known(d2)) { tmp.push_back(-1); } else { tmp.push_back(d1 * d2); } } else if (proposed_dim == -4) { // split the source dim s into two dims // read the left dim and then the right dim (either can be -1) CHECK_LT(i + 2, params_len); CHECK_LT(src_idx, dshape_len); const int d0 = dshape_vec[src_idx++]; IType d1 = param_shape_vec[++i]; IType d2 = param_shape_vec[++i]; CHECK(d1 != -1 || d2 != -1) << "Split dims cannot both be -1."; if (d1 == -1 && d0 >= 0) d1 = d0 / d2; // d0 must be known to do this if (d2 == -1 && d0 >= 0) d2 = d0 / d1; // d0 must be known to do this CHECK(d1 * d2 == static_cast<IType>(d0) || static_cast<IType>(d0) == IType(-1)) << "Split dims " << d1 << ", " << d2 << " do not divide original dim " << d0; tmp.push_back(d1); tmp.push_back(d2); } else { // greater than 0, new shape tmp.push_back(proposed_dim); src_idx++; } } if (inf_idx >= 0) { if (shape_is_known(dshape)) { IType new_size = 1; for (IType x : tmp) new_size *= x; tmp[inf_idx] = dshape.Size() / new_size; } else { tmp[inf_idx] = -1; } } if (reverse) { std::reverse(param_shape_vec.begin(), param_shape_vec.end()); std::reverse(dshape_vec.begin(), dshape_vec.end()); std::reverse(tmp.begin(), tmp.end()); } mxnet::TShape oshape(tmp.begin(), tmp.end()); return oshape; } inline bool ReverseReshapeInferShape(mxnet::TShape *in, const mxnet::TShape& out) { if (shape_is_known(*in) && shape_is_known(out)) { return true; } else if (!shape_is_known(out)) { return false; } else { int zero_axis = -1; int known_dim_size_prod = 1; for (int i = 0; i < in->ndim(); i++) { if (!mxnet::dim_size_is_known(*in, i)) { if (zero_axis != -1) return false; // more than 1 zero found. else zero_axis = i; } else { known_dim_size_prod *= (*in)[i]; } } (*in)[zero_axis] = out.Size() / known_dim_size_prod; return true; } } inline bool ReshapeShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const ReshapeParam& param_ = nnvm::get<ReshapeParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]"; CHECK_EQ(out_attrs->size(), 1U); mxnet::TShape &dshape = (*in_attrs)[0]; if (!mxnet::ndim_is_known(dshape)) return false; mxnet::TShape oshape; if (param_.shape.ndim() != 0) { oshape = InferReshapeShape(param_.shape, dshape, param_.reverse); } else if (param_.target_shape.ndim() != -1) { LOG(INFO) << "Using target_shape will be deprecated."; oshape = param_.target_shape; int neg_count = 0; index_t inf_idx = 0; index_t start_idx = param_.keep_highest ? 1 : 0; if (param_.keep_highest) { oshape[0] = dshape[0]; } for (int i = start_idx; i < oshape.ndim(); ++i) { if (oshape[i] == 0) { neg_count++; inf_idx = i; } } if (neg_count == 1) { oshape[inf_idx] = 1; oshape[inf_idx] = dshape.Size() / oshape.Size(); } } else { return shape_is_known((*out_attrs)[0]) && ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]); } ReverseReshapeInferShape(&dshape, oshape); #if 0 CHECK_EQ(oshape.Size(), dshape.Size()) << "Target shape size is different to source. " << "Target: " << oshape << "\nSource: " << dshape; #endif SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape); return ReverseReshapeInferShape(&(*in_attrs)[0], (*out_attrs)[0]); } inline bool FlattenShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]"; CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape &dshape = (*in_attrs)[0]; if (!shape_is_known(dshape)) return false; int target_dim = 1; for (int i = 1; i < dshape.ndim(); ++i) { target_dim *= dshape[i]; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, mshadow::Shape2(dshape[0], target_dim)); return true; } struct TransposeParam : public dmlc::Parameter<TransposeParam> { mxnet::TShape axes; DMLC_DECLARE_PARAMETER(TransposeParam) { DMLC_DECLARE_FIELD(axes).set_default(mxnet::TShape(0, -1)) .describe("Target axis order. By default the axes will be inverted."); } bool operator==(const TransposeParam &other) const { return this->axes == other.axes; } }; /*! * \brief This function performs transpose operation on a 2D matrix by utilizing the L1 cache * \param in input tensor * \param out output tensor * \param row shape of dim 0 of input * \param col shape of dim 1 of input * \tparam DType Data type * \tparam is_addto */ template<typename DType, bool is_addto> MSHADOW_XINLINE void Transpose2D(const DType *in, DType *out, index_t row, index_t col) { // ensure cache line hits and prevent cache miss for any configuration // L1 cache size to be utilized = 32kb = 2^15 // Largest size of a single unit of any dtype <= 8 byte = 2^3 // Number of elements - (2^15/2^3) = 2^12 // Block-size - 2^6 v 2^6 (64 v 64) // But we could leverage unrolling of for loops (for parallelization) // Block-size - 2^5 v 2^5 (32 v 32) with potential 4 pragma for loop unrolled // blocksize * blocksize * num_threads = cache_size / dtype_size // Instead of explicit unroll, let compiler figure out optimal unroll factor const index_t blocksize = 32; // collapse 2 parallelizes 2 for loops // inner 2 for loops aren't parallelized to prevent cache miss // Microsoft Visual C++ compiler does not support omp collapse #ifdef _MSC_VER #pragma omp parallel for #else #pragma omp parallel for collapse(2) #endif // _MSC_VER for (index_t i = 0; i < row; i += blocksize) { for (index_t j = 0; j < col; j += blocksize) { // transpose the block for (index_t a = j; (a < blocksize + j) && (a < col); ++a) { for (index_t b = i; (b < blocksize + i) && (b < row); ++b) { if (!is_addto) { out[a * row + b] = in[b * col + a]; } else { out[a * row + b] += in[b * col + a]; } } } } } } inline bool IsIdentityTranspose(const TShape& axes) { for (dim_t i = 0; i < axes.ndim(); i++) { if (axes[i] != i) return false; } return true; } template<typename xpu, bool is_addto = false> void TransposeImpl(RunContext ctx, const TBlob& src, const TBlob& ret, const mxnet::TShape& axes) { using namespace mshadow; using namespace mshadow::expr; CHECK_EQ(src.type_flag_, ret.type_flag_); // zero-size tensor, no need to compute if (src.shape_.Size() == 0U) return; Stream<xpu> *s = ctx.get_stream<xpu>(); #ifdef __CUDACC__ // This transpose can be used only if there exist n and m such that: // params = (0, ..., n-1, n+m, ..., params.size, n, ..., n+m-1) // Example: (0, 2, 3, 1) or (0, 3, 1, 2), but not (0, 2, 1, 3). if (isPseudo2DTranspose(axes)) { MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, { transpose_pseudo2D<DType, is_addto>(ret, src, axes, s); }); return; } #endif // Special handle the identity case if (IsIdentityTranspose(axes)) { MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, { Tensor<xpu, 1, DType> in = src.get_with_shape<xpu, 1, DType>(mshadow::Shape1(src.Size()), s); Tensor<xpu, 1, DType> out = ret.get_with_shape<xpu, 1, DType>(mshadow::Shape1(ret.Size()), s); if (!is_addto) { // Use memcpy to accelerate the speed Copy(out, in, s); } else { mxnet_op::Kernel<mxnet_op::op_with_req<mshadow_op::identity, kAddTo>, xpu>::Launch( s, ret.Size(), out.dptr_, in.dptr_); } }); return; } // Handle the general transpose case MSHADOW_TYPE_SWITCH(ret.type_flag_, DType, { switch (axes.ndim()) { case 2: { Tensor<xpu, 2, DType> in = src.get<xpu, 2, DType>(s); Tensor<xpu, 2, DType> out = ret.get<xpu, 2, DType>(s); if (ctx.get_ctx().dev_mask() == cpu::kDevMask) { Transpose2D<DType, is_addto>(in.dptr_, out.dptr_, in.shape_[0], in.shape_[1]); } else { LOG(FATAL) << "Not Implemented. We should never reach here because the 2D case " "in GPU has been covered by transpose_pseudo2D." " Report an issue in Github."; } break; } case 3: { Tensor<xpu, 3, DType> in = src.get<xpu, 3, DType>(s); Tensor<xpu, 3, DType> out = ret.get<xpu, 3, DType>(s); if (!is_addto) { out = transpose(in, axes.get<3>()); } else { out += transpose(in, axes.get<3>()); } break; } case 4: { Tensor<xpu, 4, DType> in = src.get<xpu, 4, DType>(s); Tensor<xpu, 4, DType> out = ret.get<xpu, 4, DType>(s); if (!is_addto) { out = transpose(in, axes.get<4>()); } else { out += transpose(in, axes.get<4>()); } break; } case 5: { Tensor<xpu, 5, DType> in = src.get<xpu, 5, DType>(s); Tensor<xpu, 5, DType> out = ret.get<xpu, 5, DType>(s); if (!is_addto) { out = transpose(in, axes.get<5>()); } else { out += transpose(in, axes.get<5>()); } break; } case 6: { Tensor<xpu, 6, DType> in = src.get<xpu, 6, DType>(s); Tensor<xpu, 6, DType> out = ret.get<xpu, 6, DType>(s); if (!is_addto) { out = transpose(in, axes.get<6>()); } else { out += transpose(in, axes.get<6>()); } break; } default: LOG(FATAL) << "Transpose support at most 6 dimensions"; break; } }); } // matrix transpose template<typename xpu> void Transpose(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { if (req[0] == kNullOp) { return; } const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed); CHECK(req[0] == kWriteTo || req[0] == kAddTo) << "Transpose only supports kNullOp, kWriteTo and kAddTo"; mxnet::TShape axes; if (param.axes.ndim() == 0) { axes = mxnet::TShape(inputs[0].ndim(), -1); for (int i = 0; i < axes.ndim(); ++i) { axes[i] = axes.ndim() - 1 - i; } } else { axes = common::CanonicalizeAxes(param.axes); } if (req[0] == kAddTo) { TransposeImpl<xpu, true>(ctx.run_ctx, inputs[0], outputs[0], axes); } else { TransposeImpl<xpu, false>(ctx.run_ctx, inputs[0], outputs[0], axes); } } inline bool TransposeShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const TransposeParam& param = nnvm::get<TransposeParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); mxnet::TShape& shp = (*in_attrs)[0]; mxnet::TShape& out_shp = (*out_attrs)[0]; CHECK_LE(shp.ndim(), 6) << "Transpose support at most 6 dimensions"; if (shp.ndim() == -1 && out_shp.ndim() == -1) return false; // none of the shapes is known if (out_shp.ndim() >= 0 && shp.ndim() >= 0) CHECK_EQ(out_shp.ndim(), shp.ndim()); mxnet::TShape get(std::max(shp.ndim(), out_shp.ndim()), -1); mxnet::TShape ret(std::max(shp.ndim(), out_shp.ndim()), -1); if (param.axes.ndim() == 0) { for (int i = 0; i < shp.ndim(); ++i) { ret[i] = shp[shp.ndim()-1-i]; } for (int i = 0; i < out_shp.ndim(); ++i) { get[shp.ndim()-1-i] = out_shp[i]; } } else { CHECK_EQ(std::max(shp.ndim(), out_shp.ndim()), param.axes.ndim()); for (int i = 0; i < shp.ndim(); ++i) { CHECK(param.axes[i] < static_cast<int64_t>(shp.ndim())); ret[i] = shp[param.axes[i]]; } for (int i = 0; i < out_shp.ndim(); ++i) { get[param.axes[i]] = out_shp[i]; } } SHAPE_ASSIGN_CHECK(*in_attrs, 0, get); SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret); return shape_is_known(ret); } struct ExpandDimParam : public dmlc::Parameter<ExpandDimParam> { int axis; DMLC_DECLARE_PARAMETER(ExpandDimParam) { DMLC_DECLARE_FIELD(axis) .describe("Position where new axis is to be inserted. Suppose that " "the input `NDArray`'s dimension is `ndim`, the range of " "the inserted axis is `[-ndim, ndim]`"); } bool operator==(const ExpandDimParam &other) const { return this->axis == other.axis; } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s; axis_s << axis; (*dict)["axis"] = axis_s.str(); } }; inline bool ExpandDimShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const ExpandDimParam& param = nnvm::get<ExpandDimParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); if (!mxnet::ndim_is_known(in_attrs->at(0)) && !mxnet::ndim_is_known(out_attrs->at(0))) { return false; } mxnet::TShape& ishape = (*in_attrs)[0]; mxnet::TShape& oshape = (*out_attrs)[0]; int indim = ishape.ndim(); bool unknown_ishape = false; if (-1 == indim) { indim = oshape.ndim() - 1; unknown_ishape = true; } int axis = param.axis; if (axis < 0) { axis += indim + 1; } CHECK(axis >= 0 && axis <= indim) << "axis must be in the range [" << -indim << ", " << indim << "] (" << param.axis << " provided)"; mxnet::TShape ret(indim + 1, -1); for (int i = 0; i < axis; ++i) { ret[i] = (unknown_ishape? -1 : ishape[i]); } ret[axis] = 1; for (int i = axis+1; i < indim+1; ++i) { ret[i] = (unknown_ishape? -1 : ishape[i-1]); } SHAPE_ASSIGN_CHECK(*out_attrs, 0, ret); ret = mxnet::TShape(indim, -1); for (int i = 0; i < axis; ++i) ret[i] = oshape[i]; for (int i = axis+1; i < indim+1; ++i) ret[i-1] = oshape[i]; SHAPE_ASSIGN_CHECK(*in_attrs, 0, ret); return shape_is_known(in_attrs->at(0)) && shape_is_known(out_attrs->at(0)); } // Currently MKLDNN only supports step = 1 or step has no value inline bool SupportMKLDNNSlice(const SliceParam& param) { if (param.step.ndim() == 0U) return true; for (int i = 0; i < param.step.ndim(); ++i) { if (param.step[i].has_value() && param.step[i].value() != 1) return false; } return true; } inline bool SliceForwardInferStorageType(const nnvm::NodeAttrs& attrs, const int dev_mask, DispatchMode* dispatch_mode, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1); CHECK_EQ(out_attrs->size(), 1); const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); const auto& in_stype = in_attrs->at(0); auto& out_stype = out_attrs->at(0); bool dispatched = false; const auto dispatch_ex = DispatchMode::kFComputeEx; // If step = 1, no need to fallback; otherwise fallback to dense bool trivial_step = false; if (param.step.ndim() == 0U) { trivial_step = true; } else if (param.step.ndim() == 1U && (!param.step[0].has_value() || param.step[0].value() == 1)) { trivial_step = true; } if (in_stype == kDefaultStorage) { #if MXNET_USE_MKLDNN == 1 if (dev_mask == Context::kCPU && MKLDNNEnvSet() && SupportMKLDNNSlice(param)) { dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode, dispatch_ex); } #endif if (!dispatched) { dispatched = storage_type_assign(&out_stype, kDefaultStorage, dispatch_mode, DispatchMode::kFCompute); } } if (!dispatched && in_stype == kCSRStorage && trivial_step) { dispatched = storage_type_assign(&out_stype, kCSRStorage, dispatch_mode, dispatch_ex); } if (!dispatched) { dispatched = dispatch_fallback(out_attrs, dispatch_mode); } return dispatched; } // slice the indptr of a csr struct SliceCsrIndPtr { template<typename IType> MSHADOW_XINLINE static void Map(int i, IType* out, const IType* in, const IType* base) { KERNEL_ASSIGN(out[i], kWriteTo, in[i] - *base); } }; /* * a wrapper to launch SliceCsrIndPtr kernel. * slice [src[begin] .. src[end]) and store in dst[0, end - begin) */ template<typename xpu, typename IType> void SliceCsrIndPtrImpl(const int begin, const int end, RunContext ctx, const IType* src, IType* dst) { using namespace mshadow; using namespace mxnet_op; Stream<xpu> *s = ctx.get_stream<xpu>(); int indptr_len = end - begin + 1; Kernel<SliceCsrIndPtr, xpu>::Launch(s, indptr_len, dst, src + begin, src + begin); } /* * Slice a CSR NDArray for first dimension */ template<typename xpu> void SliceDimOneCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx, const NDArray &in, const NDArray &out) { using namespace mshadow; using namespace mxnet_op; using namespace csr; nnvm::dim_t begin_row = begin[0]; nnvm::dim_t end_row = end[0]; nnvm::dim_t indptr_len = end_row - begin_row + 1; out.CheckAndAllocAuxData(kIndPtr, Shape1(indptr_len)); // assume idx indptr share the same type MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIndPtr), RType, { MSHADOW_IDX_TYPE_SWITCH(in.aux_type(kIdx), IType, { MSHADOW_TYPE_SWITCH(in.dtype(), DType, { RType* in_indptr = in.aux_data(kIndPtr).dptr<RType>(); RType* out_indptr = out.aux_data(kIndPtr).dptr<RType>(); SliceCsrIndPtrImpl<xpu, RType>(begin_row, end_row, ctx.run_ctx, in_indptr, out_indptr); Stream<xpu> *s = ctx.get_stream<xpu>(); RType nnz = 0; mshadow::Copy(Tensor<cpu, 1, RType>(&nnz, Shape1(1)), Tensor<xpu, 1, RType>(out_indptr + indptr_len - 1, Shape1(1), s)); // return csr zeros if nnz = 0 if (nnz == 0) { out.set_aux_shape(kIdx, Shape1(0)); return; } // copy indices and values out.CheckAndAllocAuxData(kIdx, Shape1(nnz)); out.CheckAndAllocData(Shape1(nnz)); IType* in_idx = in.aux_data(kIdx).dptr<IType>(); IType* out_idx = out.aux_data(kIdx).dptr<IType>(); DType* in_data = in.data().dptr<DType>(); DType* out_data = out.data().dptr<DType>(); RType offset = 0; mshadow::Copy(Tensor<cpu, 1, RType>(&offset, Shape1(1)), Tensor<xpu, 1, RType>(in_indptr + begin_row, Shape1(1), s)); mshadow::Copy(Tensor<xpu, 1, IType>(out_idx, Shape1(nnz), s), Tensor<xpu, 1, IType>(in_idx + offset, Shape1(nnz), s), s); mshadow::Copy(Tensor<xpu, 1, DType>(out_data, Shape1(nnz), s), Tensor<xpu, 1, DType>(in_data + offset, Shape1(nnz), s), s); }); }); }); } /*! * \brief slice a CSRNDArray for two dimensions */ struct SliceDimTwoCsrAssign { /*! * \brief This function slices a CSRNDArray on axis one between begin_col and end_col * \param i loop index * \param out_idx output csr ndarray column indices * \param out_data output csr ndarray data * \param out_indptr output csr ndarray row index pointer * \param in_idx input csr ndarray column indices * \param in_data input csr ndarray data * \param in_indptr input csr ndarray row index pointer * \param begin_col begin column indice * \param end_col end column indice */ template<typename IType, typename RType, typename DType> MSHADOW_XINLINE static void Map(int i, IType* out_idx, DType* out_data, const RType* out_indptr, const IType* in_idx, const DType* in_data, const RType* in_indptr, const int begin_col, const int end_col) { RType ind = out_indptr[i]; for (RType j = in_indptr[i]; j < in_indptr[i+1]; j++) { // indices of CSRNDArray are in ascending order per row if (in_idx[j] >= end_col) { break; } else if (in_idx[j] >= begin_col) { out_idx[ind] = in_idx[j] - begin_col; out_data[ind] = in_data[j]; ind++; } } } }; /* * Slice a CSR NDArray for two dimensions */ template<typename xpu> void SliceDimTwoCsrImpl(const mxnet::TShape &begin, const mxnet::TShape &end, const OpContext& ctx, const NDArray &in, const NDArray &out); template<typename xpu> void SliceCsrImpl(const SliceParam &param, const OpContext& ctx, const NDArray &in, OpReqType req, const NDArray &out) { if (req == kNullOp) return; CHECK_NE(req, kAddTo) << "kAddTo for Slice on CSR input is not supported"; CHECK_NE(req, kWriteInplace) << "kWriteInplace for Slice on CSR input is not supported"; const mxnet::TShape ishape = in.shape(); const mxnet::TShape oshape = out.shape(); int N = ishape.ndim(); mxnet::TShape begin(N, -1), end(N, -1); for (int i = 0; i < N; ++i) { int s = 0; if (i < param.begin.ndim() && param.begin[i]) { s = *param.begin[i]; if (s < 0) s += ishape[i]; } begin[i] = s; end[i] = s + oshape[i]; } switch (N) { case 1: { SliceDimOneCsrImpl<xpu>(begin, end, ctx, in, out); break; } case 2: { SliceDimTwoCsrImpl<xpu>(begin, end, ctx, in, out); break; } default: LOG(FATAL) << "CSR is only for 2-D shape"; break; } } template<typename xpu> void SliceEx(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(), 1); CHECK_EQ(outputs.size(), 1); const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); auto in_stype = inputs[0].storage_type(); if (in_stype == kCSRStorage) { SliceCsrImpl<xpu>(param, ctx, inputs[0], req[0], outputs[0]); } else { LOG(FATAL) << "Slice not implemented for storage type" << in_stype; } } template<int ndim> inline bool GetIndexRange(const mxnet::TShape& dshape, const mxnet::Tuple<dmlc::optional<index_t>>& param_begin, const mxnet::Tuple<dmlc::optional<index_t>>& param_end, const mxnet::Tuple<dmlc::optional<index_t>>& param_step, common::StaticArray<index_t, ndim>* begin, common::StaticArray<index_t, ndim>* end, common::StaticArray<index_t, ndim>* step) { // Function returns false if output is zero-sized, true otherwise. bool zero_size_shape = false; CHECK_NE(dshape.ndim(), 0U); CHECK_LE(param_begin.ndim(), dshape.ndim()) << "Slicing axis exceeds data dimensions"; CHECK_LE(param_end.ndim(), dshape.ndim()) << "Slicing axis exceeds data dimensions"; CHECK_EQ(param_begin.ndim(), param_end.ndim()) << "begin and end must have the same length"; CHECK_EQ(ndim, dshape.ndim()) << "Static array size=" << ndim << " is not equal to data shape ndim=" << dshape.ndim(); if (param_step.ndim() > 0) { CHECK_EQ(param_step.ndim(), param_begin.ndim()) << "step and begin must have the same length"; } for (int i = 0; i < param_begin.ndim(); ++i) { index_t s = param_step.ndim() > 0 && param_step[i].has_value() ? param_step[i].value() : 1; CHECK_NE(s, 0) << "slice op step[" << i << "] cannot be 0"; index_t b = 0, e = 0; const index_t len = dshape[i]; if (len > 0) { b = param_begin[i].has_value() ? param_begin[i].value() : (s < 0 ? len - 1 : 0); e = param_end[i].has_value() ? param_end[i].value() : (s < 0 ? -1 : len); if (b < 0) { b += len; } if (e < 0 && param_end[i].has_value()) { e += len; } // move the begin and end to correct position for calculating dim size b = (b < 0 && s > 0) ? 0 : b; b = (b > len - 1 && s < 0) ? len - 1 : b; // if the start value lead to empty tensor under step s, use -1 for indication b = (b < 0 || b > len - 1) ? -1 : b; e = e > -1 ? e : -1; e = e > len ? len : e; } else if (len == 0) { b = 0; e = 0; } (*begin)[i] = b; (*end)[i] = e; (*step)[i] = s; // checking begin==end if (b == e) { zero_size_shape = true; } } for (int i = param_begin.ndim(); i < dshape.ndim(); ++i) { (*begin)[i] = 0; (*end)[i] = dshape[i]; (*step)[i] = 1; } return zero_size_shape; } inline void SetSliceOpOutputDimSize(const mxnet::TShape& dshape, const index_t i, const index_t b, const index_t e, const index_t s, mxnet::TShape* oshape) { if (!mxnet::dim_size_is_known(dshape, i)) { (*oshape)[i] = -1; return; } if (e != b && b >= 0) { if (s > 0) { (*oshape)[i] = e > b ? (e - b - 1) / s + 1 : 0; } else { (*oshape)[i] = e < b ? (b - e - 1) / (-s) + 1 : 0; } } else { (*oshape)[i] = 0; } } inline bool SliceOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape& dshape = (*in_attrs)[0]; if (!mxnet::ndim_is_known(dshape)) return false; CHECK_GT(dshape.ndim(), 0) << "slice only works for ndim > 0"; const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); mxnet::TShape oshape = dshape; MXNET_NDIM_SWITCH(dshape.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step); for (int i = 0; i < param.begin.ndim(); ++i) { const index_t b = begin[i], e = end[i], s = step[i]; SetSliceOpOutputDimSize(dshape, i, b, e, s, &oshape); } }) SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape); return shape_is_known(dshape) && shape_is_known(oshape); } template<int ndim, int req, typename xpu> struct slice_forward; template<int ndim, int req> struct slice_forward<ndim, req, gpu> { // i is the i-th row after flattening out into 2D tensor template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data, const mshadow::Shape<ndim> dshape, const mshadow::Shape<ndim> oshape, const common::StaticArray<index_t, ndim> begin, const common::StaticArray<index_t, ndim> step) { const index_t data_last_dim_size = dshape[ndim-1]; const index_t out_last_dim_size = oshape[ndim-1]; const index_t step_last_dim = step[ndim-1]; const index_t begin_last_dim = begin[ndim-1]; const index_t j = i % out_last_dim_size; index_t irow = 0; // row id of flattend 2D data index_t stride = 1; index_t idx = i / out_last_dim_size; #pragma unroll for (int k = ndim - 2; k >= 0; --k) { irow += stride * ((idx % oshape[k]) * step[k] + begin[k]); idx /= oshape[k]; stride *= dshape[k]; } KERNEL_ASSIGN(out[i], req, data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]); } }; template<int ndim, int req> struct slice_forward<ndim, req, cpu> { // i is the i-th row after flattening out into 2D tensor template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* data, const mshadow::Shape<ndim> dshape, const mshadow::Shape<ndim> oshape, const common::StaticArray<index_t, ndim> begin, const common::StaticArray<index_t, ndim> step) { const index_t data_last_dim_size = dshape[ndim-1]; const index_t out_last_dim_size = oshape[ndim-1]; const index_t step_last_dim = step[ndim-1]; const index_t begin_last_dim = begin[ndim-1]; index_t out_offset = i * out_last_dim_size; for (index_t j = 0; j < out_last_dim_size; ++j) { index_t irow = 0; // row id of flattend 2D data index_t stride = 1; index_t idx = i; #pragma unroll for (int k = ndim - 2; k >= 0; --k) { irow += stride * ((idx % oshape[k]) * step[k] + begin[k]); idx /= oshape[k]; stride *= dshape[k]; } KERNEL_ASSIGN(out[out_offset++], req, data[irow * data_last_dim_size + j * step_last_dim + begin_last_dim]); } } }; template<typename xpu> void SliceOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); if (req[0] == kNullOp) return; using namespace mshadow; Stream<xpu>* s = ctx.get_stream<xpu>(); const TBlob& data = inputs[0]; const TBlob& out = outputs[0]; if (out.Size() == 0) return; const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); MXNET_NDIM_SWITCH(data.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(data.shape_, param.begin, param.end, param.step, &begin, &end, &step); MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { size_t num_threads = out.shape_.FlatTo2D()[0]; if (std::is_same<xpu, gpu>::value) { num_threads *= out.shape_.get<ndim>()[ndim - 1]; } mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s, num_threads, out.dptr<DType>(), data.dptr<DType>(), data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step); }) }) }) } template<int ndim, int req, typename xpu> struct slice_assign; template<int ndim, int req> struct slice_assign<ndim, req, cpu> { // i is the i-th row after flattening out into 2D tensor template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val, const mshadow::Shape<ndim> oshape, const mshadow::Shape<ndim> vshape, const common::StaticArray<index_t, ndim> begin, const common::StaticArray<index_t, ndim> step) { const index_t data_last_dim_size = oshape[ndim-1]; const index_t out_last_dim_size = vshape[ndim-1]; const index_t step_last_dim = step[ndim-1]; const index_t begin_last_dim = begin[ndim-1]; index_t offset = i * out_last_dim_size; for (index_t j = 0; j < out_last_dim_size; ++j) { index_t irow = 0; // row id of flattend 2D out index_t stride = 1; index_t idx = i; #pragma unroll for (int k = ndim - 2; k >= 0; --k) { irow += stride * ((idx % vshape[k]) * step[k] + begin[k]); idx /= vshape[k]; stride *= oshape[k]; } KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim], req, val[offset++]); } } }; template<int ndim, int req> struct slice_assign<ndim, req, gpu> { // i is the i-th row after flattening out into 2D tensor template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* val, const mshadow::Shape<ndim> oshape, const mshadow::Shape<ndim> vshape, const common::StaticArray<index_t, ndim> begin, const common::StaticArray<index_t, ndim> step) { const index_t data_last_dim_size = oshape[ndim-1]; const index_t out_last_dim_size = vshape[ndim-1]; const index_t step_last_dim = step[ndim-1]; const index_t begin_last_dim = begin[ndim-1]; const index_t j = i % out_last_dim_size; index_t irow = 0; // row id of flattend 2D out index_t stride = 1; index_t idx = i / out_last_dim_size; #pragma unroll for (int k = ndim - 2; k >= 0; --k) { irow += stride * ((idx % vshape[k]) * step[k] + begin[k]); idx /= vshape[k]; stride *= oshape[k]; } KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim], req, val[i]); } }; template<typename xpu> void SliceOpBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); if (req[0] == kNullOp) return; using namespace mshadow; Stream<xpu>* s = ctx.get_stream<xpu>(); const TBlob& ograd = inputs[0]; const TBlob& igrad = outputs[0]; const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); if (req[0] == kWriteTo) { Fill(s, igrad, req[0], 0); } else if (req[0] == kWriteInplace) { LOG(FATAL) << "_slice_backward does not support kWriteInplace"; } if (ograd.Size() == 0) return; MXNET_NDIM_SWITCH(ograd.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(igrad.shape_, param.begin, param.end, param.step, &begin, &end, &step); MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { int num_threads = ograd.shape_.FlatTo2D()[0]; if (std::is_same<xpu, gpu>::value) { num_threads *= ograd.shape_.get<ndim>()[ndim - 1]; } mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads, igrad.dptr<DType>(), ograd.dptr<DType>(), igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step); }) }) }) } inline bool SliceAssignOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 2U); CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape& dshape = (*in_attrs)[0]; if (!mxnet::ndim_is_known(dshape)) return false; mxnet::TShape vshape = dshape; // vshape is the value shape on the right hand side const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); MXNET_NDIM_SWITCH(dshape.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(dshape, param.begin, param.end, param.step, &begin, &end, &step); for (int i = 0; i < param.begin.ndim(); ++i) { const int b = begin[i], e = end[i], s = step[i]; SetSliceOpOutputDimSize(dshape, i, b, e, s, &vshape); } }) SHAPE_ASSIGN_CHECK(*in_attrs, 1, vshape); SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape); return true; } template<typename xpu> void SliceAssignOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; CHECK_EQ(inputs.size(), 2U); // data[index] = val, data and val are two inputs CHECK_EQ(outputs.size(), 1U); if (req[0] == kNullOp) return; Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& data = inputs[0]; const TBlob& val = inputs[1]; const TBlob& out = outputs[0]; if (req[0] == kWriteTo) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s); Copy(out, in, s); }); } else if (req[0] != kWriteInplace) { LOG(FATAL) << "_slice_assign only supports kWriteTo and kWriteInplace"; } const SliceParam& param = nnvm::get<SliceParam>(attrs.parsed); MXNET_NDIM_SWITCH(data.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step, &begin, &end, &step); if (zero_size_shape) { return; // slice_assign of zero-sized subspace needs no operation. } MSHADOW_TYPE_SWITCH(out.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { int num_threads = val.shape_.FlatTo2D()[0]; if (std::is_same<xpu, gpu>::value) { num_threads *= val.shape_.get<ndim>()[ndim - 1]; } mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads, out.dptr<DType>(), val.dptr<DType>(), out.shape_.get<ndim>(), val.shape_.get<ndim>(), begin, step); }) }) }) } struct SliceAssignScalarParam : public dmlc::Parameter<SliceAssignScalarParam> { double scalar; mxnet::Tuple<dmlc::optional<index_t>> begin, end; mxnet::Tuple<dmlc::optional<index_t>> step; DMLC_DECLARE_PARAMETER(SliceAssignScalarParam) { DMLC_DECLARE_FIELD(scalar) .set_default(0) .describe("The scalar value for assignment."); DMLC_DECLARE_FIELD(begin) .describe("starting indices for the slice operation, supports negative indices."); DMLC_DECLARE_FIELD(end) .describe("ending indices for the slice operation, supports negative indices."); DMLC_DECLARE_FIELD(step) .set_default(mxnet::Tuple<dmlc::optional<index_t>>()) .describe("step for the slice operation, supports negative values."); } }; inline bool SliceAssignScalarOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape& dshape = (*in_attrs)[0]; if (!shape_is_known(dshape)) return false; SHAPE_ASSIGN_CHECK(*out_attrs, 0, dshape); return true; } template<int ndim> struct slice_assign_scalar { // i is the i-th row after flattening out into 2D tensor template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType val, const OpReqType req, const mshadow::Shape<ndim> oshape, const mshadow::Shape<ndim> vshape, const common::StaticArray<index_t, ndim> begin, const common::StaticArray<index_t, ndim> step) { const index_t data_last_dim_size = oshape[ndim-1]; const index_t out_last_dim_size = vshape[ndim-1]; const index_t step_last_dim = step[ndim-1]; const index_t begin_last_dim = begin[ndim-1]; for (index_t j = 0; j < out_last_dim_size; ++j) { index_t irow = 0; // row id of flattend 2D out index_t stride = 1; index_t idx = i; #pragma unroll for (int k = ndim - 2; k >= 0; --k) { irow += stride * ((idx % vshape[k]) * step[k] + begin[k]); idx /= vshape[k]; stride *= oshape[k]; } KERNEL_ASSIGN(out[irow * data_last_dim_size + j * step_last_dim + begin_last_dim], req, val); } } }; template<typename xpu> void SliceAssignScalarOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); using namespace mshadow; Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& data = inputs[0]; const TBlob& out = outputs[0]; if (req[0] == kWriteTo) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Tensor<xpu, 1, DType> in = inputs[0].FlatTo1D<xpu, DType>(s); Tensor<xpu, 1, DType> out = outputs[0].FlatTo1D<xpu, DType>(s); Copy(out, in, s); }); } else if (req[0] != kWriteInplace) { LOG(FATAL) << "_crop_assign_scalar only supports kWriteTo and kWriteInplace"; } mxnet::TShape vshape = data.shape_; const SliceAssignScalarParam& param = nnvm::get<SliceAssignScalarParam>(attrs.parsed); MXNET_NDIM_SWITCH(data.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; bool zero_size_shape = GetIndexRange(data.shape_, param.begin, param.end, param.step, &begin, &end, &step); if (zero_size_shape) { return; // slice_assign of zero-sized subspaced needs no operation. } for (index_t i = 0; i < param.begin.ndim(); ++i) { const int b = begin[i], e = end[i], s = step[i]; SetSliceOpOutputDimSize(data.shape_, i, b, e, s, &vshape); } MSHADOW_TYPE_SWITCH_WITH_BOOL(out.type_flag_, DType, { mxnet_op::Kernel<slice_assign_scalar<ndim>, xpu>::Launch(s, vshape.FlatTo2D()[0], out.dptr<DType>(), static_cast<DType>(param.scalar), req[0], out.shape_.get<ndim>(), vshape.get<ndim>(), begin, step); }) }) } struct SliceAxisParam : public dmlc::Parameter<SliceAxisParam> { int axis; index_t begin; dmlc::optional<index_t> end; DMLC_DECLARE_PARAMETER(SliceAxisParam) { DMLC_DECLARE_FIELD(axis) .describe("Axis along which to be sliced, supports negative indexes."); DMLC_DECLARE_FIELD(begin) .describe("The beginning index along the axis to be sliced, " " supports negative indexes."); DMLC_DECLARE_FIELD(end) .describe("The ending index along the axis to be sliced, " " supports negative indexes."); } }; inline void GetSliceAxisParams(const SliceAxisParam& param, const mxnet::TShape& ishape, int* axis, index_t* begin, index_t* end) { *axis = param.axis; if (*axis < 0) { *axis += ishape.ndim(); } CHECK(*axis < ishape.ndim() && *axis >= 0) << "Transformed axis must be smaller than the source ndim and larger than zero! Recieved axis=" << param.axis << ", src_ndim=" << ishape.ndim() << ", transformed axis=" << *axis; index_t axis_size = static_cast<index_t>(ishape[*axis]); *begin = param.begin; *end = -1; if (*begin < 0) { *begin += axis_size; } if (axis_size > 0) { if (!static_cast<bool>(param.end)) { *end = axis_size; } else { *end = param.end.value(); if (*end < 0) { *end += axis_size; } } CHECK(*end <= axis_size) << "Invalid end for end=" << *end << " as axis_size is " << axis_size; CHECK((*begin < *end)) << "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end; } else { *begin = 0; *end = 0; } CHECK(*end >= 0) << "Invalid begin, end, get begin=" << param.begin << ", end=" << param.end; CHECK(*begin >= 0) << "Invalid begin for begin=" << param.begin; } inline bool SliceAxisShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); mxnet::TShape& ishape = (*in_attrs)[0]; if (!mxnet::ndim_is_known(ishape)) return false; int axis; index_t begin, end; GetSliceAxisParams(param, ishape, &axis, &begin, &end); if (!mxnet::dim_size_is_known(ishape, axis)) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape); return false; } mxnet::TShape shape(ishape.ndim(), -1); for (int i = 0; i < ishape.ndim(); ++i) { if (i == axis) { shape[i] = static_cast<index_t>(end - begin); } else { shape[i] = ishape[i]; } } SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape); return shape_is_known(shape); } template<typename xpu> void SliceAxis(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow::expr; const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); int axis; index_t begin, end; GetSliceAxisParams(param, inputs[0].shape_, &axis, &begin, &end); int ndim = outputs[0].ndim(); if (axis + 1 == ndim) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { mshadow::Tensor<xpu, 2, DType> in = inputs[0].FlatTo2D<xpu, DType>(s); mshadow::Tensor<xpu, 2, DType> out = outputs[0].FlatTo2D<xpu, DType>(s); ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end)); }); } else { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { mshadow::Tensor<xpu, 3, DType> in = inputs[0].FlatTo3D<xpu, DType>(axis, s); mshadow::Tensor<xpu, 3, DType> out = outputs[0].FlatTo3D<xpu, DType>(axis, s); ASSIGN_DISPATCH(out, req[0], slice<1>(in, begin, end)); }); } } // Backward pass of broadcast over the given axis template<typename xpu> void SliceAxisGrad_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { if (outputs[0].shape_.Size() == 0) { return; } const SliceAxisParam& param = nnvm::get<SliceAxisParam>(attrs.parsed); using namespace mshadow::op; using namespace mshadow::expr; mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); int axis; index_t begin, end; GetSliceAxisParams(param, outputs[0].shape_, &axis, &begin, &end); int ndim = outputs[0].shape_.ndim(); if (axis + 1 == ndim) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { mshadow::Tensor<xpu, 2, DType> ograd = inputs[0].FlatTo2D<xpu, DType>(s); mshadow::Tensor<xpu, 2, DType> igrad = outputs[0].FlatTo2D<xpu, DType>(s); if (req[0] == kAddTo) { slice<1>(igrad, begin, end) += F<identity>(ograd); } else if (req[0] == kWriteTo) { igrad = 0.0f; slice<1>(igrad, begin, end) = F<identity>(ograd); } else { CHECK_EQ(req[0], kNullOp); } }); } else { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { mshadow::Tensor<xpu, 3, DType> ograd = inputs[0].FlatTo3D<xpu, DType>(axis, s); mshadow::Tensor<xpu, 3, DType> igrad = outputs[0].FlatTo3D<xpu, DType>(axis, s); if (req[0] == kAddTo) { slice<1>(igrad, begin, end) += F<identity>(ograd); } else if (req[0] == kWriteTo) { igrad = 0.0f; slice<1>(igrad, begin, end) = F<identity>(ograd); } else { CHECK_EQ(req[0], kNullOp); } }); } } struct SliceLikeParam : public dmlc::Parameter<SliceLikeParam> { mxnet::Tuple<int> axes; DMLC_DECLARE_PARAMETER(SliceLikeParam) { DMLC_DECLARE_FIELD(axes).set_default(mxnet::Tuple<int>()) .describe("List of axes on which input data will be sliced according to the " "corresponding size of the second input. By default will slice on " "all axes. Negative axes are supported."); } }; inline bool SliceLikeShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 2U); CHECK_EQ(out_attrs->size(), 1U); mxnet::TShape& ishape = (*in_attrs)[0]; mxnet::TShape& from_shape = (*in_attrs)[1]; if (param.axes.ndim() == 0) { CHECK_EQ(ishape.ndim(), from_shape.ndim()) << "By default slice_axis performs slice on all axes, but ndim mismatch " "for inputs: " << ishape.ndim() << " vs. " << from_shape.ndim(); for (int i = 0; i < ishape.ndim(); ++i) { CHECK_GE(ishape[i], from_shape[i]) << "Slice axis " << i << " with size " << from_shape[i] << "exceeds limit of input with size " << ishape[i]; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, from_shape); } else { mxnet::TShape shape(ishape); for (int i = 0; i < param.axes.ndim(); ++i) { int axis = param.axes[i]; if (axis < 0) { axis += ishape.ndim(); } CHECK_GE(axis, 0) << "Slice axis: " << param.axes[i] << " too small"; CHECK_GT(ishape.ndim(), axis) << "Slice axis: " << axis << " exceeds first input: " << ishape.ndim(); CHECK_GT(from_shape.ndim(), axis) << "Slice axis: " << axis << " exceeds second input: " << from_shape.ndim(); shape[axis] = from_shape[axis]; CHECK_GE(ishape[axis], from_shape[axis]) << "Slice axis " << axis << " with size " << from_shape[axis] << "exceeds limit of input with size " << ishape[axis]; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape); } return true; } inline void SliceLikeInferRanges(const mxnet::TShape& dshape, const mxnet::TShape& fshape, const mxnet::Tuple<int>& axes, mxnet::Tuple<dmlc::optional<index_t>>* param_begin, mxnet::Tuple<dmlc::optional<index_t>>* param_end, mxnet::Tuple<dmlc::optional<index_t>>* param_step) { std::vector<dmlc::optional<index_t>> pb(dshape.ndim()); std::vector<dmlc::optional<index_t>> pe(dshape.ndim()); std::vector<dmlc::optional<index_t>> ps(dshape.ndim()); if (axes.ndim() == 0) { for (int i = 0; i < dshape.ndim(); ++i) { pb[i] = 0; pe[i] = fshape[i]; ps[i] = 1; } } else { for (int i = 0; i < axes.ndim(); ++i) { int axis = axes[i]; if (axis < 0) { axis += dshape.ndim(); } CHECK_GE(axis, 0) << "Slice axis: " << axes[i] << " too small"; CHECK_LT(axis, dshape.ndim()) << "Slice axis: " << axis << " exceeds first input: " << dshape.ndim(); CHECK_LT(axis, fshape.ndim()) << "Slice axis: " << axis << " exceeds first input: " << fshape.ndim(); pb[axis] = 0; pe[axis] = fshape[axis]; ps[axis] = 1; } } *param_begin = mxnet::Tuple<dmlc::optional<index_t>>(pb.begin(), pb.end()); *param_end = mxnet::Tuple<dmlc::optional<index_t>>(pe.begin(), pe.end()); *param_step = mxnet::Tuple<dmlc::optional<index_t>>(ps.begin(), ps.end()); } template<typename xpu> void SliceLikeForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); using namespace mshadow::expr; const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& data = inputs[0]; const TBlob& out = outputs[0]; const mxnet::TShape& ishape = data.shape_; const mxnet::TShape& from_shape = inputs[1].shape_; mxnet::Tuple<dmlc::optional<index_t>> param_begin; mxnet::Tuple<dmlc::optional<index_t>> param_end; mxnet::Tuple<dmlc::optional<index_t>> param_step; SliceLikeInferRanges(ishape, from_shape, param.axes, &param_begin, &param_end, &param_step); MXNET_NDIM_SWITCH(data.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(data.shape_, param_begin, param_end, param_step, &begin, &end, &step); MSHADOW_TYPE_SWITCH(out.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { int num_threads = out.shape_.FlatTo2D()[0]; if (std::is_same<xpu, gpu>::value) { num_threads *= out.shape_.get<ndim>()[ndim - 1]; } mxnet_op::Kernel<slice_forward<ndim, Req, xpu>, xpu>::Launch(s, num_threads, out.dptr<DType>(), data.dptr<DType>(), data.shape_.get<ndim>(), out.shape_.get<ndim>(), begin, step); }) }) }) } template<typename xpu> void SliceLikeBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 2U); CHECK_EQ(req.size(), 2U); using namespace mshadow; Stream<xpu>* s = ctx.get_stream<xpu>(); if (req[1] != kNullOp && req[1] != kAddTo) { Fill(s, outputs[1], req[1], 0); // Second input not relavant to gradients. } if (req[0] == kNullOp) return; const TBlob& ograd = inputs[0]; const TBlob& igrad = outputs[0]; const SliceLikeParam& param = nnvm::get<SliceLikeParam>(attrs.parsed); if (req[0] == kWriteTo) { Fill(s, igrad, req[0], 0); } else if (req[0] == kWriteInplace) { LOG(FATAL) << "_slice_like_backward does not support kWriteInplace"; } const mxnet::TShape& ishape = ograd.shape_; const mxnet::TShape& from_shape = outputs[1].shape_; mxnet::Tuple<dmlc::optional<index_t>> param_begin; mxnet::Tuple<dmlc::optional<index_t>> param_end; mxnet::Tuple<dmlc::optional<index_t>> param_step; SliceLikeInferRanges(ishape, from_shape, param.axes, &param_begin, &param_end, &param_step); MXNET_NDIM_SWITCH(ograd.ndim(), ndim, { common::StaticArray<index_t, ndim> begin, end, step; GetIndexRange(ograd.shape_, param_begin, param_end, param_step, &begin, &end, &step); MSHADOW_TYPE_SWITCH(ograd.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { int num_threads = ograd.shape_.FlatTo2D()[0]; if (std::is_same<xpu, gpu>::value) { num_threads *= ograd.shape_.get<ndim>()[ndim - 1]; } mxnet_op::Kernel<slice_assign<ndim, Req, xpu>, xpu>::Launch(s, num_threads, igrad.dptr<DType>(), ograd.dptr<DType>(), igrad.shape_.get<ndim>(), ograd.shape_.get<ndim>(), begin, step); }) }) }) } struct ClipParam : public dmlc::Parameter<ClipParam> { real_t a_min, a_max; DMLC_DECLARE_PARAMETER(ClipParam) { DMLC_DECLARE_FIELD(a_min) .describe("Minimum value"); DMLC_DECLARE_FIELD(a_max) .describe("Maximum value"); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream a_min_s, a_max_s; a_min_s << a_min; a_max_s << a_max; (*dict)["a_min"] = a_min_s.str(); (*dict)["a_max"] = a_max_s.str(); } }; struct clip { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* datas, const float a_min, const float a_max) { DType data = datas[i]; if (data > a_max) { out[i] = a_max; } else if (data < a_min) { out[i] = a_min; } else { out[i] = data; } } }; struct clip_grad { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out, const DType* grad, const DType* datas, const float a_min, const float a_max) { DType data = datas[i]; if (data > a_max) { out[i] = 0; } else if (data < a_min) { out[i] = 0; } else { out[i] = grad[i]; } } }; template<typename xpu> void Clip(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed); CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_); Stream<xpu> *s = ctx.get_stream<xpu>(); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { mxnet_op::Kernel<mxnet::op::clip, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), param.a_min, param.a_max); }); } template<typename xpu> void ClipEx(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[0].dtype(), outputs[0].dtype()); CHECK_EQ(inputs[0].storage_type(), outputs[0].storage_type()); CHECK_NE(inputs[0].storage_type(), kDefaultStorage); UnaryOp::MapToFCompute<xpu>(attrs, ctx, inputs, req, outputs, Clip<xpu>); } template<typename xpu> void ClipGrad_(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mxnet_op; const ClipParam& param = nnvm::get<ClipParam>(attrs.parsed); CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_); Stream<xpu> *s = ctx.get_stream<xpu>(); MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Kernel<clip_grad, xpu>::Launch(s, outputs[0].Size(), outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>(), param.a_min, param.a_max); }); } /*! * \brief The parameters of the repeat operator include * the number of repeating time and axis (optional). * The parameters will be later used to deduce the * output ndarray shape in bool RepeatShape() function. */ struct RepeatParam : public dmlc::Parameter<RepeatParam> { int repeats = 1; dmlc::optional<int> axis; DMLC_DECLARE_PARAMETER(RepeatParam) { DMLC_DECLARE_FIELD(repeats) .describe("The number of repetitions for each element."); DMLC_DECLARE_FIELD(axis) .set_default(dmlc::optional<int>()) .describe("The axis along which to repeat values." " The negative numbers are interpreted counting from the backward." " By default, use the flattened input array," " and return a flat output array."); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream repeats_s, axis_s; repeats_s << repeats; axis_s << axis; (*dict)["repeats"] = repeats_s.str(); (*dict)["axis"] = axis_s.str(); } }; /*! * \brief Helper function for getting user input params for the operator repeat. * Sanity check the user input values. */ inline void GetRepeatParams(const RepeatParam& param, const mxnet::TShape& ishape, int* repeats, dmlc::optional<int>* axisOpt) { *repeats = param.repeats; CHECK_GE(*repeats, 0) << "repeats cannot be a negative number"; *axisOpt = param.axis; if (static_cast<bool>(*axisOpt)) { int ndims = ishape.ndim(); int axis = axisOpt->value(); if (axis < 0) { axis += ndims; } CHECK(axis >= 0 && axis < ndims) << "axis = " << axisOpt->value() << " out of bounds"; } } inline bool RepeatOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape& ishape = (*in_attrs)[0]; int repeats = 0; dmlc::optional<int> axisOpt; GetRepeatParams(param, ishape, &repeats, &axisOpt); // If 0 repeats, return an empty 1-dim, 0-size array if (0 == repeats) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(1, 0)); return true; } // If repeats > 0, multiply the size of the corresponding axis by repeats if (static_cast<bool>(axisOpt)) { int ndims = ishape.ndim(); int axis = axisOpt.value(); if (axis < 0) { axis += ndims; } mxnet::TShape shape(ishape.ndim(), -1); for (int i = 0; i < ishape.ndim(); ++i) { if (i == axis) { shape[i] = repeats * ishape[i]; } else { shape[i] = ishape[i]; } } SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape); } else { // If axis is not input by user, return a flat 1D array of size = in.size*repeats mxnet::TShape shape(1, ishape.Size() * repeats); SHAPE_ASSIGN_CHECK(*out_attrs, 0, shape); } return shape_is_known(out_attrs->at(0)); } inline bool RepeatOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); if ((*in_attrs)[0] != -1) { TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]); } else if ((*out_attrs)[0] != -1) { TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]); } return true; } /*! * \brief Reshape the input and output tensors for * using broadcast_to to achieve the funcitonality * of operator repeat. * \return a pair of mxnet::TShape's, first is the reshaped * input shape, second is the reshaped output shape. */ inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForRepeatOp( const mxnet::TShape& ishape, const dmlc::optional<int>& axisOpt, const int repeats) { if (static_cast<bool>(axisOpt)) { int axis = axisOpt.value(); int ndim = ishape.ndim(); if (axis < 0) { axis += ndim; } CHECK(axis >= 0 && axis < ishape.ndim()) << "Invalid input of axis"; // reshape the input tensor by adding a dim at the (axis+1)-th dim mxnet::TShape rshape(ishape.ndim()+1, 1); // the shape we want to broadcast to mxnet::TShape bshape(rshape.ndim(), 1); int i = 0; while (i <= axis) { rshape[i] = bshape[i] = ishape[i]; ++i; } rshape[i] = 1; bshape[i] = repeats; while (i < ishape.ndim()) { rshape[i+1] = ishape[i]; bshape[i+1] = ishape[i]; ++i; } return std::make_pair(rshape, bshape); } else { // axis is not input by user // reshape the tensor into shape (ishape.Size(), 1) // then add one dim at axis = 1 and broadcast to // shape (ishape.Size(), repeats) mxnet::TShape rshape(2, 1); rshape[0] = ishape.Size(); rshape[1] = 1; mxnet::TShape bshape(2, 1); bshape[0] = rshape[0]; bshape[1] = repeats; return std::make_pair(rshape, bshape); } } template<typename xpu> void RepeatOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { const TBlob& iTBlob = inputs[0]; const mxnet::TShape& ishape = iTBlob.shape_; if (!shape_is_known(ishape)) return; int repeats = 0; dmlc::optional<int> axisOpt; const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed); GetRepeatParams(param, ishape, &repeats, &axisOpt); if (0 == repeats) return; std::pair<mxnet::TShape, mxnet::TShape> rshapes = \ ReshapeInputOutputForRepeatOp(ishape, axisOpt, repeats); // reshaped input tblob TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(), inputs[0].type_flag_, inputs[0].dev_id()); std::vector<TBlob> newInputs = {iblob}; // reshaped output tblob TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(), outputs[0].type_flag_, outputs[0].dev_id()); std::vector<TBlob> newOutputs = {oblob}; BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs); } /*! * \brief Compute the gradient of the loss function * with respect to the input of the operator. * Backpropagation is employed to implement the * chain rule. * \param inputs the gradient of the loss function * with respect to the outputs of the operator * \param outputs the gradient of the loss function * with respect to the inputs of the operator */ template<typename xpu> void RepeatOpBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); const mxnet::TShape& oshape = outputs[0].shape_; if (!shape_is_known(oshape)) return; int repeats = 0; dmlc::optional<int> axisOpt; const RepeatParam& param = nnvm::get<RepeatParam>(attrs.parsed); GetRepeatParams(param, oshape, &repeats, &axisOpt); if (0 == repeats) return; std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForRepeatOp(oshape, axisOpt, repeats); // reshaped output grad tblob TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(), outputs[0].type_flag_, outputs[0].dev_id()); std::vector<TBlob> newOutputs = {oblob}; // reshaped input grad tblob TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(), inputs[0].type_flag_, inputs[0].dev_id()); std::vector<TBlob> newInputs = {iblob}; ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>( ctx, newInputs, req, newOutputs, rshapes.first); } struct TileParam : public dmlc::Parameter<TileParam> { mxnet::Tuple<int> reps; DMLC_DECLARE_PARAMETER(TileParam) { DMLC_DECLARE_FIELD(reps) .describe("The number of times for repeating the tensor a. Each dim size of reps" " must be a positive integer." " If reps has length d, the result will have dimension of max(d, a.ndim);" " If a.ndim < d, a is promoted to be d-dimensional by prepending new axes." " If a.ndim > d, reps is promoted to a.ndim by pre-pending 1's to it."); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream reps_s; reps_s << reps; (*dict)["reps"] = reps_s.str(); } }; inline bool TileOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); const TileParam& param = nnvm::get<TileParam>(attrs.parsed); const mxnet::TShape& ishape = (*in_attrs)[0]; if (!shape_is_known(ishape)) { return false; } const mxnet::Tuple<int>& reps = param.reps; // If reps is empty, return a identical input array if (reps.ndim() == 0) { SHAPE_ASSIGN_CHECK(*out_attrs, 0, ishape); return true; } mxnet::TShape oshape(std::max(ishape.ndim(), reps.ndim()), -1); int i1 = ishape.ndim() - 1; int i2 = reps.ndim() - 1; for (int i = oshape.ndim() - 1; i >= 0; --i) { if (i1 >= 0 && i2 >= 0) { oshape[i] = ishape[i1--] * reps[i2--]; } else if (i1 >= 0) { oshape[i] = ishape[i1--]; } else if (i2 >= 0) { oshape[i] = reps[i2--]; } } // If reps contains 0s, oshape is a zero-size shape. // Need to distinguish between np_shape mode and legacy mode. if (!Imperative::Get()->is_np_shape()) { common::ConvertToNumpyShape(&oshape); } SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape); return shape_is_known(oshape); } inline bool TileOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); if ((*in_attrs)[0] != -1) { TYPE_ASSIGN_CHECK(*out_attrs, 0, (*in_attrs)[0]); } else if ((*out_attrs)[0] != -1) { TYPE_ASSIGN_CHECK(*in_attrs, 0, (*out_attrs)[0]); } return true; } /*! * \brief Reshape the input and output tensors for * using broadcast_to to achieve the functionality * of operator tile. * \return a pair of mxnet::TShape's, first is the reshaped * input shape, second is the reshaped output shape. */ inline std::pair<mxnet::TShape, mxnet::TShape> ReshapeInputOutputForTileOp( const mxnet::TShape& ishape, const mxnet::Tuple<int>& reps) { if (reps.ndim() == 0) { return std::make_pair(ishape, ishape); } // The shape we want to broadcast to mxnet::TShape bshape(std::max(ishape.ndim(), reps.ndim()) * 2, 1); // The shape of the input tensor after adding new axes before each dim mxnet::TShape rshape(bshape.ndim(), 1); int i1 = ishape.ndim() - 1; int i2 = reps.ndim() - 1; for (int i = bshape.ndim() - 1; i >= 0; --i) { if (0 == (i & 1)) { bshape[i] = (i2 >= 0? reps[i2--] : 1); rshape[i] = 1; } else { rshape[i] = bshape[i] = (i1 >= 0? ishape[i1--] : 1); } } return std::make_pair(rshape, bshape); } /*! * \brief Implementation of tiling the input tensor a based * on the user-input shape, reps. * If a.ndim < reps.ndim, new axes are pre-pended to a. For example, * the input tensor has shape (3,), and the reps is (2, 4); the input * tensor would be reshaped to (1, 3). * If a.ndim > reps.ndim, pre-pending 1's to reps. For example, * the input tensor has shape (2, 3, 4, 5), and reps is (2, 2); * the reps would be changed to (1, 1, 2, 2). * Suppose we have a.ndim = reps.ndim now. To achieve tiling, * we utilize the operator broadcast_to. For example, for a tensor * of shape (2, 3, 4, 5) and reps (2, 8, 9, 3), we first reshape * the tensor to the shape (1, 2, 1, 3, 1, 4, 1, 5) by adding * one axis before each dimension. Then, we want to broadcast * the new tensor to shape (2, 2, 8, 3, 9, 4, 3, 5). The final * output tensor would have shape (2*2, 8*3, 9*4, 3*5). */ template<typename xpu> void TileOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); if (inputs[0].Size() == 0) return; const mxnet::TShape& ishape = inputs[0].shape_; const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps; // If any one of the number in reps is zero, return immediately for (int i = 0; i < reps.ndim(); ++i) { if (0 == reps[i]) return; } std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(ishape, reps); // reshaped input tblob TBlob iblob(inputs[0].dptr_, rshapes.first, inputs[0].dev_mask(), inputs[0].type_flag_, inputs[0].dev_id()); std::vector<TBlob> newInputs = {iblob}; // reshaped output tblob TBlob oblob(outputs[0].dptr_, rshapes.second, outputs[0].dev_mask(), outputs[0].type_flag_, outputs[0].dev_id()); std::vector<TBlob> newOutputs = {oblob}; BroadcastCompute<xpu>(attrs, ctx, newInputs, req, newOutputs); } /*! * \brief Compute the gradient of the loss function * with respect to the input of the operator. * Backpropagation is employed to implement the * chain rule. * \param inputs the gradient of the loss function * with respect to the outputs of the operator * \param outputs the gradient of the loss function * with respect to the inputs of the operator */ template<typename xpu> void TileOpBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); if (inputs[0].Size() == 0) return; const mxnet::TShape& oshape = outputs[0].shape_; const mxnet::Tuple<int>& reps = nnvm::get<TileParam>(attrs.parsed).reps; // If any one of the number in reps is zero, return immediately for (int i = 0; i < reps.ndim(); ++i) { if (0 == reps[i]) return; } std::pair<mxnet::TShape, mxnet::TShape> rshapes = ReshapeInputOutputForTileOp(oshape, reps); // reshaped output grad tblob TBlob oblob(outputs[0].dptr_, rshapes.first, outputs[0].dev_mask(), outputs[0].type_flag_, outputs[0].dev_id()); std::vector<TBlob> newOutputs = {oblob}; // reshaped input grad tblob TBlob iblob(inputs[0].dptr_, rshapes.second, inputs[0].dev_mask(), inputs[0].type_flag_, inputs[0].dev_id()); std::vector<TBlob> newInputs = {iblob}; ReduceAxesComputeImpl<xpu, mshadow::red::sum, false, false>( ctx, newInputs, req, newOutputs, rshapes.first); } struct ReverseParam : public dmlc::Parameter<ReverseParam> { mxnet::Tuple<int> axis; DMLC_DECLARE_PARAMETER(ReverseParam) { DMLC_DECLARE_FIELD(axis) .describe("The axis which to reverse elements."); } }; #define REVERSE_MAX_DIM 10U struct reverse { MSHADOW_XINLINE static index_t ReverseIndex(index_t idx, index_t nreversedim, const index_t * stride_, const index_t * trailing_) { index_t outputIndex = idx; for (index_t i = 0; i < nreversedim; ++i) { const index_t low = outputIndex % trailing_[i]; index_t high = outputIndex / trailing_[i]; const index_t x = high%stride_[i]; high /= stride_[i]; outputIndex = (high*stride_[i] + stride_[i] - 1 - x)*trailing_[i] + low; } return outputIndex; } #ifdef __CUDACC__ template<typename DType> __device__ static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst, const index_t * stride_, const index_t * trailing_) { __shared__ index_t stride_share[REVERSE_MAX_DIM]; __shared__ index_t trailing_share[REVERSE_MAX_DIM]; if (threadIdx.x < REVERSE_MAX_DIM) { stride_share[threadIdx.x] = stride_[threadIdx.x]; trailing_share[threadIdx.x] = trailing_[threadIdx.x]; } __syncthreads(); index_t new_idx = ReverseIndex(index, nreversedim, stride_share, trailing_share); dst[new_idx] = src[index]; } #else template<typename DType> MSHADOW_XINLINE static void Map(index_t index, index_t nreversedim, const DType *src, DType *dst, const index_t * stride_, const index_t * trailing_) { index_t new_idx = ReverseIndex(index, nreversedim, stride_, trailing_); dst[new_idx] = src[index]; } #endif }; template<typename xpu> void ReverseOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mxnet_op; const ReverseParam& param = nnvm::get<ReverseParam>(attrs.parsed); CHECK_EQ(inputs[0].type_flag_, outputs[0].type_flag_); CHECK_LT(param.axis.ndim(), REVERSE_MAX_DIM); Stream<xpu> *s = ctx.get_stream<xpu>(); const mxnet::TShape& ishape = inputs[0].shape_; std::vector<index_t> stride_(param.axis.ndim()); std::vector<index_t> trailing_(param.axis.ndim()); index_t reverse_index = 0; for (int axis : param.axis) { CHECK_LT(axis, ishape.ndim()); stride_[reverse_index] = ishape[axis]; trailing_[reverse_index] = 1; for (int i2 = axis + 1; i2 < ishape.ndim(); ++i2) { trailing_[reverse_index] *= ishape[i2]; } reverse_index++; } #ifdef __CUDACC__ mshadow::Tensor<xpu, 1, uint8_t> workspace = ctx.requested[0].get_space_typed<xpu, 1, uint8_t>( mshadow::Shape1(reverse_index * sizeof(index_t) * 2), s); auto stride_workspace = workspace.dptr_; auto trailing_workspace = workspace.dptr_ + reverse_index * sizeof(index_t); cudaMemcpyAsync(stride_workspace, thrust::raw_pointer_cast(stride_.data()), stride_.size() * sizeof(index_t), cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s)); cudaMemcpyAsync(trailing_workspace, thrust::raw_pointer_cast(trailing_.data()), trailing_.size() * sizeof(index_t), cudaMemcpyHostToDevice, mshadow::Stream<gpu>::GetStream(s)); #endif #ifdef __CUDACC__ MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index, inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), reinterpret_cast<index_t*>(stride_workspace), reinterpret_cast<index_t*>(trailing_workspace)); }); #else MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { Kernel<reverse, xpu>::Launch(s, inputs[0].Size(), reverse_index, inputs[0].dptr<DType>(), outputs[0].dptr<DType>(), stride_.data(), trailing_.data()); }); #endif } struct StackParam : public dmlc::Parameter<StackParam> { int axis; int num_args; DMLC_DECLARE_PARAMETER(StackParam) { DMLC_DECLARE_FIELD(axis) .set_default(0) .describe("The axis in the result array along which the input arrays are stacked."); DMLC_DECLARE_FIELD(num_args).set_lower_bound(1) .describe("Number of inputs to be stacked."); } }; inline bool StackOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const StackParam& param = dmlc::get<StackParam>(attrs.parsed); mxnet::TShape dshape; for (const mxnet::TShape& i : (*in_attrs)) { shape_assign(&dshape, i); } if (!shape_is_known(dshape)) return false; mxnet::TShape oshape(dshape.ndim() + 1, -1); int axis = CheckAxis(param.axis, oshape.ndim()); for (int i = 0; i < axis; ++i) { oshape[i] = dshape[i]; } oshape[axis] = param.num_args; for (index_t i = axis + 1; i < oshape.ndim(); ++i) { oshape[i] = dshape[i-1]; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, oshape); return shape_is_known(oshape); } template<typename xpu> void StackOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow::expr; const StackParam& param = dmlc::get<StackParam>(attrs.parsed); int axis = CheckAxis(param.axis, outputs[0].ndim()); Stream<xpu> *s = ctx.get_stream<xpu>(); MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, { std::vector<Tensor<xpu, 3, DType> > data(inputs.size()); Tensor<xpu, 3, DType> out; size_t leading = 1, trailing = 1; for (int i = 0; i < axis; ++i) { leading *= outputs[0].shape_[i]; } for (int i = axis + 1; i < outputs[0].ndim(); ++i) { trailing *= outputs[0].shape_[i]; } size_t mid = outputs[0].shape_[axis]; Shape<3> oshape = Shape3(leading, mid, trailing); out = outputs[0].get_with_shape<xpu, 3, DType>(oshape, s); for (size_t i = 0; i < inputs.size(); ++i) { Shape<3> dshape = Shape3(leading, 1, trailing); data[i] = inputs[i].get_with_shape<xpu, 3, DType>(dshape, s); } Concatenate(data, &out, 1, req[0]); }) } template<typename xpu> void StackOpBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow::expr; const StackParam& param = dmlc::get<StackParam>(attrs.parsed); int axis = CheckAxis(param.axis, inputs[0].ndim()); Stream<xpu> *s = ctx.get_stream<xpu>(); MSHADOW_TYPE_SWITCH_WITH_BOOL(inputs[0].type_flag_, DType, { std::vector<Tensor<xpu, 3, DType> > grad_in(outputs.size()); Tensor<xpu, 3, DType> grad; size_t leading = 1, trailing = 1; for (int i = 0; i < axis; ++i) { leading *= inputs[0].shape_[i]; } for (int i = axis + 1; i < inputs[0].ndim(); ++i) { trailing *= inputs[0].shape_[i]; } size_t mid = inputs[0].shape_[axis]; Shape<3> oshape = Shape3(leading, mid, trailing); grad = inputs[0].get_with_shape<xpu, 3, DType>(oshape, s); for (size_t i = 0; i < outputs.size(); ++i) { Shape<3> dshape = Shape3(leading, 1, trailing); grad_in[i] = outputs[i].get_with_shape<xpu, 3, DType>(dshape, s); } Split(grad, &grad_in, 1, req); }) } struct SqueezeParam : public dmlc::Parameter<SqueezeParam> { dmlc::optional<mxnet::Tuple<int>> axis; DMLC_DECLARE_PARAMETER(SqueezeParam) { DMLC_DECLARE_FIELD(axis) .set_default(dmlc::optional<mxnet::Tuple<int>>()) .describe("Selects a subset of the single-dimensional entries in the shape." " If an axis is selected with shape entry greater than one, an error is raised."); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream axis_s; axis_s << axis; (*dict)["axis"] = axis_s.str(); } }; // Given a shape that may have dim size equal to 0, // move all the zeros to the last of the shape array // and keep the relative order of the non-zero values. // Returns the new shape size after moving all zeros to the end. inline size_t SqueezeShapeHelper(mxnet::TShape* shape) { CHECK(shape != nullptr); size_t count = 0; for (int i = 0; i < shape->ndim(); ++i) { if ((*shape)[i] == -1) { ++count; } else { std::swap((*shape)[i], (*shape)[i-count]); } } return shape->ndim() - count; } inline bool SqueezeShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector *in_attrs, mxnet::ShapeVector *out_attrs) { const SqueezeParam& param = nnvm::get<SqueezeParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U) << "Input: [data]"; CHECK_EQ(out_attrs->size(), 1U); const mxnet::TShape& dshape = in_attrs->at(0); const int dndim = dshape.ndim(); if (!shape_is_known(dshape)) return false; mxnet::TShape oshape = dshape; if (param.axis.has_value()) { // preprocess axis mxnet::Tuple<int> axes = param.axis.value(); for (int i = 0; i < axes.ndim(); ++i) { if (axes[i] < 0) { axes[i] += dndim; CHECK_GE(axes[i], 0) << "axis " << axes[i] - dndim << " is out of bounds for array of dimension " << dndim; } CHECK_LT(axes[i], dndim) << "axis " << axes[i] << " is out of bounds for array of dimension " << dndim; CHECK_EQ(dshape[axes[i]], 1) << "cannot select an axis to squeeze out which has size=" << dshape[axes[i]] << " not equal to one"; CHECK_NE(oshape[axes[i]], -1) << "duplicate value in axis"; oshape[axes[i]] = -1; } } else { for (int i = 0; i < oshape.ndim(); ++i) { if (oshape[i] == 1) oshape[i] = -1; } } size_t oshape_size = SqueezeShapeHelper(&oshape); if (oshape_size == 0) { // corner case when dshape is (1, 1, 1, 1) oshape[0] = 1; oshape_size = 1; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, mxnet::TShape(oshape.data(), oshape.data()+oshape_size)); return true; } struct DepthToSpaceParam : public dmlc::Parameter<DepthToSpaceParam> { int block_size; DMLC_DECLARE_PARAMETER(DepthToSpaceParam) { DMLC_DECLARE_FIELD(block_size) .describe("Blocks of [block_size. block_size] are moved"); } }; inline bool DepthToSpaceOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Depth To Space requires exactly 4D tensor"; mxnet::TShape expected_out(4, -1); mxnet::TShape& in_shape = in_attrs->at(0); int block = param.block_size; CHECK_NE(block, 0) << "block_size must be a positive integer value"; CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0"; CHECK_EQ(in_shape[1] % (block * block), 0) << "Cannot perform Depth To Space operation on the specified tensor." " Dimension:1(depth dimension) should be a multiple of 'block^2'"; CHECK_NE(in_shape[0], 0) << "Operation requires a 4D tensor. Size of dimension:0 cannot be 0"; CHECK_NE(in_shape[2], 0) << "Operation requires a 4D tensor. Size of dimension:2 cannot be 0"; CHECK_NE(in_shape[3], 0) << "Operation requires a 4D tensor. Size of dimension:3 cannot be 0"; expected_out[0] = in_shape[0]; expected_out[1] = in_shape[1] / (block * block); int i = 2; while (i < expected_out.ndim()) { expected_out[i] = in_shape[i] * block; ++i; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out); return shape_is_known(expected_out); } inline bool DepthToSpaceOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return out_attrs->at(0) != -1; } /*! * \brief This function updates the value of input index from where the data element * needs to be fetched and written out to the ith location in output tensor * \param index_position index within offset array to get offset of given dimension * \param dim_size size of current dimension * \param idx output tensor index * \param inp_index index within input tensor from where value is retrieved * \param offset_arr array containing the linear offset of input tensor */ MSHADOW_XINLINE void update_index(index_t index_position, index_t dim_size, index_t *idx, index_t *inp_index, const index_t* offset_arr) { index_t next_idx_val = *idx / dim_size; *inp_index += (*idx - next_idx_val * dim_size) * offset_arr[index_position]; *idx = next_idx_val; } /*! * \brief This function performs the tensor transpose (0, 1, 2, 3, 4, 5) -> * (0, 3, 4, 1, 5, 2) by computing linear index within input tensor to be mapped * to the ith index of output tensor * \param i tensor index * \param out_data output tensor * \param in_data input tensor * \param block size of chunks to be moved out of depth dimension * \param size array containing the size of each dimension of input tensor * \param offset_arr array containing the linear offset of input tensor */ template<int req> struct depth_to_space_forward { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data, const int block, const index_t* size, const index_t* offset_arr) { index_t inp_index = 0, idx = i, dim_size; dim_size = block; update_index(2, dim_size, &idx, &inp_index, offset_arr); dim_size = size[3]; update_index(5, dim_size, &idx, &inp_index, offset_arr); dim_size = block; update_index(1, dim_size, &idx, &inp_index, offset_arr); dim_size = size[2]; update_index(4, dim_size, &idx, &inp_index, offset_arr); dim_size = size[1] / (block * block); update_index(3, dim_size, &idx, &inp_index, offset_arr); dim_size = size[0]; update_index(0, dim_size, &idx, &inp_index, offset_arr); KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]); } }; /*! * \brief This function calculates the linear offset for each dimension of * input tensor and stores them in an array, which is later used in * performing depth_to_space operation * \param i global thread id * \param offset_arr array to be populated with offset values * \param size array to be populated with size of each dimension of input tensor * \param block size of chunks to be moved out of depth dimension * \param size0 size of Dim 0 of input tensor * \param size1 size of Dim 1 of input tensor * \param size2 size of Dim 2 of input tensor * \param size3 size of Dim 3 of input tensor */ template<int req> struct compute_offset_for_depth_to_space { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block, const index_t size0, const index_t size1, const index_t size2, const index_t size3) { size[0] = size0; size[1] = size1; size[2] = size2; size[3] = size3; offset_arr[5] = 1; offset_arr[4] = offset_arr[5] * size[3]; offset_arr[3] = offset_arr[4] * size[2]; offset_arr[2] = offset_arr[3] * size[1] / (block * block); offset_arr[1] = offset_arr[2] * block; offset_arr[0] = offset_arr[1] * block; } }; template<typename xpu> void DepthToSpaceOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& in_data = inputs[0]; const TBlob& out_data = outputs[0]; const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed); using namespace mxnet_op; int block = param.block_size; mshadow::Tensor<xpu, 1, char> workspace = ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s); char* workspace_curr_ptr = workspace.dptr_; index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr); index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6); MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { Kernel<compute_offset_for_depth_to_space<req_type>, xpu>::Launch( s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1], in_data.shape_[2], in_data.shape_[3]); Kernel<depth_to_space_forward<req_type>, xpu>::Launch( s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(), block, size, offset_arr); }); }); } inline bool SpaceToDepthOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); CHECK_EQ(in_attrs->at(0).ndim(), 4) << "Operation Space To Depth requires exactly 4D tensor"; mxnet::TShape expected_out(in_attrs->at(0).ndim(), -1); mxnet::TShape& in_shape = in_attrs->at(0); int block = param.block_size; CHECK_NE(block, 0) << "block_size must be a positive integer value"; CHECK_NE(in_shape[0], 0) << "Operation requires a 4D tensor. Size of dimension:0 cannot be 0"; CHECK_NE(in_shape[1], 0) << "Depth dimension:1 cannot be 0"; CHECK_NE(in_shape[2], 0) << "Operation requires a 4D tensor. Size of dimension:2 cannot be 0"; CHECK_EQ(in_shape[2] % block, 0) << "Cannot perform Depth To Space operation on the specified tensor." " Dimension:2(1st Space dimension) should be a multiple of 'block' "; CHECK_NE(in_shape[3], 0) << "Operation requires a 4D tensor. Size of dimension:3 cannot be 0"; CHECK_EQ(in_shape[3] % block, 0) << "Cannot perform Depth To Space operation on the specified tensor." " Dimension:3(2nd space dimension) should be a multiple of 'block' "; expected_out[0] = in_shape[0]; expected_out[1] = in_shape[1] * block * block; int i = 2; while (i < expected_out.ndim()) { expected_out[i] = in_shape[i] / block; ++i; } SHAPE_ASSIGN_CHECK(*out_attrs, 0, expected_out); return shape_is_known(expected_out); } inline bool SpaceToDepthOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); CHECK_EQ(out_attrs->size(), 1U); TYPE_ASSIGN_CHECK(*out_attrs, 0, in_attrs->at(0)); TYPE_ASSIGN_CHECK(*in_attrs, 0, out_attrs->at(0)); return out_attrs->at(0) != -1; } /*! * \brief This function preforms the tensor transpose (0, 1, 2, 3, 4, 5) -> * (0, 3, 5, 1, 2, 4) by computing linear index within input tensor to be mapped * to the ith index of output tensor * \param i tensor index * \param out_data output tensor * \param in_data input tensor * \param block size of chunks to be moved out of depth dimension * \param size array containing the size of each dimension of input tensor * \param offset_arr array containing the linear offset of input tensor */ template<int req> struct space_to_depth_forward { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* out_data, const DType* in_data, const int block, const index_t* size, const index_t* offset_arr) { index_t inp_index = 0, idx = i, dim_size; dim_size = size[3] / block; update_index(4, dim_size, &idx, &inp_index, offset_arr); dim_size = size[2] / block; update_index(2, dim_size, &idx, &inp_index, offset_arr); dim_size = size[1]; update_index(1, dim_size, &idx, &inp_index, offset_arr); dim_size = block; update_index(5, dim_size, &idx, &inp_index, offset_arr); dim_size = block; update_index(3, dim_size, &idx, &inp_index, offset_arr); dim_size = size[0]; update_index(0, dim_size, &idx, &inp_index, offset_arr); KERNEL_ASSIGN(out_data[i], req, in_data[inp_index]); } }; /*! * \brief This function calculates the linear offset for each dimension of * input tensor and stores them in an array, which is later used in * performing space_to_depth operation * \param i global thread id * \param offset_arr array to be populated with offset values * \param size array to be populated with size of each dimension of input tensor * \param block size of chunks to be moved out of depth dimension * \param size0 size of Dim 0 of input tensor * \param size1 size of Dim 1 of input tensor * \param size2 size of Dim 2 of input tensor * \param size3 size of Dim 3 of input tensor */ template<int req> struct compute_offset_for_space_to_depth { template<typename DType> MSHADOW_XINLINE static void Map(index_t i, DType* offset_arr, DType* size, const int block, const index_t size0, const index_t size1, const index_t size2, const index_t size3) { size[0] = size0; size[1] = size1; size[2] = size2; size[3] = size3; offset_arr[5] = 1; offset_arr[4] = offset_arr[5] * block; offset_arr[3] = offset_arr[4] * size[3] / block; offset_arr[2] = offset_arr[3] * block; offset_arr[1] = offset_arr[2] * size[2] / block; offset_arr[0] = offset_arr[1] * size[1]; } }; template<typename xpu> void SpaceToDepthOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), 1U); CHECK_EQ(req.size(), 1U); mshadow::Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& in_data = inputs[0]; const TBlob& out_data = outputs[0]; const DepthToSpaceParam& param = nnvm::get<DepthToSpaceParam>(attrs.parsed); using namespace mxnet_op; int block = param.block_size; mshadow::Tensor<xpu, 1, char> workspace = ctx.requested[0].get_space_typed<xpu, 1, char>(mshadow::Shape1(sizeof(index_t) * 10), s); char* workspace_curr_ptr = workspace.dptr_; index_t* offset_arr = reinterpret_cast<index_t*>(workspace_curr_ptr); index_t* size = reinterpret_cast<index_t*>(workspace_curr_ptr + sizeof(index_t) * 6); MSHADOW_TYPE_SWITCH(out_data.type_flag_, DType, { MXNET_ASSIGN_REQ_SWITCH(req[0], req_type, { Kernel<compute_offset_for_space_to_depth<req_type>, xpu>::Launch( s, 1, offset_arr, size, block, in_data.shape_[0], in_data.shape_[1], in_data.shape_[2], in_data.shape_[3]); Kernel<space_to_depth_forward<req_type>, xpu>::Launch( s, out_data.Size(), out_data.dptr<DType>(), in_data.dptr<DType>(), block, size, offset_arr); }); }); } namespace split_enum { enum SplitOpInputs {kData}; } // namespace split_enum struct SplitParam : public dmlc::Parameter<SplitParam> { mxnet::TShape indices; int axis; bool squeeze_axis; int sections; DMLC_DECLARE_PARAMETER(SplitParam) { DMLC_DECLARE_FIELD(indices) .describe("Indices of splits. The elements should denote the boundaries of at which split" " is performed along the `axis`."); DMLC_DECLARE_FIELD(axis).set_default(1) .describe("Axis along which to split."); DMLC_DECLARE_FIELD(squeeze_axis).set_default(0) .describe("If true, Removes the axis with length 1 from the shapes of the output arrays." " **Note** that setting `squeeze_axis` to ``true`` removes axis with length 1" " only along the `axis` which it is split." " Also `squeeze_axis` can be set to ``true``" " only if ``input.shape[axis] == num_outputs``."); DMLC_DECLARE_FIELD(sections).set_default(0) .describe("Number of sections if equally splitted. Default to 0 which means split by indices."); } void SetAttrDict(std::unordered_map<std::string, std::string>* dict) { std::ostringstream indices_s, axis_s, squeeze_axis_s, sections_s; indices_s << indices; axis_s << axis; squeeze_axis_s << squeeze_axis; sections_s << sections; (*dict)["indices"] = indices_s.str(); (*dict)["axis"] = axis_s.str(); (*dict)["squeeze_axis"] = squeeze_axis_s.str(); (*dict)["sections"] = sections_s.str(); } }; // struct SplitParam inline mxnet::TShape GetSplitIndices(const mxnet::TShape& ishape, int axis, int sections) { mxnet::TShape indices(sections+1, -1); indices[0] = 0; int64_t section_size_b = (int64_t) (ishape[axis] / sections); int64_t section_size_a = section_size_b + 1; int section_a = ishape[axis] % sections; for (int i = 0; i < sections; ++i) { if ( i < section_a ) { indices[i+1] = section_size_a * (i + 1); } else { indices[i+1] = section_size_b + indices[i]; } } return indices; } inline bool SplitOpType(const nnvm::NodeAttrs& attrs, std::vector<int>* in_attrs, std::vector<int>* out_attrs) { CHECK_EQ(in_attrs->size(), 1U); int dtype = (*in_attrs)[0]; CHECK_NE(dtype, -1) << "First input must have specified type"; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); out_attrs->clear(); int num_outputs = (param.sections > 0) ? param.sections : param.indices.ndim(); for (int i = 0; i < num_outputs; ++i) { out_attrs->push_back(dtype); } return true; } inline bool SplitOpShapeImpl(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs, const int real_axis) { using namespace mshadow; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); mxnet::TShape dshape = in_attrs->at(split_enum::kData); mxnet::TShape ishape = in_attrs->at(split_enum::kData); const mxnet::TShape indices = (param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices; int num_outputs = (param.sections > 0) ? indices.ndim() - 1 : indices.ndim(); // Pre-compute squeezed output shape for future usage mxnet::TShape squeezed_dshape = dshape; for (int d = real_axis; d < squeezed_dshape.ndim() - 1; ++d) { squeezed_dshape[d] = squeezed_dshape[d+1]; } squeezed_dshape = mxnet::TShape(&squeezed_dshape[0], &squeezed_dshape[squeezed_dshape.ndim()-1]); // Assign shape to every output for (int i = 0; i < num_outputs; ++i) { int start = indices[i]; int end = (i < num_outputs - 1) ? indices[i + 1] : ishape[real_axis]; if (ishape[real_axis] == 0U) { end = start; } else { CHECK(start <= end) << "start " << start << " is not less than end " << end << "for subarray " << i; CHECK(end <= ishape[real_axis]) << "end " << end << " is no less than the size of the axis " << ishape[real_axis]; } dshape[real_axis] = (end - start); if (param.squeeze_axis) { CHECK_EQ(end - start, 1U) << "expected axis size of 1 but got " << end - start; SHAPE_ASSIGN_CHECK(*out_attrs, i, squeezed_dshape); } else { SHAPE_ASSIGN_CHECK(*out_attrs, i, dshape); } } mxnet::TShape back_calculate_dshape = ishape; back_calculate_dshape[real_axis] = 0; for (int d = 0; d < real_axis; ++d) { back_calculate_dshape[d] = (*out_attrs)[0][d]; } if (param.squeeze_axis) { back_calculate_dshape[real_axis] = num_outputs; } else { for (int i = 0; i < num_outputs; ++i) { back_calculate_dshape[real_axis] += (*out_attrs)[i][real_axis]; } } for (int d = real_axis + 1; d < ishape.ndim(); ++d) { if (param.squeeze_axis) { back_calculate_dshape[d] = (*out_attrs)[0][d - 1]; } else { back_calculate_dshape[d] = (*out_attrs)[0][d]; } } SHAPE_ASSIGN_CHECK(*in_attrs, split_enum::kData, back_calculate_dshape); return true; } inline bool SplitOpShape(const nnvm::NodeAttrs& attrs, mxnet::ShapeVector* in_attrs, mxnet::ShapeVector* out_attrs) { using namespace mshadow; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); CHECK_EQ(in_attrs->size(), 1U); mxnet::TShape dshape = in_attrs->at(split_enum::kData); if (!mxnet::ndim_is_known(dshape)) return false; if (param.axis >= 0) { CHECK_LT(param.axis, dshape.ndim()); } else { CHECK_LT(param.axis + dshape.ndim(), dshape.ndim()); } int real_axis = param.axis; if (real_axis < 0) { real_axis += dshape.ndim(); } return SplitOpShapeImpl(attrs, in_attrs, out_attrs, real_axis); } struct SplitKernel { /*! * \brief Map function for forward split_v2 operator * \param i global thread id * \param in_data ptr to input buffer * \param out_data ptr to ptr of outputs buffer * \param indices ptr to indices buffer * \param num_sections # of sections after split * \param axis_size size of axis to be splitted on * \param trailing_size step size within the data buffer of the axis to be splitted on */ template<typename DType> static MSHADOW_XINLINE void Map(size_t i, const DType *in_data, DType** out_data, const size_t* indices, const size_t num_sections, const size_t axis_size, const size_t trailing_size) { size_t idx = i / trailing_size % axis_size; size_t target = 0; for (size_t section = 0; section < num_sections && indices[section] <= idx; target = section++) {} DType* target_data = out_data[target]; const size_t mid_idx = idx - indices[target]; const size_t head_idx = i / (trailing_size * axis_size); const size_t tail_idx = i % trailing_size; const size_t section_size = indices[target + 1] - indices[target]; const size_t target_idx = head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx; target_data[target_idx] = in_data[i]; } }; struct ConcatenateKernel { /*! * \brief Map function for backward split_v2 operator * \param i global thread id * \param out_grad ptr to ptr of out grads buffer * \param in_grad ptr to input grad buffer * \param indices ptr to indices buffer * \param num_sections # of sections after split * \param axis_size size of axis to be splitted on * \param trailing_size step size within the data buffer of the axis to be splitted on */ template<typename DType> static MSHADOW_XINLINE void Map(size_t i, DType** out_grad, DType* in_grad, const size_t* indices, const size_t num_sections, const size_t axis_size, const size_t trailing_size) { size_t idx = i / trailing_size % axis_size; size_t src = 0; for (size_t section = 0; section < num_sections && indices[section] <= idx; src = section++) {} DType* src_grad = out_grad[src]; const size_t mid_idx = idx - indices[src]; const size_t head_idx = i / (trailing_size * axis_size); const size_t tail_idx = i % trailing_size; const size_t section_size = indices[src + 1] - indices[src]; const size_t src_idx = head_idx * trailing_size * section_size + mid_idx * trailing_size + tail_idx; in_grad[i] = src_grad[src_idx]; } }; template<typename xpu> inline void SplitOpForwardImpl(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const int real_axis) { using namespace mshadow; using namespace mshadow::expr; using namespace mxnet_op; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); Stream<xpu> *s = ctx.get_stream<xpu>(); const TBlob& input_data = inputs[split_enum::kData]; size_t leading = 1, trailing = 1; CHECK_LT(real_axis, input_data.ndim()); size_t mid = input_data.shape_[real_axis]; for (int i = 0; i < real_axis; ++i) { leading *= input_data.shape_[i]; } for (int i = real_axis + 1; i < input_data.ndim(); ++i) { trailing *= input_data.shape_[i]; } size_t workspace_size = 0; const mxnet::TShape& ishape = input_data.shape_; const mxnet::TShape split_pts = (param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices; std::vector<size_t> indices; for (const auto& section : split_pts) { indices.push_back(section); } if (param.sections == 0) { indices.push_back(ishape[real_axis]); } workspace_size += indices.size() * sizeof(size_t); MSHADOW_TYPE_SWITCH(input_data.type_flag_, DType, { std::vector<DType*> output_data; for (const TBlob& data : outputs) { output_data.push_back(data.dptr<DType>()); } workspace_size += output_data.size() * sizeof(DType*); Tensor<xpu, 1, char> workspace = ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s); Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size())); Tensor<xpu, 1, size_t> indices_xpu_tensor( reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size())); Tensor<cpu, 1, DType*> ptrs_cpu_tensor(output_data.data(), Shape1(output_data.size())); Tensor<xpu, 1, DType*> ptrs_xpu_tensor( reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)), Shape1(output_data.size())); mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s); mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s); Kernel<SplitKernel, xpu>::Launch( s, input_data.Size(), input_data.dptr<DType>(), ptrs_xpu_tensor.dptr_, indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing); }); } template<typename xpu> inline void SplitOpForward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow::expr; using namespace mxnet_op; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); CHECK_EQ(inputs.size(), 1U); CHECK_EQ(outputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim()); const TBlob& input_data = inputs[split_enum::kData]; int real_axis = param.axis; if (real_axis < 0) { real_axis += input_data.ndim(); } SplitOpForwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis); } template<typename xpu> inline void SplitOpBackwardImpl(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs, const int real_axis) { using namespace mshadow; using namespace mshadow::expr; using namespace mxnet_op; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); Stream<xpu> *s = ctx.get_stream<xpu>(); TBlob input_grad = outputs[split_enum::kData]; size_t leading = 1, trailing = 1; CHECK_LT(real_axis, input_grad.ndim()); size_t mid = input_grad.shape_[real_axis]; for (int i = 0; i < real_axis; ++i) { leading *= input_grad.shape_[i]; } for (int i = real_axis + 1; i < input_grad.ndim(); ++i) { trailing *= input_grad.shape_[i]; } size_t workspace_size = 0; const mxnet::TShape& ishape = input_grad.shape_; const mxnet::TShape split_pts = (param.sections > 0) ? GetSplitIndices(ishape, real_axis, param.sections) : param.indices; std::vector<size_t> indices; for (const auto& section : split_pts) { indices.push_back(section); } if (param.sections == 0) { indices.push_back(ishape[real_axis]); } workspace_size += indices.size() * sizeof(size_t); MSHADOW_TYPE_SWITCH(input_grad.type_flag_, DType, { std::vector<DType*> out_grads; for (const TBlob& output_grad : inputs) { out_grads.push_back(output_grad.dptr<DType>()); } workspace_size += out_grads.size() * sizeof(DType*); Tensor<xpu, 1, char> workspace = ctx.requested[0].get_space_typed<xpu, 1, char>(Shape1(workspace_size), s); Tensor<cpu, 1, size_t> indices_cpu_tensor(indices.data(), Shape1(indices.size())); Tensor<xpu, 1, size_t> indices_xpu_tensor( reinterpret_cast<size_t*>(workspace.dptr_), Shape1(indices.size())); Tensor<cpu, 1, DType*> ptrs_cpu_tensor(out_grads.data(), Shape1(inputs.size())); Tensor<xpu, 1, DType*> ptrs_xpu_tensor( reinterpret_cast<DType**>(workspace.dptr_ + indices.size() * sizeof(size_t)), Shape1(inputs.size())); mshadow::Copy(indices_xpu_tensor, indices_cpu_tensor, s); mshadow::Copy(ptrs_xpu_tensor, ptrs_cpu_tensor, s); Kernel<ConcatenateKernel, xpu>::Launch( s, input_grad.Size(), ptrs_xpu_tensor.dptr_, input_grad.dptr<DType>(), indices_xpu_tensor.dptr_, indices.size() - 1, mid, trailing); }); } template<typename xpu> inline void SplitOpBackward(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mshadow; using namespace mshadow::expr; using namespace mxnet_op; const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); CHECK_EQ(inputs.size(), (param.sections > 0) ? param.sections : param.indices.ndim()) << "out grad vector size mush match the output size"; CHECK_EQ(outputs.size(), 1U); int real_axis = param.axis; if (real_axis < 0) { real_axis += outputs[split_enum::kData].ndim(); } SplitOpBackwardImpl<xpu>(attrs, ctx, inputs, req, outputs, real_axis); } inline uint32_t SplitNumOutputs(const NodeAttrs& attrs) { const SplitParam& param = nnvm::get<SplitParam>(attrs.parsed); return (param.sections > 0) ? param.sections : param.indices.ndim(); } } // namespace op } // namespace mxnet namespace std { template<> struct hash<mxnet::op::TransposeParam> { size_t operator()(const mxnet::op::TransposeParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axes); return ret; } }; template<> struct hash<mxnet::op::ReshapeParam> { size_t operator()(const mxnet::op::ReshapeParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.target_shape); ret = dmlc::HashCombine(ret, val.keep_highest); ret = dmlc::HashCombine(ret, val.shape); ret = dmlc::HashCombine(ret, val.reverse); return ret; } }; template<> struct hash<mxnet::op::ExpandDimParam> { size_t operator()(const mxnet::op::ExpandDimParam& val) { size_t ret = 0; ret = dmlc::HashCombine(ret, val.axis); return ret; } }; } // namespace std #endif // MXNET_OPERATOR_TENSOR_MATRIX_OP_INL_H_
detector.c
#include "darknet.h" #include <unistd.h> static int coco_ids[] = {1,2,3,4,5,6,7,8,9,10,11,13,14,15,16,17,18,19,20,21,22,23,24,25,27,28,31,32,33,34,35,36,37,38,39,40,41,42,43,44,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,67,70,72,73,74,75,76,77,78,79,80,81,82,84,85,86,87,88,89,90}; void train_detector(char *datacfg, char *cfgfile, char *weightfile, int *gpus, int ngpus, int clear) { list *options = read_data_cfg(datacfg); char *train_images = option_find_str(options, "train", "data/train.list"); char *backup_directory = option_find_str(options, "backup", "/backup/"); srand(time(0)); char *base = basecfg(cfgfile); printf("%s\n", base); float avg_loss = -1; network **nets = calloc(ngpus, sizeof(network)); srand(time(0)); int seed = rand(); int i; for(i = 0; i < ngpus; ++i){ srand(seed); #ifdef GPU cuda_set_device(gpus[i]); #endif nets[i] = load_network(cfgfile, weightfile, clear); nets[i]->learning_rate *= ngpus; } srand(time(0)); network *net = nets[0]; int imgs = net->batch * net->subdivisions * ngpus; printf("Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); data train, buffer; layer l = net->layers[net->n - 1]; int classes = l.classes; float jitter = l.jitter; list *plist = get_paths(train_images); //int N = plist->size; char **paths = (char **)list_to_array(plist); load_args args = get_base_args(net); args.coords = l.coords; args.paths = paths; args.n = imgs; args.m = plist->size; args.classes = classes; args.jitter = jitter; args.num_boxes = l.max_boxes; args.d = &buffer; args.type = DETECTION_DATA; //args.type = INSTANCE_DATA; args.threads = 64; pthread_t load_thread = load_data(args); double time; int count = 0; //while(i*imgs < N*120){ while(get_current_batch(net) < net->max_batches){ if(l.random && count++%10 == 0){ printf("Resizing\n"); int dim = (rand() % 10 + 10) * 32; if (get_current_batch(net)+200 > net->max_batches) dim = 608; //int dim = (rand() % 4 + 16) * 32; printf("%d\n", dim); args.w = dim; args.h = dim; pthread_join(load_thread, 0); train = buffer; free_data(train); load_thread = load_data(args); #pragma omp parallel for for(i = 0; i < ngpus; ++i){ resize_network(nets[i], dim, dim); } net = nets[0]; } time=what_time_is_it_now(); pthread_join(load_thread, 0); train = buffer; load_thread = load_data(args); /* int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[10] + 1 + k*5); if(!b.x) break; printf("loaded: %f %f %f %f\n", b.x, b.y, b.w, b.h); } */ /* int zz; for(zz = 0; zz < train.X.cols; ++zz){ image im = float_to_image(net->w, net->h, 3, train.X.vals[zz]); int k; for(k = 0; k < l.max_boxes; ++k){ box b = float_to_box(train.y.vals[zz] + k*5, 1); printf("%f %f %f %f\n", b.x, b.y, b.w, b.h); draw_bbox(im, b, 1, 1,0,0); } show_image(im, "truth11"); cvWaitKey(0); save_image(im, "truth11"); } */ printf("Loaded: %lf seconds\n", what_time_is_it_now()-time); time=what_time_is_it_now(); float loss = 0; #ifdef GPU if(ngpus == 1){ loss = train_network(net, train); } else { loss = train_networks(nets, ngpus, train, 4); } #else loss = train_network(net, train); #endif if (avg_loss < 0) avg_loss = loss; avg_loss = avg_loss*.9 + loss*.1; i = get_current_batch(net); printf("%ld: %f, %f avg, %f rate, %lf seconds, %d images\n", get_current_batch(net), loss, avg_loss, get_current_rate(net), what_time_is_it_now()-time, i*imgs); if(i%100==0){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s.backup", backup_directory, base); save_weights(net, buff); } if(i%10000==0 || (i < 1000 && i%100 == 0)){ #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_%d.weights", backup_directory, base, i); save_weights(net, buff); } free_data(train); } #ifdef GPU if(ngpus != 1) sync_nets(nets, ngpus, 0); #endif char buff[256]; sprintf(buff, "%s/%s_final.weights", backup_directory, base); save_weights(net, buff); } static int get_coco_image_id(char *filename) { char *p = strrchr(filename, '/'); char *c = strrchr(filename, '_'); if(c) p = c; return atoi(p+1); } static void print_cocos(FILE *fp, char *image_path, detection *dets, int num_boxes, int classes, int w, int h) { int i, j; int image_id = get_coco_image_id(image_path); for(i = 0; i < num_boxes; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; float bx = xmin; float by = ymin; float bw = xmax - xmin; float bh = ymax - ymin; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]) fprintf(fp, "{\"image_id\":%d, \"category_id\":%d, \"bbox\":[%f, %f, %f, %f], \"score\":%f},\n", image_id, coco_ids[j], bx, by, bw, bh, dets[i].prob[j]); } } } void print_detector_detections(FILE **fps, char *id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2. + 1; float xmax = dets[i].bbox.x + dets[i].bbox.w/2. + 1; float ymin = dets[i].bbox.y - dets[i].bbox.h/2. + 1; float ymax = dets[i].bbox.y + dets[i].bbox.h/2. + 1; if (xmin < 1) xmin = 1; if (ymin < 1) ymin = 1; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ if (dets[i].prob[j]) fprintf(fps[j], "%s %f %f %f %f %f\n", id, dets[i].prob[j], xmin, ymin, xmax, ymax); } } } void print_imagenet_detections(FILE *fp, int id, detection *dets, int total, int classes, int w, int h) { int i, j; for(i = 0; i < total; ++i){ float xmin = dets[i].bbox.x - dets[i].bbox.w/2.; float xmax = dets[i].bbox.x + dets[i].bbox.w/2.; float ymin = dets[i].bbox.y - dets[i].bbox.h/2.; float ymax = dets[i].bbox.y + dets[i].bbox.h/2.; if (xmin < 0) xmin = 0; if (ymin < 0) ymin = 0; if (xmax > w) xmax = w; if (ymax > h) ymax = h; for(j = 0; j < classes; ++j){ int class = j; if (dets[i].prob[class]) fprintf(fp, "%d %d %f %f %f %f %f\n", id, j+1, dets[i].prob[class], xmin, ymin, xmax, ymax); } } } void validate_detector_flip(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 2); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); image input = make_image(net->w, net->h, net->c*2); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data, 1); flip_image(val_resized[t]); copy_cpu(net->w*net->h*net->c, val_resized[t].data, 1, input.data + net->w*net->h*net->c, 1); network_predict(net, input.data); int w = val[t].w; int h = val[t].h; int num = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &num); if (nms) do_nms_sort(dets, num, classes, nms); if (coco){ print_cocos(fp, path, dets, num, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, num, classes, w, h); } else { print_detector_detections(fps, id, dets, num, classes, w, h); } free_detections(dets, num); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector(char *datacfg, char *cfgfile, char *weightfile, char *outfile) { int j; list *options = read_data_cfg(datacfg); char *valid_images = option_find_str(options, "valid", "data/train.list"); char *name_list = option_find_str(options, "names", "data/names.list"); char *prefix = option_find_str(options, "results", "results"); char **names = get_labels(name_list); char *mapf = option_find_str(options, "map", 0); int *map = 0; if (mapf) map = read_map(mapf); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths(valid_images); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int classes = l.classes; char buff[1024]; char *type = option_find_str(options, "eval", "voc"); FILE *fp = 0; FILE **fps = 0; int coco = 0; int imagenet = 0; if(0==strcmp(type, "coco")){ if(!outfile) outfile = "coco_results"; snprintf(buff, 1024, "%s/%s.json", prefix, outfile); fp = fopen(buff, "w"); fprintf(fp, "[\n"); coco = 1; } else if(0==strcmp(type, "imagenet")){ if(!outfile) outfile = "imagenet-detection"; snprintf(buff, 1024, "%s/%s.txt", prefix, outfile); fp = fopen(buff, "w"); imagenet = 1; classes = 200; } else { if(!outfile) outfile = "comp4_det_test_"; fps = calloc(classes, sizeof(FILE *)); for(j = 0; j < classes; ++j){ snprintf(buff, 1024, "%s/%s%s.txt", prefix, outfile, names[j]); fps[j] = fopen(buff, "w"); } } int m = plist->size; int i=0; int t; float thresh = .005; float nms = .45; int nthreads = 4; image *val = calloc(nthreads, sizeof(image)); image *val_resized = calloc(nthreads, sizeof(image)); image *buf = calloc(nthreads, sizeof(image)); image *buf_resized = calloc(nthreads, sizeof(image)); pthread_t *thr = calloc(nthreads, sizeof(pthread_t)); load_args args = {0}; args.w = net->w; args.h = net->h; //args.type = IMAGE_DATA; args.type = LETTERBOX_DATA; for(t = 0; t < nthreads; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } double start = what_time_is_it_now(); for(i = nthreads; i < m+nthreads; i += nthreads){ fprintf(stderr, "%d\n", i); for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ pthread_join(thr[t], 0); val[t] = buf[t]; val_resized[t] = buf_resized[t]; } for(t = 0; t < nthreads && i+t < m; ++t){ args.path = paths[i+t]; args.im = &buf[t]; args.resized = &buf_resized[t]; thr[t] = load_data_in_thread(args); } for(t = 0; t < nthreads && i+t-nthreads < m; ++t){ char *path = paths[i+t-nthreads]; char *id = basecfg(path); float *X = val_resized[t].data; network_predict(net, X); int w = val[t].w; int h = val[t].h; int nboxes = 0; detection *dets = get_network_boxes(net, w, h, thresh, .5, map, 0, &nboxes); if (nms) do_nms_sort(dets, nboxes, classes, nms); if (coco){ print_cocos(fp, path, dets, nboxes, classes, w, h); } else if (imagenet){ print_imagenet_detections(fp, i+t-nthreads+1, dets, nboxes, classes, w, h); } else { print_detector_detections(fps, id, dets, nboxes, classes, w, h); } free_detections(dets, nboxes); free(id); free_image(val[t]); free_image(val_resized[t]); } } for(j = 0; j < classes; ++j){ if(fps) fclose(fps[j]); } if(coco){ fseek(fp, -2, SEEK_CUR); fprintf(fp, "\n]\n"); fclose(fp); } fprintf(stderr, "Total Detection Time: %f Seconds\n", what_time_is_it_now() - start); } void validate_detector_recall(char *cfgfile, char *weightfile) { network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); fprintf(stderr, "Learning Rate: %g, Momentum: %g, Decay: %g\n", net->learning_rate, net->momentum, net->decay); srand(time(0)); list *plist = get_paths("data/coco_val_5k.list"); char **paths = (char **)list_to_array(plist); layer l = net->layers[net->n-1]; int j, k; int m = plist->size; int i=0; float thresh = .001; float iou_thresh = .5; float nms = .4; int total = 0; int correct = 0; int proposals = 0; float avg_iou = 0; for(i = 0; i < m; ++i){ char *path = paths[i]; image orig = load_image_color(path, 0, 0); image sized = resize_image(orig, net->w, net->h); char *id = basecfg(path); network_predict(net, sized.data); int nboxes = 0; detection *dets = get_network_boxes(net, sized.w, sized.h, thresh, .5, 0, 1, &nboxes); if (nms) do_nms_obj(dets, nboxes, 1, nms); char labelpath[4096]; find_replace(path, "images", "labels", labelpath); find_replace(labelpath, "JPEGImages", "labels", labelpath); find_replace(labelpath, ".jpg", ".txt", labelpath); find_replace(labelpath, ".JPEG", ".txt", labelpath); int num_labels = 0; box_label *truth = read_boxes(labelpath, &num_labels); for(k = 0; k < nboxes; ++k){ if(dets[k].objectness > thresh){ ++proposals; } } for (j = 0; j < num_labels; ++j) { ++total; box t = {truth[j].x, truth[j].y, truth[j].w, truth[j].h}; float best_iou = 0; for(k = 0; k < l.w*l.h*l.n; ++k){ float iou = box_iou(dets[k].bbox, t); if(dets[k].objectness > thresh && iou > best_iou){ best_iou = iou; } } avg_iou += best_iou; if(best_iou > iou_thresh){ ++correct; } } fprintf(stderr, "%5d %5d %5d\tRPs/Img: %.2f\tIOU: %.2f%%\tRecall:%.2f%%\n", i, correct, total, (float)proposals/(i+1), avg_iou*100/total, 100.*correct/total); free(id); free_image(orig); free_image(sized); } } void test_detector_folder( char *datacfg, /* cfg/coco.data */ char *cfgfile, /* 配置文件 */ char *weightfile, /* 权重文件 */ char *input_folder, /* 输入文件路径 */ char *output_folder, /* 输出文件路径 */ float thresh, /* 阈值 */ float hier_thresh) { // if( !(input_folder && output_folder) ){ // printf("Please Provide Image Folder"); // return; // } if( !input_folder ){ printf("Please Provide Input Image Folder"); return; } if( !output_folder ){ printf("Please Provide Output Image Folder"); return; } // 加载 coco.data list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", "data/names.list"); // darknet/data/coco.names char **names = get_labels(name_list); // 读取标签. image **alphabet = load_alphabet(); // 加载配置文件和权重文件. network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); double time; // 输入图像和输出图像 char buff[256],buff2[256]; char *input_img_name = buff; char *output_file = buff2; float nms=.45; // TODO FILE *fp; int save_result_txt = 1; int img_counter = -1; while(1) { img_counter++; // 输入输出图像名相同. strncpy(input_img_name, input_folder, 256); char frame_index_c[256]; // sprintf(frame_index_c,"/frame%04d.jpg",img_counter); // Important!!! change file name sprintf(frame_index_c,"/%04d_rgb_raw.jpg",img_counter); // format into 6 digit // sprintf(frame_index_c,"/%04d.png",img_counter); strcat(input_img_name,frame_index_c); if( access( input_img_name, F_OK ) == -1 ) { printf("Cannot find image %s \n",input_img_name); break; } // 输出文件路径. strncpy(output_file, output_folder, 256); // NOTE 保存 txt 检测结果. if (save_result_txt==1) { char frame_index_c3[256]; sprintf(frame_index_c3,"_txts/%04d_yolo2_%.2f.txt",img_counter,thresh); // format into 6 digit char * result_file=strcat(output_file,frame_index_c3); // printf("save to txt: %s \n",result_file); fp = fopen(result_file,"w+"); if (fp == NULL) { printf("Cannot save to file %s \n",result_file); break; } } strncpy(output_file, output_folder, 256); char frame_index_c2[256]; sprintf(frame_index_c2,"/%04d_yolo2_%.2f",img_counter,thresh); // format into 6 digit strcat(output_file,frame_index_c2); image im = load_image_color(input_img_name,0,0); image sized = letterbox_image(im, net->w, net->h); layer l = net->layers[net->n-1]; float *X = sized.data; time=what_time_is_it_now(); network_predict(net, X); if (img_counter%10==0) printf("%s: Predicted in %f seconds.\n", input_img_name, what_time_is_it_now()-time); int nboxes = 0; detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); if (save_result_txt==0) draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes); // if want to show classes, prob in terminal. See inside function. else draw_save_detections(im, dets, nboxes, thresh, names, alphabet, l.classes,fp); free_detections(dets, nboxes); save_image(im, output_file); free_image(im); free_image(sized); if (save_result_txt==1) fclose(fp); } } void test_detector(char *datacfg, char *cfgfile, char *weightfile, char *filename, float thresh, float hier_thresh, char *outfile, int fullscreen) { list *options = read_data_cfg(datacfg); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); image **alphabet = load_alphabet(); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); double time; char buff[256]; char *input = buff; float nms=.45; while(1){ if(filename){ strncpy(input, filename, 256); } else { printf("Enter Image Path: "); fflush(stdout); input = fgets(input, 256, stdin); if(!input) return; strtok(input, "\n"); } image im = load_image_color(input,0,0); image sized = letterbox_image(im, net->w, net->h); //image sized = resize_image(im, net->w, net->h); //image sized2 = resize_max(im, net->w); //image sized = crop_image(sized2, -((net->w - sized2.w)/2), -((net->h - sized2.h)/2), net->w, net->h); //resize_network(net, sized.w, sized.h); layer l = net->layers[net->n-1]; float *X = sized.data; time=what_time_is_it_now(); network_predict(net, X); printf("%s: Predicted in %f seconds.\n", input, what_time_is_it_now()-time); int nboxes = 0; detection *dets = get_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 1, &nboxes); //printf("%d\n", nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); draw_detections(im, dets, nboxes, thresh, names, alphabet, l.classes); free_detections(dets, nboxes); if(outfile){ save_image(im, outfile); } else{ save_image(im, "predictions"); #ifdef OPENCV cvNamedWindow("predictions", CV_WINDOW_NORMAL); if(fullscreen){ cvSetWindowProperty("predictions", CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); } show_image(im, "predictions"); cvWaitKey(0); cvDestroyAllWindows(); #endif } free_image(im); free_image(sized); if (filename) break; } } /* void censor_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; float *X = in_s.data; network_predict(net, X); int nboxes = 0; detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 0, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int left = b.x-b.w/2.; int top = b.y-b.h/2.; censor_image(in, left, top, b.w, b.h); } } show_image(in, base); cvWaitKey(10); free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } void extract_detector(char *datacfg, char *cfgfile, char *weightfile, int cam_index, const char *filename, int class, float thresh, int skip) { #ifdef OPENCV char *base = basecfg(cfgfile); network *net = load_network(cfgfile, weightfile, 0); set_batch_network(net, 1); srand(2222222); CvCapture * cap; int w = 1280; int h = 720; if(filename){ cap = cvCaptureFromFile(filename); }else{ cap = cvCaptureFromCAM(cam_index); } if(w){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_WIDTH, w); } if(h){ cvSetCaptureProperty(cap, CV_CAP_PROP_FRAME_HEIGHT, h); } if(!cap) error("Couldn't connect to webcam.\n"); cvNamedWindow(base, CV_WINDOW_NORMAL); cvResizeWindow(base, 512, 512); float fps = 0; int i; int count = 0; float nms = .45; while(1){ image in = get_image_from_stream(cap); //image in_s = resize_image(in, net->w, net->h); image in_s = letterbox_image(in, net->w, net->h); layer l = net->layers[net->n-1]; show_image(in, base); int nboxes = 0; float *X = in_s.data; network_predict(net, X); detection *dets = get_network_boxes(net, in.w, in.h, thresh, 0, 0, 1, &nboxes); //if (nms) do_nms_obj(boxes, probs, l.w*l.h*l.n, l.classes, nms); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); for(i = 0; i < nboxes; ++i){ if(dets[i].prob[class] > thresh){ box b = dets[i].bbox; int size = b.w*in.w > b.h*in.h ? b.w*in.w : b.h*in.h; int dx = b.x*in.w-size/2.; int dy = b.y*in.h-size/2.; image bim = crop_image(in, dx, dy, size, size); char buff[2048]; sprintf(buff, "results/extract/%07d", count); ++count; save_image(bim, buff); free_image(bim); } } free_detections(dets, nboxes); free_image(in_s); free_image(in); float curr = 0; fps = .9*fps + .1*curr; for(i = 0; i < skip; ++i){ image in = get_image_from_stream(cap); free_image(in); } } #endif } */ /* void network_detect(network *net, image im, float thresh, float hier_thresh, float nms, detection *dets) { network_predict_image(net, im); layer l = net->layers[net->n-1]; int nboxes = num_boxes(net); fill_network_boxes(net, im.w, im.h, thresh, hier_thresh, 0, 0, dets); if (nms) do_nms_sort(dets, nboxes, l.classes, nms); } */ void run_detector(int argc, char **argv) { char *prefix = find_char_arg(argc, argv, "-prefix", 0); float thresh = find_float_arg(argc, argv, "-thresh", .5); float hier_thresh = find_float_arg(argc, argv, "-hier", .5); int cam_index = find_int_arg(argc, argv, "-c", 0); int frame_skip = find_int_arg(argc, argv, "-s", 0); int avg = find_int_arg(argc, argv, "-avg", 3); if(argc < 4){ fprintf(stderr, "usage: %s %s [train/test/valid] [cfg] [weights (optional)]\n", argv[0], argv[1]); return; } char *gpu_list = find_char_arg(argc, argv, "-gpus", 0); char *outfile = find_char_arg(argc, argv, "-out", 0); int *gpus = 0; int gpu = 0; int ngpus = 0; if(gpu_list){ printf("%s\n", gpu_list); int len = strlen(gpu_list); ngpus = 1; int i; for(i = 0; i < len; ++i){ if (gpu_list[i] == ',') ++ngpus; } gpus = calloc(ngpus, sizeof(int)); for(i = 0; i < ngpus; ++i){ gpus[i] = atoi(gpu_list); gpu_list = strchr(gpu_list, ',')+1; } } else { gpu = gpu_index; gpus = &gpu; ngpus = 1; } int clear = find_arg(argc, argv, "-clear"); int fullscreen = find_arg(argc, argv, "-fullscreen"); int width = find_int_arg(argc, argv, "-w", 0); int height = find_int_arg(argc, argv, "-h", 0); int fps = find_int_arg(argc, argv, "-fps", 0); //int class = find_int_arg(argc, argv, "-class", 0); char *datacfg = argv[3]; char *cfg = argv[4]; char *weights = (argc > 5) ? argv[5] : 0; char *filename = (argc > 6) ? argv[6]: 0; if(0==strcmp(argv[2], "test")) test_detector(datacfg, cfg, weights, filename, thresh, hier_thresh, outfile, fullscreen); else if(0==strcmp(argv[2], "train")) train_detector(datacfg, cfg, weights, gpus, ngpus, clear); else if(0==strcmp(argv[2], "valid")) validate_detector(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "valid2")) validate_detector_flip(datacfg, cfg, weights, outfile); else if(0==strcmp(argv[2], "recall")) validate_detector_recall(cfg, weights); else if(0==strcmp(argv[2], "demo")) { list *options = read_data_cfg(datacfg); int classes = option_find_int(options, "classes", 20); char *name_list = option_find_str(options, "names", "data/names.list"); char **names = get_labels(name_list); demo(cfg, weights, thresh, cam_index, filename, names, classes, frame_skip, prefix, avg, hier_thresh, width, height, fps, fullscreen); } //else if(0==strcmp(argv[2], "extract")) extract_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); //else if(0==strcmp(argv[2], "censor")) censor_detector(datacfg, cfg, weights, cam_index, filename, class, thresh, frame_skip); }
GB_binop__min_int8.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the Generated2/ folder, do not edit it // (it is auto-generated from Generator/*). #include "GB.h" #ifndef GBCOMPACT #include "GB_emult.h" #include "GB_control.h" #include "GB_ek_slice.h" #include "GB_dense.h" #include "GB_atomics.h" #include "GB_bitmap_assign_methods.h" #include "GB_binop__include.h" // C=binop(A,B) is defined by the following types and operators: // A+B function (eWiseAdd): GB (_AaddB__min_int8) // A.*B function (eWiseMult): GB (_AemultB_08__min_int8) // A.*B function (eWiseMult): GB (_AemultB_02__min_int8) // A.*B function (eWiseMult): GB (_AemultB_04__min_int8) // A.*B function (eWiseMult): GB (_AemultB_bitmap__min_int8) // A*D function (colscale): GB (_AxD__min_int8) // D*A function (rowscale): GB (_DxB__min_int8) // C+=B function (dense accum): GB (_Cdense_accumB__min_int8) // C+=b function (dense accum): GB (_Cdense_accumb__min_int8) // C+=A+B function (dense ewise3): GB (_Cdense_ewise3_accum__min_int8) // C=A+B function (dense ewise3): GB (_Cdense_ewise3_noaccum__min_int8) // C=scalar+B GB (_bind1st__min_int8) // C=scalar+B' GB (_bind1st_tran__min_int8) // C=A+scalar GB (_bind2nd__min_int8) // C=A'+scalar GB (_bind2nd_tran__min_int8) // C type: int8_t // A type: int8_t // A pattern? 0 // B type: int8_t // B pattern? 0 // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int8_t #define GB_BTYPE \ int8_t #define GB_CTYPE \ int8_t // true if the types of A and B are identical #define GB_ATYPE_IS_BTYPE \ 1 // true if the types of C and A are identical #define GB_CTYPE_IS_ATYPE \ 1 // true if the types of C and B are identical #define GB_CTYPE_IS_BTYPE \ 1 // aij = Ax [pA] #define GB_GETA(aij,Ax,pA,A_iso) \ int8_t aij = GBX (Ax, pA, A_iso) // true if values of A are not used #define GB_A_IS_PATTERN \ 0 \ // bij = Bx [pB] #define GB_GETB(bij,Bx,pB,B_iso) \ int8_t bij = GBX (Bx, pB, B_iso) // true if values of B are not used #define GB_B_IS_PATTERN \ 0 \ // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ int8_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA,A_iso) \ cij = GBX (Ax, pA, A_iso) // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB,B_iso) \ cij = GBX (Bx, pB, B_iso) #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z,x,y,i,j) \ z = GB_IMIN (x, y) ; // true if the binop must be flipped #define GB_BINOP_FLIP \ 0 // op is second #define GB_OP_IS_SECOND \ 0 // do the numerical phases of GB_add and GB_emult #define GB_PHASE_2_OF_2 // hard-coded loops can be vectorized #define GB_PRAGMA_SIMD_VECTORIZE GB_PRAGMA_SIMD // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_MIN || GxB_NO_INT8 || GxB_NO_MIN_INT8) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB (_Cdense_ewise3_accum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_accum_template.c" } //------------------------------------------------------------------------------ // C = A+B, all 3 matrices dense //------------------------------------------------------------------------------ void GB (_Cdense_ewise3_noaccum__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #include "GB_dense_ewise3_noaccum_template.c" } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumB__min_int8) ( GrB_Matrix C, const GrB_Matrix B, const int64_t *B_ek_slicing, const int B_ntasks, const int B_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB (_Cdense_accumb__min_int8) ( GrB_Matrix C, const GB_void *p_bwork, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else { // get the scalar b for C += b, of type int8_t int8_t bwork = (*((int8_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_AxD__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix D, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_colscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = D*B, row scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB (_DxB__min_int8) ( GrB_Matrix C, const GrB_Matrix D, const GrB_Matrix B, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *restrict Cx = (int8_t *) C->x ; #include "GB_AxB_rowscale_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseAdd: C=A+B, C<M>=A+B, C<!M>=A+B //------------------------------------------------------------------------------ GrB_Info GB (_AaddB__min_int8) ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool is_eWiseUnion, const GB_void *alpha_scalar_in, const GB_void *beta_scalar_in, const bool Ch_is_Mh, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else GB_WERK_DECLARE (M_ek_slicing, int64_t) ; GB_WERK_DECLARE (A_ek_slicing, int64_t) ; GB_WERK_DECLARE (B_ek_slicing, int64_t) ; int8_t alpha_scalar ; int8_t beta_scalar ; if (is_eWiseUnion) { alpha_scalar = (*((int8_t *) alpha_scalar_in)) ; beta_scalar = (*((int8_t *) beta_scalar_in )) ; } #include "GB_add_template.c" GB_FREE_WORKSPACE ; return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, or C<M!>=A.*B where C is sparse/hyper //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_08__min_int8) ( GrB_Matrix C, const int C_sparsity, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict C_to_M, const int64_t *restrict C_to_A, const int64_t *restrict C_to_B, const GB_task_struct *restrict TaskList, const int C_ntasks, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_08_meta.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<#> = A.*B when A is sparse/hyper and B is bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_02__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool flipxy, const int64_t *restrict Cp_kfirst, const int64_t *A_ek_slicing, const int A_ntasks, const int A_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #if GB_BINOP_FLIP // The operator is not commutative, and does not have a flipped // variant. For example z=atan2(y,x). if (flipxy) { // use fmult(y,x) #undef GB_FLIPPED #define GB_FLIPPED 1 #include "GB_emult_02_template.c" } else { // use fmult(x,y) #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" } #else // No need to handle the flip: the operator is either commutative, or // has been handled by changing z=div(y,x) to z=rdiv(x,y) for example. #undef GB_FLIPPED #define GB_FLIPPED 0 #include "GB_emult_02_template.c" #endif return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C<M> = A.*B, M sparse/hyper, A and B bitmap/full //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_04__min_int8) ( GrB_Matrix C, const GrB_Matrix M, const bool Mask_struct, const GrB_Matrix A, const GrB_Matrix B, const int64_t *restrict Cp_kfirst, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_emult_04_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // eWiseMult: C=A.*B, C<M>=A.*B, C<!M>=A.*B where C is bitmap //------------------------------------------------------------------------------ GrB_Info GB (_AemultB_bitmap__min_int8) ( GrB_Matrix C, const int ewise_method, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const int64_t *M_ek_slicing, const int M_ntasks, const int M_nthreads, const int C_nthreads, GB_Context Context ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_bitmap_emult_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (x,Bx): apply a binary operator to a matrix with scalar bind1st //------------------------------------------------------------------------------ GrB_Info GB (_bind1st__min_int8) ( GB_void *Cx_output, // Cx and Bx may be aliased const GB_void *x_input, const GB_void *Bx_input, const int8_t *restrict Bb, int64_t bnz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t *Cx = (int8_t *) Cx_output ; int8_t x = (*((int8_t *) x_input)) ; int8_t *Bx = (int8_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < bnz ; p++) { if (!GBB (Bb, p)) continue ; int8_t bij = GBX (Bx, p, false) ; Cx [p] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB (_bind2nd__min_int8) ( GB_void *Cx_output, // Cx and Ax may be aliased const GB_void *Ax_input, const GB_void *y_input, const int8_t *restrict Ab, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; int8_t *Cx = (int8_t *) Cx_output ; int8_t *Ax = (int8_t *) Ax_input ; int8_t y = (*((int8_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int8_t aij = GBX (Ax, p, false) ; Cx [p] = GB_IMIN (aij, y) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (x, A'): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (x, aij), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (x, aij) ; \ } GrB_Info GB (_bind1st_tran__min_int8) ( GrB_Matrix C, const GB_void *x_input, const GrB_Matrix A, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { // GB_unop_transpose.c uses GB_ATYPE, but A is // the 2nd input to binary operator z=f(x,y). #undef GB_ATYPE #define GB_ATYPE \ int8_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t x = (*((const int8_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int8_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int8_t aij = GBX (Ax, pA, false) ; \ Cx [pC] = GB_IMIN (aij, y) ; \ } GrB_Info GB (_bind2nd_tran__min_int8) ( GrB_Matrix C, const GrB_Matrix A, const GB_void *y_input, int64_t *restrict *Workspaces, const int64_t *restrict A_slice, int nworkspaces, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int8_t y = (*((const int8_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
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] = 24; tile_size[1] = 24; tile_size[2] = 4; tile_size[3] = 32; tile_size[4] = -1; // for timekeeping int ts_return = -1; struct timeval start, end, result; double tdiff = 0.0, min_tdiff=1.e100; const int BASE = 1024; // initialize variables // srand(42); for (i = 1; i < Nz; i++) { for (j = 1; j < Ny; j++) { for (k = 1; k < Nx; k++) { A[0][i][j][k] = 1.0 * (rand() % BASE); roc2[i][j][k] = 2.0 * (rand() % BASE); } } } #ifdef LIKWID_PERFMON LIKWID_MARKER_INIT; #pragma omp parallel { LIKWID_MARKER_THREADINIT; #pragma omp barrier LIKWID_MARKER_START("calc"); } #endif int num_threads = 1; #if defined(_OPENMP) num_threads = omp_get_max_threads(); #endif const double coef0 = -0.28472; const double coef1 = 0.16000; const double coef2 = -0.02000; const double coef3 = 0.00254; const double coef4 = -0.00018; for(test=0; test<TESTS; test++){ gettimeofday(&start, 0); // serial execution - Addition: 6 && Multiplication: 2 #pragma scop for (t = 0; t < Nt; t++) { for (i = 4; i < Nz-4; i++) { for (j = 4; j < Ny-4; j++) { for (k = 4; k < Nx-4; k++) { A[(t+1)%2][i][j][k] = 2.0*A[t%2][i][j][k] - A[(t+1)%2][i][j][k] + roc2[i][j][k]*( coef0* A[t%2][i ][j ][k ] + coef1*(A[t%2][i-1][j ][k ] + A[t%2][i+1][j ][k ] + A[t%2][i ][j-1][k ] + A[t%2][i ][j+1][k ] + A[t%2][i ][j ][k-1] + A[t%2][i ][j ][k+1]) + coef2*(A[t%2][i-2][j ][k ] + A[t%2][i+2][j ][k ] + A[t%2][i ][j-2][k ] + A[t%2][i ][j+2][k ] + A[t%2][i ][j ][k-2] + A[t%2][i ][j ][k+2]) + coef3*(A[t%2][i-3][j ][k ] + A[t%2][i+3][j ][k ] + A[t%2][i ][j-3][k ] + A[t%2][i ][j+3][k ] + A[t%2][i ][j ][k-3] + A[t%2][i ][j ][k+3]) + coef4*(A[t%2][i-4][j ][k ] + A[t%2][i+4][j ][k ] + A[t%2][i ][j-4][k ] + A[t%2][i ][j+4][k ] + A[t%2][i ][j ][k-4] + A[t%2][i ][j ][k+4]) ); } } } } #pragma endscop gettimeofday(&end, 0); ts_return = timeval_subtract(&result, &end, &start); tdiff = (double) (result.tv_sec + result.tv_usec * 1.0e-6); min_tdiff = MIN(min_tdiff, tdiff); printf("Rank 0 TEST# %d time: %f\n", test, tdiff); } PRINT_RESULTS(4, "constant") #ifdef LIKWID_PERFMON #pragma omp parallel { LIKWID_MARKER_STOP("calc"); } LIKWID_MARKER_CLOSE; #endif // Free allocated arrays for(i=0; i<Nz; i++){ for(j=0;j<Ny;j++){ free(A[0][i][j]); free(A[1][i][j]); free(roc2[i][j]); } free(A[0][i]); free(A[1][i]); free(roc2[i]); } free(A[0]); free(A[1]); free(roc2); return 0; }
ch_ompss.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <assert.h> #include "ch_common.h" #include "../timing.h" void cholesky_mpi(const int ts, const int nt, double *A[nt][nt], double *B, double *C[nt], int *block_rank) { #pragma omp parallel { #pragma omp single { INIT_TIMING(omp_get_num_threads()); START_TIMING(TIME_TOTAL); { START_TIMING(TIME_CREATE); for (int k = 0; k < nt; k++) { if (block_rank[k*nt+k] == mype) { #pragma omp task depend(out: A[k][k]) firstprivate(k) { //printf("Computing potrf in k=%d\n", k); START_TIMING(TIME_POTRF); omp_potrf(A[k][k], ts, ts); END_TIMING(TIME_POTRF); } } int comm_sentinel; // <-- sentinel, never actual referenced if (block_rank[k*nt+k] == mype && np != 1) { // use comm_sentinel to make sure this task runs before the communication tasks below #pragma omp task depend(in: A[k][k], comm_sentinel) firstprivate(k) { //printf("Communicating potrf in k=%d\n", k); START_TIMING(TIME_COMM); MPI_Request *reqs = NULL; int nreqs = 0; char send_flags[np]; reset_send_flags(send_flags); for (int kk = k+1; kk < nt; kk++) { if (!send_flags[block_rank[k*nt+kk]]) { ++nreqs; send_flags[block_rank[k*nt+kk]] = 1; } } reqs = malloc(sizeof(MPI_Request)*nreqs); nreqs = 0; for (int dst = 0; dst < np; dst++) { if (send_flags[dst] && dst != mype) { MPI_Request send_req; //printf("Sending potrf block to %d in k=%d\n", dst, k); MPI_Isend(A[k][k], ts*ts, MPI_DOUBLE, dst, k*nt+k, MPI_COMM_WORLD, &send_req); reqs[nreqs++] = send_req; } } //printf("Waiting for potrf block in k=%d\n", k); waitall(reqs, nreqs); free(reqs); END_TIMING(TIME_COMM); } } else if (block_rank[k*nt+k] != mype) { // use comm_sentinel to make sure this task runs before the communication tasks below #pragma omp task depend(out: B) depend(in:comm_sentinel) firstprivate(k) { START_TIMING(TIME_COMM); int recv_flag = 0; for (int i = k + 1; i < nt; i++) { if (block_rank[k*nt+i] == mype) { recv_flag = 1; break; } } if (recv_flag) { MPI_Request recv_req; MPI_Irecv(B, ts*ts, MPI_DOUBLE, block_rank[k*nt+k], k*nt+k, MPI_COMM_WORLD, &recv_req); //printf("Receiving potrf block from %d in k=%d\n", block_rank[k*nt+k], k); waitall(&recv_req, 1); } END_TIMING(TIME_COMM); } } for (int i = k + 1; i < nt; i++) { if (block_rank[k*nt+i] == mype) { if (block_rank[k*nt+k] == mype) { #pragma omp task depend(in: A[k][k], comm_sentinel) depend(out: A[k][i]) firstprivate(k, i) { START_TIMING(TIME_TRSM); omp_trsm(A[k][k], A[k][i], ts, ts); END_TIMING(TIME_TRSM); } } else { #pragma omp task depend(in: B, comm_sentinel) depend(out: A[k][i]) firstprivate(k, i) { START_TIMING(TIME_TRSM); omp_trsm(B, A[k][i], ts, ts); END_TIMING(TIME_TRSM); } } } } #pragma omp task depend(inout: comm_sentinel) firstprivate(k) shared(A) { START_TIMING(TIME_COMM); char send_flags[np]; reset_send_flags(send_flags); int nreqs = 0; // upper bound in case all our blocks have to be sent int max_req = (nt-k)*(np-1); MPI_Request *reqs = malloc(sizeof(*reqs)*max_req); for (int i = k + 1; i < nt; i++) { if (block_rank[k*nt+i] == mype && np != 1) { for (int ii = k + 1; ii < i; ii++) { if (!send_flags[block_rank[ii*nt+i]]) { send_flags[block_rank[ii*nt+i]] = 1; } } for (int ii = i + 1; ii < nt; ii++) { if (!send_flags[block_rank[i*nt+ii]]) { send_flags[block_rank[i*nt+ii]] = 1; } } if (!send_flags[block_rank[i*nt+i]]) send_flags[block_rank[i*nt+i]] = 1; for (int dst = 0; dst < np; dst++) { if (send_flags[dst] && dst != mype) { MPI_Request send_req; MPI_Isend(A[k][i], ts*ts, MPI_DOUBLE, dst, k*nt+i, MPI_COMM_WORLD, &send_req); reqs[nreqs++] = send_req; } } reset_send_flags(send_flags); } if (block_rank[k*nt+i] != mype) { int recv_flag = 0; for (int ii = k + 1; ii < i; ii++) { if (block_rank[ii*nt+i] == mype) recv_flag = 1; } for (int ii = i + 1; ii < nt; ii++) { if (block_rank[i*nt+ii] == mype) recv_flag = 1; } if (block_rank[i*nt+i] == mype) recv_flag = 1; if (recv_flag) { MPI_Request recv_req; MPI_Irecv(C[i], ts*ts, MPI_DOUBLE, block_rank[k*nt+i], k*nt+i, MPI_COMM_WORLD, &recv_req); reqs[nreqs++] = recv_req; } } } //printf("Waiting for trsm blocks in k=%d\n", k); waitall(reqs, nreqs); free(reqs); END_TIMING(TIME_COMM); } for (int i = k + 1; i < nt; i++) { for (int j = k + 1; j < i; j++) { if (block_rank[j*nt+i] == mype) { if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] == mype) { #pragma omp task depend(in: A[k][i], A[k][j]) depend(out: A[j][i]) firstprivate(k, j, i) { START_TIMING(TIME_GEMM); omp_gemm(A[k][i], A[k][j], A[j][i], ts, ts); END_TIMING(TIME_GEMM); } } else if (block_rank[k*nt+i] != mype && block_rank[k*nt+j] == mype) { #pragma omp task depend(in: A[k][j], comm_sentinel) depend(out: A[j][i]) firstprivate(k, j, i) { START_TIMING(TIME_GEMM); omp_gemm(C[i], A[k][j], A[j][i], ts, ts); END_TIMING(TIME_GEMM); } } else if (block_rank[k*nt+i] == mype && block_rank[k*nt+j] != mype) { #pragma omp task depend(in: A[k][i], comm_sentinel) depend(out: A[j][i]) firstprivate(k, j, i) { START_TIMING(TIME_GEMM); omp_gemm(A[k][i], C[j], A[j][i], ts, ts); END_TIMING(TIME_GEMM); } } else { #pragma omp task depend(in: comm_sentinel) depend(out: A[j][i]) firstprivate(k, j, i) { START_TIMING(TIME_GEMM); omp_gemm(C[i], C[j], A[j][i], ts, ts); END_TIMING(TIME_GEMM); } } } } if (block_rank[i*nt+i] == mype) { if (block_rank[k*nt+i] == mype) { #pragma omp task depend(in: A[k][i]) depend(out: A[i][i]) firstprivate(k, i) { START_TIMING(TIME_SYRK); omp_syrk(A[k][i], A[i][i], ts, ts); END_TIMING(TIME_SYRK); } } else { #pragma omp task depend(in: comm_sentinel) depend(out: A[i][i]) firstprivate(k, i) { START_TIMING(TIME_SYRK); omp_syrk(C[i], A[i][i], ts, ts); END_TIMING(TIME_SYRK); } } } } } END_TIMING(TIME_CREATE); } #pragma omp taskwait END_TIMING(TIME_TOTAL); MPI_Barrier(MPI_COMM_WORLD); PRINT_TIMINGS(); FREE_TIMING(); }// pragma omp single }// pragma omp parallel }
GB_binop__islt_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_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_uint64 // A.*B function (eWiseMult): GB_AemultB__islt_uint64 // A*D function (colscale): GB_AxD__islt_uint64 // D*A function (rowscale): GB_DxB__islt_uint64 // C+=B function (dense accum): GB_Cdense_accumB__islt_uint64 // C+=b function (dense accum): GB_Cdense_accumb__islt_uint64 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__islt_uint64 // C=scalar+B GB_bind1st__islt_uint64 // C=scalar+B' GB_bind1st_tran__islt_uint64 // C=A+scalar GB_bind2nd__islt_uint64 // C=A'+scalar GB_bind2nd_tran__islt_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) ; // 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_ISLT || GxB_NO_UINT64 || GxB_NO_ISLT_UINT64) //------------------------------------------------------------------------------ // 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__islt_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__islt_uint64 ( 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__islt_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__islt_uint64 ( 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 uint64_t *GB_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__islt_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 *GB_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 //------------------------------------------------------------------------------ #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__islt_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 *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__islt_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 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__islt_uint64 ( 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 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__islt_uint64 ( 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 ; 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__islt_uint64 ( 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 \ 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__islt_uint64 ( 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 uint64_t y = (*((const uint64_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
GB_unaryop__one_int16_int16.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2019, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__one_int16_int16 // op(A') function: GB_tran__one_int16_int16 // C type: int16_t // A type: int16_t // cast: ; // unaryop: cij = 1 #define GB_ATYPE \ int16_t #define GB_CTYPE \ int16_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ ; #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = 1 ; // casting #define GB_CASTING(z, x) \ ; ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (x, aij) ; \ GB_OP (GB_CX (pC), x) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ONE || GxB_NO_INT16) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__one_int16_int16 ( int16_t *restrict Cx, const int16_t *restrict Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #pragma omp parallel for num_threads(nthreads) schedule(static) for (int64_t p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__one_int16_int16 ( GrB_Matrix C, const GrB_Matrix A, int64_t *restrict *Rowcounts, GBI_single_iterator Iter, const int64_t *restrict A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
jacobi_float_avx2.c
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/timeb.h> #include <malloc.h> #include <math.h> #define REAL float static double read_timer_ms() { struct timeb tm; ftime(&tm); return (double) tm.time * 1000.0 + (double) tm.millitm; } /************************************************************ * program to solve a finite difference * discretization of Helmholtz equation : * (d2/dx2)u + (d2/dy2)u - alpha u = f * using Jacobi iterative method. * * Modified: Sanjiv Shah, Kuck and Associates, Inc. (KAI), 1998 * Author: Joseph Robicheaux, Kuck and Associates, Inc. (KAI), 1998 * * This c version program is translated by * Chunhua Liao, University of Houston, Jan, 2005 * * Directives are used in this code to achieve parallelism. * All do loops are parallelized with default 'static' scheduling. * * Input : n - grid dimension in x direction * m - grid dimension in y direction * alpha - Helmholtz constant (always greater than 0.0) * tol - error tolerance for iterative solver * relax - Successice over relaxation parameter * mits - Maximum iterations for iterative solver * * On output * : u(n,m) - Dependent variable (solutions) * : f(n,m) - Right hand side function *************************************************************/ #define DEFAULT_DIMSIZE 256 void print_array(char *title, char *name, REAL *A, int n, int m) { printf("%s:\n", title); int i, j; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%s[%d][%d]:%f ", name, i, j, A[i * m + j]); } printf("\n"); } printf("\n"); } /* subroutine initialize (n,m,alpha,dx,dy,u,f) ****************************************************** * Initializes data * Assumes exact solution is u(x,y) = (1-x^2)*(1-y^2) * ******************************************************/ void initialize(int n, int m, REAL alpha, REAL *dx, REAL *dy, REAL *u_p, REAL *f_p) { int i; int j; int xx; int yy; REAL (*u)[m] = (REAL (*)[m]) u_p; REAL (*f)[m] = (REAL (*)[m]) f_p; //double PI=3.1415926; *dx = (2.0 / (n - 1)); *dy = (2.0 / (m - 1)); /* Initialize initial condition and RHS */ //#pragma omp parallel for private(xx,yy,j,i) for (i = 0; i < n; i++) for (j = 0; j < m; j++) { xx = ((int) (-1.0 + (*dx * (i - 1)))); yy = ((int) (-1.0 + (*dy * (j - 1)))); u[i][j] = 0.0; f[i][j] = (((((-1.0 * alpha) * (1.0 - (xx * xx))) * (1.0 - (yy * yy))) - (2.0 * (1.0 - (xx * xx)))) - (2.0 * (1.0 - (yy * yy)))); } } /* subroutine error_check (n,m,alpha,dx,dy,u,f) implicit none ************************************************************ * Checks error between numerical and exact solution * ************************************************************/ void error_check(int n, int m, REAL alpha, REAL dx, REAL dy, REAL *u_p, REAL *f_p) { int i; int j; REAL xx; REAL yy; REAL temp; REAL error; error = 0.0; REAL (*u)[m] = (REAL (*)[m]) u_p; REAL (*f)[m] = (REAL (*)[m]) f_p; for (i = 0; i < n; i++) for (j = 0; j < m; j++) { xx = (-1.0 + (dx * (i - 1))); yy = (-1.0 + (dy * (j - 1))); temp = (u[i][j] - ((1.0 - (xx * xx)) * (1.0 - (yy * yy)))); error = (error + (temp * temp)); } error = (sqrt(error) / (n * m)); printf("Solution Error: %2.6g\n", error); } void jacobi_seq(int n, int m, REAL dx, REAL dy, REAL alpha, REAL relax, REAL *u_p, REAL *f_p, REAL tol, int mits); void jacobi_omp(int n, int m, REAL dx, REAL dy, REAL alpha, REAL relax, REAL *u_p, REAL *f_p, REAL tol, int mits); int main(int argc, char *argv[]) { int n = DEFAULT_DIMSIZE; int m = DEFAULT_DIMSIZE; REAL alpha = 0.0543; REAL tol = 0.0000000001; REAL relax = 1.0; int mits = 5000; /*fprintf(stderr, "Usage: jacobi [<n> <m> <alpha> <tol> <relax> <mits>]\n"); fprintf(stderr, "\tn - grid dimension in x direction, default: %d\n", n); fprintf(stderr, "\tm - grid dimension in y direction, default: n if provided or %d\n", m); fprintf(stderr, "\talpha - Helmholtz constant (always greater than 0.0), default: %g\n", alpha); fprintf(stderr, "\ttol - error tolerance for iterative solver, default: %g\n", tol); fprintf(stderr, "\trelax - Successice over relaxation parameter, default: %g\n", relax); fprintf(stderr, "\tmits - Maximum iterations for iterative solver, default: %d\n", mits);*/ if (argc == 2) { sscanf(argv[1], "%d", &n); m = n; } else if (argc == 3) { sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &m); } else if (argc == 4) { sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &m); sscanf(argv[3], "%g", &alpha); } else if (argc == 5) { sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &m); sscanf(argv[3], "%g", &alpha); sscanf(argv[4], "%g", &tol); } else if (argc == 6) { sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &m); sscanf(argv[3], "%g", &alpha); sscanf(argv[4], "%g", &tol); sscanf(argv[5], "%g", &relax); } else if (argc == 7) { sscanf(argv[1], "%d", &n); sscanf(argv[2], "%d", &m); sscanf(argv[3], "%g", &alpha); sscanf(argv[4], "%g", &tol); sscanf(argv[5], "%g", &relax); sscanf(argv[6], "%d", &mits); } else { /* the rest of arg ignored */ } printf("jacobi %d %d %g %g %g %d\n", n, m, alpha, tol, relax, mits); printf("------------------------------------------------------------------------------------------------------\n"); /** init the array */ REAL *u = (REAL *) malloc(sizeof(REAL) * n * m); REAL *uomp = (REAL *) malloc(sizeof(REAL) * n * m); REAL *f = (REAL *) malloc(sizeof(REAL) * n * m); REAL dx; /* grid spacing in x direction */ REAL dy; /* grid spacing in y direction */ initialize(n, m, alpha, &dx, &dy, u, f); memcpy(uomp, u, sizeof(REAL) * n * m); //warming up jacobi_seq(n, m, dx, dy, alpha, relax, u, f, tol, mits); jacobi_omp(n, m, dx, dy, alpha, relax, uomp, f, tol, mits); initialize(n, m, alpha, &dx, &dy, u, f); memcpy(uomp, u, sizeof(REAL) * n * m); int num_runs = 20; double elapsed = 0; for(int i = 0; i < 20; i++) { double elapsed1 = read_timer_ms(); jacobi_seq(n, m, dx, dy, alpha, relax, u, f, tol, mits); elapsed += read_timer_ms() - elapsed1; } printf("seq elasped time(ms): %4f\n", elapsed/num_runs); //double mflops = (0.001 * mits * (n - 2) * (m - 2) * 13) / elapsed; //printf("MFLOPS: %12.6g\n", mflops); puts("================"); double elapsed2 = 0; for(int i = 0; i < 20; i++) { double elapsed3 = read_timer_ms(); jacobi_omp(n, m, dx, dy, alpha, relax, uomp, f, tol, mits); elapsed2 += read_timer_ms() - elapsed3; } printf("OpenMP elasped time(ms): %4f\n", elapsed2/num_runs); //mflops = (0.001 * mits * (n - 2) * (m - 2) * 13) / elapsed; //printf("MFLOPS: %12.6g\n", mflops); //print_array("Sequential Run", "u",(REAL*)u, n, m); error_check(n, m, alpha, dx, dy, u, f); free(u); free(f); free(uomp); return 0; } /* subroutine jacobi (n,m,dx,dy,alpha,omega,u,f,tol,mits) ****************************************************************** * Subroutine HelmholtzJ * Solves poisson equation on rectangular grid assuming : * (1) Uniform discretization in each direction, and * (2) Dirichlect boundary conditions * * Jacobi method is used in this routine * * Input : n,m Number of grid points in the X/Y directions * dx,dy Grid spacing in the X/Y directions * alpha Helmholtz eqn. coefficient * omega Relaxation factor * f(n,m) Right hand side function * u(n,m) Dependent variable/Solution * tol Tolerance for iterative solver * mits Maximum number of iterations * * Output : u(n,m) - Solution *****************************************************************/ void jacobi_seq(int n, int m, REAL dx, REAL dy, REAL alpha, REAL omega, REAL *u_p, REAL *f_p, REAL tol, int mits) { int i, j, k; REAL error; REAL ax; REAL ay; REAL b; REAL resid; REAL uold[n][m]; REAL (*u)[m] = (REAL (*)[m]) u_p; REAL (*f)[m] = (REAL (*)[m]) f_p; /* * Initialize coefficients */ /* X-direction coef */ ax = (1.0 / (dx * dx)); /* Y-direction coef */ ay = (1.0 / (dy * dy)); /* Central coeff */ b = (((-2.0 / (dx * dx)) - (2.0 / (dy * dy))) - alpha); error = (10.0 * tol); k = 1; while ((k <= mits) && (error > tol)) { error = 0.0; /* Copy new solution into old */ for (i = 0; i < n; i++) for (j = 0; j < m; j++) uold[i][j] = u[i][j]; for (i = 1; i < (n - 1); i++) for (j = 1; j < (m - 1); j++) { resid = (ax * (uold[i - 1][j] + uold[i + 1][j]) + ay * (uold[i][j - 1] + uold[i][j + 1]) + b * uold[i][j] - f[i][j]) / b; //printf("i: %d, j: %d, resid: %f\n", i, j, resid); u[i][j] = uold[i][j] - omega * resid; error = error + resid * resid; } /* Error check */ //if (k % 500 == 0) // printf("Finished %d iteration with error: %g\n", k, error); error = sqrt(error) / (n * m); k = k + 1; } /* End iteration loop */ printf("Total Number of Iterations: %d\n", k); printf("Residual: %.15g\n", error); } void jacobi_omp(int n, int m, REAL dx, REAL dy, REAL alpha, REAL omega, REAL *u_p, REAL *f_p, REAL tol, int mits) { int i, j, k; REAL error; REAL ax; REAL ay; REAL b; REAL resid; REAL *tmp = (REAL *) malloc(sizeof(REAL) * n * m); REAL (*uold)[m] = (REAL (*)[m]) tmp; REAL (*u)[m] = (REAL (*)[m]) u_p; REAL (*f)[m] = (REAL (*)[m]) f_p; /* * Initialize coefficients */ /* X-direction coef */ ax = (1.0 / (dx * dx)); /* Y-direction coef */ ay = (1.0 / (dy * dy)); /* Central coeff */ b = (((-2.0 / (dx * dx)) - (2.0 / (dy * dy))) - alpha); error = (10.0 * tol); k = 1; while ((k <= mits) && (error > tol)) { error = 0.0; //printf("===================== iteration %d ===========================\n", k); /* Copy new solution into old */ for (i = 0; i < n; i++) #pragma omp simd simdlen(8) for (j = 0; j < m; j++) uold[i][j] = u[i][j]; for (i = 1; i < (n - 1); i++) #pragma omp simd simdlen(8) reduction(+:error) for (j = 1; j < (m - 1); j++) { resid = (ax * (uold[i - 1][j] + uold[i + 1][j]) + ay * (uold[i][j - 1] + uold[i][j + 1]) + b * uold[i][j] - f[i][j]) / b; //printf("i: %d, j: %d, resid: %f\n", i, j, resid); u[i][j] = uold[i][j] - omega * resid; error = error + resid * resid; } /* Error check */ //if (k % 500 == 0) // printf("Finished %d iteration with error: %g\n", k, error); error = sqrt(error) / (n * m); k = k + 1; } /* End iteration loop */ printf("Total Number of Iterations: %d\n", k); printf("Residual: %.15g\n", error); free(tmp); }
GB_unaryop__abs_fp32_fp64.c
//------------------------------------------------------------------------------ // GB_unaryop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_iterator.h" #include "GB_unaryop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop__abs_fp32_fp64 // op(A') function: GB_tran__abs_fp32_fp64 // C type: float // A type: double // cast: float cij = (float) aij // unaryop: cij = fabsf (aij) #define GB_ATYPE \ double #define GB_CTYPE \ float // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ double aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = fabsf (x) ; // casting #define GB_CASTING(z, aij) \ float z = (float) aij ; // cij = op (cast (aij)) #define GB_CAST_OP(pC,pA) \ { \ /* aij = Ax [pA] */ \ GB_GETA (aij, Ax, pA) ; \ /* Cx [pC] = op (cast (aij)) */ \ GB_CASTING (z, aij) ; \ GB_OP (GB_CX (pC), z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_ABS || GxB_NO_FP32 || GxB_NO_FP64) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop__abs_fp32_fp64 ( float *Cx, // Cx and Ax may be aliased double *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GB_CAST_OP (p, p) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_tran__abs_fp32_fp64 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unaryop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
templatemath.h
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ /* * templatemath.h * * Created on: Jan 1, 2016 * Author: agibsonccc */ #ifndef TEMPLATEMATH_H_ #define TEMPLATEMATH_H_ #include <dll.h> #include <pointercast.h> #include <platformmath.h> #define BFLOAT16_MAX_VALUE 32737. #define HALF_MAX_VALUE 65504. #define FLOAT_MAX_VALUE 3.4028235E38 #define DOUBLE_MAX_VALUE 1.7976931348623157E308 #define FLOAT_MIN_NORMAL 1.17549435e-38 #ifndef M_E #define M_E 2.718281828459 #endif namespace nd4j { #ifdef __CUDACC__ #endif namespace math { template<typename T> math_def inline T nd4j_abs(T value); template<typename T> math_def inline void nd4j_swap(T &val1, T &val2); template<typename T> math_def inline T nd4j_max(T val1, T val2); template<typename T> math_def inline T nd4j_min(T val1, T val2); template<typename T, typename Z> math_def inline Z nd4j_re(T val1, T val2); template<typename T, typename Z> math_def inline Z nd4j_rint(T val1); template<typename T, typename Z> math_def inline Z nd4j_copysign(T val1, T val2); //#ifndef __CUDACC__ template<typename X, typename Y, typename Z> math_def inline Z nd4j_dot(X *x, Y *y, int length); //#endif template<typename T, typename Z> math_def inline Z nd4j_ceil(T val1); template<typename T> math_def inline bool nd4j_isnan(T val1); template<typename T> math_def inline bool nd4j_isinf(T val1); template<typename T> math_def inline bool nd4j_isfin(T val1); template<typename T, typename Z> math_def inline Z nd4j_cos(T val); template<typename T, typename Z> math_def inline Z nd4j_cosh(T val); template<typename X, typename Z> math_def inline Z nd4j_exp(X val); template<typename T, typename Z> math_def inline Z nd4j_floor(T val); template<typename X, typename Z> math_def inline Z nd4j_log(X val); template<typename X, typename Y, typename Z> math_def inline Z nd4j_pow(X val, Y val2); template<typename T, typename Z> math_def inline Z nd4j_round(T val); template<typename X, typename Y, typename Z> math_def inline Z nd4j_remainder(X num, Y denom); template<typename X, typename Y, typename Z> math_def inline Z nd4j_fmod(X num, Y denom); template<typename T, typename Z> math_def inline Z nd4j_erf(T num); template<typename T, typename Z> math_def inline Z nd4j_erfc(T num); template<typename T, typename Z> math_def inline Z nd4j_sigmoid(T val) { return (Z) 1.0f / ((Z) 1.0f + nd4j_exp<T, Z>(-val)); } template<typename T, typename Z> math_def inline Z nd4j_elu(T val) { if (val >= (T) 0.f) return val; else return nd4j_exp<T, Z>(val) - (Z) 1.0f; //return val >= 0.0 ? val : (nd4j_exp<T>(val) - 1.0); } template<typename T, typename Z> math_def inline Z nd4j_leakyrelu(T val,T alpha) { if (val < (T) 0.0f) return alpha * val; else return val; } template<typename T, typename Z> math_def inline Z nd4j_eluderivative(T val) { if (val >= (T) 0.0f) return (Z) 1.0f; else return nd4j_exp<T, Z>(val); //return val >= 0.0 ? 1.0 : nd4j_exp(val); } template<typename T, typename Z> math_def inline Z nd4j_sin(T val); template<typename T, typename Z> math_def inline Z nd4j_sinh(T val); template<typename T, typename Z> math_def inline Z softplus(T val) { return nd4j_log<T, Z>((Z) 1.0f + nd4j_exp<T, Z>(val)); } template<typename T, typename Z> math_def inline Z nd4j_softsign(T val) { return val / ((T) 1.0f + nd4j::math::nd4j_abs<T>(val)); } template<typename X, typename Z> math_def inline Z nd4j_sqrt(X val); template<typename X, typename Z> math_def inline Z nd4j_tanh(X val); template<typename T, typename Z> math_def inline Z nd4j_tan(T val); template<typename X, typename Z> math_def inline Z nd4j_atan2(X val1, X val2); template<typename X, typename Z> math_def inline Z nd4j_atan2(X val1, X val2) { return p_atan2<Z>(static_cast<Z>(val1), static_cast<Z>(val2)); } template<typename T, typename Z> math_def inline Z nd4j_tan(T tval) { auto val = static_cast<Z>(tval); return nd4j_log<Z, Z>((val + (Z)1.f / ((Z) 1.f - val)) * (Z) 0.5f); } template<typename T, typename Z> math_def inline Z nd4j_tanhderivative(T val) { Z tanh = nd4j_tanh<T,Z>(val); return (Z) 1.0f - tanh * tanh; } template <typename T, typename Z> math_def inline T nd4j_sigmoidderivative(T val) { Z sigmoid = nd4j_sigmoid<T,Z>(val); return sigmoid * ((Z) 1.0f - sigmoid); } template<typename T, typename Z> math_def inline T nd4j_softsignderivative(T val) { T y = (T) 1.0f + nd4j_abs(val); return (Z) 1.0f / (y * y); } template<typename T, typename Z> math_def inline T nd4j_sgn(T val) { return val < (T) 0.0f ? (Z) -1.0f : val > (T) 0.0f ? (Z) 1.0f : (Z) 0.0f; } template<typename T, typename Z> math_def inline Z nd4j_sign(T val) { return nd4j_sgn<T, Z>(val); } template<typename T, typename Z> math_def inline Z nd4j_signum(T val) { return nd4j_sgn<T, Z>(val); } //#ifndef __CUDACC__ /* template<> math_def inline float16 nd4j_dot<float16>(float16 *x, float16 *y, int length) { float16 dot = (float16) 0.0f; // TODO: since we can't use simd on unions, we might use something else here. for(int e = 0; e < length; e++) { dot += x[e] * y[e]; } return dot; } */ template<typename X, typename Y, typename Z> math_def inline Z nd4j_dot(X *x, Y *y, int length) { Z dot = (Z)0.0f; //#pragma omp simd reduction(+:dot) for(int e = 0; e < length; e++) { dot += static_cast<Z>(x[e]) * static_cast<Z>(y[e]); } return dot; } //#endif template<typename T, typename Z> math_def inline Z nd4j_acos(T val); template<typename T, typename Z> math_def inline Z nd4j_acosh(T val); template<typename T, typename Z> math_def inline Z nd4j_asin(T val); template<typename T, typename Z> math_def inline Z nd4j_asinh(T val); template<typename T, typename Z> math_def inline Z nd4j_asinh(T val) { //Math.log(Math.sqrt(Math.pow(x, 2) + 1) + x) return nd4j_log<Z, Z>(nd4j_sqrt<Z, Z>(nd4j_pow<T,T,Z>(val, (T) 2) + (Z) 1.f) + (Z) val); } template<typename T, typename Z> math_def inline Z nd4j_atan(T val); template<typename T, typename Z> math_def inline Z nd4j_atanh(T val); template<> math_def inline float16 nd4j_abs<float16>(float16 value) { #ifdef NATIVE_HALFS if (value < (float16) 0.f) { return float16(__hneg(value.data)); } else return value; #else return (float16) fabsf((float) value); #endif } template<> math_def inline bfloat16 nd4j_abs<bfloat16>(bfloat16 value) { return (bfloat16) fabsf((float) value); } template<> math_def inline float nd4j_abs<float>(float value) { return fabsf(value); } template<> math_def inline double nd4j_abs<double>(double value) { return fabs(value); } template<> math_def inline int nd4j_abs<int>(int value) { return abs(value); } template<> math_def inline Nd4jLong nd4j_abs<Nd4jLong>(Nd4jLong value) { return llabs(value); } template<> math_def inline bool nd4j_abs<bool>(bool value) { return value; } template<> math_def inline uint8_t nd4j_abs<uint8_t>(uint8_t value) { return value; } template<> math_def inline uint16_t nd4j_abs<uint16_t>(uint16_t value) { return value; } template<> math_def inline uint32_t nd4j_abs<uint32_t>(uint32_t value) { return value; } template<> math_def inline Nd4jULong nd4j_abs<Nd4jULong>(Nd4jULong value) { return value; } template<> math_def inline int8_t nd4j_abs<int8_t>(int8_t value) { return value < 0 ? -value : value; } template<> math_def inline int16_t nd4j_abs<int16_t>(int16_t value) { return value < 0 ? -value : value; } template<> math_def inline bool nd4j_isnan<float16>(float16 value) { return *(value.data.getXP()) == 0x7fffU; } template<> math_def inline bool nd4j_isnan<bfloat16>(bfloat16 value) { return value == bfloat16::nan(); //0x7fffU; } template<> math_def inline bool nd4j_isnan<float>(float value) { return value != value; } template<> math_def inline bool nd4j_isnan<double>(double value) { return value != value; } template<> math_def inline bool nd4j_isnan<int>(int value) { return false; } template<> math_def inline bool nd4j_isnan<uint32_t>(uint32_t value) { return false; } template<> math_def inline bool nd4j_isnan<uint16_t>(uint16_t value) { return false; } template<> math_def inline bool nd4j_isnan<uint8_t>(uint8_t value) { return false; } template<> math_def inline bool nd4j_isnan<int16_t>(int16_t value) { return false; } template<> math_def inline bool nd4j_isnan<int8_t>(int8_t value) { return false; } template<> math_def inline bool nd4j_isnan<bool>(bool value) { return false; } template<> math_def inline bool nd4j_isnan<Nd4jLong>(Nd4jLong value) { return false; } template<> math_def inline bool nd4j_isnan<Nd4jULong>(Nd4jULong value) { return false; } template<> math_def inline bool nd4j_isinf<float16>(float16 value) { return value < (float16) -HALF_MAX_VALUE || value > (float16) HALF_MAX_VALUE; } template<> math_def inline bool nd4j_isinf<bfloat16>(bfloat16 value) { return value < (bfloat16) -BFLOAT16_MAX_VALUE || value > (bfloat16) BFLOAT16_MAX_VALUE; } template<> math_def inline bool nd4j_isinf<float>(float value) { #ifdef __CUDACC__ return isinf(value); #else return std::isinf(value); #endif //return value < -FLOAT_MAX_VALUE || value > FLOAT_MAX_VALUE; } template<> math_def inline bool nd4j_isinf<double>(double value) { #ifdef __CUDACC__ return isinf(value); #else return std::isinf(value); #endif //return value < -DOUBLE_MAX_VALUE || value > DOUBLE_MAX_VALUE; } template<> math_def inline bool nd4j_isinf<int>(int value) { return false; } template<> math_def inline bool nd4j_isinf<uint32_t>(uint32_t value) { return false; } template<> math_def inline bool nd4j_isinf<uint16_t>(uint16_t value) { return false; } template<> math_def inline bool nd4j_isinf<uint8_t>(uint8_t value) { return false; } template<> math_def inline bool nd4j_isinf<int16_t>(int16_t value) { return false; } template<> math_def inline bool nd4j_isinf<int8_t>(int8_t value) { return false; } template<> math_def inline bool nd4j_isinf<bool>(bool value) { return false; } template<> math_def inline bool nd4j_isinf<Nd4jLong>(Nd4jLong value) { return false; } template<> math_def inline bool nd4j_isinf<Nd4jULong>(Nd4jULong value) { return false; } template<typename T> math_def inline bool nd4j_isfin(T value) { return !nd4j_isnan<T>(value) && !nd4j_isinf<T>(value); } template<> math_def inline float16 nd4j_copysign<float16>(float16 val1, float16 val2) { return (float16) copysignf((float) val1, (float) val2); } template<> math_def inline float nd4j_copysign<float>(float val1, float val2) { return copysignf(val1, val2); } template<> math_def inline double nd4j_copysign<double>(double val1, double val2) { return copysign(val1, val2); } template<> math_def inline int nd4j_copysign<int>(int val1, int val2) { if (val2 < 0) return -(nd4j_abs<int>(val1)); else return nd4j_abs<int>(val1); } template<> math_def inline Nd4jLong nd4j_copysign<Nd4jLong>(Nd4jLong val1, Nd4jLong val2) { if (val2 < 0) return -(nd4j_abs<Nd4jLong>(val1)); else return nd4j_abs<Nd4jLong>(val1); } template<> math_def inline bool nd4j_max(bool val1, bool val2) { return (val1 || val2) ? true : false; } template<typename T> math_def inline T nd4j_max(T val1, T val2) { return val1 > val2 ? val1 : val2; } template<> math_def inline bool nd4j_min(bool val1, bool val2) { return (val1 && val2) ? true : false; } template<typename T> math_def inline T nd4j_min(T val1, T val2) { return val1 < val2 ? val1 : val2; } template <typename X, typename Z> math_def inline Z nd4j_ceil(X val) { return static_cast<Z>(p_ceil<X>(val)); } template <typename X, typename Z> math_def inline Z nd4j_round(X val) { return static_cast<Z>(p_round<X>(val)); } template <typename X, typename Z> math_def inline Z nd4j_asin(X val) { return p_asin<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_atan(X val) { return p_atan<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_atanh(X val) { return p_atanh<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_cosh(X val) { return p_cosh<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_rint(X val) { return p_rint<X>(val); } template <typename X, typename Z> math_def inline Z nd4j_sinh(X val) { return p_sinh<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_acos(X val) { return p_acos<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_acosh(X val) { return p_acosh<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_cos(X val) { return p_cos<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_exp(X val) { return p_exp<X>(val); } template<typename X, typename Z> math_def inline Z nd4j_floor(X val) { return static_cast<Z>(p_floor<X>(val)); } template<typename X, typename Z> math_def inline Z nd4j_log(X val) { return static_cast<Z>(p_log<X>(val)); } /** * This func is special case - it must return floating point value, and optionally Y arg can be floating point argument * @tparam X * @tparam Y * @tparam Z * @param val * @param val2 * @return */ template <typename X, typename Y, typename Z> math_def inline Z nd4j_pow(X val, Y val2) { return p_pow<Z>(static_cast<Z>(val), static_cast<Z>(val2)); } template<typename T> math_def inline T nd4j_re(T val1, T val2) { if (val1 == (T) 0.0f && val2 == (T) 0.0f) return (T) 0.0f; return nd4j_abs<T>(val1 - val2) / (nd4j_abs<T>(val1) + nd4j_abs<T>(val2)); } template <typename X, typename Y, typename Z> math_def inline Z nd4j_remainder(X val, Y val2) { return p_remainder<Z>(static_cast<Z>(val), static_cast<Z>(val2)); } template <typename X, typename Y, typename Z> math_def inline Z nd4j_fmod(X val, Y val2) { return p_fmod<Z>(static_cast<Z>(val), static_cast<Z>(val2)); } template <typename X, typename Z> math_def inline Z nd4j_sin(X val) { return p_sin<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_sqrt(X val) { return p_sqrt<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_tanh(X val) { return p_tanh<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_erf(X val) { return p_erf<Z>(static_cast<Z>(val)); } template <typename X, typename Z> math_def inline Z nd4j_erfc(X val) { return p_erfc<Z>(static_cast<Z>(val)); } template<typename T> math_def inline void nd4j_swap(T &val1, T &val2) { T temp = val1; val1=val2; val2=temp; }; #ifdef __CUDACC__ namespace atomics { template <typename T> inline __device__ T nd4j_atomicAdd(T* address, T val); template <typename T> inline __device__ T nd4j_atomicSub(T* address, T val); template <typename T> inline __device__ T nd4j_atomicMul(T* address, T val); template <typename T> inline __device__ T nd4j_atomicDiv(T* address, T val); template <> inline __device__ double nd4j_atomicAdd<double>(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int *) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed,__double_as_longlong(val + __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); } template <> inline __device__ float16 nd4j_atomicAdd<float16>(float16* address, float16 val) { int* address_as_ull = (int*) address; long addr = (long) address; bool misaligned = addr & 0x3; if (misaligned) address_as_ull = (int *) (addr - 2); PAIR old, assumed, fresh; old.W = *address_as_ull; do { if (!misaligned) { float16 res = ((float16) old.B.H) + val; fresh.B.H = res.data; fresh.B.L = old.B.L; } else { float16 res = ((float16) old.B.L) + val; fresh.B.L = res.data; fresh.B.H = old.B.H; } assumed.W = old.W; old.W = atomicCAS(address_as_ull, assumed.W, fresh.W); } while (assumed.W != old.W); if (!misaligned) return old.B.H; else return old.B.L; } template <> inline __device__ bfloat16 nd4j_atomicAdd<bfloat16>(bfloat16* address, bfloat16 val) { int* address_as_ull = (int*) address; long addr = (long)(address); bool misaligned = addr & 0x3; if (misaligned) address_as_ull = (int *) (addr - 2); BPAIR old, assumed, fresh; old.W = *address_as_ull; do { if (!misaligned) { bfloat16 res = old.B.H + val; fresh.B.H = res; fresh.B.L = old.B.L; } else { bfloat16 res = old.B.L + val; fresh.B.L = res; fresh.B.H = old.B.H; } assumed.W = old.W; old.W = atomicCAS(address_as_ull, assumed.W, fresh.W); } while (assumed.W != old.W); if (!misaligned) return old.B.H; else return old.B.L; } template <> inline __device__ double nd4j_atomicSub<double>(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int *) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed,__double_as_longlong(val - __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); } template <> inline __device__ double nd4j_atomicMul<double>(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int*) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed,__double_as_longlong(val * __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); } template <> inline __device__ double nd4j_atomicDiv<double>(double* address, double val) { unsigned long long int* address_as_ull = (unsigned long long int*) address; unsigned long long int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed,__double_as_longlong(val / __longlong_as_double(assumed))); } while (assumed != old); return __longlong_as_double(old); } template <> inline __device__ float nd4j_atomicAdd<float>(float* address, float val) { return atomicAdd(address,val); } template <> inline __device__ float nd4j_atomicSub<float>(float* address, float val) { int* address_as_ull = (int*) address; int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __float_as_int(val - __float_as_int(assumed))); } while (assumed != old); return __int_as_float(old); } template <> inline __device__ float nd4j_atomicMul<float>(float* address, float val) { int* address_as_ull = ( int*)address; int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __float_as_int(val * __float_as_int(assumed))); } while (assumed != old); return __int_as_float(old); } template <> inline __device__ float nd4j_atomicDiv<float>(float* address, float val) { int* address_as_ull = (int*)address; int old = *address_as_ull, assumed; do { assumed = old; old = atomicCAS(address_as_ull, assumed, __float_as_int(val * __float_as_int(assumed))); } while (assumed != old); return __int_as_float(old); } } #endif } } #endif /* TEMPLATEMATH_H_ */
ast-dump-openmp-distribute-simd.c
// RUN: %clang_cc1 -triple x86_64-unknown-unknown -fopenmp -ast-dump %s | FileCheck --match-full-lines -implicit-check-not=openmp_structured_block %s void test_one(int x) { #pragma omp distribute simd for (int i = 0; i < x; i++) ; } void test_two(int x, int y) { #pragma omp distribute simd for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_three(int x, int y) { #pragma omp distribute simd collapse(1) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_four(int x, int y) { #pragma omp distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) ; } void test_five(int x, int y, int z) { #pragma omp distribute simd collapse(2) for (int i = 0; i < x; i++) for (int i = 0; i < y; i++) for (int i = 0; i < z; i++) ; } // CHECK: TranslationUnitDecl {{.*}} <<invalid sloc>> <invalid sloc> // CHECK: |-FunctionDecl {{.*}} <{{.*}}ast-dump-openmp-distribute-simd.c:3:1, line:7:1> line:3:6 test_one 'void (int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:22, line:7:1> // CHECK-NEXT: | `-OMPDistributeSimdDirective {{.*}} <line:4:1, col:28> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:5:3, line:6:5> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:5:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:6:5> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:4:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-simd.c:4:1) *const restrict' // CHECK-NEXT: | | `-VarDecl {{.*}} <line:5:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:9:1, line:14:1> line:9:6 test_two 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:15, col:19> col:19 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:22, col:26> col:26 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:29, line:14:1> // CHECK-NEXT: | `-OMPDistributeSimdDirective {{.*}} <line:10:1, col:28> // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:11:3, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:11:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:12:5, line:13:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:12:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:13:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:10:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-simd.c:10:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:11:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:12:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:11:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:12:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:16:1, line:21:1> line:16:6 test_three 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:17, col:21> col:21 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:24, col:28> col:28 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:31, line:21:1> // CHECK-NEXT: | `-OMPDistributeSimdDirective {{.*}} <line:17:1, col:40> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:29, col:39> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:38> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:38> 'int' 1 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:18:3, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:18:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:19:5, line:20:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:19:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:20:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:17:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-simd.c:17:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:18:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:19:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:18:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:19:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: |-FunctionDecl {{.*}} <line:23:1, line:28:1> line:23:6 test_four 'void (int, int)' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: | |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: | `-CompoundStmt {{.*}} <col:30, line:28:1> // CHECK-NEXT: | `-OMPDistributeSimdDirective {{.*}} <line:24:1, col:40> // CHECK-NEXT: | |-OMPCollapseClause {{.*}} <col:29, col:39> // CHECK-NEXT: | | `-ConstantExpr {{.*}} <col:38> 'int' // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:38> 'int' 2 // CHECK-NEXT: | `-CapturedStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | | |-ForStmt {{.*}} <line:25:3, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:25:8, col:17> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ForStmt {{.*}} <line:26:5, line:27:7> // CHECK-NEXT: | | | |-DeclStmt {{.*}} <line:26:10, col:19> // CHECK-NEXT: | | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | | |-<<<NULL>>> // CHECK-NEXT: | | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-NullStmt {{.*}} <line:27:7> // CHECK-NEXT: | | |-ImplicitParamDecl {{.*}} <line:24:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-simd.c:24:1) *const restrict' // CHECK-NEXT: | | |-VarDecl {{.*}} <line:25:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | `-VarDecl {{.*}} <line:26:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | |-DeclRefExpr {{.*}} <line:25:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | `-DeclRefExpr {{.*}} <line:26:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-FunctionDecl {{.*}} <line:30:1, line:36:1> line:30:6 test_five 'void (int, int, int)' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:16, col:20> col:20 used x 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:23, col:27> col:27 used y 'int' // CHECK-NEXT: |-ParmVarDecl {{.*}} <col:30, col:34> col:34 used z 'int' // CHECK-NEXT: `-CompoundStmt {{.*}} <col:37, line:36:1> // CHECK-NEXT: `-OMPDistributeSimdDirective {{.*}} <line:31:1, col:40> // CHECK-NEXT: |-OMPCollapseClause {{.*}} <col:29, col:39> // CHECK-NEXT: | `-ConstantExpr {{.*}} <col:38> 'int' // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:38> 'int' 2 // CHECK-NEXT: `-CapturedStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: |-CapturedDecl {{.*}} <<invalid sloc>> <invalid sloc> nothrow // CHECK-NEXT: | |-ForStmt {{.*}} <line:32:3, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:32:8, col:17> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:19, col:23> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:19> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:19> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:26, col:27> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:26> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:33:5, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:33:10, col:19> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:21, col:25> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:21> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:21> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:25> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:28, col:29> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:28> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-ForStmt {{.*}} <line:34:7, line:35:9> // CHECK-NEXT: | | |-DeclStmt {{.*}} <line:34:12, col:21> // CHECK-NEXT: | | | `-VarDecl {{.*}} <col:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | | | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: | | |-<<<NULL>>> // CHECK-NEXT: | | |-BinaryOperator {{.*}} <col:23, col:27> 'int' '<' // CHECK-NEXT: | | | |-ImplicitCastExpr {{.*}} <col:23> 'int' <LValueToRValue> // CHECK-NEXT: | | | | `-DeclRefExpr {{.*}} <col:23> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | | `-ImplicitCastExpr {{.*}} <col:27> 'int' <LValueToRValue> // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:27> 'int' lvalue ParmVar {{.*}} 'z' 'int' // CHECK-NEXT: | | |-UnaryOperator {{.*}} <col:30, col:31> 'int' postfix '++' // CHECK-NEXT: | | | `-DeclRefExpr {{.*}} <col:30> 'int' lvalue Var {{.*}} 'i' 'int' // CHECK-NEXT: | | `-NullStmt {{.*}} <line:35:9> // CHECK-NEXT: | |-ImplicitParamDecl {{.*}} <line:31:1> col:1 implicit __context 'struct (anonymous at {{.*}}ast-dump-openmp-distribute-simd.c:31:1) *const restrict' // CHECK-NEXT: | |-VarDecl {{.*}} <line:32:8, col:16> col:12 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:16> 'int' 0 // CHECK-NEXT: | |-VarDecl {{.*}} <line:33:10, col:18> col:14 used i 'int' cinit // CHECK-NEXT: | | `-IntegerLiteral {{.*}} <col:18> 'int' 0 // CHECK-NEXT: | `-VarDecl {{.*}} <line:34:12, col:20> col:16 used i 'int' cinit // CHECK-NEXT: | `-IntegerLiteral {{.*}} <col:20> 'int' 0 // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:32:23> 'int' lvalue ParmVar {{.*}} 'x' 'int' // CHECK-NEXT: |-DeclRefExpr {{.*}} <line:33:25> 'int' lvalue ParmVar {{.*}} 'y' 'int' // CHECK-NEXT: `-DeclRefExpr {{.*}} <line:34:27> 'int' lvalue ParmVar {{.*}} 'z' 'int'
5493.c
/* POLYBENCH/GPU-OPENMP * * This file is a part of the Polybench/GPU-OpenMP suite * * Contact: * William Killian <killian@udel.edu> * * Copyright 2013, The University of Delaware */ #include <stdio.h> #include <unistd.h> #include <string.h> #include <math.h> /* Include polybench common header. */ #include <polybench.h> /* Include benchmark-specific header. */ /* Default data type is double, default size is 4096x4096. */ #include "convolution-2d.h" /* Array initialization. */ static void init_array (int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj)) { // printf("Initializing Array\n"); int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { A[i][j] = ((DATA_TYPE) (i + j) / nj); } } /* DCE code. Must scan the entire live-out data. Can be used also to check the correctness of the output. */ static void print_array(int ni, int nj, DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; for (i = 0; i < ni; i++) for (j = 0; j < nj; j++) { fprintf(stderr, DATA_PRINTF_MODIFIER, B[i][j]); if ((i * NJ + j) % 20 == 0) fprintf(stderr, "\n"); } fprintf(stderr, "\n"); } /* Main computational kernel. The whole function will be timed, including the call and return. */ static void kernel_conv2d(int ni, int nj, DATA_TYPE POLYBENCH_2D(A,NI,NJ,ni,nj), DATA_TYPE POLYBENCH_2D(B,NI,NJ,ni,nj)) { int i, j; #pragma scop #pragma omp parallel for private(i, j) collapse(#P12) schedule(#P9, #P11) num_threads(#P11) #pragma omp for (i = 1; i < _PB_NI - 1; ++i) { for (j = 1; j < _PB_NJ - 1; ++j) { B[i][j] = 0.2 * A[i-1][j-1] + 0.5 * A[i-1][j] + -0.8 * A[i-1][j+1] + -0.3 * A[ i ][j-1] + 0.6 * A[ i ][j] + -0.9 * A[ i ][j+1] + 0.4 * A[i+1][j-1] + 0.7 * A[i+1][j] + 0.1 * A[i+1][j+1]; } } #pragma endscop // printf("Kernal computation complete !!\n"); } int main(int argc, char** argv) { /* Retrieve problem size. */ int ni = NI; int nj = NJ; /* Variable declaration/allocation. */ POLYBENCH_2D_ARRAY_DECL(A, DATA_TYPE, NI, NJ, ni, nj); POLYBENCH_2D_ARRAY_DECL(B, DATA_TYPE, NI, NJ, ni, nj); /* Initialize array(s). */ init_array (ni, nj, POLYBENCH_ARRAY(A)); /* Start timer. */ //polybench_start_instruments; polybench_timer_start(); /* Run kernel. */ kernel_conv2d (ni, nj, POLYBENCH_ARRAY(A), POLYBENCH_ARRAY(B)); /* Stop and print timer. */ polybench_timer_stop(); polybench_timer_print(); //polybench_stop_instruments; //polybench_print_instruments; /* Prevent dead-code elimination. All live-out data must be printed by the function call in argument. */ polybench_prevent_dce(print_array(ni, nj, POLYBENCH_ARRAY(B))); /* Be clean. */ POLYBENCH_FREE_ARRAY(A); POLYBENCH_FREE_ARRAY(B); return 0; }
rawSHA384_fmt_plug.c
/* * This file is part of John the Ripper password cracker, * Copyright (c) 2010 by Solar Designer * based on rawMD4_fmt.c code, with trivial changes by groszek. * * Rewritten Spring 2013, JimF. SSE code added and released with the following terms: * No copyright is claimed, and the software is hereby placed in the public domain. * In case this attempt to disclaim copyright and place the software in the public * domain is deemed null and void, then the software is Copyright (c) 2011 JimF * and it is hereby released to the general public under the following * terms: * * This software may be modified, redistributed, and used for any * purpose, in source and binary forms, with or without modification. */ #if FMT_EXTERNS_H extern struct fmt_main fmt_rawSHA384; #elif FMT_REGISTERS_H john_register_one(&fmt_rawSHA384); #else #include "arch.h" #include "sha2.h" #include "stdint.h" #include "params.h" #include "common.h" #include "johnswap.h" #include "formats.h" //#undef SIMD_COEF_64 //#undef SIMD_PARA_SHA512 /* * Only effective for SIMD. * Undef to disable reversing steps for benchmarking. */ #define REVERSE_STEPS #ifdef _OPENMP #ifdef SIMD_COEF_64 #ifndef OMP_SCALE #define OMP_SCALE 1024 #endif #else #ifndef OMP_SCALE #define OMP_SCALE 2048 #endif #endif #include <omp.h> #endif #include "simd-intrinsics.h" #include "memdbg.h" #define FORMAT_LABEL "Raw-SHA384" #define FORMAT_NAME "" #define FORMAT_TAG "$SHA384$" #define TAG_LENGTH (sizeof(FORMAT_TAG) - 1) #ifdef SIMD_COEF_64 #define ALGORITHM_NAME SHA512_ALGORITHM_NAME #else #define ALGORITHM_NAME "32/" ARCH_BITS_STR " " SHA2_LIB #endif #define BENCHMARK_COMMENT "" #define BENCHMARK_LENGTH -1 #ifdef SIMD_COEF_64 #define PLAINTEXT_LENGTH 111 #else #define PLAINTEXT_LENGTH 125 #endif #define CIPHERTEXT_LENGTH 96 #define BINARY_SIZE DIGEST_SIZE #define DIGEST_SIZE 48 #define DIGEST_SIZE_512 64 #define BINARY_ALIGN 8 #define SALT_SIZE 0 #define SALT_ALIGN 1 #ifdef SIMD_COEF_64 #define MIN_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #define MAX_KEYS_PER_CRYPT (SIMD_COEF_64*SIMD_PARA_SHA512) #else #define MIN_KEYS_PER_CRYPT 1 #define MAX_KEYS_PER_CRYPT 1 #endif static struct fmt_tests tests[] = { {"a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$a8b64babd0aca91a59bdbb7761b421d4f2bb38280d3a75ba0f21f2bebc45583d446c598660c94ce680c47d19c30783a7", "password"}, {"$SHA384$8cafed2235386cc5855e75f0d34f103ccc183912e5f02446b77c66539f776e4bf2bf87339b4518a7cb1c2441c568b0f8", "12345678"}, {"$SHA384$38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", ""}, {"94e75dd8e1f16d7df761d76c021ad98c283791008b98368e891f411fc5aa1a83ef289e348abdecf5e1ba6971604a0cb0", "UPPERCASE"}, {NULL} }; #ifdef SIMD_COEF_64 #define GETPOS(i, index) ( (index&(SIMD_COEF_64-1))*8 + ((i)&(0xffffffff-7))*SIMD_COEF_64 + (7-((i)&7)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64*8 ) static ARCH_WORD_64 (*saved_key); static ARCH_WORD_64 (*crypt_out); #else static int (*saved_len); static char (*saved_key)[PLAINTEXT_LENGTH + 1]; static ARCH_WORD_64 (*crypt_out)[DIGEST_SIZE / sizeof(ARCH_WORD_64)]; #endif static void init(struct fmt_main *self) { #ifdef _OPENMP int omp_t; omp_t = omp_get_max_threads(); self->params.min_keys_per_crypt *= omp_t; omp_t *= OMP_SCALE; self->params.max_keys_per_crypt *= omp_t; #endif #ifndef SIMD_COEF_64 saved_len = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_len)); saved_key = mem_calloc(self->params.max_keys_per_crypt, sizeof(*saved_key)); crypt_out = mem_calloc(self->params.max_keys_per_crypt, sizeof(*crypt_out)); #else saved_key = mem_calloc_align(self->params.max_keys_per_crypt * SHA_BUF_SIZ, sizeof(*saved_key), MEM_ALIGN_SIMD); crypt_out = mem_calloc_align(self->params.max_keys_per_crypt * DIGEST_SIZE_512 / sizeof(ARCH_WORD_64), sizeof(*crypt_out), MEM_ALIGN_SIMD); #endif } static void done(void) { MEM_FREE(crypt_out); MEM_FREE(saved_key); #ifndef SIMD_COEF_64 MEM_FREE(saved_len); #endif } static int valid(char *ciphertext, struct fmt_main *self) { char *p, *q; p = ciphertext; if (!strncmp(p, FORMAT_TAG, TAG_LENGTH)) p += TAG_LENGTH; q = p; while (atoi16[ARCH_INDEX(*q)] != 0x7F) q++; return !*q && q - p == CIPHERTEXT_LENGTH; } static char *split(char *ciphertext, int index, struct fmt_main *self) { static char out[TAG_LENGTH + CIPHERTEXT_LENGTH + 1]; if (!strncmp(ciphertext, FORMAT_TAG, TAG_LENGTH)) ciphertext += TAG_LENGTH; memcpy(out, FORMAT_TAG, TAG_LENGTH); memcpy(out + TAG_LENGTH, ciphertext, CIPHERTEXT_LENGTH + 1); strlwr(out + TAG_LENGTH); return out; } void *get_binary(char *ciphertext) { static ARCH_WORD_64 *outw; unsigned char *out; char *p; int i; if (!outw) outw = mem_calloc_tiny(DIGEST_SIZE, BINARY_ALIGN); out = (unsigned char*)outw; p = ciphertext + TAG_LENGTH; for (i = 0; i < DIGEST_SIZE; i++) { out[i] = (atoi16[ARCH_INDEX(*p)] << 4) | atoi16[ARCH_INDEX(p[1])]; p += 2; } #ifdef SIMD_COEF_64 alter_endianity_to_BE64(out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha384_reverse(outw); #endif #endif return out; } #ifdef SIMD_COEF_64 #define HASH_IDX (((unsigned int)index&(SIMD_COEF_64-1))+(unsigned int)index/SIMD_COEF_64*8*SIMD_COEF_64 + 3*SIMD_COEF_64) static int get_hash_0 (int index) { return crypt_out[HASH_IDX] & PH_MASK_0; } static int get_hash_1 (int index) { return crypt_out[HASH_IDX] & PH_MASK_1; } static int get_hash_2 (int index) { return crypt_out[HASH_IDX] & PH_MASK_2; } static int get_hash_3 (int index) { return crypt_out[HASH_IDX] & PH_MASK_3; } static int get_hash_4 (int index) { return crypt_out[HASH_IDX] & PH_MASK_4; } static int get_hash_5 (int index) { return crypt_out[HASH_IDX] & PH_MASK_5; } static int get_hash_6 (int index) { return crypt_out[HASH_IDX] & PH_MASK_6; } #else static int get_hash_0(int index) { return crypt_out[index][3] & PH_MASK_0; } static int get_hash_1(int index) { return crypt_out[index][3] & PH_MASK_1; } static int get_hash_2(int index) { return crypt_out[index][3] & PH_MASK_2; } static int get_hash_3(int index) { return crypt_out[index][3] & PH_MASK_3; } static int get_hash_4(int index) { return crypt_out[index][3] & PH_MASK_4; } static int get_hash_5(int index) { return crypt_out[index][3] & PH_MASK_5; } static int get_hash_6(int index) { return crypt_out[index][3] & PH_MASK_6; } #endif static int binary_hash_0(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_0; } static int binary_hash_1(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_1; } static int binary_hash_2(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_2; } static int binary_hash_3(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_3; } static int binary_hash_4(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_4; } static int binary_hash_5(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_5; } static int binary_hash_6(void *binary) { return ((ARCH_WORD_64*)binary)[3] & PH_MASK_6; } static void set_key(char *key, int index) { #ifdef SIMD_COEF_64 #if ARCH_ALLOWS_UNALIGNED const ARCH_WORD_64 *wkey = (ARCH_WORD_64*)key; #else char buf_aligned[PLAINTEXT_LENGTH + 1] JTR_ALIGN(sizeof(uint64_t)); const ARCH_WORD_64 *wkey = is_aligned(key, sizeof(uint64_t)) ? (ARCH_WORD_64*)key : (ARCH_WORD_64*)strcpy(buf_aligned, key); #endif ARCH_WORD_64 *keybuffer = &((ARCH_WORD_64*)saved_key)[(index&(SIMD_COEF_64-1)) + (unsigned int)index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64]; ARCH_WORD_64 *keybuf_word = keybuffer; unsigned int len; ARCH_WORD_64 temp; len = 0; while((unsigned char)(temp = *wkey++)) { if (!(temp & 0xff00)) { *keybuf_word = JOHNSWAP64((temp & 0xff) | (0x80 << 8)); len++; goto key_cleaning; } if (!(temp & 0xff0000)) { *keybuf_word = JOHNSWAP64((temp & 0xffff) | (0x80 << 16)); len+=2; goto key_cleaning; } if (!(temp & 0xff000000)) { *keybuf_word = JOHNSWAP64((temp & 0xffffff) | (0x80ULL << 24)); len+=3; goto key_cleaning; } if (!(temp & 0xff00000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffff) | (0x80ULL << 32)); len+=4; goto key_cleaning; } if (!(temp & 0xff0000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffULL) | (0x80ULL << 40)); len+=5; goto key_cleaning; } if (!(temp & 0xff000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffULL) | (0x80ULL << 48)); len+=6; goto key_cleaning; } if (!(temp & 0xff00000000000000ULL)) { *keybuf_word = JOHNSWAP64((temp & 0xffffffffffffffULL) | (0x80ULL << 56)); len+=7; goto key_cleaning; } *keybuf_word = JOHNSWAP64(temp); len += 8; keybuf_word += SIMD_COEF_64; } *keybuf_word = 0x8000000000000000ULL; key_cleaning: keybuf_word += SIMD_COEF_64; while(*keybuf_word) { *keybuf_word = 0; keybuf_word += SIMD_COEF_64; } keybuffer[15*SIMD_COEF_64] = len << 3; #else int len = strlen(key); saved_len[index] = len; if (len > PLAINTEXT_LENGTH) len = saved_len[index] = PLAINTEXT_LENGTH; memcpy(saved_key[index], key, len); #endif } static char *get_key(int index) { #ifdef SIMD_COEF_64 unsigned i; ARCH_WORD_64 s; static char out[PLAINTEXT_LENGTH + 1]; unsigned char *wucp = (unsigned char*)saved_key; s = ((ARCH_WORD_64*)saved_key)[15*SIMD_COEF_64 + (index&(SIMD_COEF_64-1)) + index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64] >> 3; for(i = 0; i < (unsigned)s; i++) out[i] = wucp[ GETPOS(i, index) ]; out[i] = 0; return (char*) out; #else saved_key[index][saved_len[index]] = 0; return saved_key[index]; #endif } #ifndef REVERSE_STEPS #undef SSEi_REVERSE_STEPS #define SSEi_REVERSE_STEPS 0 #endif static int crypt_all(int *pcount, struct db_salt *salt) { const int count = *pcount; int index = 0; #ifdef _OPENMP #pragma omp parallel for for (index = 0; index < count; index += MAX_KEYS_PER_CRYPT) #endif { #ifdef SIMD_COEF_64 SIMDSHA512body(&saved_key[index/SIMD_COEF_64*SHA_BUF_SIZ*SIMD_COEF_64], &crypt_out[index/SIMD_COEF_64*8*SIMD_COEF_64], NULL, SSEi_REVERSE_STEPS|SSEi_MIXED_IN|SSEi_CRYPT_SHA384); #else SHA512_CTX ctx; SHA384_Init(&ctx); SHA384_Update(&ctx, saved_key[index], saved_len[index]); SHA384_Final((unsigned char *)crypt_out[index], &ctx); #endif } return count; } static int cmp_all(void *binary, int count) { unsigned int index; for (index = 0; index < count; index++) #ifdef SIMD_COEF_64 if (((ARCH_WORD_64*)binary)[3] == crypt_out[HASH_IDX]) #else if ( ((ARCH_WORD_64*)binary)[0] == crypt_out[index][0] ) #endif return 1; return 0; } static int cmp_one(void *binary, int index) { #ifdef SIMD_COEF_64 return ((ARCH_WORD_64*)binary)[3] == crypt_out[HASH_IDX]; #else return *(ARCH_WORD_64*)binary == crypt_out[index][0]; #endif } static int cmp_exact(char *source, int index) { ARCH_WORD_64 *binary = get_binary(source); char *key = get_key(index); SHA512_CTX ctx; ARCH_WORD_64 crypt_out[DIGEST_SIZE / sizeof(ARCH_WORD_64)]; SHA384_Init(&ctx); SHA384_Update(&ctx, key, strlen(key)); SHA384_Final((unsigned char*)crypt_out, &ctx); #ifdef SIMD_COEF_64 alter_endianity_to_BE64(crypt_out, DIGEST_SIZE/8); #ifdef REVERSE_STEPS sha384_reverse(crypt_out); #endif #endif return !memcmp(binary, crypt_out, DIGEST_SIZE); } struct fmt_main fmt_rawSHA384 = { { FORMAT_LABEL, FORMAT_NAME, "SHA384 " ALGORITHM_NAME, BENCHMARK_COMMENT, BENCHMARK_LENGTH, 0, PLAINTEXT_LENGTH, BINARY_SIZE, BINARY_ALIGN, SALT_SIZE, SALT_ALIGN, MIN_KEYS_PER_CRYPT, MAX_KEYS_PER_CRYPT, FMT_CASE | FMT_8_BIT | FMT_OMP | FMT_OMP_BAD | FMT_SPLIT_UNIFIES_CASE, { NULL }, { FORMAT_TAG }, tests }, { init, done, fmt_default_reset, fmt_default_prepare, valid, split, get_binary, fmt_default_salt, { NULL }, fmt_default_source, { binary_hash_0, binary_hash_1, binary_hash_2, binary_hash_3, binary_hash_4, binary_hash_5, binary_hash_6 }, fmt_default_salt_hash, NULL, fmt_default_set_salt, set_key, get_key, fmt_default_clear_keys, crypt_all, { get_hash_0, get_hash_1, get_hash_2, get_hash_3, get_hash_4, get_hash_5, get_hash_6 }, cmp_all, cmp_one, cmp_exact } }; #endif /* plugin stanza */
trans_gain.c
/* Daala video codec Copyright (c) 2013 Daala project 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. 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.*/ /* 1D coding gain (dB) ********************** AR p=.95 4x4 8x8 16x16 ------------------------------------------ KLT 7.5825 8.8462 9.4781 DCT 7.5701 8.8259 9.4555 CDF(9/7) 8.4687 9.4592 9.7866 LappedKLT 8.5633 9.4908 9.8951 LappedDCT 8.5523 9.4871 9.8929 Subset 1 4x4 8x8 16x16 ------------------------------------------ KLT original 8.7714 10.2588 11.0039 collapsed 8.7714 10.2588 11.0039 monty 8.7654 10.2628 11.0292 DCT 8.7620 10.2427 10.9861 8.7620 10.2427 10.9861 8.7561 10.2467 11.0115 CDF(9/7) 9.3794 10.5932 11.0685 9.3845 10.5957 11.0825 9.4155 10.6576 11.1965 LappedKLT 9.6276 10.7860 11.3254 9.6277 10.7867 11.3296 9.6295 10.8056 11.3722 LappedDCT 9.6213 10.7832 11.3230 9.6214 10.7839 11.3272 9.6232 10.8028 11.3698 Subset 3 4x4 8x8 16x16 ------------------------------------------ KLT original 10.5669 12.3711 13.2694 collapsed 10.5669 12.3711 13.2694 monty 10.5495 12.3573 13.2729 DCT 10.5546 12.3532 13.2535 10.5547 12.3532 13.2535 10.5373 12.3395 13.2572 CDF(9/7) 11.3102 12.6838 13.1845 11.3106 12.6871 13.2009 11.3389 12.7764 13.4084 LappedKLT 11.6048 13.0138 13.6488 11.6046 13.0136 13.6491 11.5922 13.0126 13.6790 LappedDCT 11.5970 13.0111 13.6464 11.5968 13.0110 13.6467 11.5844 13.0099 13.6766 */ /* 2D coding gain (dB) ********************** AR p=.95 4x4 8x8 16x16 ------------------------------------------ KLT 15.1649 17.6924 18.9562 DCT 15.1403 17.6518 18.9109 CDF(9/7) 16.9374 18.9183 19.5731 LappedKLT 17.1265 18.9816 19.7902 LappedDCT 17.1047 18.9741 19.7858 Subset 1 4x4 8x8 16x16 ------------------------------------------ KLT original 12.4432 ------- ------- collapsed 12.4428 ------- ------- monty 12.4732 13.6167 14.1170 DCT 12.3695 ------- ------- 12.3698 ------- ------- 12.4182 13.5473 14.0536 CDF(9/7) ------- ------- ------- ------- ------- ------- 13.1425 13.8184 14.0110 LappedKLT 13.2807 ------- ------- 13.2808 ------- ------- 13.3452 14.1273 14.4041 LappedDCT 13.2682 ------- ------- 13.2685 ------- ------- 13.3330 14.1215 14.3981 Subset 3 4x4 8x8 16x16 ------------------------------------------ KLT monty 14.9078 16.2416 16.7839 DCT 14.8313 16.1578 16.7221 CDF(9/7) 15.7553 16.4760 16.6656 LappedKLT 15.9763 16.8549 17.1181 LappedDCT 15.9627 16.8507 17.1152 */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdlib.h> #include "od_defs.h" #include "od_filter.h" #include "trans_tools.h" #define BLOCKSIZE_LOG (4) #define USE_LAPPING (1) #define USE_KLT (1) #define USE_DCT (0) #define USE_WAVELET (0) #define USE_2D (1) #define USE_FILES (1) #define USE_AR95 (0) #define COMPUTE_NATHAN (1) #define PRINT_COV (0) #define BLOCKSIZE (1<<BLOCKSIZE_LOG) #if USE_WAVELET #if BLOCKSIZE_LOG==1 # define SUPPORT (20) #else # if BLOCKSIZE_LOG==2 # define SUPPORT (40) # else # if BLOCKSIZE_LOG==3 # define SUPPORT (80) # else # if BLOCKSIZE_LOG==4 # define SUPPORT (160) # else # error "no support configuration for transform size" # endif # endif # endif #endif #else #if USE_LAPPING||COMPUTE_NATHAN /* larger than needed for 'new' covariance code, but it won't alter the answer, just produce a larger than needed covariance matrix. It is needed to make the boundary conditions of the 'old' covariance code match the trans and trans2d utils */ #define SUPPORT (BLOCKSIZE*2) #else #define SUPPORT (BLOCKSIZE) #endif #endif const int *f; typedef void (*ne_fdct_func_1d)(double *_out,const double *_in,int _in_stride); typedef void (*ne_idct_func_1d)(double *_out,int _out_stride,const double *_in); extern const ne_idct_func_1d OD_IDCT_1D_DOUBLE[OD_NBSIZES]; extern const ne_fdct_func_1d OD_FDCT_1D_DOUBLE[OD_NBSIZES]; #if USE_FILES typedef struct { int sz; uint64_t *n; uint64_t *acc_i; uint64_t *acc_j; uint64_t *acc_ij; double *cov; } cov_state; static void cov_init(cov_state *_this, int _sz){ _this->sz = _sz; _this->n = (uint64_t *)calloc(_sz,sizeof(*_this->n)); _this->acc_i = (uint64_t *)calloc(_sz,sizeof(*_this->acc_i)); _this->acc_j = (uint64_t *)calloc(_sz,sizeof(*_this->acc_j)); _this->acc_ij= (uint64_t *)calloc(_sz,sizeof(*_this->acc_ij)); _this->cov = (double *)calloc(_sz,sizeof(*_this->cov)); } static void cov_clear(cov_state *_this){ if(_this){ if(_this->n) free(_this->n); if(_this->acc_i) free(_this->acc_i); if(_this->acc_j) free(_this->acc_j); if(_this->acc_ij) free(_this->acc_ij); if(_this->cov) free(_this->cov); } } #if USE_2D /* 1D and 2D could both use the same generalized code, but it would be harder to read */ static void cov_accumulate_2d(cov_state *_this, const unsigned char *_data, int _stride, int _w, int _h){ int x,y,i,j; int sz = sqrt(_this->sz); for(i=0;i<sz;i++){ for(j=0;j<sz;j++){ int ij = i*sz+j; for(y=0;y<_h-i;y++){ const unsigned char *di=_data+y*_stride; const unsigned char *dj=_data+(y+i)*_stride+j; for(x=0;x<_w-j;x++){ ++_this->n[ij]; _this->acc_i[ij] += di[x]; _this->acc_j[ij] += dj[x]; _this->acc_ij[ij] += di[x]*dj[x]; } } } } } #else static void cov_accumulate_1d(cov_state *_this, const unsigned char *_data, int _stride, int _n){ int i,j; for(i=0;i<_this->sz;i++){ const unsigned char *di=_data; const unsigned char *dj=_data+i*_stride; for(j=0;j<_n-i;j++){ ++_this->n[i]; _this->acc_i[i] += di[j*_stride]; _this->acc_j[i] += dj[j*_stride]; _this->acc_ij[i] += di[j*_stride]*dj[j*_stride]; } } } #endif static void cov_combine(cov_state *_a,const cov_state *_b){ int i; for(i=0;i<_a->sz;i++){ _a->acc_i[i] += _b->acc_i[i]; _a->acc_j[i] += _b->acc_j[i]; _a->acc_ij[i] += _b->acc_ij[i]; _a->n[i] += _b->n[i]; } } static void cov_compute(cov_state *_this){ int i; for(i=0;i<_this->sz;i++) _this->cov[i] = ((double)_this->acc_ij[i] - (double)_this->acc_i[i]* _this->acc_j[i]/_this->n[i])/_this->n[i]; for(i=1;i<_this->sz;i++) _this->cov[i] /= _this->cov[0]; _this->cov[0]=1.; } static void process_files(trans_ctx *_ctx, cov_state *_cov, int _argc, const char *_argv[]){ int ai; #pragma omp parallel for schedule(dynamic) for(ai=1;ai<_argc;ai++){ FILE *fin; video_input vid; video_input_info info; video_input_ycbcr ycbcr; int tid; cov_state *cov; int x0,y0,x1,y1; fin=fopen(_argv[ai],"rb"); if(fin==NULL){ fprintf(stderr,"Could not open '%s' for reading.\n",_argv[ai]); continue; } if(video_input_open(&vid,fin)<0){ fprintf(stderr,"Error reading video info from '%s'.\n",_argv[ai]); continue; } video_input_get_info(&vid,&info); if(video_input_fetch_frame(&vid,ycbcr,NULL)<0){ fprintf(stderr,"Error reading first frame from '%s'.\n",_argv[ai]); continue; } tid=OD_OMP_GET_THREAD; cov=_cov+tid; x0 = info.pic_x; y0 = info.pic_y; x1 = x0 + info.pic_w; y1 = y0 + info.pic_h; fprintf(stderr,"%s\n",_argv[ai]); /* map */ { int stride=ycbcr[0].stride; const unsigned char *data=ycbcr[0].data; #if COMPUTE_NATHAN /* block-based full covariance computation (unlord style) */ int nxblocks=info.pic_w>>BLOCKSIZE_LOG; int nyblocks=info.pic_h>>BLOCKSIZE_LOG; trans_ctx *ctx=_ctx+tid; # if USE_2D unsigned char buf[SUPPORT][SUPPORT]; int x,y,i,j; image_ctx_init(&ctx->img,_argv[ai],nxblocks,nyblocks); for(y=0;y<nyblocks*BLOCKSIZE-SUPPORT+1;y++){ for(x=0;x<nxblocks*BLOCKSIZE-SUPPORT+1;x++){ for(j=0;j<SUPPORT;j++){ for(i=0;i<SUPPORT;i++){ buf[j][i]=data[(y0+y+j)*stride+(x0+x+i)]; } } trans_data_add(&ctx->td,(unsigned char *)buf); } } # else unsigned char buf[SUPPORT]; int x,y,z; image_ctx_init(&ctx->img,_argv[ai],nxblocks,nyblocks); /* add the rows */ for(y=0;y<nyblocks*BLOCKSIZE;y++){ for(x=0;x<nxblocks*BLOCKSIZE-SUPPORT+1;x++){ for(z=0;z<SUPPORT;z++){ buf[z]=data[(y+y0)*stride+x+x0+z]; } trans_data_add(&ctx->td,buf); } } /* add the columns */ for(y=0;y<nyblocks*BLOCKSIZE-SUPPORT+1;y++){ for(x=0;x<nxblocks*BLOCKSIZE;x++){ for(z=0;z<SUPPORT;z++){ buf[z]=data[(y0+y+z)*stride+x+x0]; } trans_data_add(&ctx->td,buf); } } # endif #endif /* Direct computation of collapsed covariance matrix (monty style) */ #if USE_2D cov_accumulate_2d(cov,data+y0*stride+x0,stride,x1-x0,y1-y0); #else { int x,y; for(y=y0;y<y1;y++) cov_accumulate_1d(cov,data+y*stride+x0,1,x1-x0); for(x=x0;x<x1;x++) cov_accumulate_1d(cov,data+y0*stride+x,stride,y1-y0); } #endif } video_input_close(&vid); } } #endif #if USE_WAVELET /* some lifting CDF (9/7) wavelet code from Google Code's axonlib */ /* http://code.google.com/p/axonlib/source/browse/trunk/extern/dwt97.c?spec=svn19&r=19 */ /* single stage of decomposition */ static void fwt97_i(double* x,int n){ double temp[SUPPORT]; double a; int i; /* Predict 1 */ a=-1.586134342; for (i=1;i<n-2;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[n-1]+=2*a*x[n-2]; /* Update 1 */ a=-0.05298011854; for (i=2;i<n;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[0]+=2*a*x[1]; /* Predict 2 */ a=0.8829110762; for (i=1;i<n-2;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[n-1]+=2*a*x[n-2]; /* Update 2 */ a=0.4435068522; for (i=2;i<n;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[0]+=2*a*x[1]; /* Scale */ a=1/1.149604398; for (i=0;i<n;i++) { if (i%2) x[i]*=a; else x[i]/=a; } /* Pack */ for (i=0;i<n;i++){ if (i%2==0) temp[i/2]=x[i]; else temp[n/2+i/2]=x[i]; } for (i=0;i<n;i++) x[i]=temp[i]; } /* single stage of reconstruction */ void iwt97_i(double* x,int n){ double temp[SUPPORT]; double a; int i; /* Unpack */ for (i=0;i<n/2;i++){ temp[i*2]=x[i]; temp[i*2+1]=x[i+n/2]; } for (i=0;i<n;i++) x[i]=temp[i]; /* Undo scale */ a=1.149604398; for (i=0;i<n;i++) { if (i%2) x[i]*=a; else x[i]/=a; } /* Undo update 2 */ a=-0.4435068522; for (i=2;i<n;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[0]+=2*a*x[1]; /* Undo predict 2 */ a=-0.8829110762; for (i=1;i<n-2;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[n-1]+=2*a*x[n-2]; /* Undo update 1 */ a=0.05298011854; for (i=2;i<n;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[0]+=2*a*x[1]; /* Undo predict 1 */ a=1.586134342; for (i=1;i<n-2;i+=2) x[i]+=a*(x[i-1]+x[i+1]); x[n-1]+=2*a*x[n-2]; } /* multistage decomposition */ void fwt97(double *out, int n, double *in, int support){ int i=n,j=support,k; while((i&1)==0){ fwt97_i(in,j); i>>=1; for(k=0;k<i;k++) out[i+k] = in[((((j*3)>>1)-i)>>1) + k]; j>>=1; } for(k=0;k<i;k++) out[k] = in[((j-i)>>1) + k]; } /* multistage reconstruction */ void iwt97(double *out, int support, double *in, int n){ int i=n,j=support,k; for(k=0;k<support;k++) out[k]=0; while((i&1)==0){ i>>=1; for(k=0;k<i;k++) out[((((j*3)>>1)-i)>>1) + k]=in[i+k]; j>>=1; } for(k=0;k<i;k++) out[((j-i)>>1) + k]=in[k]; i<<=1; j<<=1; while(j<=support){ iwt97_i(out,j); i<<=1; j<<=1; } } #endif #if USE_KLT void symeigen(double *out, double *cov, int support){ int i; int j; int k; for(i=0;i<support;i++) for(j=0;j<support;j++) out[i*support+j]=i==j; for(;;){ double mod=0.; for(i=0,j=0,k=0;k<support;k++){ int m; for(m=k+1;m<support;m++){ double q; q=fabs(cov[k*support+m]); if(q>mod){ mod=q; i=k; j=m; } } } if(mod<1E-11)break; { double th=0.5*atan2(2*cov[i*support+j],cov[i*support+i]-cov[j*support+j]); double c=cos(th); double s=sin(th); for(k=0;k<support;k++){ double t; t=c*cov[k*support+i]+s*cov[k*support+j]; cov[k*support+j]=-s*cov[k*support+i]+c*cov[k*support+j]; cov[k*support+i]=t; } for(k=0;k<support;k++){ double t; t=c*cov[i*support+k]+s*cov[j*support+k]; cov[j*support+k]=-s*cov[i*support+k]+c*cov[j*support+k]; cov[i*support+k]=t; } for(k=0;k<support;k++){ double t; t=c*out[i*support+k]+s*out[j*support+k]; out[j*support+k]=-s*out[i*support+k]+c*out[j*support+k]; out[i*support+k]=t; } } } /* for(j=0;j<BLOCKSIZE;j++)eigenvalue[j]=cov[j][j]; don't need eigenvalues */ } void flap_2d(double out[BLOCKSIZE][BLOCKSIZE], double in[SUPPORT][SUPPORT], const int _f[]){ int i,j; #if USE_LAPPING #if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES /* columns */ for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ double work[BLOCKSIZE*2]; for(j=0;j<BLOCKSIZE*2;j++) work[j]=in[j+SUPPORT/2-BLOCKSIZE][i]; (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[0],&work[0],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[BLOCKSIZE],&work[BLOCKSIZE],_f); for(j=0;j<BLOCKSIZE*2;j++) in[j+SUPPORT/2-BLOCKSIZE][i]=work[j]; } /* rows */ for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&in[i][SUPPORT/2-BLOCKSIZE],&in[i][SUPPORT/2-BLOCKSIZE],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&in[i][SUPPORT/2],&in[i][SUPPORT/2],_f); } #else # error "Need a prefilter implementation for this block size." #endif #endif for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) out[i][j]=in[i+SUPPORT/2-BLOCKSIZE/2][j+SUPPORT/2-BLOCKSIZE/2]; } void ilap_2d(double out[SUPPORT][SUPPORT], double in[BLOCKSIZE][BLOCKSIZE], const int _f[]){ int i,j; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) out[i][j]=0; for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) out[i+SUPPORT/2-BLOCKSIZE/2][j+SUPPORT/2-BLOCKSIZE/2]=in[i][j]; #if USE_LAPPING #if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES /* columns */ for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ double work[BLOCKSIZE*2]; for(j=0;j<BLOCKSIZE*2;j++) work[j]=out[j+SUPPORT/2-BLOCKSIZE][i]; (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[0],&work[0],_f); (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[BLOCKSIZE],&work[BLOCKSIZE],_f); for(j=0;j<BLOCKSIZE*2;j++) out[j+SUPPORT/2-BLOCKSIZE][i]=work[j]; } /* rows */ for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&out[i][SUPPORT/2-BLOCKSIZE],&out[i][SUPPORT/2-BLOCKSIZE],_f); (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&out[i][SUPPORT/2],&out[i][SUPPORT/2],_f); } #else # error "Need a prefilter implementation for this block size." #endif #endif } void flap_4d(double out[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE], double in[SUPPORT][SUPPORT][SUPPORT][SUPPORT], const int _f[]){ int i,j,k,l; #if USE_LAPPING #if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ for(j=SUPPORT/2-BLOCKSIZE;j<SUPPORT/2+BLOCKSIZE;j++){ for(k=SUPPORT/2-BLOCKSIZE;k<SUPPORT/2+BLOCKSIZE;k++){ double work[BLOCKSIZE*2]; /* [ ][i][j][k] */ for(l=0;l<BLOCKSIZE*2;l++) work[l]=in[l+SUPPORT/2-BLOCKSIZE][i][j][k]; (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[0],&work[0],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[BLOCKSIZE],&work[BLOCKSIZE],_f); for(l=0;l<BLOCKSIZE*2;l++) in[l+SUPPORT/2-BLOCKSIZE][i][j][k]=work[l]; } } } for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ for(j=SUPPORT/2-BLOCKSIZE;j<SUPPORT/2+BLOCKSIZE;j++){ for(k=SUPPORT/2-BLOCKSIZE;k<SUPPORT/2+BLOCKSIZE;k++){ double work[BLOCKSIZE*2]; /* [i][ ][j][k] */ for(l=0;l<BLOCKSIZE*2;l++) work[l]=in[i][l+SUPPORT/2-BLOCKSIZE][j][k]; (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[0],&work[0],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[BLOCKSIZE],&work[BLOCKSIZE],_f); for(l=0;l<BLOCKSIZE*2;l++) in[i][l+SUPPORT/2-BLOCKSIZE][j][k]=work[l]; } } } for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ for(j=SUPPORT/2-BLOCKSIZE;j<SUPPORT/2+BLOCKSIZE;j++){ for(k=SUPPORT/2-BLOCKSIZE;k<SUPPORT/2+BLOCKSIZE;k++){ double work[BLOCKSIZE*2]; /* [i][j][ ][k] */ for(l=0;l<BLOCKSIZE*2;l++) work[l]=in[i][j][l+SUPPORT/2-BLOCKSIZE][k]; (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[0],&work[0],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&work[BLOCKSIZE],&work[BLOCKSIZE],_f); for(l=0;l<BLOCKSIZE*2;l++) in[i][j][l+SUPPORT/2-BLOCKSIZE][k]=work[l]; } } } for(i=SUPPORT/2-BLOCKSIZE;i<SUPPORT/2+BLOCKSIZE;i++){ for(j=SUPPORT/2-BLOCKSIZE;j<SUPPORT/2+BLOCKSIZE;j++){ for(k=SUPPORT/2-BLOCKSIZE;k<SUPPORT/2+BLOCKSIZE;k++){ /* [i][j][k][ ] */ (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&in[i][j][k][SUPPORT/2-BLOCKSIZE],&in[i][j][k][SUPPORT/2-BLOCKSIZE],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&in[i][j][k][SUPPORT/2],&in[i][j][k][SUPPORT/2],_f); } } } #else # error "Need a prefilter implementation for this block size." #endif #endif for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) for(k=0;k<BLOCKSIZE;k++) for(l=0;l<BLOCKSIZE;l++) out[i*BLOCKSIZE+j][k*BLOCKSIZE+l]=in [i+SUPPORT/2-BLOCKSIZE/2] [j+SUPPORT/2-BLOCKSIZE/2] [k+SUPPORT/2-BLOCKSIZE/2] [l+SUPPORT/2-BLOCKSIZE/2]; } void gklt_1d(double klt[BLOCKSIZE][BLOCKSIZE], double cov[SUPPORT][SUPPORT], const int *_f){ static double workA[SUPPORT][SUPPORT]; static double workB[BLOCKSIZE][BLOCKSIZE]; int i,j; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) workA[i][j]=cov[i][j]; flap_2d(workB,workA,_f); symeigen(&klt[0][0],&workB[0][0],BLOCKSIZE); } void gklt_2d(double klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE], double cov[SUPPORT][SUPPORT][SUPPORT][SUPPORT], const int *_f){ static double workA[SUPPORT][SUPPORT][SUPPORT][SUPPORT]; static double workB[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]; int i,j,k,l; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) for(k=0;k<SUPPORT;k++) for(l=0;l<SUPPORT;l++) workA[i][j][k][l]=cov[i][j][k][l]; flap_4d(workB,workA,_f); symeigen(&klt[0][0],&workB[0][0],BLOCKSIZE*BLOCKSIZE); } void gklt_1d_collapsed(double klt[BLOCKSIZE][BLOCKSIZE], double cov[SUPPORT], const int *_f){ static double workA[SUPPORT][SUPPORT]; static double workB[BLOCKSIZE][BLOCKSIZE]; int i,j; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) workA[i][j]=cov[abs(i-j)]; flap_2d(workB,workA,_f); symeigen(&klt[0][0],&workB[0][0],BLOCKSIZE); } void gklt_2d_collapsed(double klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE], double cov[SUPPORT][SUPPORT], const int *_f){ static double workA[SUPPORT][SUPPORT][SUPPORT][SUPPORT]; static double workB[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]; int i,j,k,l; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) for(k=0;k<SUPPORT;k++) for(l=0;l<SUPPORT;l++) workA[i][j][k][l]=cov[abs(i-k)][abs(j-l)]; flap_4d(workB,workA,_f); symeigen(&klt[0][0],&workB[0][0],BLOCKSIZE*BLOCKSIZE); } void fklt(double *out, double *in, double *klt, int support){ int i,j; for(i=0;i<support;i++){ double acc=0.; for(j=0;j<support;j++) acc += klt[i*support+j]*in[j]; out[i]=acc; } } void iklt(double *out, double *in, double *klt, int support){ int i,j; for(i=0;i<support;i++){ double acc=0.; for(j=0;j<support;j++) acc+=klt[j*support+i]*in[j]; out[i]=acc; } } #endif void b_analysis_1d(double *_out,int _out_stride,const double *_in,int _in_stride, const int *_f, double _klt[BLOCKSIZE][BLOCKSIZE]){ int j; double t[SUPPORT]; double w[BLOCKSIZE]; for(j=0;j<SUPPORT;j++) t[j]=_in[j*_in_stride]; #if USE_WAVELET fwt97(w,BLOCKSIZE,t,SUPPORT); for(j=0;j<BLOCKSIZE;j++){ _out[j*_out_stride]=w[j]; } #else # if USE_LAPPING # if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&t[SUPPORT/2-BLOCKSIZE],&t[SUPPORT/2-BLOCKSIZE],_f); (*NE_PRE_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&t[SUPPORT/2],&t[SUPPORT/2],_f); # else # error "Need a prefilter implementation for this block size." # endif # endif # if USE_KLT fklt(&w[0],&t[SUPPORT/2-BLOCKSIZE/2],&_klt[0][0],BLOCKSIZE); # elif USE_DCT # if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES (*OD_FDCT_1D_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (w,&t[SUPPORT/2-BLOCKSIZE/2],1); # else # error "Need an fDCT implementation for this block size." # endif # else for(j=0;j<BLOCKSIZE;j++) w[j]=t[j+SUPPORT/2-BLOCKSIZE/2]; # endif for(j=0;j<BLOCKSIZE;j++) _out[j*_out_stride]=w[j]; #endif } void b_analysis_2d(double *_out,int _out_stride_i,int _out_stride_j, const double *_in,int _in_stride_i,int _in_stride_j, const int *_f, double _klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]){ #if USE_KLT /* KLT is a non-separable 2D transform */ double lap[SUPPORT][SUPPORT]; double work[BLOCKSIZE][BLOCKSIZE]; double temp[BLOCKSIZE][BLOCKSIZE]; int i,j; for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) lap[i][j]=*(_in+i*_in_stride_i+j*_in_stride_j); flap_2d(work,lap,_f); fklt(&temp[0][0],&work[0][0],&_klt[0][0],BLOCKSIZE*BLOCKSIZE); for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) *(_out+i*_out_stride_i+j*_out_stride_j)=temp[i][j]; #else double work[SUPPORT][BLOCKSIZE]; int i; /* DCT and DWT are separable 1D transforms */ /* lapping performed inside b_analysis */ for(i=0;i<SUPPORT;i++) b_analysis_1d(&work[i][0],1,_in+i*_in_stride_i,_in_stride_j,_f,NULL); for(i=0;i<BLOCKSIZE;i++) b_analysis_1d(_out+_out_stride_i*i,_out_stride_j,&work[0][i],BLOCKSIZE,_f,NULL); #endif } void b_synthesis_1d(double *_out,int _out_stride,const double *_in,int _in_stride, const int *_f, double _klt[BLOCKSIZE][BLOCKSIZE]){ int j; double w[SUPPORT]; double t[SUPPORT]; for(j=0;j<SUPPORT;j++){ t[j]=0; w[j]=0; } #if USE_WAVELET for(j=0;j<BLOCKSIZE;j++) w[j]=_in[j*_in_stride]; iwt97(t,SUPPORT,w,BLOCKSIZE); #else for(j=0;j<BLOCKSIZE;j++){ w[SUPPORT/2-BLOCKSIZE/2+j]=_in[j*_in_stride]; } # if USE_KLT iklt(&t[SUPPORT/2-BLOCKSIZE/2],&w[SUPPORT/2-BLOCKSIZE/2],&_klt[0][0],BLOCKSIZE); # elif USE_DCT # if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES (*OD_IDCT_1D_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&t[SUPPORT/2-BLOCKSIZE/2],1,&w[SUPPORT/2-BLOCKSIZE/2]); # else # error "Need an iDCT implementation for this block size." # endif # else for(j=0;j<SUPPORT;j++) t[j]=w[j]; # endif # if USE_LAPPING # if BLOCKSIZE_LOG>=OD_LOG_BSIZE0&&BLOCKSIZE_LOG<OD_LOG_BSIZE0+OD_NBSIZES (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&t[SUPPORT/2-BLOCKSIZE],&t[SUPPORT/2-BLOCKSIZE],_f); (*NE_POST_FILTER_DOUBLE[BLOCKSIZE_LOG-OD_LOG_BSIZE0]) (&t[SUPPORT/2],&t[SUPPORT/2],_f); # else # error "Need a postfilter implementation for this block size." # endif # endif #endif for(j=0;j<SUPPORT;j++) _out[j*_out_stride]=t[j]; } void b_synthesis_2d(double *_out,int _out_stride_i,int _out_stride_j, const double *_in,int _in_stride_i,int _in_stride_j, const int *_f, double _klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]){ #if USE_KLT /* KLT is a non-separable 2D transform */ double temp[BLOCKSIZE][BLOCKSIZE]; double work[BLOCKSIZE][BLOCKSIZE]; double lap[SUPPORT][SUPPORT]; int i,j; for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) temp[i][j]=*(_in+i*_in_stride_i+j*_in_stride_j); iklt(&work[0][0],&temp[0][0],&_klt[0][0],BLOCKSIZE*BLOCKSIZE); ilap_2d(lap,work,_f); for(i=0;i<SUPPORT;i++) for(j=0;j<SUPPORT;j++) *(_out+i*_out_stride_i+j*_out_stride_j)=lap[i][j]; #else double work[SUPPORT][BLOCKSIZE]; int i; /* DCT and DWT are separable 1D transforms */ /* lapping performed inside b_analysis */ for(i=0;i<BLOCKSIZE;i++) b_synthesis_1d(&work[0][i],BLOCKSIZE,_in+i*_in_stride_i,_in_stride_j,_f,NULL); for(i=0;i<SUPPORT;i++) b_synthesis_1d(_out+_out_stride_i*i,_out_stride_j,&work[i][0],1,_f,NULL); #endif } #if USE_2D static double cg_2d_i(double rggt[SUPPORT][SUPPORT][BLOCKSIZE][BLOCKSIZE], const int *_f, double _klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]){ double r[BLOCKSIZE][BLOCKSIZE][BLOCKSIZE][BLOCKSIZE]; double s[SUPPORT][BLOCKSIZE]; double ggrggt[BLOCKSIZE][BLOCKSIZE][BLOCKSIZE][BLOCKSIZE]; double cg=0; int i; int j; int v; int u; int k; int l; /* G1*P*G2*R*(G2*P*G1)^T */ for(v=0;v<BLOCKSIZE;v++) for(j=0;j<BLOCKSIZE;j++) b_analysis_2d(&ggrggt[v][j][0][0], 1,BLOCKSIZE, &rggt[0][0][v][j], BLOCKSIZE*BLOCKSIZE*SUPPORT, BLOCKSIZE*BLOCKSIZE, f,_klt); /* H1*P*H2 */ for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) for(k=0;k<BLOCKSIZE;k++) for(l=0;l<BLOCKSIZE;l++) r[i][j][k][l] = (i*BLOCKSIZE+j==k*BLOCKSIZE+l)?1:0; for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) b_synthesis_2d(&rggt[0][0][i][j], BLOCKSIZE*BLOCKSIZE, SUPPORT*BLOCKSIZE*BLOCKSIZE, &r[i][j][0][0], BLOCKSIZE,1, _f,_klt); /* ((H1*P*H2)^T*H1*P*H2)_ii */ for(i=0;i<BLOCKSIZE;i++){ for(j=0;j<BLOCKSIZE;j++){ s[i][j]=0; for(u=0;u<SUPPORT;u++){ for(v=0;v<SUPPORT;v++){ s[i][j]+=rggt[u][v][i][j]*rggt[u][v][i][j]; } } } } /* (G1*P*G2*R*(G1*P*G2)^T)_ii * ((H1*P*H2)^T*H1*P*H2)_ii */ for(i=0;i<BLOCKSIZE;i++) for(j=0;j<BLOCKSIZE;j++) cg-=10*log10(ggrggt[i][j][i][j]*s[i][j]); return cg/(BLOCKSIZE*BLOCKSIZE); } double cg_2d(double _in[SUPPORT][SUPPORT][SUPPORT][SUPPORT], const int *_f){ int v; int j; double ret; double (*rggt)[SUPPORT][BLOCKSIZE][BLOCKSIZE] = (double (*)[SUPPORT][BLOCKSIZE][BLOCKSIZE]) malloc(SUPPORT*SUPPORT*BLOCKSIZE*BLOCKSIZE*sizeof(****rggt)); double klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]; #if USE_KLT gklt_2d(klt,_in,_f); #endif /* R*(G2*P*G1)^T */ for(v=0;v<SUPPORT;v++) for(j=0;j<SUPPORT;j++) b_analysis_2d(&rggt[v][j][0][0], 1,BLOCKSIZE, &_in[0][0][v][j], SUPPORT*SUPPORT*SUPPORT, SUPPORT*SUPPORT, _f,klt); ret = cg_2d_i(rggt,f,klt); free(rggt); return ret; } double cg_2d_collapsed(double _in[SUPPORT][SUPPORT],const int *_f){ int v; int u; int j; int i; double ret; double r[SUPPORT][SUPPORT]; double (*rggt)[SUPPORT][BLOCKSIZE][BLOCKSIZE] = (double (*)[SUPPORT][BLOCKSIZE][BLOCKSIZE]) malloc(SUPPORT*SUPPORT*BLOCKSIZE*BLOCKSIZE*sizeof(****rggt)); double klt[BLOCKSIZE*BLOCKSIZE][BLOCKSIZE*BLOCKSIZE]; #if USE_KLT gklt_2d_collapsed(klt,_in,_f); #endif /* R*(G2*P*G1)^T */ for(v=0;v<SUPPORT;v++){ for(j=0;j<SUPPORT;j++){ for(u=0;u<SUPPORT;u++) for(i=0;i<SUPPORT;i++) r[u][i]=_in[abs(u-v)][abs(i-j)]; b_analysis_2d(&rggt[v][j][0][0], 1,BLOCKSIZE, &r[0][0],SUPPORT,1,_f,klt); } } ret = cg_2d_i(rggt,f,klt); free(rggt); return ret; } #else static double cg_1d_i(double rgt[SUPPORT][BLOCKSIZE], const int *_f, double klt[BLOCKSIZE][BLOCKSIZE]){ int j; int i; double r[BLOCKSIZE]; double grgt[BLOCKSIZE][BLOCKSIZE]; double cg=0; /* G*R*G^T */ for(i=0;i<BLOCKSIZE;i++) b_analysis_1d(&grgt[0][i],BLOCKSIZE,&rgt[0][i],BLOCKSIZE,_f,klt); /* H */ for(j=0;j<BLOCKSIZE;j++){ for(i=0;i<BLOCKSIZE;i++){ r[i]=i==j?1:0; } b_synthesis_1d(&rgt[0][j],BLOCKSIZE,r,1,_f,klt); } /* (G*R*G^T)_ii * (H^T*H)_ii */ for(j=0;j<BLOCKSIZE;j++){ double h=0; for(i=0;i<SUPPORT;i++){ h+=rgt[i][j]*rgt[i][j]; } cg-=10*log10(grgt[j][j]*h); } return cg/BLOCKSIZE; } double cg_1d(double in[SUPPORT][SUPPORT],const int *_f){ int j; double rgt[SUPPORT][BLOCKSIZE]; double klt[BLOCKSIZE][BLOCKSIZE]; #if USE_KLT gklt_1d(klt,in,_f); #endif /* R*G^T */ for(j=0;j<SUPPORT;j++){ b_analysis_1d(&rgt[j][0],1,in[j],1,_f,klt); } return cg_1d_i(rgt,f,klt); } double cg_1d_collapsed(double in[SUPPORT],const int *_f){ int j; int i; double r[SUPPORT]; double rgt[SUPPORT][BLOCKSIZE]; double klt[BLOCKSIZE][BLOCKSIZE]; #if USE_KLT gklt_1d_collapsed(klt,in,_f); #endif /* R*G^T */ for(j=0;j<SUPPORT;j++){ for(i=0;i<SUPPORT;i++){ r[i]=in[abs(i-j)]; } b_analysis_1d(&rgt[j][0],1,r,1,_f,klt); } return cg_1d_i(rgt,f,klt); } #endif #if USE_FILES int main(int _argc,const char *_argv[]){ cov_state cvs[NUM_PROCS]; #if COMPUTE_NATHAN trans_ctx ctx[NUM_PROCS]; double r[SUPPORT*SUPPORT]; /* maximum for 2d */ #else trans_ctx *ctx=NULL; #endif int i; #if BLOCKSIZE==4 f=OD_FILTER_PARAMS4; #elif BLOCKSIZE==8 f=OD_FILTER_PARAMS8; #elif BLOCKSIZE==16 f=OD_FILTER_PARAMS16; #else # error "Need filter params for this block size." #endif for(i=0;i<NUM_PROCS;i++){ #if USE_2D cov_init(&cvs[i],SUPPORT*SUPPORT); #else cov_init(&cvs[i],SUPPORT); #endif } #if COMPUTE_NATHAN for(i=0;i<NUM_PROCS;i++){ #if USE_2D trans_data_init(&ctx[i].td,SUPPORT*SUPPORT); #else trans_data_init(&ctx[i].td,SUPPORT); #endif } #endif OD_OMP_SET_THREADS(NUM_PROCS); process_files(ctx,cvs,_argc,_argv); for(i=1;i<NUM_PROCS;i++) cov_combine(&cvs[0],&cvs[i]); cov_compute(&cvs[0]); #if COMPUTE_NATHAN for(i=1;i<NUM_PROCS;i++) trans_data_combine(&ctx[0].td,&ctx[i].td); trans_data_normalize(&ctx[0].td); #endif #if PRINT_COV { int i,j; fprintf(stdout,"collapsed_cov=\n"); for(j=0;j<cvs[0].sz/SUPPORT;j++){ for(i=0;i<SUPPORT;i++){ fprintf(stdout,"%s %- 12.6G",i>0?",":"",cvs[0].cov[j*SUPPORT+i]); } fprintf(stdout,"\n"); } } #endif #if USE_2D #if COMPUTE_NATHAN fprintf(stdout,"original cg=%-24.16G\n", cg_2d((double(*)[SUPPORT][SUPPORT][SUPPORT])ctx[0].td.cov,f)); trans_data_collapse(&ctx[0].td,SUPPORT,r); fprintf(stdout,"collapse cg=%-24.16G\n", cg_2d_collapsed((double(*)[SUPPORT])r,f)); #endif fprintf(stdout,"monty cg=%-24.16G\n", cg_2d_collapsed((double(*)[SUPPORT])cvs[0].cov,f)); #else #if COMPUTE_NATHAN fprintf(stdout,"original cg=%-24.16G\n", cg_1d((double (*)[SUPPORT])ctx[0].td.cov,f)); trans_data_collapse(&ctx[0].td,1,r); fprintf(stdout,"collapse cg=%-24.16G\n", cg_1d_collapsed(r,f)); #endif fprintf(stdout,"monty cg=%-24.16G\n", cg_1d_collapsed(cvs[0].cov,f)); #endif for(i=0;i<NUM_PROCS;i++) cov_clear(&cvs[i]); #if COMPUTE_NATHAN for(i=0;i<NUM_PROCS;i++) trans_data_clear(&ctx[i].td); #endif return EXIT_SUCCESS; } #else int main(int _argc,const char *_argv[]){ #if USE_2D double cov[SUPPORT][SUPPORT]; double *r=&cov[0][0]; #else double cov[SUPPORT]; double *r=&cov[0]; #endif #if BLOCKSIZE==4 f=OD_FILTER_PARAMS4; #elif BLOCKSIZE==8 f=OD_FILTER_PARAMS8; #elif BLOCKSIZE==16 f=OD_FILTER_PARAMS16; #else # error "Need filter params for this block size." #endif # if USE_2D auto_regressive_collapsed(r,SUPPORT*SUPPORT,SUPPORT,0.95); fprintf(stdout,"AR p=.95 cg=%-24.18G\n",cg_2d_collapsed(cov,f)); # else auto_regressive_collapsed(r,SUPPORT,1,0.95); fprintf(stdout,"AR p=.95 cg=%-24.18G\n",cg_1d_collapsed(cov,f)); # endif return EXIT_SUCCESS; } #endif
tov_interp.h
// This C header file reads a TOV solution from data file and performs // 1D interpolation of the solution to a desired radius. // Author: Zachariah B. Etienne // zachetie **at** gmail **dot* com #include "stdio.h" #include "stdlib.h" #include "math.h" #include "string.h" #define REAL double //#define STANDALONE_UNIT_TEST int count_num_lines_in_file(FILE *in1Dpolytrope) { int numlines_in_file = 0; char * line = NULL; size_t len = 0; ssize_t read; while ((read = getline(&line, &len, in1Dpolytrope)) != -1) { numlines_in_file++; } rewind(in1Dpolytrope); free(line); return numlines_in_file; } int read_datafile__set_arrays(FILE *in1Dpolytrope, REAL *r_Schw_arr,REAL *rho_arr,REAL *P_arr,REAL *M_arr,REAL *expnu_arr,REAL *exp4phi_arr,REAL *rbar_arr) { char * line = NULL; size_t len = 0; ssize_t read; int which_line = 0; while ((read = getline(&line, &len, in1Dpolytrope)) != -1) { // Define the line delimiters (i.e., the stuff that goes between the data on a given // line of data. Here, we define both spaces " " and tabs "\t" as data delimiters. const char delimiters[] = " \t"; //Now we define "token", a pointer to the first column of data char *token; //Each successive time we call strtok(NULL,blah), we read in a new column of data from // the originally defined character array, as pointed to by token. token=strtok(line, delimiters); if(token==NULL) { printf("BADDDD\n"); return 1; } r_Schw_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); rho_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); P_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); M_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); expnu_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); exp4phi_arr[which_line] = strtod(token, NULL); token = strtok( NULL, delimiters ); rbar_arr[which_line] = strtod(token, NULL); which_line++; } free(line); return 0; } void TOV_interpolate_1D(REAL rrbar,const REAL Rbar,const int Rbar_idx,const int interp_stencil_size, const int numlines_in_file,const REAL *r_Schw_arr,const REAL *rho_arr,const REAL *P_arr,const REAL *M_arr,const REAL *expnu_arr,const REAL *exp4phi_arr,const REAL *rbar_arr, REAL *rho,REAL *P,REAL *M,REAL *expnu,REAL *exp4phi) { // Find interpolation index using Bisection root-finding algorithm: int bisection_idx_finder(const REAL rr, const int numlines_in_file, const REAL *rbar_arr) { int x1 = 0; int x2 = numlines_in_file-1; REAL y1 = rrbar-rbar_arr[x1]; REAL y2 = rrbar-rbar_arr[x2]; if(y1*y2 >= 0) { fprintf(stderr,"INTERPOLATION BRACKETING ERROR %e | %e %e\n",rr,y1,y2); exit(1); } for(int i=0;i<numlines_in_file;i++) { int x_midpoint = (x1+x2)/2; REAL y_midpoint = rrbar-rbar_arr[x_midpoint]; if(y_midpoint*y1 < 0) { x2 = x_midpoint; y2 = y_midpoint; } else { x1 = x_midpoint; y1 = y_midpoint; } if( abs(x2-x1) == 1 ) { // If rbar_arr[x1] is closer to rrbar than rbar_arr[x2] then return x1: if(fabs(rrbar-rbar_arr[x1]) < fabs(rrbar-rbar_arr[x2])) return x1; // Otherwiser return x2: return x2; } } fprintf(stderr,"INTERPOLATION BRACKETING ERROR: DID NOT CONVERGE.\n"); exit(1); } // For this case, we know that for all functions, f(r) = f(-r) if(rrbar < 0) rrbar = -rrbar; // First find the central interpolation stencil index: int idx = bisection_idx_finder(rrbar,numlines_in_file,rbar_arr); #ifdef MAX #undef MAX #endif #define MAX(A, B) ( ((A) > (B)) ? (A) : (B) ) int idxmin = MAX(0,idx-interp_stencil_size/2-1); #ifdef MIN #undef MIN #endif #define MIN(A, B) ( ((A) < (B)) ? (A) : (B) ) // -= Do not allow the interpolation stencil to cross the star's surface =- // max index is when idxmin + (interp_stencil_size-1) = Rbar_idx // -> idxmin at most can be Rbar_idx - interp_stencil_size + 1 if(rrbar < Rbar) { idxmin = MIN(idxmin,Rbar_idx - interp_stencil_size + 1); } else { idxmin = MAX(idxmin,Rbar_idx+1); idxmin = MIN(idxmin,numlines_in_file - interp_stencil_size + 1); } // Now perform the Lagrange polynomial interpolation: // First set the interpolation coefficients: REAL rbar_sample[interp_stencil_size]; for(int i=idxmin;i<idxmin+interp_stencil_size;i++) { rbar_sample[i-idxmin] = rbar_arr[i]; } REAL l_i_of_r[interp_stencil_size]; for(int i=0;i<interp_stencil_size;i++) { REAL numer = 1.0; REAL denom = 1.0; for(int j=0;j<i;j++) { numer *= rrbar - rbar_sample[j]; denom *= rbar_sample[i] - rbar_sample[j]; } for(int j=i+1;j<interp_stencil_size;j++) { numer *= rrbar - rbar_sample[j]; denom *= rbar_sample[i] - rbar_sample[j]; } l_i_of_r[i] = numer/denom; } // Then perform the interpolation: *rho = 0.0; *P = 0.0; *M = 0.0; *expnu = 0.0; *exp4phi = 0.0; REAL r_Schw = 0.0; for(int i=idxmin;i<idxmin+interp_stencil_size;i++) { r_Schw += l_i_of_r[i-idxmin] * r_Schw_arr[i]; *rho += l_i_of_r[i-idxmin] * rho_arr[i]; *P += l_i_of_r[i-idxmin] * P_arr[i]; *M += l_i_of_r[i-idxmin] * M_arr[i]; *expnu += l_i_of_r[i-idxmin] * expnu_arr[i]; *exp4phi += l_i_of_r[i-idxmin] * exp4phi_arr[i]; } if(rrbar > Rbar) { *rho = 0; *P = 0; *M = M_arr[Rbar_idx+1]; *expnu = 1. - 2.*(*M) / r_Schw; *exp4phi = pow(r_Schw / rrbar,2.0); } } #ifdef STANDALONE_UNIT_TEST int main() { // Open the data file: char filename[100]; sprintf(filename,"../outputTOVpolytrope.txt"); FILE *in1Dpolytrope = fopen(filename, "r"); if (in1Dpolytrope == NULL) { fprintf(stderr,"ERROR: could not open file %s\n",filename); exit(1); } // Count the number of lines in the data file: int numlines_in_file = count_num_lines_in_file(in1Dpolytrope); // Allocate space for all data arrays: REAL *r_Schw_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *rho_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *P_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *M_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *expnu_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *exp4phi_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); REAL *rbar_arr = (REAL *)malloc(sizeof(REAL)*numlines_in_file); // Read from the data file, filling in arrays if(read_datafile__set_arrays(in1Dpolytrope, r_Schw_arr,rho_arr,P_arr,M_arr,expnu_arr,exp4phi_arr,rbar_arr) == 1) { fprintf(stderr,"ERROR WHEN READING FILE %s!\n",filename); exit(1); } fclose(in1Dpolytrope); REAL Rbar = -100; int Rbar_idx = -100; for(int i=1;i<numlines_in_file;i++) { if(rho_arr[i-1]>0 && rho_arr[i]==0) { Rbar = rbar_arr[i-1]; Rbar_idx = i-1; } } if(Rbar<0) { fprintf(stderr,"Error: could not find r=R from data file.\n"); exit(1); } // Next, interpolate! // Create trial radius array: int num_r_pts = 100000; //REAL *r_out_arr = (REAL *)malloc(sizeof(REAL)*num_r_pts); struct drand48_data randBuffer; srand48_r(1313, &randBuffer); #pragma omp parallel for for(int i=0;i<num_r_pts;i++) { REAL rrbar; drand48_r(&randBuffer,&rrbar); //rrbar *= 10.; //rbar_arr[numlines_in_file-1]; rrbar = rrbar*0.1 + 0.8; //rbar_arr[numlines_in_file-1]; REAL rho,P,M,expnu,exp4phi; TOV_interpolate_1D(rrbar,Rbar,Rbar_idx,4, numlines_in_file,r_Schw_arr,rho_arr,P_arr,M_arr,expnu_arr,exp4phi_arr,rbar_arr, &rho,&P,&M,&expnu,&exp4phi); printf("%e %e %e %e %e %e\n",rrbar,rho,P,M,expnu,exp4phi); } // Free the malloc()'s! free(r_Schw_arr); free(rho_arr); free(P_arr); free(M_arr); free(expnu_arr); free(exp4phi_arr); free(rbar_arr); return 0; } #endif
GB_unop__tan_fc32_fc32.c
//------------------------------------------------------------------------------ // GB_unop: hard-coded functions for each built-in unary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2020, All Rights Reserved. // http://suitesparse.com See GraphBLAS/Doc/License.txt for license. //------------------------------------------------------------------------------ // If this file is in the Generated/ folder, do not edit it (auto-generated). #include "GB.h" #ifndef GBCOMPACT #include "GB_control.h" #include "GB_unop__include.h" // C=unop(A) is defined by the following types and operators: // op(A) function: GB_unop_apply__tan_fc32_fc32 // op(A') function: GB_unop_tran__tan_fc32_fc32 // C type: GxB_FC32_t // A type: GxB_FC32_t // cast: GxB_FC32_t cij = aij // unaryop: cij = ctanf (aij) #define GB_ATYPE \ GxB_FC32_t #define GB_CTYPE \ GxB_FC32_t // aij = Ax [pA] #define GB_GETA(aij,Ax,pA) \ GxB_FC32_t aij = Ax [pA] #define GB_CX(p) Cx [p] // unary operator #define GB_OP(z, x) \ z = ctanf (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] = ctanf (z) ; \ } // disable this operator and use the generic case if these conditions hold #define GB_DISABLE \ (GxB_NO_TAN || GxB_NO_FC32) //------------------------------------------------------------------------------ // Cx = op (cast (Ax)): apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_apply__tan_fc32_fc32 ( GxB_FC32_t *Cx, // Cx and Ax may be aliased const GxB_FC32_t *Ax, int64_t anz, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { GxB_FC32_t aij = Ax [p] ; GxB_FC32_t z = aij ; Cx [p] = ctanf (z) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = op (cast (A')): transpose, typecast, and apply a unary operator //------------------------------------------------------------------------------ GrB_Info GB_unop_tran__tan_fc32_fc32 ( GrB_Matrix C, const GrB_Matrix A, int64_t *GB_RESTRICT *Rowcounts, GBI_single_iterator Iter, const int64_t *GB_RESTRICT A_slice, int naslice ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #define GB_PHASE_2_OF_2 #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
nr_direct.c
/* * */ #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> //#include <omp.h> #include "config.h" #include "cint.h" #include "optimizer.h" #include "nr_direct.h" // 9f or 7g or 5h functions should be enough #define MAXCGTO 64 #define DECLARE_ALL \ const int *ao_loc = envs->ao_loc; \ const int *shls_offset = envs->shls_offset; \ const int ioff = ao_loc[shls_offset[0]]; \ const int joff = ao_loc[shls_offset[2]]; \ const int koff = ao_loc[shls_offset[4]]; \ const int loff = ao_loc[shls_offset[6]]; \ const int i0 = ao_loc[ish] - ioff; \ const int j0 = ao_loc[jsh] - joff; \ const int i1 = ao_loc[ish+1] - ioff; \ const int j1 = ao_loc[jsh+1] - joff; \ const int di = i1 - i0; \ const int dj = j1 - j0; \ const int ncomp = envs->ncomp; \ int shls[4]; \ double *buf = malloc(sizeof(double)*di*dj*MAXCGTO*MAXCGTO*ncomp); \ void (*pf)(double *eri, double *dm, JKArray *vjk, int *shls, \ int i0, int i1, int j0, int j1, \ int k0, int k1, int l0, int l1); \ int (*fprescreen)(); \ if (vhfopt) { \ fprescreen = vhfopt->fprescreen; \ } else { \ fprescreen = CVHFnoscreen; \ } \ int ksh, lsh, k0, k1, l0, l1, idm; #define INTOR_AND_CONTRACT \ if ((*fprescreen)(shls, vhfopt, \ envs->atm, envs->bas, envs->env) \ && (*intor)(buf, shls, envs->atm, envs->natm, \ envs->bas, envs->nbas, envs->env, envs->cintopt)) { \ k0 = ao_loc[ksh] - koff; \ l0 = ao_loc[lsh] - loff; \ k1 = ao_loc[ksh+1] - koff; \ l1 = ao_loc[lsh+1] - loff; \ for (idm = 0; idm < n_dm; idm++) { \ pf = jkop[idm]->contract; \ (*pf)(buf, dms[idm], vjk[idm], shls, \ i0, i1, j0, j1, k0, k1, l0, l1); \ } \ } /* * for given ksh, lsh, loop all ish, jsh */ void CVHFdot_nrs1(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { DECLARE_ALL; const int ksh0 = shls_offset[4]; const int ksh1 = shls_offset[5]; const int lsh0 = shls_offset[6]; const int lsh1 = shls_offset[7]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh < lsh1; lsh++) { shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } free(buf); } /* * for given ish, jsh, loop all ksh > lsh */ static void dot_nrs2sub(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { DECLARE_ALL; const int ksh0 = shls_offset[4]; const int ksh1 = shls_offset[5]; const int lsh0 = shls_offset[6]; shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh < ksh1; ksh++) { for (lsh = lsh0; lsh <= ksh; lsh++) { shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } free(buf); } void CVHFdot_nrs2ij(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish >= jsh) { CVHFdot_nrs1(intor, jkop, vjk, dms, n_dm, ish, jsh, vhfopt, envs); } } void CVHFdot_nrs2kl(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { dot_nrs2sub(intor, jkop, vjk, dms, n_dm, ish, jsh, vhfopt, envs); } void CVHFdot_nrs4(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish >= jsh) { dot_nrs2sub(intor, jkop, vjk, dms,n_dm, ish, jsh, vhfopt, envs); } } void CVHFdot_nrs8(int (*intor)(), JKOperator **jkop, JKArray **vjk, double **dms, int n_dm, int ish, int jsh, CVHFOpt *vhfopt, IntorEnvs *envs) { if (ish < jsh) { return; } DECLARE_ALL; const int ksh0 = shls_offset[4]; const int lsh0 = shls_offset[6]; // to make fjk compatible to C-contiguous dm array, put ksh, lsh inner loop shls[0] = ish; shls[1] = jsh; for (ksh = ksh0; ksh <= ish; ksh++) { for (lsh = lsh0; lsh <= ksh; lsh++) { /* when ksh==ish, (lsh<jsh) misses some integrals (eg k<i&&l>j). * These integrals are calculated in the next (ish,jsh) pair. To show * that, we just need to prove that every elements in shell^4 appeared * only once in fjk_s8. */ if ((ksh == ish) && (lsh > jsh)) { break; } shls[2] = ksh; shls[3] = lsh; INTOR_AND_CONTRACT; } } free(buf); } static void assemble_v(double *vjk, JKArray *jkarray, int *ao_loc) { int ish0 = jkarray->v_bra_sh0; int ish1 = jkarray->v_bra_sh1; int jsh0 = jkarray->v_ket_sh0; int jsh1 = jkarray->v_ket_sh1; int njsh = jsh1 - jsh0; int vrow = jkarray->v_dims[0]; int vcol = jkarray->v_dims[1]; int ncomp = jkarray->ncomp; int voffset = ao_loc[ish0] * vcol + ao_loc[jsh0]; int i, j, ish, jsh; int di, dj, icomp; int optr; double *data, *pv; for (ish = ish0; ish < ish1; ish++) { for (jsh = jsh0; jsh < jsh1; jsh++) { optr = jkarray->outptr[ish*njsh+jsh-jkarray->offset0_outptr]; if (optr != NOVALUE) { di = ao_loc[ish+1] - ao_loc[ish]; dj = ao_loc[jsh+1] - ao_loc[jsh]; data = jkarray->data + optr; pv = vjk + ao_loc[ish]*vcol+ao_loc[jsh] - voffset; for (icomp = 0; icomp < ncomp; icomp++) { for (i = 0; i < di; i++) { for (j = 0; j < dj; j++) { pv[i*vcol+j] += data[i*dj+j]; } } pv += vrow * vcol; data += di * dj; } } } } } /* * drv loop over ij, generate eris of kl for given ij, call fjk to * calculate vj, vk. * * n_dm is the number of dms for one [array(ij|kl)], it is also the size of dms and vjk * ncomp is the number of components that produced by intor * shls_offset = [ishstart, ishend, jshstart, jshend, kshstart, kshend, lshstart, lshend] * * ao_loc[i+1] = ao_loc[i] + CINTcgto_spheric(i, bas) for i = 0..nbas * * Return [(ptr[ncomp,nao,nao] in C-contiguous) for ptr in vjk] */ void CVHFnr_direct_drv(int (*intor)(), void (*fdot)(), JKOperator **jkop, double **dms, double **vjk, int n_dm, int ncomp, int *shls_offset, int *ao_loc, CINTOpt *cintopt, CVHFOpt *vhfopt, int *atm, int natm, int *bas, int nbas, double *env) { IntorEnvs envs = {natm, nbas, atm, bas, env, shls_offset, ao_loc}; envs.cintopt = cintopt; envs.ncomp = ncomp; int idm; size_t size; for (idm = 0; idm < n_dm; idm++) { size = jkop[idm]->data_size(shls_offset, ao_loc) * ncomp; memset(vjk[idm], 0, sizeof(double)*size); } const int ish0 = shls_offset[0]; const int ish1 = shls_offset[1]; const int jsh0 = shls_offset[2]; const int jsh1 = shls_offset[3]; const int nish = ish1 - ish0; const int njsh = jsh1 - jsh0; #pragma omp parallel default(none) \ shared(intor, fdot, jkop, ao_loc, shls_offset, \ dms, vjk, n_dm, ncomp, nbas, vhfopt, envs) { int i, j, ij, ij1; JKArray *v_priv[n_dm]; for (i = 0; i < n_dm; i++) { v_priv[i] = jkop[i]->allocate(shls_offset, ao_loc, ncomp); } #pragma omp for nowait schedule(dynamic, 1) for (ij = 0; ij < nish*njsh; ij++) { ij1 = nish*njsh-1 - ij; // if (ij % 2) { ///* interlace the iteration to balance memory usage // * map [0,1,2...,N] to [0,N,1,N-1,...] */ // ij1 = nish*njsh-1 - ij/2; // } else { // ij1 = ij / 2; // } i = ij1 / njsh + ish0; j = ij1 % njsh + jsh0; (*fdot)(intor, jkop, v_priv, dms, n_dm, i, j, vhfopt, &envs); } #pragma omp critical { for (i = 0; i < n_dm; i++) { assemble_v(vjk[i], v_priv[i], ao_loc); jkop[i]->deallocate(v_priv[i]); } } } }
GB_binop__eq_int16.c
//------------------------------------------------------------------------------ // GB_binop: hard-coded functions for each built-in binary operator //------------------------------------------------------------------------------ // SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 //------------------------------------------------------------------------------ // If this file is in the 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__eq_int16 // A.*B function (eWiseMult): GB_AemultB__eq_int16 // A*D function (colscale): GB_AxD__eq_int16 // D*A function (rowscale): GB_DxB__eq_int16 // C+=B function (dense accum): GB_Cdense_accumB__eq_int16 // C+=b function (dense accum): GB_Cdense_accumb__eq_int16 // C+=A+B function (dense ewise3): (none) // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__eq_int16 // C=scalar+B GB_bind1st__eq_int16 // C=scalar+B' GB_bind1st_tran__eq_int16 // C=A+scalar GB_bind2nd__eq_int16 // C=A'+scalar GB_bind2nd_tran__eq_int16 // C type: bool // A type: int16_t // B,b type: int16_t // BinaryOp: cij = (aij == bij) #define GB_ATYPE \ int16_t #define GB_BTYPE \ int16_t #define GB_CTYPE \ 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) \ int16_t aij = Ax [pA] // bij = Bx [pB] #define GB_GETB(bij,Bx,pB) \ int16_t bij = Bx [pB] // declare scalar of the same type as C #define GB_CTYPE_SCALAR(t) \ bool t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y, i, j) \ z = (x == y) ; // 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_EQ || GxB_NO_INT16 || GxB_NO_EQ_INT16) //------------------------------------------------------------------------------ // 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__eq_int16 ( GrB_Matrix C, const GrB_Matrix A, const GrB_Matrix B, const int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else #include "GB_dense_ewise3_noaccum_template.c" return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += B, accumulate a sparse matrix into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumB__eq_int16 ( 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__eq_int16 ( 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 int16_t int16_t bwork = (*((int16_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__eq_int16 ( 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__eq_int16 ( GrB_Matrix C, const GrB_Matrix D, bool D_is_pattern, const GrB_Matrix B, bool B_is_pattern, int nthreads ) { #if GB_DISABLE return (GrB_NO_VALUE) ; #else 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 //------------------------------------------------------------------------------ #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__eq_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const bool Ch_is_Mh, const int64_t *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__eq_int16 ( GrB_Matrix C, const int C_sparsity, const GrB_Matrix M, const bool Mask_struct, const bool Mask_comp, const GrB_Matrix A, const GrB_Matrix B, const 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__eq_int16 ( 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 bool *Cx = (bool *) Cx_output ; int16_t x = (*((int16_t *) x_input)) ; int16_t *Bx = (int16_t *) Bx_input ; int64_t p ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Bb, p)) continue ; int16_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__eq_int16 ( 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 ; bool *Cx = (bool *) Cx_output ; int16_t *Ax = (int16_t *) Ax_input ; int16_t y = (*((int16_t *) y_input)) ; #pragma omp parallel for num_threads(nthreads) schedule(static) for (p = 0 ; p < anz ; p++) { if (!GBB (Ab, p)) continue ; int16_t aij = 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) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = (x == aij) ; \ } GrB_Info GB_bind1st_tran__eq_int16 ( 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 \ int16_t #if GB_DISABLE return (GrB_NO_VALUE) ; #else int16_t x = (*((const int16_t *) x_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif #undef GB_ATYPE #define GB_ATYPE \ int16_t } //------------------------------------------------------------------------------ // C = op (A', y): transpose and apply a binary operator //------------------------------------------------------------------------------ // cij = op (aij, y), no typecasting (in spite of the macro name) #undef GB_CAST_OP #define GB_CAST_OP(pC,pA) \ { \ int16_t aij = Ax [pA] ; \ Cx [pC] = (aij == y) ; \ } GrB_Info GB_bind2nd_tran__eq_int16 ( 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 int16_t y = (*((const int16_t *) y_input)) ; #include "GB_unop_transpose.c" return (GrB_SUCCESS) ; #endif } #endif
tvreg.c
/** * @file tvreg.c * @brief TV-regularized image restoration * @author Pascal Getreuer <getreuer@gmail.com> * * Copyright (c) 2010-2012, Pascal Getreuer * All rights reserved. * * 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>. */ #include <math.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include "tvregopt.h" // #ifdef MATLAB_MEX_FILE // #include "tvregmex.h" // #endif #include "dsolve_inc.c" #if defined(TVREG_DENOISE) || defined(TVREG_INPAINT) #include "usolve_gs_inc.c" #endif #ifdef TVREG_DECONV #include "usolve_dct_inc.c" #include "usolve_dft_inc.c" #endif #ifdef TVREG_USEZ #include "zsolve_inc.c" #endif /** * @brief Total variation based image restoration * @param u initial guess, overwritten with restored image * @param f input image * @param Width, Height, NumChannels dimensions of the input image * @param Opt tvregopt options object * @return 0 on failure, 1 on success, 2 on maximum iterations exceeded * * This routine implements simultaneous denoising, deconvolution, and * inpainting with total variation (TV) regularization, using either the * Gaussian (L2), Laplace (L1), or Poisson noise model, such that Kernel*u is * approximately f outside of the inpainting domain. * * The input image f should be a contiguous array of size Width by Height by * NumChannels in planar row-major order, * f[x + Width*(y + Height*k)] = kth component of pixel (x,y). * * The image intensity values of f should be scaled so that the maximum * intensity range of the true clean image is from 0 to 1. It is allowed that * f have values outside of [0,1] (as spurious noisy pixels can exceed this * range), but it should be scaled so that the restored image is in [0,1]. * This scaling is especially important for the Poisson noise model. * * Typically, NumChannels is either 1 (grayscale image) or 3 (color image), * but NumChannels is allowed to be any positive integer. If NumChannels > 1, * then vectorial TV (VTV) regularization is used in place of TV. * * Image u is both an input and output of the routine. Image u should be * set by the caller to an initial guess, for example a good generic * initialization is to set u as a copy of f. Image u is overwritten with the * restored image. * * Other options are specified through the options object Opt. First use * tvregopt Opt = TvRegNewOpt() * to create a new options object with default options (denoising with the * Gaussian noise model). Then use the following functions to make settings. * * - TvRegSetLambda(): set fidelity weight * - TvRegSetVaryingLambda(): set spatially varying fidelity weight * - TvRegSetKernel(): Kernel for deconvolution problems * - TvRegSetTol(): convergence tolerance * - TvRegSetMaxIter(): maximum number of iterations * - TvRegSetNoiseModel(): noise model * - TvRegSetGamma1(): constraint weight on d = grad u * - TvRegSetGamma2(): constraint weight on z = Ku * - TvRegSetPlotFun(): custom plotting function * * When done, call TvRegFreeOpt() to free the options object. Setting * Opt = NULL uses the default options (denoising with Gaussian noise model). * * The split Bregman method is used to solve the minimization, * T. Goldstein and S. Osher, "The Split Bregman Algorithm for L1 * Regularized Problems", UCLA CAM Report 08-29. * * The routine automatically adapts the algorithm according to the inputs. If * no deconvolution is needed, Gauss-Seidel is used to solve the u-subproblem. * If the kernel is symmetric, a DCT-based solver is applied and, if not, a * (slower) Fourier-based solver. For the Gaussian noise model, the routine * uses a simpler splitting of the problem with two auxiliary variables. For * non-Gaussian noise models, a splitting with three auxiliary variables is * applied. */ int TvRestore(num *u, const num *f, int Width, int Height, int NumChannels, tvregopt *Opt) { const long NumPixels = ((long)Width) * ((long)Height); const long NumEl = NumPixels * NumChannels; tvregsolver S; usolver USolveFun = NULL; zsolver ZSolveFun = NULL; num DiffNorm; int i, Success = 0, DeconvFlag, DctFlag, Iter; if(!u || !f || u == f || Width < 2 || Height < 2 || NumChannels <= 0) return 0; /*** Set algorithm flags ***********************************************/ S.Opt = (Opt) ? *Opt : TvRegDefaultOpt; if(!TvRestoreChooseAlgorithm(&S.UseZ, &DeconvFlag, &DctFlag, &USolveFun, &ZSolveFun, &S.Opt)) return 0; #if !defined(TVREG_DENOISE) && !defined(TVREG_INPAINT) if(!DeconvFlag) { if(!S.Opt.VaryingLambda) fprintf(stderr, "Please recompile with TVREG_DENOISE " "for denoising problems.\n"); else fprintf(stderr, "Please recompile with TVREG_INPAINT " "for inpainting problems.\n"); return 0; } #endif if(S.Opt.VaryingLambda && (S.Opt.LambdaWidth != Width || S.Opt.LambdaHeight != Height)) { fprintf(stderr, "Image is %dx%d but lambda is %dx%d.\n", Width, Height, S.Opt.LambdaWidth, S.Opt.LambdaHeight); return 0; } S.u = u; S.f = f; S.Width = S.PadWidth = Width; S.Height = S.PadHeight = Height; S.NumChannels = NumChannels; S.Alpha = ((!S.UseZ) ? S.Opt.Lambda : S.Opt.Gamma2) / S.Opt.Gamma1; /*** Allocate memory ***************************************************/ S.d = S.dtilde = NULL; #ifdef TVREG_USEZ S.z = S.ztilde = NULL; #endif #ifdef TVREG_DECONV S.A = S.B = S.ATrans = S.BTrans = S.KernelTrans = S.DenomTrans = NULL; S.TransformA = S.TransformB = S.InvTransformA = S.InvTransformB = NULL; #endif if(!(S.d = (numvec2 *)Malloc(sizeof(numvec2)*NumEl)) || !(S.dtilde = (numvec2 *)Malloc(sizeof(numvec2)*NumEl))) goto Catch; if(S.UseZ) #ifndef TVREG_USEZ { /* We need z but do not have it, show error message. */ if(S.Opt.NoiseModel != NOISEMODEL_L2) fprintf(stderr, "Please recompile with TVREG_NONGAUSSIAN " "for non-Gaussian noise models.\n"); else fprintf(stderr, "Please recompile with TVREG_DECONV and " "TVREG_INPAINT for deconvolution-inpainting problems.\n"); goto Catch; } #else { /* Allocate memory for z and ztilde */ if(!(S.z = (num *)Malloc(sizeof(num)*NumEl)) || !(S.ztilde = (num *)Malloc(sizeof(num)*NumEl))) goto Catch; /* Initialize z = ztilde = u */ memcpy(S.z, S.u, sizeof(num)*NumEl); memcpy(S.ztilde, S.u, sizeof(num)*NumEl); } #endif if(!DeconvFlag) S.Ku = u; else #ifndef TVREG_DECONV { /* We need deconvolution but do not have it, show error message. */ fprintf(stderr, "Please recompile with TVREG_DECONV " "for deconvolution problems.\n"); goto Catch; } #else /* The following applies only for problems with deconvolution */ if(DctFlag) { /* Prepare for DCT-based deconvolution */ long PadNumPixels = ((long)Width + 1) * ((long)Height + 1); if(!(S.ATrans = (num *)FFT(malloc)(sizeof(num)*NumEl)) || !(S.BTrans = (num *)FFT(malloc)(sizeof(num)*NumEl)) || !(S.A = (num *)FFT(malloc)(sizeof(num)*NumEl)) || !(S.B = (num *)FFT(malloc)( sizeof(num)*PadNumPixels*NumChannels)) || !(S.KernelTrans = (num *)FFT(malloc)(sizeof(num)*PadNumPixels)) || !(S.DenomTrans = (num *)Malloc(sizeof(num)*NumPixels)) || !InitDeconvDct(&S)) goto Catch; } else { /* Prepare for Fourier-based deconvolution */ long NumTransPixels, NumTransEl, PadNumEl; int TransWidth; S.PadWidth = 2*Width; S.PadHeight = 2*Height; TransWidth = S.PadWidth/2 + 1; NumTransPixels = ((long)TransWidth) * ((long)S.PadHeight); NumTransEl = NumTransPixels * NumChannels; PadNumEl = (((long)S.PadWidth) * S.PadHeight) * NumChannels; if(!(S.ATrans = (num *)FFT(malloc)(sizeof(numcomplex)*NumTransEl)) || !(S.BTrans = (num *)FFT(malloc)(sizeof(numcomplex)*NumTransEl)) || !(S.A = (num *)FFT(malloc)(sizeof(num)*PadNumEl)) || !(S.B = (num *)FFT(malloc)(sizeof(num)*PadNumEl)) || !(S.KernelTrans = (num *) FFT(malloc)(sizeof(numcomplex)*NumTransPixels)) || !(S.DenomTrans = (num *)Malloc(sizeof(num)*NumTransPixels)) || !InitDeconvFourier(&S)) goto Catch; } #endif /*** Algorithm initializations *****************************************/ /* Set convergence threshold scaled by norm of f */ for(i = 0, S.fNorm = 0; i < NumEl; i++) S.fNorm += f[i] * f[i]; S.fNorm = (num)sqrt(S.fNorm); if(S.fNorm == 0) /* Special case, input image is zero */ { memcpy(u, f, sizeof(num)*NumEl); Success = 1; goto Catch; } /* Initialize d = dtilde = 0 */ for(i = 0; i < NumEl; i++) S.d[i].x = S.d[i].y = 0; for(i = 0; i < NumEl; i++) S.dtilde[i].x = S.dtilde[i].y = 0; DiffNorm = (S.Opt.Tol > 0) ? 1000*S.Opt.Tol : 1000; Success = 2; if(S.Opt.PlotFun && !S.Opt.PlotFun(0, 0, DiffNorm, u, Width, Height, NumChannels, S.Opt.PlotParam)) goto Catch; /*** Algorithm main loop: Bregman iterations ***************************/ for(Iter = 1; Iter <= S.Opt.MaxIter; Iter++) { /* Solve d subproblem and update dtilde */ DSolve(&S); /* Solve u subproblem */ DiffNorm = USolveFun(&S); if(Iter >= 2 + S.UseZ && DiffNorm < S.Opt.Tol) break; #ifdef TVREG_USEZ /* Solve z subproblem and update ztilde */ if(S.UseZ) ZSolveFun(&S); #endif if(S.Opt.PlotFun && !(S.Opt.PlotFun(0, Iter, DiffNorm, u, Width, Height, NumChannels, S.Opt.PlotParam))) goto Catch; } /*** End of main loop **************************************************/ Success = (Iter <= S.Opt.MaxIter) ? 1 : 2; if(S.Opt.PlotFun) S.Opt.PlotFun(Success, (Iter <= S.Opt.MaxIter) ? Iter : S.Opt.MaxIter, DiffNorm, u, Width, Height, NumChannels, S.Opt.PlotParam); Catch: /*** Release memory ****************************************************/ if(S.dtilde) Free(S.dtilde); if(S.d) Free(S.d); #ifdef TVREG_USEZ if(S.ztilde) Free(S.ztilde); if(S.z) Free(S.z); #endif #ifdef TVREG_DECONV if(DeconvFlag) { if(S.DenomTrans) Free(S.DenomTrans); if(S.KernelTrans) FFT(free)(S.KernelTrans); if(S.B) FFT(free)(S.B); if(S.A) FFT(free)(S.A); if(S.BTrans) FFT(free)(S.BTrans); if(S.ATrans) FFT(free)(S.ATrans); #ifdef _OPENMP #pragma omp critical (fftw) #endif { FFT(destroy_plan)(S.InvTransformB); FFT(destroy_plan)(S.TransformB); FFT(destroy_plan)(S.InvTransformA); FFT(destroy_plan)(S.TransformA); } /*FFT(cleanup)();*/ } #endif return Success; } /** @brief Test if Kernel is whole-sample symmetric */ static int IsSymmetric(const num *Kernel, int KernelWidth, int KernelHeight) { int x, xr, y, yr; if(KernelWidth % 2 == 0 || KernelHeight % 2 == 0) return 0; for(y = 0, yr = KernelHeight - 1; y < KernelHeight; y++, yr--) for(x = 0, xr = KernelWidth - 1; x < KernelWidth; x++, xr--) if(Kernel[x + KernelWidth*y] != Kernel[xr + KernelWidth*y] || Kernel[x + KernelWidth*y] != Kernel[x + KernelWidth*yr]) return 0; return 1; } /** @brief Algorithm planning function */ static int TvRestoreChooseAlgorithm(int *UseZ, int *DeconvFlag, int *DctFlag, usolver *USolveFun, zsolver *ZSolveFun, const tvregopt *Opt) { if(!Opt) return 0; /* UseZ decides between the simpler d,u splitting or the d,u,z splitting of the problem. ZSolveFun selects the z-subproblem solver. */ *UseZ = (Opt->NoiseModel != NOISEMODEL_L2); #ifndef TVREG_USEZ *ZSolveFun = NULL; #else switch(Opt->NoiseModel) { case NOISEMODEL_L2: *ZSolveFun = ZSolveL2; break; case NOISEMODEL_L1: *ZSolveFun = ZSolveL1; break; case NOISEMODEL_POISSON: *ZSolveFun = ZSolvePoisson; break; default: return 0; } #endif /* If there is a kernel, set DeconvFlag */ if(Opt->Kernel) { /* Must use d,u,z splitting for deconvolution with spatially-varying lambda */ if(Opt->VaryingLambda) *UseZ = 1; *DeconvFlag = 1; /* Use faster DCT solver if kernel is symmetric in both dimensions */ *DctFlag = IsSymmetric(Opt->Kernel, Opt->KernelWidth, Opt->KernelHeight); } else *DeconvFlag = *DctFlag = 0; /* Select the u-subproblem solver */ if(!*DeconvFlag) /* Gauss-Seidel solver for denoising and inpainting */ #if defined(TVREG_DENOISE) || defined(TVREG_INPAINT) *USolveFun = (!Opt->VaryingLambda) ? UGaussSeidelConstantLambda : UGaussSeidelVaryingLambda; #else *USolveFun = NULL; #endif #ifdef TVREG_DECONV #ifdef TVREG_USEZ else if(*UseZ) *USolveFun = (*DctFlag) ? UDeconvDctZ : UDeconvFourierZ; #endif else *USolveFun = (*DctFlag) ? UDeconvDct : UDeconvFourier; #endif return 1; }
DRB060-matrixmultiply-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* Classic i-k-j matrix multiplication */ #define N 100 #define M 100 #define K 100 double a[N][M],b[M][K],c[N][K]; int mmm() { int i,j,k; #pragma omp parallel for private(j,k) for (i = 0; i < N; i++) for (k = 0; k < K; k++) for (j = 0; j < M; j++) c[i][j]= c[i][j]+a[i][k]*b[k][j]; return 0; } int main() { mmm(); return 0; }
synchronousCmapDeepBkzSimilarity.h
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* This file is part of the program and software framework */ /* CMAP-ENUM --- Configurable Massively Parallel Solver for ENUM */ /* */ /* Copyright Written by Nariaki Tateiwa <n-tateiwa@kyudai.jp>, */ /* Yuji Shinano <shinano@zib.de>, */ /* Copyright (C) 2021 by Zuse Institute Berlin, */ /* licensed under LGPL version 3 or later. */ /* */ /* This code 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 3 */ /* of the License, or (at your option) any later version. */ /* */ /* This program is distributed in the hope that it will be useful, */ /* but WITHOUT ANY WARRANTY; without even the implied warranty of */ /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */ /* GNU Lesser General Public License for more details. */ /* */ /* You should have received a copy of the GNU Lesser General Public License */ /* along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /**@file synchronousCmapDeepBkzSimilarity.h * @brief Calculation of similarity of bases for synchronousCmapdeepbkz. * @author Nariaki Tateiwa, Yuji Shinano * * * */ /*---+----1----+----2----+----3----+----4----+----5----+----6----+----7----+----8----+----9----+----0----+----1----+----2*/ #ifndef __SYNCHRONOUS_CMAP_DEEPBKZ_SIMILARITY_H__ #define __SYNCHRONOUS_CMAP_DEEPBKZ_SIMILARITY_H__ #include <vector> #include <chrono> #include <random> #include <deque> #include <set> #include <eigen3/Eigen/Core> #include <eigen3/Eigen/SVD> namespace BasisSimilarity { /// index to calculate grassmann metric std::vector<int> grassmannIndexes; /// calculate grassmann metric Eigen::MatrixXd scores_geodesic_metric; Eigen::MatrixXd scores_chordal_metric; Eigen::MatrixXd scores_fubini_study_metric; Eigen::MatrixXd scores_chordal_2norm_metric; Eigen::MatrixXd scores_chordal_fnorm_metric; Eigen::MatrixXd scores_projection_2norm_metric; Eigen::MatrixXd scores_max_metric; Eigen::MatrixXd scores_mean_metric; Eigen::VectorXd scores_num_upper_duplicate; Eigen::VectorXd scores_num_all_duplicate; /// /// @brief setter of grassmannIndexes /// @param[in] inGrassmannIndexes /// void setGrassmannIndexes( std::vector<int> inGrassmannIndexes ) { grassmannIndexes = inGrassmannIndexes; } /// /// @brief similarity log header /// @param[in] n dimension /// @return std::string /// std::string outputSimilarityOfBasisHeader( int n ) { assert( grassmannIndexes.size() > 0 ); std::ostringstream s; s << "SimilarityStatus" << ",time" << ",numPairs"; std::vector<std::string> metrics{"num_upper_duplicate", "num_all_duplicate"}; std::vector<std::string> grassmannMetricNames{ "grassmann_geodesic", "grassmann_chordal", "grassmann_fubini", "grassmann_chordal_2norm", "grassmann_chordal_fnorm", "grassmann_projection_2norm", "grassmann_max", "grassmann_mean" }; for( auto name : grassmannMetricNames ) { for( auto i : grassmannIndexes ) { std::ostringstream metric; metric << name << "_" << i; metrics.push_back(metric.str()); } } for( auto metric : metrics ) { s << "," << metric << "_min"; s << "," << metric << "_max"; s << "," << metric << "_average"; } return s.str(); } /// /// @brief sampling of vector /// @tparam T population type /// @param[in] population list /// @param[out] sampled list /// @param[in] sampled size /// template<typename T> void sample( T &list, T &sampled_list, int size ) { assert( static_cast<int>(list.size()) >= size ); std::vector<int> indexes(list.size(), 0); for ( size_t i = 0; i < list.size(); ++i ) indexes[i] = i; std::random_device seed_gen; // std::mt19937 engine {seed_gen()}; std::mt19937 engine {0}; std::shuffle(indexes.begin(), indexes.end(), engine); sampled_list.resize(size); for ( int i = 0; i < size; ++i ) sampled_list[i] = list[indexes[i]]; } /// /// @brief sign function /// @param[in] x /// @return sign of x ( 1 or -1 ) /// int sign( int x ) { if( x >= 0 ) return 1; else return -1; } /// /// @brief max(k; A(i) == B(i) || A(i) == -B(i) for all i <= k ) /// @param[in] basisA basis /// @param[in] basisB basis /// @return number of matches from the top of the basis vector /// double num_upper_duplicate( MatrixXi& basisA, MatrixXi& basisB ) { double score = 0.0; for( int i = 0; i < basisA.rows(); i++ ) { if( sign(basisA.coeff(i, 0))*basisA.row(i) == sign(basisB.coeff(i, 0))*basisB.row(i) ) score += 1; else break; } return score; } /// /// @brief coun ( ( A(i) == B(i) || A(i) == -B(i) ) for all i ) /// @param[in] basisA basis /// @param[in] basisB basis /// @return number of basis vector overlaps /// double num_all_duplicate( MatrixXi& basisA, MatrixXi& basisB ) { double score = 0.0; for( int i = 0; i < basisA.rows(); i++ ) { if( sign(basisA.coeff(i, 0))*basisA.row(i) == sign(basisB.coeff(i, 0))*basisB.row(i) ) score += 1; } return score; } /// @brief set Gram-Schmidt matrix /// @parma[in] basis /// @parma[out] GSO Gram-Schmidt of basis /// void setGramSchmidt( MatrixXi& basis, Eigen::MatrixXd& GSO ) { GSO = MatrixXi(basis).cast<double>() .transpose() .householderQr() .householderQ() .transpose(); } /// /// @brief Grassmann Geodesic Metric /// @param[in] cc canonical correlations /// @details sqrt(sum(theta_i^2 for 0 <= i < m)) /// = sqrt(sum(acos(cc(i))^2 for 0 <= i < m)) /// double grassmann_geodesic_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = 0.0; double theta = 0.0; for( int i = 0; i < m; ++i ) { theta = std::acos(cc(i)); d += theta * theta; } return std::sqrt(d); } /// /// @brief Grassmann Chordal Metric = projection frobenius metric /// @param[in] cc canonicalCorrelations /// @details 2^(-1/2) frobenius_norm(GSOA*GSOA^T - GSOB*GSOB^T) /// = sqrt(sum(sin^2(theta_i) for 0 <= i < m)) /// = sqrt(sum(1 - cos^2(theta_i) for 0 <= i < m)) /// = sqrt(m - sum(cc(i)^2) for 0 <= i <= m) /// double grassmann_chordal_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = m; for( int i = 0; i < m; i++ ) d -= cc(i) * cc(i); return std::sqrt(d); } /// /// @brief Grassmann Fubini-Study Metric /// @param[in] cc canonical correlations /// @details acos(prod(cos(theta_i) for 0 <= i < m)) /// = acos(prod(cc(i) for 0 <= i < m)) /// double grassmann_fubini_study_metric( Eigen::VectorXd &cc ) { return std::acos( cc.prod() ); } /// /// @brief Grassmann Chordal 2-norm Metric /// @param[in] cc canonical correlations /// @details 2norm( U*GSOA^T - V*GSOB ) /// = infinity_norm(2*sin(theta_i/2) for 0 <= i < m) /// = 2 * max(sin(theta_i/2) for 0 <= i < m) /// = 2 * sqrt( max(sin^2(theta_i/2) for 0 <= i < m) ) (because 0 < theta_i < pi) /// = 2 * sqrt( max((1-cc(i))/2 for 0 <= i < m) ) /// double grassmann_chordal_2norm_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = (1.0 - cc(0)) / 2.0; for( int i = 1; i < m; ++i ) { d = std::max(d, (1.0 - cc(i))/2.0); } return 2.0 * std::sqrt(d); } /// /// @brief Grassmann Chordal frobenius-norm Metric /// @param[in] cc canonical correlations /// @details frobenius_norm( U*GSOA^T - V*GSOB ) /// = 2_norm(2*sin(theta_i/2) for 0 <= i < m) /// = 2 * sqrt(sum(sin^2(theta_i/2) for 0 <= i < m) /// = 2 * sqrt(sum((1-cc(i))/2 for 0 <= i < m) /// double grassmann_chordal_fnorm_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = 0.0; for( int i = 0; i < m; ++i ) { d += (1.0 - cc(i)) / 2.0; } return 2.0 * std::sqrt(d); } /// /// @brief Grassmann Projection 2-norm Metric /// @param[in] cc canonicalCorrelations /// @details 2norm( GSOA*GSOA^T - GSOB*GSOB^T ) /// infinity_norm( sin(theta_i) ) for 0 <= i < m) ) /// = sqrt( max( sin^2(theta_i) for 0 <= i < m) ) (because 0 <= theta_i <= pi) /// = sqrt( max( 1 - cos^2(theta_i) for 0 <= i < m) ) /// = sqrt( max( 1 - cc(i)^2 for 0 <= i < m) ) /// double grassmann_projection_2norm_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = 1.0 - cc(0) * cc(0); if( d < 1.0e-5 ) return 0; for( int i = 1; i < m; ++i ) { d = std::max(d, 1.0 - cc(i) * cc(i)); } return std::sqrt(d); } /// /// @brief Grassmann max Metric /// @param[in] cc canonicalCorrelations /// @details min( sin(theta_i) ) for 0 <= i < m) ) /// = sqrt( min( sin^2(theta_i) for 0 <= i < m) ) (because 0 <= theta_i <= pi) /// = sqrt( min( 1 - cos^2(theta_i) for 0 <= i < m) ) /// = sqrt( min( 1 - cc(i)^2 for 0 <= i < m) ) /// = sqrt( 1 - cc(m-1)^2 ) /// double grassmann_max_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = 1.0 - cc(m-1) * cc(m-1); if( d < 1.0e-5 ) return 0; return std::sqrt(d); } /// /// @brief Grassmann Mean Metric /// @param[in] cc canonicalCorrelations /// @details mean( sin(\theta_i)^2 for 0 <= i <= m ) /// = mean( 1 - cos(\theta_i)^2 for 0 <= i <= m ) /// double grassmann_mean_metric( Eigen::VectorXd &cc ) { int m = cc.size(); double d = 0.0; for( int i = 0; i < m; i++ ) d += 1.0 - cc(i)*cc(i); return d / static_cast<double>(m); } /// /// @brief output log /// @param[in] basisDeque container of basis /// @param[in] time /// @param[in] n dimension of basis /// @param[in] num_threads number threads /// @param[in] verbose ( 0: not, 1: light, 2: medium, 3: heave ) /// std::string outputSimilarityOfBasis( std::deque<MatrixXi*> &basisDeque, double time, int n, int numThreads=1, int verbose=0 ) { int numBasis = basisDeque.size(); int numPairs = numBasis * (numBasis-1) / 2; int k = -1; double tol = 1e-6; std::vector<std::pair<int, int>> combinations; combinations.resize(numPairs); k = -1; for ( int i = 0; i < numBasis; ++i ) { for ( int j = i+1; j < numBasis; ++j ) { combinations[++k] = std::make_pair(i, j); } } // sampling int nSamples = -1; if( nSamples == -1 ){ nSamples = combinations.size(); } nSamples = std::min(nSamples, static_cast<int>(combinations.size())); decltype(combinations) sampledConbinations; sample( combinations, sampledConbinations, nSamples ); // calculate GSO matrix std::vector<Eigen::MatrixXd> GSOList; GSOList.resize(basisDeque.size()); std::set<int> calcGSOindexes; for( auto pair : sampledConbinations ) { calcGSOindexes.insert(pair.first); calcGSOindexes.insert(pair.second); } for( auto _k : calcGSOindexes ) { Eigen::MatrixXd GSO; setGramSchmidt(*basisDeque.at(_k), GSO); GSOList[_k] = GSO; } // calculate grassmann metric scores_geodesic_metric .resize(nSamples, grassmannIndexes.size()); scores_chordal_metric .resize(nSamples, grassmannIndexes.size()); scores_fubini_study_metric .resize(nSamples, grassmannIndexes.size()); scores_chordal_2norm_metric .resize(nSamples, grassmannIndexes.size()); scores_chordal_fnorm_metric .resize(nSamples, grassmannIndexes.size()); scores_projection_2norm_metric.resize(nSamples, grassmannIndexes.size()); scores_max_metric .resize(nSamples, grassmannIndexes.size()); scores_mean_metric .resize(nSamples, grassmannIndexes.size()); scores_num_upper_duplicate .resize(nSamples); scores_num_all_duplicate .resize(nSamples); int barWidth = 50; auto setProgressorCallback = [=](int _k){ double progress = static_cast<double>(_k+1) / nSamples; std::cout << "Calculate Diversity ["; int pos = barWidth * progress; for (int i = 0; i < barWidth; ++i) { if (i < pos) std::cout << "="; else if (i == pos) std::cout << ">"; else std::cout << " "; } std::cout << "] " << static_cast<int>(progress * 100.0) << " % (" << _k+1 << " / " << nSamples << ") \r"; std::cout.flush(); }; #pragma omp parallel for num_threads(numThreads) schedule(dynamic, 1) for( k = 0; k < nSamples; ++k ) { if( omp_get_thread_num() == 0 ) { setProgressorCallback(k); } int i, j; std::tie(i, j) = sampledConbinations[k]; // duplicate scores_num_upper_duplicate(k) = num_upper_duplicate( *(basisDeque.at(i)), *(basisDeque.at(j)) ); scores_num_all_duplicate(k) = num_all_duplicate( *(basisDeque.at(i)), *(basisDeque.at(j)) ); // grassmann // 1. generate sub GSO // 2. get canonical angles // 3. calculate metric for( int l = grassmannIndexes.size()-1; l > -1; --l ) { int d = grassmannIndexes[l]; Eigen::VectorXd canonicalCorrelations = Eigen::VectorXd::Ones(n-d); if( d >= n / 2.0 ) { // GSO = [b*0; b*1; ...; b*n-1] -> [b*d; ...; b*(n-1)] Eigen::MatrixXd subGSOA{GSOList.at(i).block(d,0,n-d,n)}; Eigen::MatrixXd subGSOB{GSOList.at(j).block(d,0,n-d,n)}; // calculate canonical angles JacobiSVD<Eigen::MatrixXd> SVD{subGSOA * subGSOB.transpose()}; canonicalCorrelations.tail(n-d) = SVD.singularValues(); } else if( d > 0 ) { // GSO = [b*0; b*1; ...; b*n-1] -> [b*0; ...; b*d-1] Eigen::MatrixXd subGSOA{GSOList.at(i).block(0,0,d,n)}; Eigen::MatrixXd subGSOB{GSOList.at(j).block(0,0,d,n)}; // calculate canonical angles JacobiSVD<Eigen::MatrixXd> SVD{subGSOA * subGSOB.transpose()}; canonicalCorrelations.tail(d) = SVD.singularValues(); } for( int ii = 0; ii < n-d; ++ii ) { canonicalCorrelations(ii) = std::min(std::max(canonicalCorrelations(ii), -1.0), 1.0); } if( verbose > 0 ) { std::cout << "k: " << k << " pair(" << i << ", " << j << ") d " << d << std::endl; std::cout << "canonicalCorrelations " << canonicalCorrelations.transpose() << std::endl; } if( (canonicalCorrelations.array() >= 1.0-tol).all() && (canonicalCorrelations.array() <= 1.0+tol).all() ) { // GSOA == GSOB scores_geodesic_metric(k, l) = 0.0; scores_chordal_metric(k, l) = 0.0; scores_fubini_study_metric(k, l) = 0.0; scores_chordal_2norm_metric(k, l) = 0.0; scores_chordal_fnorm_metric(k, l) = 0.0; scores_projection_2norm_metric(k, l) = 0.0; scores_max_metric(k, l) = 0.0; scores_mean_metric(k, l) = 0.0; } else { // calculate metric scores_geodesic_metric(k, l) = grassmann_geodesic_metric(canonicalCorrelations); scores_chordal_metric(k, l) = grassmann_chordal_metric(canonicalCorrelations); scores_fubini_study_metric(k, l) = grassmann_fubini_study_metric(canonicalCorrelations); scores_chordal_2norm_metric(k, l) = grassmann_chordal_2norm_metric(canonicalCorrelations); scores_chordal_fnorm_metric(k, l) = grassmann_chordal_fnorm_metric(canonicalCorrelations); scores_projection_2norm_metric(k, l) = grassmann_projection_2norm_metric(canonicalCorrelations); scores_max_metric(k, l) = grassmann_max_metric(canonicalCorrelations); scores_mean_metric(k, l) = grassmann_mean_metric(canonicalCorrelations); } } } std::cout << std::endl; std::ostringstream s; s << "SimilarityStatus" << "," << time << "," << scores_num_upper_duplicate.size(); // upper_duplicate s << "," << scores_num_upper_duplicate.minCoeff(); s << "," << scores_num_upper_duplicate.maxCoeff(); s << "," << scores_num_upper_duplicate.mean(); // all_duplicate s << "," << scores_num_all_duplicate.minCoeff(); s << "," << scores_num_all_duplicate.maxCoeff(); s << "," << scores_num_all_duplicate.mean(); for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_geodesic_metric s << "," << scores_geodesic_metric.col(i).minCoeff(); s << "," << scores_geodesic_metric.col(i).maxCoeff(); s << "," << scores_geodesic_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_chordal_metric s << "," << scores_chordal_metric.col(i).minCoeff(); s << "," << scores_chordal_metric.col(i).maxCoeff(); s << "," << scores_chordal_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_fubini_study_metric s << "," << scores_fubini_study_metric.col(i).minCoeff(); s << "," << scores_fubini_study_metric.col(i).maxCoeff(); s << "," << scores_fubini_study_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_chordal_2norm s << "," << scores_chordal_2norm_metric.col(i).minCoeff(); s << "," << scores_chordal_2norm_metric.col(i).maxCoeff(); s << "," << scores_chordal_2norm_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_chordal_fnorm s << "," << scores_chordal_fnorm_metric.col(i).minCoeff(); s << "," << scores_chordal_fnorm_metric.col(i).maxCoeff(); s << "," << scores_chordal_fnorm_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_projection_2norm s << "," << scores_projection_2norm_metric.col(i).minCoeff(); s << "," << scores_projection_2norm_metric.col(i).maxCoeff(); s << "," << scores_projection_2norm_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_max_norm s << "," << scores_max_metric.col(i).minCoeff(); s << "," << scores_max_metric.col(i).maxCoeff(); s << "," << scores_max_metric.col(i).mean(); } for( size_t i = 0; i < grassmannIndexes.size(); ++i ) { // grassmann_mean_norm s << "," << scores_mean_metric.col(i).minCoeff(); s << "," << scores_mean_metric.col(i).maxCoeff(); s << "," << scores_mean_metric.col(i).mean(); } return s.str(); } /// /// @brief output log /// @param[in] basisDeque container of basis /// @param[in] time /// @param[in] n dimension of basis /// @param[in] num_threads number threads /// @param[in] verbose ( 0: not, 1: light, 2: medium, 3: heave ) /// std::string outputSimilarityOfBasis( std::deque<MatrixXi> &basisDeque, double time, int n, int numThreads=1, int verbose=0 ) { std::deque<MatrixXi*> _basisDeque; for( int i = basisDeque.size()-1; i >= 0; --i ) { _basisDeque.push_back(&(basisDeque.at(i))); } return outputSimilarityOfBasis(_basisDeque, time, n, numThreads, verbose); } } // BasisSimilarity #endif // __SIMILARITY_H__
GB_binop__min_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__min_int64 // A.*B function (eWiseMult): GB_AemultB__min_int64 // A*D function (colscale): GB_AxD__min_int64 // D*A function (rowscale): GB_DxB__min_int64 // C+=B function (dense accum): GB_Cdense_accumB__min_int64 // C+=b function (dense accum): GB_Cdense_accumb__min_int64 // C+=A+B function (dense ewise3): GB_Cdense_ewise3_accum__min_int64 // C=A+B function (dense ewise3): GB_Cdense_ewise3_noaccum__min_int64 // C=scalar+B GB_bind1st__min_int64 // C=scalar+B' GB_bind1st_tran__min_int64 // C=A+scalar GB_bind2nd__min_int64 // C=A'+scalar GB_bind2nd_tran__min_int64 // C type: int64_t // A type: int64_t // B,b type: int64_t // BinaryOp: cij = GB_IMIN (aij, bij) #define GB_ATYPE \ int64_t #define GB_BTYPE \ int64_t #define GB_CTYPE \ int64_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) \ 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) \ int64_t t // cij = Ax [pA] #define GB_COPY_A_TO_C(cij,Ax,pA) \ cij = Ax [pA] // cij = Bx [pB] #define GB_COPY_B_TO_C(cij,Bx,pB) \ cij = Bx [pB] #define GB_CX(p) Cx [p] // binary operator #define GB_BINOP(z, x, y) \ z = GB_IMIN (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_MIN || GxB_NO_INT64 || GxB_NO_MIN_INT64) //------------------------------------------------------------------------------ // C += A+B, all 3 matrices dense //------------------------------------------------------------------------------ // The op must be MIN, MAX, PLUS, MINUS, RMINUS, TIMES, DIV, or RDIV. void GB_Cdense_ewise3_accum__min_int64 ( 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__min_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__min_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 { #include "GB_dense_subassign_23_template.c" } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C += b, accumulate a scalar into a dense matrix //------------------------------------------------------------------------------ GrB_Info GB_Cdense_accumb__min_int64 ( 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 int64_t int64_t bwork = (*((int64_t *) p_bwork)) ; #include "GB_dense_subassign_22_template.c" return (GrB_SUCCESS) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // C = A*D, column scale with diagonal D matrix //------------------------------------------------------------------------------ GrB_Info GB_AxD__min_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 int64_t *GB_RESTRICT Cx = (int64_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__min_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 int64_t *GB_RESTRICT Cx = (int64_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__min_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__min_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__min_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 int64_t *Cx = (int64_t *) 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] = GB_IMIN (x, bij) ; } return (GrB_SUCCESS) ; #endif } //------------------------------------------------------------------------------ // Cx = op (Ax,y): apply a binary operator to a matrix with scalar bind2nd //------------------------------------------------------------------------------ GrB_Info GB_bind2nd__min_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 ; int64_t *Cx = (int64_t *) 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] = GB_IMIN (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] = GB_IMIN (x, aij) ; \ } GrB_Info GB_bind1st_tran__min_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] = GB_IMIN (aij, y) ; \ } GrB_Info GB_bind2nd_tran__min_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
6a0cba_so4.c
#define _POSIX_C_SOURCE 200809L #include "stdlib.h" #include "math.h" #include "sys/time.h" #include "xmmintrin.h" #include "pmmintrin.h" #include <stdio.h> #include "omp.h" #define min(a, b) (((a) < (b)) ? (a) : (b)) #define max(a, b) (((a) > (b)) ? (a) : (b)) struct dataobj { void *restrict data; int *size; int *npsize; int *dsize; int *hsize; int *hofs; int *oofs; }; struct profiler { double section0; }; int Kernel(struct dataobj *restrict block_sizes_vec, const float h_x, const float h_y, const float h_z, struct dataobj *restrict nnz_sp_source_mask_vec, struct dataobj *restrict save_src_fxx_vec, struct dataobj *restrict save_src_fyy_vec, struct dataobj *restrict save_src_fzz_vec, struct dataobj *restrict source_id_vec, struct dataobj *restrict source_mask_vec, struct dataobj *restrict sp_source_mask_vec, struct dataobj *restrict tau_sol_xx_vec, struct dataobj *restrict tau_sol_xy_vec, struct dataobj *restrict tau_sol_xz_vec, struct dataobj *restrict tau_sol_yy_vec, struct dataobj *restrict tau_sol_yz_vec, struct dataobj *restrict tau_sol_zz_vec, struct dataobj *restrict v_sol_x_vec, struct dataobj *restrict v_sol_y_vec, struct dataobj *restrict v_sol_z_vec, const int sp_zi_m, const int time_M, const int time_m, struct profiler *timers, const int x_M, const int x_m, const int y_M, const int y_m, const int z_M, const int z_m, const int nthreads, const int nthreads_nonaffine) { int(*restrict block_sizes) __attribute__((aligned(64))) = (int(*))block_sizes_vec->data; int(*restrict nnz_sp_source_mask)[nnz_sp_source_mask_vec->size[1]] __attribute__((aligned(64))) = (int(*)[nnz_sp_source_mask_vec->size[1]])nnz_sp_source_mask_vec->data; float(*restrict save_src_fxx)[save_src_fxx_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fxx_vec->size[1]])save_src_fxx_vec->data; float(*restrict save_src_fyy)[save_src_fyy_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fyy_vec->size[1]])save_src_fyy_vec->data; float(*restrict save_src_fzz)[save_src_fzz_vec->size[1]] __attribute__((aligned(64))) = (float(*)[save_src_fzz_vec->size[1]])save_src_fzz_vec->data; int(*restrict source_id)[source_id_vec->size[1]][source_id_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_id_vec->size[1]][source_id_vec->size[2]])source_id_vec->data; int(*restrict source_mask)[source_mask_vec->size[1]][source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[source_mask_vec->size[1]][source_mask_vec->size[2]])source_mask_vec->data; int(*restrict sp_source_mask)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]] __attribute__((aligned(64))) = (int(*)[sp_source_mask_vec->size[1]][sp_source_mask_vec->size[2]])sp_source_mask_vec->data; float(*restrict tau_sol_xx)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xx_vec->size[1]][tau_sol_xx_vec->size[2]][tau_sol_xx_vec->size[3]])tau_sol_xx_vec->data; float(*restrict tau_sol_xy)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xy_vec->size[1]][tau_sol_xy_vec->size[2]][tau_sol_xy_vec->size[3]])tau_sol_xy_vec->data; float(*restrict tau_sol_xz)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_xz_vec->size[1]][tau_sol_xz_vec->size[2]][tau_sol_xz_vec->size[3]])tau_sol_xz_vec->data; float(*restrict tau_sol_yy)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yy_vec->size[1]][tau_sol_yy_vec->size[2]][tau_sol_yy_vec->size[3]])tau_sol_yy_vec->data; float(*restrict tau_sol_yz)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_yz_vec->size[1]][tau_sol_yz_vec->size[2]][tau_sol_yz_vec->size[3]])tau_sol_yz_vec->data; float(*restrict tau_sol_zz)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]] __attribute__((aligned(64))) = (float(*)[tau_sol_zz_vec->size[1]][tau_sol_zz_vec->size[2]][tau_sol_zz_vec->size[3]])tau_sol_zz_vec->data; float(*restrict v_sol_x)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_x_vec->size[1]][v_sol_x_vec->size[2]][v_sol_x_vec->size[3]])v_sol_x_vec->data; float(*restrict v_sol_y)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_y_vec->size[1]][v_sol_y_vec->size[2]][v_sol_y_vec->size[3]])v_sol_y_vec->data; float(*restrict v_sol_z)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]] __attribute__((aligned(64))) = (float(*)[v_sol_z_vec->size[1]][v_sol_z_vec->size[2]][v_sol_z_vec->size[3]])v_sol_z_vec->data; /* Flush denormal numbers to zero in hardware */ _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON); _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON); int xb_size = block_sizes[0]; int y0_blk0_size = block_sizes[3]; int x0_blk0_size = block_sizes[2]; int yb_size = block_sizes[1]; int sf = 4; int t_blk_size = 2 * sf * (time_M - time_m); /* int xb_size = 64; int yb_size = 64; x0_blk0_size = 8; y0_blk0_size = 8; */ printf(" Tiles: %d, %d ::: Blocks %d, %d \n", xb_size , yb_size , x0_blk0_size, y0_blk0_size); struct timeval start_section0, end_section0; gettimeofday(&start_section0, NULL); for (int t_blk = time_m; t_blk < sf * (time_M - time_m); t_blk += sf * t_blk_size) // for each t block { for (int xb = x_m; xb <= (x_M + sf * (time_M - time_m)); xb += xb_size) { //printf(" Change of outer xblock %d \n", xb); for (int yb = y_m; yb <= (y_M + sf * (time_M - time_m)); yb += yb_size) { for (int time = t_blk, t0 = (time) % (2), t1 = (time + 1) % (2); time <= 1 + min(t_blk + t_blk_size - 1, sf * (time_M - time_m)); time += sf, t0 = (((time / sf) % (time_M - time_m + 1)) + 1) % (2), t1 = (((time / sf) % (time_M - time_m + 1))) % (2)) { int tw = ((time / sf) % (time_M - time_m + 1)); #pragma omp parallel num_threads(nthreads) { //printf(" Change of time block : %d \n", tw); #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb); x0_blk0 <= min((x_M + time), (xb + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb); y0_blk0 <= min((y_M + time), (yb + yb_size)); y0_blk0 += y0_blk0_size) { //printf(" Change of inner xblock %d \n", x0_blk0); for (int x = x0_blk0; x <= min(min((x_M + time), (xb + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating velocity x %d \n", x - time + 4); //printf(" \n PDE update : \n"); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 64) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating velocity x %d z: %d \n", x - time + 4, z + 4); float r26 = 1.0 / h_z; float r25 = 1.0 / h_y; float r24 = 1.0 / h_x; v_sol_x[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xx[t0][x - time + 3][y - time + 4][z + 4] - tau_sol_xx[t0][x - time + 6][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_xx[t0][x - time + 5][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_xy[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_xz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_x[t0][x - time + 4][y - time + 4][z + 4]; v_sol_y[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xy[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xy[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xy[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yy[t0][x - time + 4][y - time + 3][z + 4] - tau_sol_yy[t0][x - time + 4][y - time + 6][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_yy[t0][x - time + 4][y - time + 5][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 4][z + 2] - tau_sol_yz[t0][x - time + 4][y - time + 4][z + 5]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 4][z + 3] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + v_sol_y[t0][x - time + 4][y - time + 4][z + 4]; v_sol_z[t1][x - time + 4][y - time + 4][z + 4] = r24 * (2.7280354210856e-2F * (tau_sol_xz[t0][x - time + 2][y - time + 4][z + 4] - tau_sol_xz[t0][x - time + 5][y - time + 4][z + 4]) + 7.36569563735987e-1F * (-tau_sol_xz[t0][x - time + 3][y - time + 4][z + 4] + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4])) + r25 * (2.7280354210856e-2F * (tau_sol_yz[t0][x - time + 4][y - time + 2][z + 4] - tau_sol_yz[t0][x - time + 4][y - time + 5][z + 4]) + 7.36569563735987e-1F * (-tau_sol_yz[t0][x - time + 4][y - time + 3][z + 4] + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4])) + r26 * (2.7280354210856e-2F * (tau_sol_zz[t0][x - time + 4][y - time + 4][z + 3] - tau_sol_zz[t0][x - time + 4][y - time + 4][z + 6]) + 7.36569563735987e-1F * (-tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4] + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 5])) + v_sol_z[t0][x - time + 4][y - time + 4][z + 4]; } } } } } } #pragma omp parallel num_threads(nthreads) { #pragma omp for collapse(2) schedule(dynamic, 1) for (int x0_blk0 = max((x_m + time), xb - 2); x0_blk0 <= +min((x_M + time), (xb - 2 + xb_size)); x0_blk0 += x0_blk0_size) { for (int y0_blk0 = max((y_m + time), yb - 2); y0_blk0 <= +min((y_M + time), (yb - 2 + yb_size)); y0_blk0 += y0_blk0_size) { for (int x = x0_blk0; x <= min(min((x_M + time), (xb - 2 + xb_size - 1)), (x0_blk0 + x0_blk0_size - 1)); x++) { for (int y = y0_blk0; y <= min(min((y_M + time), (yb - 2 + yb_size - 1)), (y0_blk0 + y0_blk0_size - 1)); y++) { //printf(" Updating stress x %d \n", x - time + 4); #pragma omp simd aligned(tau_sol_xx, tau_sol_xz, tau_sol_zz, v_sol_x, v_sol_z : 64) for (int z = z_m; z <= z_M; z += 1) { //printf(" Updating x %d z: %d \n", x - time + 4, z + 4); float r41 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r40 = -v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r39 = -v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r38 = v_sol_y[t1][x - time + 4][y - time + 2][z + 4] - v_sol_y[t1][x - time + 4][y - time + 5][z + 4]; float r37 = -v_sol_y[t1][x - time + 4][y - time + 3][z + 4] + v_sol_y[t1][x - time + 4][y - time + 4][z + 4]; float r36 = v_sol_z[t1][x - time + 4][y - time + 4][z + 2] - v_sol_z[t1][x - time + 4][y - time + 4][z + 5]; float r35 = -v_sol_z[t1][x - time + 4][y - time + 4][z + 3] + v_sol_z[t1][x - time + 4][y - time + 4][z + 4]; float r34 = v_sol_x[t1][x - time + 2][y - time + 4][z + 4] - v_sol_x[t1][x - time + 5][y - time + 4][z + 4]; float r33 = -v_sol_x[t1][x - time + 3][y - time + 4][z + 4] + v_sol_x[t1][x - time + 4][y - time + 4][z + 4]; float r32 = 1.0 / h_y; float r31 = 1.0 / h_z; float r30 = 1.0 / h_x; float r29 = r30 * (4.7729707730092F * r33 + 1.76776695286347e-1F * r34); float r28 = r31 * (4.7729707730092F * r35 + 1.76776695286347e-1F * r36); float r27 = r32 * (4.7729707730092F * r37 + 1.76776695286347e-1F * r38); tau_sol_xx[t1][x - time + 4][y - time + 4][z + 4] = r27 + r28 + r30 * (9.54594154601839F * r33 + 3.53553390572694e-1F * r34) + tau_sol_xx[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xy[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 3][y - time + 4][z + 4] - v_sol_y[t1][x - time + 6][y - time + 4][z + 4])) + r32 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 3][z + 4] - v_sol_x[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_xy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_xz[t1][x - time + 4][y - time + 4][z + 4] = r30 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 5][y - time + 4][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 3][y - time + 4][z + 4] - v_sol_z[t1][x - time + 6][y - time + 4][z + 4])) + r31 * (2.3864853865046F * (r39 + v_sol_x[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_x[t1][x - time + 4][y - time + 4][z + 3] - v_sol_x[t1][x - time + 4][y - time + 4][z + 6])) + tau_sol_xz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yy[t1][x - time + 4][y - time + 4][z + 4] = r28 + r29 + r32 * (9.54594154601839F * r37 + 3.53553390572694e-1F * r38) + tau_sol_yy[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_yz[t1][x - time + 4][y - time + 4][z + 4] = r31 * (2.3864853865046F * (r40 + v_sol_y[t1][x - time + 4][y - time + 4][z + 5]) + 8.83883476431735e-2F * (v_sol_y[t1][x - time + 4][y - time + 4][z + 3] - v_sol_y[t1][x - time + 4][y - time + 4][z + 6])) + r32 * (2.3864853865046F * (r41 + v_sol_z[t1][x - time + 4][y - time + 5][z + 4]) + 8.83883476431735e-2F * (v_sol_z[t1][x - time + 4][y - time + 3][z + 4] - v_sol_z[t1][x - time + 4][y - time + 6][z + 4])) + tau_sol_yz[t0][x - time + 4][y - time + 4][z + 4]; tau_sol_zz[t1][x - time + 4][y - time + 4][z + 4] = r27 + r29 + r31 * (9.54594154601839F * r35 + 3.53553390572694e-1F * r36) + tau_sol_zz[t0][x - time + 4][y - time + 4][z + 4]; } for (int sp_zi = sp_zi_m; sp_zi <= nnz_sp_source_mask[x - time][y - time] - 1; sp_zi += 1) { //printf("\n Source_injection at : "); int zind = sp_source_mask[x - time][y - time][sp_zi]; float r0 = save_src_fxx[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r1 = save_src_fyy[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; float r2 = save_src_fzz[((time / sf) % (time_M - time_m + 1))][source_id[x - time][y - time][zind]] * source_mask[x - time][y - time][zind]; tau_sol_xx[t1][x - time + 4][y - time + 4][zind + 4] += r0; tau_sol_yy[t1][x - time + 4][y - time + 4][zind + 4] += r1; tau_sol_zz[t1][x - time + 4][y - time + 4][zind + 4] += r2; //printf(" Time %d , at : %d, %d \n", tw, x - time + 4, zind + 4); } } } } } } } } } } /* End section0 */ gettimeofday(&end_section0, NULL); timers->section0 += (double)(end_section0.tv_sec - start_section0.tv_sec) + (double)(end_section0.tv_usec - start_section0.tv_usec) / 1000000; return 0; }
elemwise_binary_op.h
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /*! * Copyright (c) 2016 by Contributors * \file elemwise_binary_op.h * \brief Function definition of elementwise binary operators */ #ifndef MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #define MXNET_OPERATOR_TENSOR_ELEMWISE_BINARY_OP_H_ #include <mxnet/operator_util.h> #include <mxnet/op_attr_types.h> #include <vector> #include <string> #include <utility> #include <typeinfo> #include <algorithm> #include "../mxnet_op.h" #include "../mshadow_op.h" #include "../../engine/openmp.h" #include "elemwise_unary_op.h" #include "../../common/utils.h" #include "./init_op.h" #include "../operator_common.h" namespace mxnet { namespace op { /*! Gather binary operator functions into ElemwiseBinaryOp class */ class ElemwiseBinaryOp : public OpBase { public: /*! \brief For sparse, assume missing rvalue is 0 */ template <typename OP, int Req> struct MissingRValueOp { typedef OP Operation; template <typename DType> MSHADOW_XINLINE static void Map(int i, DType* out, const DType* lhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(lhs[i], DType(0))); } }; /*! \brief For sparse, assume missing lvalue is 0 */ template <typename OP, int Req> struct MissingLValueOp { typedef OP Operation; template <typename DType> MSHADOW_XINLINE static void Map(int i, DType* out, const DType* rhs) { KERNEL_ASSIGN(out[i], Req, OP::Map(DType(0), rhs[i])); } }; private: /*! * \brief CSR operation requires temp space */ enum ResourceRequestType { kTempSpace }; /*! * \brief Fill contiguous dense output rows with value computed from 0 lhs and 0 rhs input * CPU-Only version */ template <typename DType, typename OP, typename xpu> static inline size_t FillDense(mshadow::Stream<xpu>* s, const size_t idx_l, const size_t idx_r, const OpReqType req, mshadow::Tensor<xpu, 2, DType>* out, const size_t iter_out) { const int index_out_min = static_cast<int>(std::min(idx_l, idx_r)); if (static_cast<size_t>(index_out_min) > iter_out) { const DType zero_input_val = OP::Map(DType(0), DType(0)); #pragma omp parallel for num_threads(engine::OpenMP::Get()->GetRecommendedOMPThreadCount()) for (int i = static_cast<int>(iter_out); i < index_out_min; ++i) { Fill<false>(s, (*out)[i], req, zero_input_val); } } return static_cast<size_t>(index_out_min); // MSVC wants OMP loops to always use 'int' } static inline bool IsSameArray(const NDArray& a1, const NDArray& a2) { return a1.var() == a2.var(); } public: /*! \brief Minimum of three */ static MSHADOW_XINLINE size_t minthree(const size_t a, const size_t b, const size_t c) { return a < b ? (a < c ? a : c) : (b < c ? b : c); } private: template <typename LOP, typename ROP> static void BackwardUseNone_(const nnvm::NodeAttrs& attrs, mshadow::Stream<cpu>* s, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { using namespace mxnet_op; const 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(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch( s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template <typename xpu, typename OP> static void Compute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; mshadow::Stream<xpu>* s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); if (outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "Operator " << attrs.op->name << " does not support boolean type"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch( s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template <typename xpu, typename OP> static void MixedUnaryBackwardUseInCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu>* s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); if (mxnet::common::is_int(outputs[0].type_flag_) || outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "gradient computation of operator " << attrs.op->name << " for " << mshadow::dtype_string(outputs[0].type_flag_) << " type is not supported"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch( s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template <typename xpu, typename OP> static void MixedUnaryBackwardUseInOutCompute(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu>* s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 3U); CHECK_EQ(outputs.size(), 1U); if (mxnet::common::is_int(outputs[0].type_flag_) || outputs[0].type_flag_ == mshadow::kBool) { LOG(FATAL) << "gradient computation of operator " << attrs.op->name << " for " << mshadow::dtype_string(outputs[0].type_flag_) << " type is not supported"; } MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_REAL_TYPE_SWITCH(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[2].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch( s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[2].dptr<DType>()); } }); }); } template <typename xpu, typename OP> static void ComputeWithBool(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu>* s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_WITH_BOOL(outputs[0].type_flag_, DType, { const size_t size = (minthree(outputs[0].Size(), inputs[0].Size(), inputs[1].Size()) + DataType<DType>::kLanes - 1) / DataType<DType>::kLanes; if (size != 0) { Kernel<mxnet_op::op_with_req<OP, Req>, xpu>::Launch( s, size, outputs[0].dptr<DType>(), inputs[0].dptr<DType>(), inputs[1].dptr<DType>()); } }); }); } template <typename xpu, typename OP> static void ComputeLogic(const nnvm::NodeAttrs& attrs, const OpContext& ctx, const std::vector<TBlob>& inputs, const std::vector<OpReqType>& req, const std::vector<TBlob>& outputs) { using namespace mxnet_op; if (req[0] == kNullOp) return; Stream<xpu>* s = ctx.get_stream<xpu>(); CHECK_EQ(inputs.size(), 2U); CHECK_EQ(outputs.size(), 1U); MXNET_ASSIGN_REQ_SWITCH(req[0], Req, { MSHADOW_TYPE_SWITCH_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_
kt_thread.c
#include "kt.h" #include "kt_thread.h" #include "kt_hmap.h" /* Initial buffer size for messages. Will resize when necessary. */ #ifndef MSG_DEFAULT_BUFFER #define MSG_DEFAULT_BUFFER 1000 #endif /****************************************************************************** * THREAD FUNCTIONS *****************************************************************************/ triangle_t * get_incoming_triangle_bucket( thread_ws * * ws, int const bucket_id, int32_t * num_triangles) { int const tid = omp_get_thread_num(); thread_ws * const my_ws = ws[tid]; int32_t ntriangles = 0; /* Count the number of triangles in bucket (across all threads) */ for(int t=0; t < my_ws->num_threads; ++t) { ntriangles += ws[t]->buckets[bucket_id].num_tri_msgs; } /* resize buffer if necessary */ if(my_ws->len_tri_buffer < ntriangles) { my_ws->len_tri_buffer = ntriangles; gk_free((void **) &(my_ws->tri_buffer), LTERM); my_ws->tri_buffer = gk_malloc(ntriangles * sizeof(*my_ws->tri_buffer), "tri_buffer"); } triangle_t * const restrict buffer = my_ws->tri_buffer; /* go over each thread's bucket */ int32_t buffer_ptr = 0; for(int t=0; t < my_ws->num_threads; ++t) { /* copy incoming bucket */ int32_t const num_msgs = ws[t]->buckets[bucket_id].num_tri_msgs; if(num_msgs > 0) { triangle_t const * const msgs = ws[t]->buckets[bucket_id].tri_msgs; for(int32_t m=0; m < num_msgs; ++m) { buffer[buffer_ptr++] = msgs[m]; } /* now empty buffer */ ws[t]->buckets[bucket_id].num_tri_msgs = 0; } } *num_triangles = ntriangles; return buffer; } pair_t * get_incoming_pair_bucket( thread_ws * * ws, int const bucket_id, int32_t * num_pairs) { int const tid = omp_get_thread_num(); thread_ws * const my_ws = ws[tid]; int32_t npairs = 0; /* Count the number of pairs in bucket (across all threads) */ for(int t=0; t < my_ws->num_threads; ++t) { npairs += ws[t]->buckets[bucket_id].num_pair_msgs; } /* resize buffer if necessary */ if(my_ws->len_pair_buffer < npairs) { my_ws->len_pair_buffer = npairs; gk_free((void **) &(my_ws->pair_buffer), LTERM); my_ws->pair_buffer = gk_malloc(npairs * sizeof(*my_ws->pair_buffer), "pair_buffer"); } pair_t * const restrict buffer = my_ws->pair_buffer; /* go over each thread's bucket */ int32_t buffer_ptr = 0; for(int t=0; t < my_ws->num_threads; ++t) { /* copy incoming bucket */ int32_t const num_msgs = ws[t]->buckets[bucket_id].num_pair_msgs; if(num_msgs > 0) { pair_t const * const msgs = ws[t]->buckets[bucket_id].pair_msgs; for(int32_t m=0; m < num_msgs; ++m) { buffer[buffer_ptr++] = msgs[m]; } /* now empty buffer */ ws[t]->buckets[bucket_id].num_pair_msgs = 0; } } *num_pairs = npairs; return buffer; } int64_t * get_incoming_edge_bucket( thread_ws * * ws, int const bucket_id, int64_t * num_edges, int const which) { assert(which >= 0); assert(which < 2); int const tid = omp_get_thread_num(); thread_ws * const my_ws = ws[tid]; int64_t nedges = 0; /* Count the number of edges in bucket (across all threads) */ for(int t=0; t < my_ws->num_threads; ++t) { if(which == 0) { nedges += ws[t]->buckets[bucket_id].num_edge_msgs; } else { nedges += ws[t]->buckets[bucket_id].num_edge_msgs2; } } /* resize buffer if necessary */ if(which == 0) { if(my_ws->len_edge_buffer < nedges) { my_ws->len_edge_buffer = nedges; gk_free((void **) &(my_ws->edge_buffer), LTERM); my_ws->edge_buffer = gk_malloc(nedges * sizeof(*my_ws->edge_buffer), "edge_buffer"); } } else { if(my_ws->len_edge_buffer2 < nedges) { my_ws->len_edge_buffer2 = nedges; gk_free((void **) &(my_ws->edge_buffer2), LTERM); my_ws->edge_buffer2 = gk_malloc(nedges * sizeof(*my_ws->edge_buffer2), "edge_buffer2"); } } int64_t * const restrict buffer = (which == 0) ? \ my_ws->edge_buffer : my_ws->edge_buffer2; if(which == 0) { /* go over each thread's bucket */ int32_t buffer_ptr = 0; for(int t=0; t < my_ws->num_threads; ++t) { /* copy incoming bucket */ int64_t const num_msgs = ws[t]->buckets[bucket_id].num_edge_msgs; int64_t const * const msgs = ws[t]->buckets[bucket_id].edge_msgs; for(int64_t m=0; m < num_msgs; ++m) { buffer[buffer_ptr++] = msgs[m]; } /* now empty buffer */ ws[t]->buckets[bucket_id].num_edge_msgs = 0; } } else { /* go over each thread's bucket */ int32_t buffer_ptr = 0; for(int t=0; t < my_ws->num_threads; ++t) { /* copy incoming bucket */ int64_t const num_msgs = ws[t]->buckets[bucket_id].num_edge_msgs2; int64_t const * const msgs = ws[t]->buckets[bucket_id].edge_msgs2; for(int64_t m=0; m < num_msgs; ++m) { buffer[buffer_ptr++] = msgs[m]; } /* now empty buffer */ ws[t]->buckets[bucket_id].num_edge_msgs2 = 0; } } *num_edges = nedges; return buffer; } void send_thread_tri_msg( triangle_t const * const triangle, int const bucket_dest, thread_ws * ws) { assert(bucket_dest >= 0); assert(bucket_dest < ws->num_buckets); assert(triangle->u < triangle->v); assert(triangle->u < triangle->w); assert(triangle->v < triangle->w); assert(triangle->u >= 0); assert(triangle->v >= 0); assert(triangle->w >= 0); thread_msg * const restrict dest_msgs = &(ws->buckets[bucket_dest]); /* resize if necessary */ if(dest_msgs->num_tri_msgs == dest_msgs->max_tri_msgs) { dest_msgs->max_tri_msgs *= 2; triangle_t * big = gk_malloc(dest_msgs->max_tri_msgs * sizeof(*big), "big"); for(int32_t i=0; i < dest_msgs->num_tri_msgs; ++i) { big[i] = dest_msgs->tri_msgs[i]; } gk_free((void **) &(dest_msgs->tri_msgs), LTERM); dest_msgs->tri_msgs = big; } /* append triangle to message queue */ int32_t const idx = dest_msgs->num_tri_msgs; dest_msgs->tri_msgs[idx] = *triangle; ++(dest_msgs->num_tri_msgs); #if VERBOSE printf("TRIANGLE thread %d -> %d (%d %d %d) = %zd %zd %zd\n", omp_get_thread_num(), bucket_dest, 1+triangle->u, 1+triangle->v, 1+triangle->w, triangle->uv, triangle->vw); #endif } void send_thread_pair_msg( triangle_t const * const triangle, int const bucket_dest, thread_ws * ws) { assert(triangle->v > 0); assert(triangle->w > 0); assert(triangle->v < triangle->w); pair_t tmp; tmp.v = triangle->v; tmp.w = triangle->w; tmp.vw = triangle->vw; send_thread_pair_msg_explicit(&tmp, bucket_dest, ws); } void send_thread_pair_msg_explicit( pair_t const * const pair, int const bucket_dest, thread_ws * ws) { assert(bucket_dest >= 0); assert(bucket_dest < ws->num_buckets); thread_msg * const restrict dest_msgs = &(ws->buckets[bucket_dest]); /* resize if necessary */ if(dest_msgs->num_pair_msgs == dest_msgs->max_pair_msgs) { dest_msgs->max_pair_msgs *= 2; pair_t * big = gk_malloc(dest_msgs->max_pair_msgs * sizeof(*big), "big"); for(int32_t i=0; i < dest_msgs->num_pair_msgs; ++i) { big[i] = dest_msgs->pair_msgs[i]; } gk_free((void **) &(dest_msgs->pair_msgs), LTERM); dest_msgs->pair_msgs = big; } /* append pair to message queue */ int32_t const idx = dest_msgs->num_pair_msgs; dest_msgs->pair_msgs[idx] = *pair; ++(dest_msgs->num_pair_msgs); #if VERBOSE printf("PAIR thread %d -> %d (%d %d)\n", omp_get_thread_num(), bucket_dest, pair->v, pair->w); #endif } void send_thread_edge_msg( int64_t edge_id, int const bucket_dest, thread_ws * ws, int const which) { assert(bucket_dest >= 0); assert(bucket_dest < ws->num_buckets); thread_msg * const restrict dest_msgs = &(ws->buckets[bucket_dest]); /* resize if necessary */ if(which == 0) { if(dest_msgs->num_edge_msgs == dest_msgs->max_edge_msgs) { dest_msgs->max_edge_msgs *= 2; int64_t * big = gk_malloc(dest_msgs->max_edge_msgs * sizeof(*big), "big"); for(int32_t i=0; i < dest_msgs->num_edge_msgs; ++i) { big[i] = dest_msgs->edge_msgs[i]; } gk_free((void **) &(dest_msgs->edge_msgs), LTERM); dest_msgs->edge_msgs = big; } /* append pair to message queue */ int32_t const idx = dest_msgs->num_edge_msgs; dest_msgs->edge_msgs[idx] = edge_id; ++(dest_msgs->num_edge_msgs); } else { if(dest_msgs->num_edge_msgs2 == dest_msgs->max_edge_msgs2) { dest_msgs->max_edge_msgs2 *= 2; int64_t * big = gk_malloc(dest_msgs->max_edge_msgs2 * sizeof(*big), "big"); for(int32_t i=0; i < dest_msgs->num_edge_msgs2; ++i) { big[i] = dest_msgs->edge_msgs2[i]; } gk_free((void **) &(dest_msgs->edge_msgs2), LTERM); dest_msgs->edge_msgs2 = big; } /* append pair to message queue */ int32_t const idx = dest_msgs->num_edge_msgs2; dest_msgs->edge_msgs2[idx] = edge_id; ++(dest_msgs->num_edge_msgs2); } #if VERBOSE printf("EDGE thread-%d -> bucket-%d edge-%zd \n", omp_get_thread_num(), bucket_dest, edge_id); #endif } thread_ws * * alloc_thread_ws( gk_graph_t const * const lgraph, gk_graph_t const * const ugraph) { int const nthreads = omp_get_max_threads(); int64_t const nedges = ugraph->xadj[ugraph->nvtxs]; ssize_t const max_degree = gk_max(graph_max_degree(lgraph), graph_max_degree(ugraph)); int32_t const max_support = max_elem(ugraph->iadjwgt, nedges); printf("max_support: %d\n\n", max_support); thread_ws * * ws = gk_malloc(nthreads * sizeof(*ws), "ws"); /* each thread has outgoing buffers for all threads */ #pragma omp parallel { thread_ws * my_ws = gk_malloc(sizeof(*my_ws), "ws[tid]"); my_ws->num_threads = nthreads; my_ws->num_buckets = nthreads * KT_BUCKETS_PER_THREAD; my_ws->buckets = gk_malloc(my_ws->num_buckets * sizeof(*(my_ws->buckets)), "messages"); /* allocate message to each thread */ for(int b=0; b < my_ws->num_buckets; ++b) { my_ws->buckets[b].max_tri_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_tri_msgs = 0; my_ws->buckets[b].tri_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(triangle_t), "triangles"); my_ws->buckets[b].max_pair_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_pair_msgs = 0; my_ws->buckets[b].pair_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(pair_t), "pairs"); my_ws->buckets[b].max_edge_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_edge_msgs = 0; my_ws->buckets[b].edge_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(int64_t), "edges"); } /* buffer for finding triangles */ my_ws->w_ids = gk_malloc(max_support * sizeof(*my_ws->w_ids), "w_ids"); my_ws->uw_idxs = gk_malloc(max_support * sizeof(*my_ws->uw_idxs), "uw_idxs"); my_ws->vw_idxs = gk_malloc(max_support * sizeof(*my_ws->vw_idxs), "vw_idxs"); #if USE_HMAP my_ws->hmap = alloc_hmap(max_degree); #endif /* initially empty buffers */ my_ws->tri_buffer = NULL; my_ws->pair_buffer = NULL; my_ws->edge_buffer = NULL; my_ws->edge_buffer2 = NULL; my_ws->len_tri_buffer = 0; my_ws->len_pair_buffer = 0; my_ws->len_edge_buffer = 0; my_ws->len_edge_buffer = 0; my_ws->len_edge_buffer2 = 0; /* store my workspace */ ws[omp_get_thread_num()] = my_ws; } /* end omp parallel */ return ws; } thread_ws * * alloc_thread_ws_big( gk_graph_t const * const graph) { int const nthreads = omp_get_max_threads(); int64_t const nedges = graph->xadj[graph->nvtxs]; ssize_t const max_degree = graph_max_degree(graph); thread_ws * * ws = gk_malloc(nthreads * sizeof(*ws), "ws"); /* each thread has outgoing buffers for all threads */ #pragma omp parallel { thread_ws * my_ws = gk_malloc(sizeof(*my_ws), "ws[tid]"); my_ws->num_threads = nthreads; my_ws->num_buckets = nthreads * KT_BUCKETS_PER_THREAD; my_ws->buckets = gk_malloc(my_ws->num_buckets * sizeof(*(my_ws->buckets)), "messages"); /* allocate message to each thread */ for(int b=0; b < my_ws->num_buckets; ++b) { my_ws->buckets[b].max_tri_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_tri_msgs = 0; my_ws->buckets[b].tri_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(triangle_t), "triangles"); my_ws->buckets[b].max_pair_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_pair_msgs = 0; my_ws->buckets[b].pair_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(pair_t), "pairs"); my_ws->buckets[b].max_epair_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_epair_msgs = 0; my_ws->buckets[b].epair_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(pair_t), "pairs"); my_ws->buckets[b].max_edge_msgs = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_edge_msgs = 0; my_ws->buckets[b].edge_msgs = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(int64_t), "edges"); my_ws->buckets[b].max_edge_msgs2 = MSG_DEFAULT_BUFFER; my_ws->buckets[b].num_edge_msgs2 = 0; my_ws->buckets[b].edge_msgs2 = gk_malloc(MSG_DEFAULT_BUFFER * sizeof(int64_t), "edges2"); } /* buffer for finding triangles */ my_ws->w_ids = NULL; my_ws->uw_idxs = NULL; my_ws->vw_idxs = NULL; /* initially empty buffers */ my_ws->tri_buffer = NULL; my_ws->pair_buffer = NULL; my_ws->epair_buffer = NULL; my_ws->edge_buffer = NULL; my_ws->edge_buffer2 = NULL; my_ws->len_tri_buffer = 0; my_ws->len_pair_buffer = 0; my_ws->len_epair_buffer = 0; my_ws->len_edge_buffer = 0; my_ws->len_edge_buffer2 = 0; /* store my workspace */ ws[omp_get_thread_num()] = my_ws; } /* end omp parallel */ return ws; } void send_thread_epair_msg( epair_t * const pair, int const bucket_dest, thread_ws * ws) { assert(bucket_dest >= 0); assert(bucket_dest < ws->num_buckets); thread_msg * const restrict dest_msgs = &(ws->buckets[bucket_dest]); /* resize if necessary */ if(dest_msgs->num_epair_msgs == dest_msgs->max_epair_msgs) { dest_msgs->max_epair_msgs *= 2; epair_t * big = gk_malloc(dest_msgs->max_epair_msgs * sizeof(*big), "big"); for(int32_t i=0; i < dest_msgs->num_epair_msgs; ++i) { big[i] = dest_msgs->epair_msgs[i]; } gk_free((void **) &(dest_msgs->epair_msgs), LTERM); dest_msgs->epair_msgs = big; } /* append epair to message queue */ int32_t const idx = dest_msgs->num_epair_msgs; dest_msgs->epair_msgs[idx] = *pair; ++(dest_msgs->num_epair_msgs); #if VERBOSE printf("PAIR thread %d -> %d (%d %d)\n", omp_get_thread_num(), bucket_dest, pair->v, pair->w); #endif } epair_t * get_incoming_epair_bucket( thread_ws * * ws, int const bucket_id, int64_t * num_pairs) { int const tid = omp_get_thread_num(); thread_ws * const my_ws = ws[tid]; int32_t npairs = 0; /* Count the number of pairs in bucket (across all threads) */ for(int t=0; t < my_ws->num_threads; ++t) { npairs += ws[t]->buckets[bucket_id].num_epair_msgs; } /* resize buffer if necessary */ if(my_ws->len_epair_buffer < npairs) { my_ws->len_epair_buffer = npairs; gk_free((void **) &(my_ws->epair_buffer), LTERM); my_ws->epair_buffer = gk_malloc(npairs * sizeof(*my_ws->epair_buffer), "epair_buffer"); } epair_t * const restrict buffer = my_ws->epair_buffer; /* go over each thread's bucket */ int32_t buffer_ptr = 0; for(int t=0; t < my_ws->num_threads; ++t) { /* copy incoming bucket */ int32_t const num_msgs = ws[t]->buckets[bucket_id].num_epair_msgs; if(num_msgs > 0) { epair_t const * const msgs = ws[t]->buckets[bucket_id].epair_msgs; for(int32_t m=0; m < num_msgs; ++m) { buffer[buffer_ptr++] = msgs[m]; } /* now empty buffer */ ws[t]->buckets[bucket_id].num_epair_msgs = 0; } } *num_pairs = npairs; return buffer; } void free_thread_ws( thread_ws * * ws) { #pragma omp parallel { int const tid = omp_get_thread_num(); for(int b=0; b < ws[tid]->num_buckets; ++b) { gk_free((void **) &(ws[tid]->buckets[b].tri_msgs), LTERM); gk_free((void **) &(ws[tid]->buckets[b].pair_msgs), LTERM); gk_free((void **) &(ws[tid]->buckets[b].edge_msgs), LTERM); gk_free((void **) &(ws[tid]->buckets[b].edge_msgs2), LTERM); } #if USE_HMAP free_hmap(ws[tid]->hmap); #endif gk_free((void **) &(ws[tid]->w_ids), LTERM); gk_free((void **) &(ws[tid]->uw_idxs), LTERM); gk_free((void **) &(ws[tid]->vw_idxs), LTERM); gk_free((void **) &(ws[tid]->tri_buffer), LTERM); gk_free((void **) &(ws[tid]->pair_buffer), LTERM); gk_free((void **) &(ws[tid]->edge_buffer), LTERM); gk_free((void **) &(ws[tid]->buckets), LTERM); gk_free((void **) &(ws[tid]), LTERM); } gk_free((void **) &(ws), LTERM); } void thread_time_stats( double const * const restrict thread_times, int const num_threads, int const padding) { double total_thread_time = 0.; double min_time = thread_times[0]; double max_time = thread_times[0]; for(int t=0; t < num_threads; ++t) { double const curr_time = thread_times[t * padding]; total_thread_time += curr_time; min_time = gk_min(curr_time, min_time); max_time = gk_max(curr_time, max_time); } double const avg_time = total_thread_time / num_threads; printf("\tmin: %0.3fs avg: %0.3fs max: %0.3fs imbalance(max/avg): %0.2fx\n", min_time, avg_time, max_time, max_time / avg_time); }
layerramsubset.h
/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2018-2021 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. * *********************************************************************************/ #pragma once #include <modules/base/basemoduledefine.h> #include <inviwo/core/datastructures/image/layer.h> #include <inviwo/core/datastructures/image/layerram.h> #include <inviwo/core/datastructures/image/layerramprecision.h> #include <inviwo/core/util/glm.h> #include <algorithm> namespace inviwo { namespace util { /** * \brief extracts a subregion from a layer and returns it as a new layer * * This function extracts a subregion given by offset and extent from the input layer. * If border clamping is enabled, the output region will be clamped to lie completely within the * source layer. Otherwise (default), the areas outside the source layer will be filled with * zeros. * * @param in input layer * @param offset subregion offset in input layer * @param extent extent (width and height) of subregion * @param clampBorderOutsideImage if true, the output region is clamped to the layer boundaries * * @return std::shared_ptr<LayerRAM> */ IVW_MODULE_BASE_API std::shared_ptr<LayerRAM> layerSubSet(const Layer* in, ivec2 offset, size2_t extent, bool clampBorderOutsideImage = false); /** * \brief extracts a subregion from a layer and converts it into a new layer * * This function extracts a subregion given by offset and extent from the input layer. The values * will be converted to type T using util::glm_convert_normalized. * If border clamping is enabled, the output region will be clamped to lie completely within the * source layer. Otherwise (default), the areas outside the source layer will be filled with * zeros. * * @param in input layer * @param offset subregion offset in input layer * @param extent extent (width and height) of subregion * @param clampBorderOutsideImage if true, the output region is clamped to the layer boundaries * * @return std::shared_ptr<LayerRAMPrecision<T>> */ template <typename T> std::shared_ptr<LayerRAMPrecision<T>> layerSubSet(const Layer* in, ivec2 offset, size2_t extent, bool clampBorderOutsideImage = false); namespace detail { template <typename T> void conversionCopy(const T* src, T* dst, size_t len) { std::copy(src, src + len, dst); } template <typename To, typename From> void conversionCopy(const From* src, To* dst, size_t len) { for (size_t i = 0; i < len; i++) { dst[i] = util::glm_convert_normalized<To, From>(src[i]); } } template <typename T, typename U = T> std::shared_ptr<LayerRAMPrecision<U>> extractLayerSubSet(const LayerRAMPrecision<T>* inLayer, ivec2 offset, size2_t extent, bool clampBorderOutsideImage) { // determine parameters const ivec2 srcDim(inLayer->getDimensions()); // adjust the output dimensions to match the intersection of output and input regions const ivec2 srcOffset(glm::max(ivec2(0), offset)); const ivec2 dstOffset = clampBorderOutsideImage ? ivec2(0) : (glm::max(ivec2(0), -offset)); // clamp copy extent to source layer const ivec2 copyExtent = glm::min(ivec2(extent) - dstOffset, srcDim - srcOffset); const ivec2 dstDim = clampBorderOutsideImage ? copyExtent : ivec2(extent); // allocate space auto newLayer = std::make_shared<LayerRAMPrecision<U>>(dstDim); const auto src = inLayer->getDataTyped(); auto dst = newLayer->getDataTyped(); if (!clampBorderOutsideImage) { // clear entire layer as only parts will be copied std::fill(dst, dst + dstDim.x * dstDim.y, U(0)); } // memcpy each row to form sub layer #ifdef IVW_USE_OPENMP #pragma omp parallel for #endif for (int j = 0; j < copyExtent.y; j++) { size_t srcPos = (j + srcOffset.y) * srcDim.x + srcOffset.x; size_t dstPos = (j + dstOffset.y) * dstDim.x + dstOffset.x; conversionCopy(src + srcPos, dst + dstPos, static_cast<size_t>(copyExtent.x)); } return newLayer; } } // namespace detail } // namespace util template <typename T> std::shared_ptr<LayerRAMPrecision<T>> util::layerSubSet(const Layer* in, ivec2 offset, size2_t extent, bool clampBorderOutsideImage) { return in->getRepresentation<LayerRAM>()->dispatch<std::shared_ptr<LayerRAMPrecision<T>>>( [offset, extent, clampBorderOutsideImage](auto layerpr) { using ValueType = util::PrecisionValueType<decltype(layerpr)>; return util::detail::extractLayerSubSet<ValueType, T>(layerpr, offset, extent, clampBorderOutsideImage); }); } } // namespace inviwo
basis_tri_p1.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 basis_tri_p1.h * @brief Contains a class representing p1 (piecewise linear) basis functions on * a triangular surface mesh. * @note updated documentation */ #ifndef INCLUDE_BESTHEA_BASIS_TRI_P1_H_ #define INCLUDE_BESTHEA_BASIS_TRI_P1_H_ #include "besthea/basis_function.h" #include "besthea/triangular_surface_mesh.h" namespace besthea { namespace bem { class basis_tri_p1; } } /** * Class representing a piecewise linear function on a triangular mesh. */ class besthea::bem::basis_tri_p1 : public besthea::bem::basis_function< besthea::bem::basis_tri_p1 > { public: /** * Constructor. * @param[in] mesh Triangular surface mesh on which the basis functions are * defined. */ basis_tri_p1( const mesh_type & mesh ); /** * Destructor. */ virtual ~basis_tri_p1( ); /** * Returns the number of basis functions supported on a single element. * * This is always 3. */ virtual lo dimension_local( ) const; /** * Returns the number of basis functions on the whole mesh. * * This is the number of all nodes in the underlying triangular surface mesh. */ virtual lo dimension_global( ) const; /** * Returns the global indices of the nodes of the given element. * @param[in] i_elem Element index. * @param[out] indices Global node indices of the element. */ void do_local_to_global( lo i_elem, std::vector< lo > & indices ) const; /** * Returns the global indices of the nodes of the given element. Their order * is modified according to the given parameters (regularized quadrature). * @param[in] i_elem Element index. * @param[in] n_shared_vertices Number of shared vertices in currect elements * (regularized quadrature). * @param[in] rotation Virtual element rotation (regularized quadrature). * @param[in] swap Virtual element inversion (regularized quadrature). * @param[out] indices Global node indices of the element in modified order. */ void do_local_to_global( lo i_elem, int n_shared_vertices, int rotation, bool swap, std::vector< lo > & indices ) const; /** * Evaluates a basis function in a point in an element. The point is given by * coordinates in the reference triangle * (\f$ (x_1,x_2) \in (0,1)\times(0,1-x_1) \f$). * @param[in] i_elem Element index. * @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] n Outward normal vector on the element. * \note By the nature of the basis functions, the result does not depend on * the choice of the element, and in particular not on the outward normal * vector. */ #pragma omp declare simd uniform( this, i_elem, i_fun, n ) simdlen( DATA_WIDTH ) sc do_evaluate( [[maybe_unused]] lo i_elem, lo i_fun, sc x1_ref, sc x2_ref, [[maybe_unused]] const sc * n ) const { sc value = 0.0; if ( i_fun == 0 ) { value = 1 - x1_ref - x2_ref; } else if ( i_fun == 1 ) { value = x1_ref; } else if ( i_fun == 2 ) { value = x2_ref; } return value; } /** * Evaluates a basis function in a point in an element. The point is given by * coordinates in the reference triangle * (\f$ (x_1,x_2) \in (0,1)\times(0,1-x_1) \f$). * @param[in] i_elem Element index. * @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] n Outward normal vector on the element * @param[in] n_shared_vertices Number of shared vertices in currect elements * (regularized quadrature). * @param[in] rotation Virtual element rotation (regularized quadrature). * @param[in] swap Virtual element inversion (regularized quadrature). * \note By the nature of the basis functions, the result does not depend on * the choice of the element, and in particular not on the outward normal * vector. * \note The regularized quadrature parameters do not influence the result * either. */ #pragma omp declare simd uniform( this, i_elem, i_fun, n, n_shared_vertices, \ rotation, swap ) simdlen( DATA_WIDTH ) sc do_evaluate( [[maybe_unused]] lo i_elem, lo i_fun, sc x1_ref, sc x2_ref, [[maybe_unused]] const sc * n, [[maybe_unused]] int n_shared_vertices, [[maybe_unused]] int rotation, [[maybe_unused]] bool swap ) const { sc value = 0.0; if ( i_fun == 0 ) { value = 1 - x1_ref - x2_ref; } else if ( i_fun == 1 ) { value = x1_ref; } else if ( i_fun == 2 ) { value = x2_ref; } return value; } /** * Evaluates the surface curl of all basis functions in a given element. * @param[in] i_elem Element index. * @param[in] n Outward normal vector on the element * @param[in] n_shared_vertices Number of shared vertices in currect elements * (regularized quadrature). * @param[in] rotation Virtual element rotation (regularized quadrature). * @param[in] swap Virtual element inversion (regularized quadrature). * @param[out] curls Surface curls of all three shape functions. */ void evaluate_curl( lo i_elem, const linear_algebra::coordinates< 3 > & n, int n_shared_vertices, int rotation, bool swap, sc * curls ) const; }; #endif /* INCLUDE_BESTHEA_BASIS_TRI_P1_H_ */
omp_dem_search.h
// // Project Name: Kratos // Last Modified by: $Author: clabra $ // Date: $Date: 2007-03-29 19:37:47 $ // Revision: $Revision: 1.2 $ // // #if !defined(KRATOS_OMP_DEM_SEARCH_H_INCLUDED ) #define KRATOS_OMP_DEM_SEARCH_H_INCLUDED // System includes #include <string> #include <iostream> // include kratos definitions #include "includes/define.h" // Project includes #include "spatial_containers/dem_search.h" #include "utilities/openmp_utils.h" // Configures #include "discrete_particle_configure.h" #include "geometrical_object_configure.h" #include "node_configure.h" // Search #include "spatial_containers/bins_dynamic_objects.h" #include "spatial_containers/bins_dynamic.h" #include "custom_search/bins_dynamic_objects_periodic.h" // External includes /* Timer defines */ #include "utilities/timer.h" #ifdef CUSTOMTIMER #define KRATOS_TIMER_START(t) Timer::Start(t); #define KRATOS_TIMER_STOP(t) Timer::Stop(t); #else #define KRATOS_TIMER_START(t) #define KRATOS_TIMER_STOP(t) #endif namespace Kratos { ///@name Kratos Globals ///@{ ///@} ///@name Type Definitions ///@{ ///@} ///@name Enum's ///@{ ///@} ///@name Functions ///@{ ///@} ///@name Kratos Classes ///@{ /// Short class definition. /** Detail class definition. */ class OMP_DEMSearch : public DEMSearch<OMP_DEMSearch> { public: ///@name Type Definitions ///@{ /// Pointer definition of OMP_DEMSearch KRATOS_CLASS_POINTER_DEFINITION(OMP_DEMSearch); typedef PointType* PtrPointType; typedef std::vector<PtrPointType>* PointVector; typedef std::vector<PtrPointType>::iterator PointIterator; typedef double* DistanceVector; typedef double* DistanceIterator; //Configure Types typedef DiscreteParticleConfigure<3> ElementConfigureType; //Element typedef NodeConfigure<3> NodeConfigureType; //Node typedef GeometricalConfigure<3> GeometricalConfigureType; //Generic Geometry //Bin Types typedef BinsObjectDynamic<ElementConfigureType> BinsType; typedef BinsObjectDynamicPeriodic<ElementConfigureType> BinsTypePeriodic; typedef std::unique_ptr<BinsType> BinsUniquePointerType; typedef BinsObjectDynamic<NodeConfigureType> NodeBinsType; typedef BinsObjectDynamic<GeometricalConfigureType> GeometricalBinsType; //GeoimetricalObject typedef PointerVectorSet<GeometricalObject, IndexedObject> GeometricalObjectType; ///@} ///@name Life Cycle ///@{ /// Default constructor. OMP_DEMSearch(const double domain_min_x = 0.0, const double domain_min_y = 0.0, const double domain_min_z = 0.0, const double domain_max_x = -1.0, const double domain_max_y = -1.0, const double domain_max_z = -1.0) { mDomainPeriodicity = (domain_min_x <= domain_max_x) ? true : false; } /// Destructor. ~OMP_DEMSearch(){ } ///@} ///@name Operators ///@{ ///@} ///@name Operations ///@{ void SearchElementsInRadiusExclusiveImplementation ( ElementsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType & Radius, VectorResultElementsContainerType& rResults, VectorDistanceType& rResultsDistance ) { // KRATOS_TRY // // int MaxNumberOfElements = rStructureElements.size(); // // ElementsContainerType::ContainerType& elements_bins = const_cast<ElementsContainerType::ContainerType&>(rStructureElements.GetContainer()); // ElementsContainerType::ContainerType& elements_sear = const_cast<ElementsContainerType::ContainerType&>(rElements.GetContainer()); // // GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector; // GeometricalObjectType::ContainerType BinsElementPointerToGeometricalObjecPointerTemporalVector; // // BinsElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_bins.size()); // SearElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_sear.size()); // // for(ElementsContainerType::ContainerType::iterator it = elements_bins.begin(); it != elements_bins.end(); it++) // BinsElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); // // for(ElementsContainerType::ContainerType::iterator it = elements_sear.begin(); it != elements_sear.end(); it++) // SearElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); // // GeometricalBinsType bins(BinsElementPointerToGeometricalObjecPointerTemporalVector.begin(), BinsElementPointerToGeometricalObjecPointerTemporalVector.end()); // // #pragma omp parallel // { // GeometricalObjectType::ContainerType localResults(MaxNumberOfElements); // DistanceType localResultsDistances(MaxNumberOfElements); // std::size_t NumberOfResults = 0; // // #pragma omp for // for(std::size_t i = 0; i < elements_sear.size(); i++) // { // GeometricalObjectType::ContainerType::iterator ResultsPointer = localResults.begin(); // DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); // // NumberOfResults = bins.SearchObjectsInRadiusExclusive(SearElementPointerToGeometricalObjecPointerTemporalVector[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); // // rResults[i].reserve(NumberOfResults); // // for(GeometricalObjectType::ContainerType::iterator it = localResults.begin(); it != localResults.begin() + NumberOfResults; it++) // { // Element::Pointer elem = dynamic_pointer_cast<Element>(*it); // rResults[i].push_back(elem); // rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); // } // } // } // // KRATOS_CATCH("") KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_array = const_cast<ElementsContainerType::ContainerType&>(rElements.GetContainer()); ElementsContainerType::ContainerType& elements_ModelPart = const_cast<ElementsContainerType::ContainerType&>(rStructureElements.GetContainer()); BinsUniquePointerType p_bins = GetBins(elements_ModelPart); #pragma omp parallel { ResultElementsContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for schedule(dynamic, 100) //schedule(guided) for(int i = 0; i < static_cast<int>(elements_array.size()); i++) { ResultElementsContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); SphericParticle* p_particle = dynamic_cast<SphericParticle*>(&*elements_array[i]); const double radius = p_particle->GetSearchRadius(); NumberOfResults = p_bins->SearchObjectsInRadiusExclusive(elements_array[i],radius,ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } //MAJOR TODO: creating and destroying (when leaving the function) this BINS is not parallel and takes a significant time if we search at every time step. Can we re-use a bins and avoid allocation and deallocation?? MA KRATOS_CATCH("") } void SearchElementsInRadiusInclusiveImplementation ( ElementsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType& Radius, VectorResultElementsContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_array = const_cast<ElementsContainerType::ContainerType&>(rElements.GetContainer()); ElementsContainerType::ContainerType& elements_ModelPart = const_cast<ElementsContainerType::ContainerType&>(rStructureElements.GetContainer()); BinsUniquePointerType p_bins = GetBins(elements_ModelPart); #pragma omp parallel { ResultElementsContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_array.size()); i++) { ResultElementsContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); SphericParticle* p_particle = dynamic_cast<SphericParticle*>(&*elements_array[i]); const double radius = p_particle->GetSearchRadius(); NumberOfResults = p_bins->SearchObjectsInRadius(elements_array[i],radius,ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchElementsInRadiusExclusiveImplementation ( ElementsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType & Radius, VectorResultElementsContainerType& rResults ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_array = const_cast<ElementsContainerType::ContainerType&>(rElements.GetContainer()); ElementsContainerType::ContainerType& elements_ModelPart = const_cast<ElementsContainerType::ContainerType&>(rStructureElements.GetContainer()); BinsUniquePointerType p_bins = GetBins(elements_ModelPart); #pragma omp parallel { ResultElementsContainerType localResults(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_array.size()); i++) { ResultElementsContainerType::iterator ResultsPointer = localResults.begin(); SphericParticle* p_particle = dynamic_cast<SphericParticle*>(&*elements_array[i]); const double radius = p_particle->GetSearchRadius(); NumberOfResults = p_bins->SearchObjectsInRadiusExclusive(elements_array[i],radius,ResultsPointer,MaxNumberOfElements); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchElementsInRadiusInclusiveImplementation ( ElementsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType & Radius, VectorResultElementsContainerType& rResults ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_array = const_cast<ElementsContainerType::ContainerType&>(rElements.GetContainer()); ElementsContainerType::ContainerType& elements_ModelPart = const_cast<ElementsContainerType::ContainerType&>(rStructureElements.GetContainer()); BinsType bins(elements_ModelPart.begin(), elements_ModelPart.end()); #pragma omp parallel { ResultElementsContainerType localResults(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_array.size()); i++) { ResultElementsContainerType::iterator ResultsPointer = localResults.begin(); SphericParticle* p_particle = dynamic_cast<SphericParticle*>(&*elements_array[i]); const double radius = p_particle->GetSearchRadius(); NumberOfResults = bins.SearchObjectsInRadius(elements_array[i],radius,ResultsPointer,MaxNumberOfElements); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchNodesInRadiusExclusiveImplementation ( NodesContainerType const& rStructureNodes, NodesContainerType const& rNodes, const RadiusArrayType & Radius, VectorResultNodesContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfNodes = rStructureNodes.size(); NodesContainerType::ContainerType& nodes_array = const_cast<NodesContainerType::ContainerType&>(rNodes.GetContainer()); NodesContainerType::ContainerType& nodes_ModelPart = const_cast<NodesContainerType::ContainerType&>(rStructureNodes.GetContainer()); NodeBinsType bins(nodes_ModelPart.begin(), nodes_ModelPart.end()); #pragma omp parallel { ResultNodesContainerType localResults(MaxNumberOfNodes); DistanceType localResultsDistances(MaxNumberOfNodes); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(nodes_array.size()); i++) { ResultNodesContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadiusExclusive(nodes_array[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfNodes); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchNodesInRadiusInclusiveImplementation ( NodesContainerType const& rStructureNodes, NodesContainerType const& rNodes, const RadiusArrayType & Radius, VectorResultNodesContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfNodes = rStructureNodes.size(); NodesContainerType::ContainerType& nodes_array = const_cast<NodesContainerType::ContainerType&>(rNodes.GetContainer()); NodesContainerType::ContainerType& nodes_ModelPart = const_cast<NodesContainerType::ContainerType&>(rStructureNodes.GetContainer()); NodeBinsType bins(nodes_ModelPart.begin(), nodes_ModelPart.end()); #pragma omp parallel { ResultNodesContainerType localResults(MaxNumberOfNodes); DistanceType localResultsDistances(MaxNumberOfNodes); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(nodes_array.size()); i++) { ResultNodesContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadius(nodes_array[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfNodes); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchNodesInRadiusExclusiveImplementation ( NodesContainerType const& rStructureNodes, NodesContainerType const& rNodes, const RadiusArrayType & Radius, VectorResultNodesContainerType& rResults ) { KRATOS_TRY int MaxNumberOfNodes = rStructureNodes.size(); NodesContainerType::ContainerType& nodes_array = const_cast<NodesContainerType::ContainerType&>(rNodes.GetContainer()); NodesContainerType::ContainerType& nodes_ModelPart = const_cast<NodesContainerType::ContainerType&>(rStructureNodes.GetContainer()); NodeBinsType bins(nodes_ModelPart.begin(), nodes_ModelPart.end()); #pragma omp parallel { ResultNodesContainerType localResults(MaxNumberOfNodes); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(nodes_array.size()); i++) { ResultNodesContainerType::iterator ResultsPointer = localResults.begin(); NumberOfResults = bins.SearchObjectsInRadiusExclusive(nodes_array[i],Radius[i],ResultsPointer,MaxNumberOfNodes); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchNodesInRadiusInclusiveImplementation ( NodesContainerType const& rStructureNodes, NodesContainerType const& rNodes, const RadiusArrayType & Radius, VectorResultNodesContainerType& rResults ) { KRATOS_TRY int MaxNumberOfNodes = rStructureNodes.size(); NodesContainerType::ContainerType& nodes_array = const_cast<NodesContainerType::ContainerType&>(rNodes.GetContainer()); NodesContainerType::ContainerType& nodes_ModelPart = const_cast<NodesContainerType::ContainerType&>(rStructureNodes.GetContainer()); NodeBinsType bins(nodes_ModelPart.begin(), nodes_ModelPart.end()); #pragma omp parallel { ResultNodesContainerType localResults(MaxNumberOfNodes); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(nodes_array.size()); i++) { ResultNodesContainerType::iterator ResultsPointer = localResults.begin(); NumberOfResults = bins.SearchObjectsInRadius(nodes_array[i],Radius[i],ResultsPointer,MaxNumberOfNodes); rResults[i].insert(rResults[i].begin(),localResults.begin(),localResults.begin()+NumberOfResults); } } KRATOS_CATCH("") } void SearchGeometricalInRadiusExclusiveImplementation ( ElementsContainerType const& rStructureElements, ConditionsContainerType const& rElements, const RadiusArrayType & Radius, VectorResultConditionsContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_bins = const_cast<ElementsContainerType::ContainerType&> (rStructureElements.GetContainer()); ConditionsContainerType::ContainerType& elements_sear = const_cast<ConditionsContainerType::ContainerType&>(rElements.GetContainer()); GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector; GeometricalObjectType::ContainerType BinsElementPointerToGeometricalObjecPointerTemporalVector; SearElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_sear.size()); BinsElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_bins.size()); for(ElementsContainerType::ContainerType::iterator it = elements_bins.begin(); it != elements_bins.end(); it++) BinsElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); for(ConditionsContainerType::ContainerType::iterator it = elements_sear.begin(); it != elements_sear.end(); it++) SearElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); GeometricalBinsType bins(BinsElementPointerToGeometricalObjecPointerTemporalVector.begin(), BinsElementPointerToGeometricalObjecPointerTemporalVector.end()); #pragma omp parallel { GeometricalObjectType::ContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_sear.size()); i++) { GeometricalObjectType::ContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadiusExclusive(SearElementPointerToGeometricalObjecPointerTemporalVector[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].reserve(NumberOfResults); for(GeometricalObjectType::ContainerType::iterator it = localResults.begin(); it != localResults.begin() + NumberOfResults; it++) { Condition::Pointer elem = dynamic_pointer_cast<Condition>(*it); rResults[i].push_back(elem); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } } KRATOS_CATCH("") } void SearchGeometricalInRadiusInclusiveImplementation ( ElementsContainerType const& rStructureElements, ConditionsContainerType const& rElements, const RadiusArrayType& Radius, VectorResultConditionsContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ElementsContainerType::ContainerType& elements_bins = const_cast<ElementsContainerType::ContainerType&> (rStructureElements.GetContainer()); ConditionsContainerType::ContainerType& elements_sear = const_cast<ConditionsContainerType::ContainerType&>(rElements.GetContainer()); GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector; GeometricalObjectType::ContainerType BinsElementPointerToGeometricalObjecPointerTemporalVector; SearElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_sear.size()); BinsElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_bins.size()); for(ElementsContainerType::ContainerType::iterator it = elements_bins.begin(); it != elements_bins.end(); it++) BinsElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); for(ConditionsContainerType::ContainerType::iterator it = elements_sear.begin(); it != elements_sear.end(); it++) SearElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); GeometricalBinsType bins(BinsElementPointerToGeometricalObjecPointerTemporalVector.begin(), BinsElementPointerToGeometricalObjecPointerTemporalVector.end()); #pragma omp parallel { GeometricalObjectType::ContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_sear.size()); i++) { GeometricalObjectType::ContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadius(SearElementPointerToGeometricalObjecPointerTemporalVector[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].reserve(NumberOfResults); for(GeometricalObjectType::ContainerType::iterator it = localResults.begin(); it != localResults.begin() + NumberOfResults; it++) { Condition::Pointer elem = dynamic_pointer_cast<Condition>(*it); rResults[i].push_back(elem); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } } KRATOS_CATCH("") } void SearchGeometricalInRadiusExclusiveImplementation ( ConditionsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType & Radius, VectorResultElementsContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ConditionsContainerType::ContainerType& elements_bins = const_cast<ConditionsContainerType::ContainerType&>(rStructureElements.GetContainer()); ElementsContainerType::ContainerType& elements_sear = const_cast<ElementsContainerType::ContainerType&> (rElements.GetContainer()); GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector; GeometricalObjectType::ContainerType BinsElementPointerToGeometricalObjecPointerTemporalVector; SearElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_sear.size()); BinsElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_bins.size()); for(ElementsContainerType::ContainerType::iterator it = elements_sear.begin(); it != elements_sear.end(); it++) SearElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); for(ConditionsContainerType::ContainerType::iterator it = elements_bins.begin(); it != elements_bins.end(); it++) BinsElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); GeometricalBinsType bins(BinsElementPointerToGeometricalObjecPointerTemporalVector.begin(), BinsElementPointerToGeometricalObjecPointerTemporalVector.end()); #pragma omp parallel { GeometricalObjectType::ContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_sear.size()); i++) { GeometricalObjectType::ContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadiusExclusive(SearElementPointerToGeometricalObjecPointerTemporalVector[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].reserve(NumberOfResults); for(GeometricalObjectType::ContainerType::iterator it = localResults.begin(); it != localResults.begin() + NumberOfResults; it++) { Element::Pointer elem = dynamic_pointer_cast<Element>(*it); rResults[i].push_back(elem); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } } KRATOS_CATCH("") } void SearchGeometricalInRadiusInclusiveImplementation ( ConditionsContainerType const& rStructureElements, ElementsContainerType const& rElements, const RadiusArrayType& Radius, VectorResultElementsContainerType& rResults, VectorDistanceType& rResultsDistance ) { KRATOS_TRY int MaxNumberOfElements = rStructureElements.size(); ConditionsContainerType::ContainerType& elements_bins = const_cast<ConditionsContainerType::ContainerType&>(rStructureElements.GetContainer()); ElementsContainerType::ContainerType& elements_sear = const_cast<ElementsContainerType::ContainerType&> (rElements.GetContainer()); GeometricalObjectType::ContainerType SearElementPointerToGeometricalObjecPointerTemporalVector; GeometricalObjectType::ContainerType BinsElementPointerToGeometricalObjecPointerTemporalVector; SearElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_sear.size()); BinsElementPointerToGeometricalObjecPointerTemporalVector.reserve(elements_bins.size()); for(ElementsContainerType::ContainerType::iterator it = elements_sear.begin(); it != elements_sear.end(); it++) SearElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); for(ConditionsContainerType::ContainerType::iterator it = elements_bins.begin(); it != elements_bins.end(); it++) BinsElementPointerToGeometricalObjecPointerTemporalVector.push_back(*it); GeometricalBinsType bins(BinsElementPointerToGeometricalObjecPointerTemporalVector.begin(), BinsElementPointerToGeometricalObjecPointerTemporalVector.end()); #pragma omp parallel { GeometricalObjectType::ContainerType localResults(MaxNumberOfElements); DistanceType localResultsDistances(MaxNumberOfElements); std::size_t NumberOfResults = 0; #pragma omp for for(int i = 0; i < static_cast<int>(elements_sear.size()); i++) { GeometricalObjectType::ContainerType::iterator ResultsPointer = localResults.begin(); DistanceType::iterator ResultsDistancesPointer = localResultsDistances.begin(); NumberOfResults = bins.SearchObjectsInRadius(SearElementPointerToGeometricalObjecPointerTemporalVector[i],Radius[i],ResultsPointer,ResultsDistancesPointer,MaxNumberOfElements); rResults[i].reserve(NumberOfResults); for(GeometricalObjectType::ContainerType::iterator it = localResults.begin(); it != localResults.begin() + NumberOfResults; it++) { Element::Pointer elem = dynamic_pointer_cast<Element>(*it); rResults[i].push_back(elem); rResultsDistance[i].insert(rResultsDistance[i].begin(),localResultsDistances.begin(),localResultsDistances.begin()+NumberOfResults); } } } KRATOS_CATCH("") } ///@} ///@name Access ///@{ ///@} ///@name Inquiry ///@{ ///@} ///@name Input and output ///@{ /// Turn back information as a string. virtual std::string Info() const override { std::stringstream buffer; buffer << "OpenMPDemSearch" ; return buffer.str(); } /// Print information about this object. virtual void PrintInfo(std::ostream& rOStream) const override {rOStream << "OpenMPDemSearch";} /// Print object's data. virtual void PrintData(std::ostream& rOStream) const override {} ///@} ///@name Friends ///@{ ///@} protected: ///@name Protected static Member Variables ///@{ ///@} ///@name Protected member Variables ///@{ ///@} ///@name Protected Operators ///@{ ///@} ///@name Protected Operations ///@{ ///@} ///@name Protected Access ///@{ ///@} ///@name Protected Inquiry ///@{ ///@} ///@name Protected LifeCycle ///@{ ///@} private: ///@name Static Member Variables ///@{ ///@} ///@name Member Variables ///@{ ///@} ///@name Private Operators ///@{ ///@} ///@name Private Operations ///@{ ///@} ///@name Private Access ///@{ ///@} ///@name Private Inquiry ///@{ /// BinsUniquePointerType GetBins(ElementsContainerType::ContainerType& r_model_part_container) { if (mDomainPeriodicity){ return std::unique_ptr<BinsType>(new BinsTypePeriodic(r_model_part_container.begin(), r_model_part_container.end(), this->mDomainMin, this->mDomainMax)); } else { return std::unique_ptr<BinsType>(new BinsType(r_model_part_container.begin(), r_model_part_container.end())); } } ///@} ///@name Un accessible methods ///@{ /// Assignment operator. OMP_DEMSearch& operator=(OMP_DEMSearch const& rOther) { return *this; } /// Copy constructor. OMP_DEMSearch(OMP_DEMSearch const& rOther) { *this = rOther; } ///@} }; // Class DEMSearch ///@} ///@name Type Definitions ///@{ ///@} ///@name Input and output ///@{ /// input stream function // inline std::istream& operator >> (std::istream& rIStream, // DEMSearch& rThis){return rIStream;} // // /// output stream function // inline std::ostream& operator << (std::ostream& rOStream, // const DEMSearch& rThis) // { // rThis.PrintInfo(rOStream); // rOStream << std::endl; // rThis.PrintData(rOStream); // // return rOStream; // } ///@} ///@} addtogroup block } // namespace Kratos. #endif // KRATOS_DEM_SEARCH_H_INCLUDED defined
mg_single.c
/*-------------------------------------------------------------------- NAS Parallel Benchmarks 2.3 OpenMP C versions - MG This benchmark is an OpenMP C version of the NPB MG code. The OpenMP C versions are developed by RWCP and derived from the serial Fortran versions in "NPB 2.3-serial" developed by NAS. Permission to use, copy, distribute and modify this software for any purpose with or without fee is hereby granted. This software is provided "as is" without express or implied warranty. Send comments on the OpenMP C versions to pdp-openmp@rwcp.or.jp Information on OpenMP activities at RWCP is available at: http://pdplab.trc.rwcp.or.jp/pdperf/Omni/ Information on NAS Parallel Benchmarks 2.3 is available at: http://www.nas.nasa.gov/NAS/NPB/ --------------------------------------------------------------------*/ /*-------------------------------------------------------------------- Authors: E. Barszcz P. Frederickson A. Woo M. Yarrow OpenMP C version: S. Satoh --------------------------------------------------------------------*/ /* * #include "npb-C.h" */ #include <stdio.h> #include <stdlib.h> #include <math.h> #if defined(_OPENMP) #include <omp.h> #endif /* _OPENMP */ #include <sys/time.h> typedef int boolean; typedef struct { double real; double imag; } dcomplex; #define TRUE 1 #define FALSE 0 #define max(a,b) (((a) > (b)) ? (a) : (b)) #define min(a,b) (((a) < (b)) ? (a) : (b)) #define pow2(a) ((a)*(a)) #define get_real(c) c.real #define get_imag(c) c.imag #define cadd(c,a,b) (c.real = a.real + b.real, c.imag = a.imag + b.imag) #define csub(c,a,b) (c.real = a.real - b.real, c.imag = a.imag - b.imag) #define cmul(c,a,b) (c.real = a.real * b.real - a.imag * b.imag, \ c.imag = a.real * b.imag + a.imag * b.real) #define crmul(c,a,b) (c.real = a.real * b, c.imag = a.imag * b) extern double randlc(double *, double); extern void vranlc(int, double *, double, double *); extern void timer_clear(int); extern void timer_start(int); extern void timer_stop(int); extern double timer_read(int); extern void c_print_results(char *name, char cclass, int n1, int n2, int n3, int niter, int nthreads, double t, double mops, char *optype, int passed_verification, char *npbversion, char *compiletime, char *cc, char *clink, char *c_lib, char *c_inc, char *cflags, char *clinkflags, char *rand); /* #include "globals.h" #include "npbparams.h" */ #define CLASS 'B' /******************/ /* default values */ /******************/ #ifndef CLASS #define CLASS 'S' #endif #if CLASS == 'S' /* CLASS = S */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NX_DEFAULT 32 #define NY_DEFAULT 32 #define NZ_DEFAULT 32 #define NIT_DEFAULT 4 #define LM 5 #define LT_DEFAULT 5 #define DEBUG_DEFAULT 0 #define NDIM1 5 #define NDIM2 5 #define NDIM3 5 #define CONVERTDOUBLE FALSE #define COMPILETIME "13 Mar 2013" #define NPBVERSION "2.3" #define CS1 "gcc" #define CS2 "$(CC)" #define CS3 "(none)" #define CS4 "-I../common" #define CS5 "-fopenmp -O3" #define CS6 "-lm -fopenmp" #define CS7 "randdp" #endif #if CLASS == 'W' /* CLASS = W */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NX_DEFAULT 64 #define NY_DEFAULT 64 #define NZ_DEFAULT 64 #define NIT_DEFAULT 40 #define LM 6 #define LT_DEFAULT 6 #define DEBUG_DEFAULT 0 #define NDIM1 6 #define NDIM2 6 #define NDIM3 6 #define CONVERTDOUBLE FALSE #define COMPILETIME "13 Mar 2013" #define NPBVERSION "2.3" #define CS1 "gcc" #define CS2 "$(CC)" #define CS3 "(none)" #define CS4 "-I../common" #define CS5 "-fopenmp -O3" #define CS6 "-lm -fopenmp" #define CS7 "randdp" #endif #if CLASS == 'A' /* CLASS = A */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NX_DEFAULT 256 #define NY_DEFAULT 256 #define NZ_DEFAULT 256 #define NIT_DEFAULT 4 #define LM 8 #define LT_DEFAULT 8 #define DEBUG_DEFAULT 0 #define NDIM1 8 #define NDIM2 8 #define NDIM3 8 #define CONVERTDOUBLE FALSE #define COMPILETIME "07 Mar 2013" #define NPBVERSION "2.3" #define CS1 "identityTranslator " #define CS2 "$(CC)" #define CS3 "/export/tmp.liao6/workspace/thrifty/build64..." #define CS4 "-I../common" #define CS5 "-rose:openmp:lowering " #define CS6 "-lm" #define CS7 "randdp" #endif #if CLASS == 'B' /* CLASS = B */ /* c This file is generated automatically by the setparams utility. c It sets the number of processors and the classc of the NPB c in this directory. Do not modify it by hand. */ #define NX_DEFAULT 256 #define NY_DEFAULT 256 #define NZ_DEFAULT 256 #define NIT_DEFAULT 20 #define LM 8 #define LT_DEFAULT 8 #define DEBUG_DEFAULT 0 #define NDIM1 8 #define NDIM2 8 #define NDIM3 8 #define CONVERTDOUBLE FALSE #define COMPILETIME "03 May 2013" #define NPBVERSION "2.3" #define CS1 "gcc" #define CS2 "$(CC)" #define CS3 "(none)" #define CS4 "-I../common" #define CS5 "-fopenmp -O3" #define CS6 "-lm -fopenmp" #define CS7 "randdp" #endif /* parameters */ /* actual dimension including ghost cells for communications */ #define NM (2+(2<<(LM-1))) /* size of rhs array */ #define NV (2+(2<<(NDIM1-1))*(2+(2<<(NDIM2-1)))*(2+(2<<(NDIM3-1)))) /* size of residual array */ #define NR ((8*(NV+(NM*NM)+5*NM+7*LM))/7) /* size of communication buffer */ #define NM2 (2*NM*NM) /* maximum number of levels */ #define MAXLEVEL 11 /*---------------------------------------------------------------------*/ /* common /mg3/ */ static int nx[MAXLEVEL+1], ny[MAXLEVEL+1], nz[MAXLEVEL+1]; /* common /ClassType/ */ static char Class; /* common /my_debug/ */ static int debug_vec[8]; /* common /fap/ */ /*static int ir[MAXLEVEL], m1[MAXLEVEL], m2[MAXLEVEL], m3[MAXLEVEL];*/ static int m1[MAXLEVEL+1], m2[MAXLEVEL+1], m3[MAXLEVEL+1]; static int lt, lb; /*c--------------------------------------------------------------------- c Set at m=1024, can handle cases up to 1024^3 case c---------------------------------------------------------------------*/ #define M 1037 /* common /buffer/ */ /*static double buff[4][NM2];*/ /* parameters */ #define T_BENCH 1 #define T_INIT 2 /* global variables */ /* common /grid/ */ static int is1, is2, is3, ie1, ie2, ie3; /* functions prototypes */ static void setup(int *n1, int *n2, int *n3, int lt); static void mg3P(double ****u, double ***v, double ****r, double a[4], double c[4], int n1, int n2, int n3, int k); static void psinv( double ***r, double ***u, int n1, int n2, int n3, double c[4], int k); static void resid( double ***u, double ***v, double ***r, int n1, int n2, int n3, double a[4], int k ); static void rprj3( double ***r, int m1k, int m2k, int m3k, double ***s, int m1j, int m2j, int m3j, int k ); static void interp( double ***z, int mm1, int mm2, int mm3, double ***u, int n1, int n2, int n3, int k ); static void norm2u3(double ***r, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz); static void rep_nrm(double ***u, int n1, int n2, int n3, char *title, int kk); static void comm3(double ***u, int n1, int n2, int n3, int kk); static void zran3(double ***z, int n1, int n2, int n3, int nx, int ny, int k); static void showall(double ***z, int n1, int n2, int n3); static double power( double a, int n ); static void bubble( double ten[M][2], int j1[M][2], int j2[M][2], int j3[M][2], int m, int ind ); static void zero3(double ***z, int n1, int n2, int n3); static void nonzero(double ***z, int n1, int n2, int n3); /*-------------------------------------------------------------------- program mg c-------------------------------------------------------------------*/ int main(int argc, char *argv[]) { /*------------------------------------------------------------------------- c k is the current level. It is passed down through subroutine args c and is NOT global. it is the current iteration c------------------------------------------------------------------------*/ int k, it; double t, tinit, mflops; int nthreads = 1; /*------------------------------------------------------------------------- c These arrays are in common because they are quite large c and probably shouldn't be allocated on the stack. They c are always passed as subroutine args. c------------------------------------------------------------------------*/ double ****u, ***v, ****r; /* Dynamically allocated arrays, not linear storage across dimensions */ double a[4], c[4]; double rnm2, rnmu; double epsilon = 1.0e-8; int n1, n2, n3, nit; double verify_value; boolean verified; int i, j, l; FILE *fp; timer_clear(T_BENCH); timer_clear(T_INIT); timer_start(T_INIT); /*---------------------------------------------------------------------- c Read in and broadcast input data c---------------------------------------------------------------------*/ printf("\n\n NAS Parallel Benchmarks 2.3 OpenMP C version" " - MG Benchmark\n\n"); fp = fopen("mg.input", "r"); if (fp != NULL) { printf(" Reading from input file mg.input\n"); fscanf(fp, "%d", &lt); while(fgetc(fp) != '\n'); fscanf(fp, "%d%d%d", &nx[lt], &ny[lt], &nz[lt]); while(fgetc(fp) != '\n'); fscanf(fp, "%d", &nit); while(fgetc(fp) != '\n'); for (i = 0; i <= 7; i++) { fscanf(fp, "%d", &debug_vec[i]); } fclose(fp); } else { printf(" No input file. Using compiled defaults\n"); lt = LT_DEFAULT; nit = NIT_DEFAULT; nx[lt] = NX_DEFAULT; ny[lt] = NY_DEFAULT; nz[lt] = NZ_DEFAULT; for (i = 0; i <= 7; i++) { debug_vec[i] = DEBUG_DEFAULT; } } if ( (nx[lt] != ny[lt]) || (nx[lt] != nz[lt]) ) { Class = 'U'; } else if( nx[lt] == 32 && nit == 4 ) { Class = 'S'; } else if( nx[lt] == 64 && nit == 40 ) { Class = 'W'; } else if( nx[lt] == 256 && nit == 20 ) { Class = 'B'; } else if( nx[lt] == 512 && nit == 20 ) { Class = 'C'; } else if( nx[lt] == 256 && nit == 4 ) { Class = 'A'; } else { Class = 'U'; } /*-------------------------------------------------------------------- c Use these for debug info: c--------------------------------------------------------------------- c debug_vec(0) = 1 !=> report all norms c debug_vec(1) = 1 !=> some setup information c debug_vec(1) = 2 !=> more setup information c debug_vec(2) = k => at level k or below, show result of resid c debug_vec(3) = k => at level k or below, show result of psinv c debug_vec(4) = k => at level k or below, show result of rprj c debug_vec(5) = k => at level k or below, show result of interp c debug_vec(6) = 1 => (unused) c debug_vec(7) = 1 => (unused) c-------------------------------------------------------------------*/ a[0] = -8.0/3.0; a[1] = 0.0; a[2] = 1.0/6.0; a[3] = 1.0/12.0; if (Class == 'A' || Class == 'S' || Class =='W') { /*-------------------------------------------------------------------- c Coefficients for the S(a) smoother c-------------------------------------------------------------------*/ c[0] = -3.0/8.0; c[1] = 1.0/32.0; c[2] = -1.0/64.0; c[3] = 0.0; } else { /*-------------------------------------------------------------------- c Coefficients for the S(b) smoother c-------------------------------------------------------------------*/ c[0] = -3.0/17.0; c[1] = 1.0/33.0; c[2] = -1.0/61.0; c[3] = 0.0; } lb = 1; setup(&n1,&n2,&n3,lt); u = (double ****)malloc((lt+1)*sizeof(double ***)); for (l = lt; l >=1; l--) { u[l] = (double ***)malloc(m3[l]*sizeof(double **)); for (k = 0; k < m3[l]; k++) { u[l][k] = (double **)malloc(m2[l]*sizeof(double *)); for (j = 0; j < m2[l]; j++) { u[l][k][j] = (double *)malloc(m1[l]*sizeof(double)); } } } v = (double ***)malloc(m3[lt]*sizeof(double **)); for (k = 0; k < m3[lt]; k++) { v[k] = (double **)malloc(m2[lt]*sizeof(double *)); for (j = 0; j < m2[lt]; j++) { v[k][j] = (double *)malloc(m1[lt]*sizeof(double)); } } r = (double ****)malloc((lt+1)*sizeof(double ***)); for (l = lt; l >=1; l--) { r[l] = (double ***)malloc(m3[l]*sizeof(double **)); for (k = 0; k < m3[l]; k++) { r[l][k] = (double **)malloc(m2[l]*sizeof(double *)); for (j = 0; j < m2[l]; j++) { r[l][k][j] = (double *)malloc(m1[l]*sizeof(double)); } } } #pragma omp parallel { zero3(u[lt],n1,n2,n3); } zran3(v,n1,n2,n3,nx[lt],ny[lt],lt); #pragma omp parallel { norm2u3(v,n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); #pragma omp single { /* printf("\n norms of random v are\n"); printf(" %4d%19.12e%19.12e\n", 0, rnm2, rnmu); printf(" about to evaluate resid, k= %d\n", lt);*/ printf(" Size: %3dx%3dx%3d (class %1c)\n", nx[lt], ny[lt], nz[lt], Class); printf(" Iterations: %3d\n", nit); } resid(u[lt],v,r[lt],n1,n2,n3,a,lt); norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); /*c--------------------------------------------------------------------- c One iteration for startup c---------------------------------------------------------------------*/ mg3P(u,v,r,a,c,n1,n2,n3,lt); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); #pragma omp single setup(&n1,&n2,&n3,lt); zero3(u[lt],n1,n2,n3); } /* pragma omp parallel */ zran3(v,n1,n2,n3,nx[lt],ny[lt],lt); timer_stop(T_INIT); timer_start(T_BENCH); #pragma omp parallel firstprivate(nit) private(it) { resid(u[lt],v,r[lt],n1,n2,n3,a,lt); norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); for ( it = 1; it <= nit; it++) { mg3P(u,v,r,a,c,n1,n2,n3,lt); resid(u[lt],v,r[lt],n1,n2,n3,a,lt); } norm2u3(r[lt],n1,n2,n3,&rnm2,&rnmu,nx[lt],ny[lt],nz[lt]); #if defined(_OPENMP) #pragma omp master nthreads = omp_get_num_threads(); #endif } /* pragma omp parallel */ timer_stop(T_BENCH); t = timer_read(T_BENCH); tinit = timer_read(T_INIT); verified = FALSE; verify_value = 0.0; printf(" Initialization time: %15.3f seconds\n", tinit); printf(" Benchmark completed\n"); if (Class != 'U') { if (Class == 'S') { verify_value = 0.530770700573e-04; } else if (Class == 'W') { verify_value = 0.250391406439e-17; /* 40 iterations*/ /* 0.183103168997d-044 iterations*/ } else if (Class == 'A') { verify_value = 0.2433365309e-5; } else if (Class == 'B') { verify_value = 0.180056440132e-5; } else if (Class == 'C') { verify_value = 0.570674826298e-06; } if ( fabs( rnm2 - verify_value ) <= epsilon ) { verified = TRUE; printf(" VERIFICATION SUCCESSFUL\n"); printf(" L2 Norm is %20.12e\n", rnm2); printf(" Error is %20.12e\n", rnm2 - verify_value); } else { verified = FALSE; printf(" VERIFICATION FAILED\n"); printf(" L2 Norm is %20.12e\n", rnm2); printf(" The correct L2 Norm is %20.12e\n", verify_value); } } else { verified = FALSE; printf(" Problem size unknown\n"); printf(" NO VERIFICATION PERFORMED\n"); } if ( t != 0.0 ) { int nn = nx[lt]*ny[lt]*nz[lt]; mflops = 58.*nit*nn*1.0e-6 / t; } else { mflops = 0.0; } c_print_results("MG", Class, nx[lt], ny[lt], nz[lt], nit, nthreads, t, mflops, " floating point", verified, NPBVERSION, COMPILETIME, CS1, CS2, CS3, CS4, CS5, CS6, CS7); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /* set up a series of grid sizes */ static void setup(int *n1, int *n2, int *n3, int lt) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int k; /* decreasing from the coarse grid (last iteration?) */ for ( k = lt-1; k >= 1; k--) { nx[k] = nx[k+1]/2; ny[k] = ny[k+1]/2; nz[k] = nz[k+1]/2; } for (k = 1; k <= lt; k++) { m1[k] = nx[k]+2; m2[k] = nz[k]+2; m3[k] = ny[k]+2; } is1 = 1; ie1 = nx[lt]; *n1 = nx[lt]+2; is2 = 1; ie2 = ny[lt]; *n2 = ny[lt]+2; is3 = 1; ie3 = nz[lt]; *n3 = nz[lt]+2; if (debug_vec[1] >= 1 ) { printf(" in setup, \n"); printf(" lt nx ny nz n1 n2 n3 is1 is2 is3 ie1 ie2 ie3\n"); printf("%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d%4d\n", lt,nx[lt],ny[lt],nz[lt],*n1,*n2,*n3,is1,is2,is3,ie1,ie2,ie3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void mg3P(double ****u, double ***v, double ****r, double a[4], double c[4], int n1, int n2, int n3, int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c multigrid V-cycle routine c-------------------------------------------------------------------*/ int j; /*-------------------------------------------------------------------- c down cycle. c restrict the residual from the fine grid to the coarse c-------------------------------------------------------------------*/ for (k = lt; k >= lb+1; k--) { j = k-1; rprj3(r[k], m1[k], m2[k], m3[k], r[j], m1[j], m2[j], m3[j], k); } k = lb; /*-------------------------------------------------------------------- c compute an approximate solution on the coarsest grid c-------------------------------------------------------------------*/ zero3(u[k], m1[k], m2[k], m3[k]); psinv(r[k], u[k], m1[k], m2[k], m3[k], c, k); for (k = lb+1; k <= lt-1; k++) { j = k-1; /*-------------------------------------------------------------------- c prolongate from level k-1 to k c-------------------------------------------------------------------*/ zero3(u[k], m1[k], m2[k], m3[k]); interp(u[j], m1[j], m2[j], m3[j], u[k], m1[k], m2[k], m3[k], k); /*-------------------------------------------------------------------- c compute residual for level k c-------------------------------------------------------------------*/ resid(u[k], r[k], r[k], m1[k], m2[k], m3[k], a, k); /*-------------------------------------------------------------------- c apply smoother c-------------------------------------------------------------------*/ psinv(r[k], u[k], m1[k], m2[k], m3[k], c, k); } j = lt - 1; k = lt; interp(u[j], m1[j], m2[j], m3[j], u[lt], n1, n2, n3, k); resid(u[lt], v, r[lt], n1, n2, n3, a, k); psinv(r[lt], u[lt], n1, n2, n3, c, k); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /* similar to stencil computation */ static void psinv( double ***r, double ***u, int n1, int n2, int n3, double c[4], int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c psinv applies an approximate inverse as smoother: u = u + Cr c c This implementation costs 15A + 4M per result, where c A and M denote the costs of Addition and Multiplication. c Presuming coefficient c(3) is zero (the NPB assumes this, c but it is thus not a general case), 2A + 1M may be eliminated, c resulting in 13A + 3M. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int i3, i2, i1; double r1[M], r2[M]; #pragma omp for for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 0; i1 < n1; i1++) { r1[i1] = r[i3][i2-1][i1] + r[i3][i2+1][i1] + r[i3-1][i2][i1] + r[i3+1][i2][i1]; r2[i1] = r[i3-1][i2-1][i1] + r[i3-1][i2+1][i1] + r[i3+1][i2-1][i1] + r[i3+1][i2+1][i1]; } for (i1 = 1; i1 < n1-1; i1++) { u[i3][i2][i1] = u[i3][i2][i1] + c[0] * r[i3][i2][i1] + c[1] * ( r[i3][i2][i1-1] + r[i3][i2][i1+1] + r1[i1] ) + c[2] * ( r2[i1] + r1[i1-1] + r1[i1+1] ); /*-------------------------------------------------------------------- c Assume c(3) = 0 (Enable line below if c(3) not= 0) c--------------------------------------------------------------------- c > + c(3) * ( r2(i1-1) + r2(i1+1) ) c-------------------------------------------------------------------*/ } } } /*-------------------------------------------------------------------- c exchange boundary points c-------------------------------------------------------------------*/ comm3(u,n1,n2,n3,k); if (debug_vec[0] >= 1 ) { #pragma omp single rep_nrm(u,n1,n2,n3," psinv",k); } if ( debug_vec[3] >= k ) { #pragma omp single showall(u,n1,n2,n3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void resid( double ***u, double ***v, double ***r, int n1, int n2, int n3, double a[4], int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c resid computes the residual: r = v - Au c c This implementation costs 15A + 4M per result, where c A and M denote the costs of Addition (or Subtraction) and c Multiplication, respectively. c Presuming coefficient a(1) is zero (the NPB assumes this, c but it is thus not a general case), 3A + 1M may be eliminated, c resulting in 12A + 3M. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int i3, i2, i1; double u1[M], u2[M]; #pragma omp for for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 0; i1 < n1; i1++) { u1[i1] = u[i3][i2-1][i1] + u[i3][i2+1][i1] + u[i3-1][i2][i1] + u[i3+1][i2][i1]; u2[i1] = u[i3-1][i2-1][i1] + u[i3-1][i2+1][i1] + u[i3+1][i2-1][i1] + u[i3+1][i2+1][i1]; } for (i1 = 1; i1 < n1-1; i1++) { r[i3][i2][i1] = v[i3][i2][i1] - a[0] * u[i3][i2][i1] /*-------------------------------------------------------------------- c Assume a(1) = 0 (Enable 2 lines below if a(1) not= 0) c--------------------------------------------------------------------- c > - a(1) * ( u(i1-1,i2,i3) + u(i1+1,i2,i3) c > + u1(i1) ) c-------------------------------------------------------------------*/ - a[2] * ( u2[i1] + u1[i1-1] + u1[i1+1] ) - a[3] * ( u2[i1-1] + u2[i1+1] ); } } } /*-------------------------------------------------------------------- c exchange boundary data c--------------------------------------------------------------------*/ comm3(r,n1,n2,n3,k); if (debug_vec[0] >= 1 ) { #pragma omp single rep_nrm(r,n1,n2,n3," resid",k); } if ( debug_vec[2] >= k ) { #pragma omp single showall(r,n1,n2,n3); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void rprj3( double ***r, int m1k, int m2k, int m3k, double ***s, int m1j, int m2j, int m3j, int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c rprj3 projects onto the next coarser grid, c using a trilinear Finite Element projection: s = r' = P r c c This implementation costs 20A + 4M per result, where c A and M denote the costs of Addition and Multiplication. c Note that this vectorizes, and is also fine for cache c based machines. c-------------------------------------------------------------------*/ int j3, j2, j1, i3, i2, i1, d1, d2, d3; double x1[M], y1[M], x2, y2; if (m1k == 3) { d1 = 2; } else { d1 = 1; } if (m2k == 3) { d2 = 2; } else { d2 = 1; } if (m3k == 3) { d3 = 2; } else { d3 = 1; } #pragma omp for for (j3 = 1; j3 < m3j-1; j3++) { i3 = 2*j3-d3; /*C i3 = 2*j3-1*/ for (j2 = 1; j2 < m2j-1; j2++) { i2 = 2*j2-d2; /*C i2 = 2*j2-1*/ for (j1 = 1; j1 < m1j; j1++) { i1 = 2*j1-d1; /*C i1 = 2*j1-1*/ x1[i1] = r[i3+1][i2][i1] + r[i3+1][i2+2][i1] + r[i3][i2+1][i1] + r[i3+2][i2+1][i1]; y1[i1] = r[i3][i2][i1] + r[i3+2][i2][i1] + r[i3][i2+2][i1] + r[i3+2][i2+2][i1]; } for (j1 = 1; j1 < m1j-1; j1++) { i1 = 2*j1-d1; /*C i1 = 2*j1-1*/ y2 = r[i3][i2][i1+1] + r[i3+2][i2][i1+1] + r[i3][i2+2][i1+1] + r[i3+2][i2+2][i1+1]; x2 = r[i3+1][i2][i1+1] + r[i3+1][i2+2][i1+1] + r[i3][i2+1][i1+1] + r[i3+2][i2+1][i1+1]; s[j3][j2][j1] = 0.5 * r[i3+1][i2+1][i1+1] + 0.25 * ( r[i3+1][i2+1][i1] + r[i3+1][i2+1][i1+2] + x2) + 0.125 * ( x1[i1] + x1[i1+2] + y2) + 0.0625 * ( y1[i1] + y1[i1+2] ); } } } comm3(s,m1j,m2j,m3j,k-1); if (debug_vec[0] >= 1 ) { #pragma omp single rep_nrm(s,m1j,m2j,m3j," rprj3",k-1); } if (debug_vec[4] >= k ) { #pragma omp single showall(s,m1j,m2j,m3j); } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void interp( double ***z, int mm1, int mm2, int mm3, double ***u, int n1, int n2, int n3, int k ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c interp adds the trilinear interpolation of the correction c from the coarser grid to the current approximation: u = u + Qu' c c Observe that this implementation costs 16A + 4M, where c A and M denote the costs of Addition and Multiplication. c Note that this vectorizes, and is also fine for cache c based machines. Vector machines may get slightly better c performance however, with 8 separate "do i1" loops, rather than 4. c-------------------------------------------------------------------*/ int i3, i2, i1, d1, d2, d3, t1, t2, t3; /* c note that m = 1037 in globals.h but for this only need to be c 535 to handle up to 1024^3 c integer m c parameter( m=535 ) */ double z1[M], z2[M], z3[M]; if ( n1 != 3 && n2 != 3 && n3 != 3 ) { #pragma omp for for (i3 = 0; i3 < mm3-1; i3++) { for (i2 = 0; i2 < mm2-1; i2++) { for (i1 = 0; i1 < mm1; i1++) { z1[i1] = z[i3][i2+1][i1] + z[i3][i2][i1]; z2[i1] = z[i3+1][i2][i1] + z[i3][i2][i1]; z3[i1] = z[i3+1][i2+1][i1] + z[i3+1][i2][i1] + z1[i1]; } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3][2*i2][2*i1] = u[2*i3][2*i2][2*i1] +z[i3][i2][i1]; u[2*i3][2*i2][2*i1+1] = u[2*i3][2*i2][2*i1+1] +0.5*(z[i3][i2][i1+1]+z[i3][i2][i1]); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3][2*i2+1][2*i1] = u[2*i3][2*i2+1][2*i1] +0.5 * z1[i1]; u[2*i3][2*i2+1][2*i1+1] = u[2*i3][2*i2+1][2*i1+1] +0.25*( z1[i1] + z1[i1+1] ); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3+1][2*i2][2*i1] = u[2*i3+1][2*i2][2*i1] +0.5 * z2[i1]; u[2*i3+1][2*i2][2*i1+1] = u[2*i3+1][2*i2][2*i1+1] +0.25*( z2[i1] + z2[i1+1] ); } for (i1 = 0; i1 < mm1-1; i1++) { u[2*i3+1][2*i2+1][2*i1] = u[2*i3+1][2*i2+1][2*i1] +0.25* z3[i1]; u[2*i3+1][2*i2+1][2*i1+1] = u[2*i3+1][2*i2+1][2*i1+1] +0.125*( z3[i1] + z3[i1+1] ); } } } } else { if (n1 == 3) { d1 = 2; t1 = 1; } else { d1 = 1; t1 = 0; } if (n2 == 3) { d2 = 2; t2 = 1; } else { d2 = 1; t2 = 0; } if (n3 == 3) { d3 = 2; t3 = 1; } else { d3 = 1; t3 = 0; } #pragma omp for for ( i3 = d3; i3 <= mm3-1; i3++) { for ( i2 = d2; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-d2-1][2*i1-d1-1] = u[2*i3-d3-1][2*i2-d2-1][2*i1-d1-1] +z[i3-1][i2-1][i1-1]; } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-d2-1][2*i1-t1-1] = u[2*i3-d3-1][2*i2-d2-1][2*i1-t1-1] +0.5*(z[i3-1][i2-1][i1]+z[i3-1][i2-1][i1-1]); } } for ( i2 = 1; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-t2-1][2*i1-d1-1] = u[2*i3-d3-1][2*i2-t2-1][2*i1-d1-1] +0.5*(z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-d3-1][2*i2-t2-1][2*i1-t1-1] = u[2*i3-d3-1][2*i2-t2-1][2*i1-t1-1] +0.25*(z[i3-1][i2][i1]+z[i3-1][i2-1][i1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } } } #pragma omp for for ( i3 = 1; i3 <= mm3-1; i3++) { for ( i2 = d2; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-d2-1][2*i1-d1-1] = u[2*i3-t3-1][2*i2-d2-1][2*i1-d1-1] +0.5*(z[i3][i2-1][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-d2-1][2*i1-t1-1] = u[2*i3-t3-1][2*i2-d2-1][2*i1-t1-1] +0.25*(z[i3][i2-1][i1]+z[i3][i2-1][i1-1] +z[i3-1][i2-1][i1]+z[i3-1][i2-1][i1-1]); } } for ( i2 = 1; i2 <= mm2-1; i2++) { for ( i1 = d1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-t2-1][2*i1-d1-1] = u[2*i3-t3-1][2*i2-t2-1][2*i1-d1-1] +0.25*(z[i3][i2][i1-1]+z[i3][i2-1][i1-1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } for ( i1 = 1; i1 <= mm1-1; i1++) { u[2*i3-t3-1][2*i2-t2-1][2*i1-t1-1] = u[2*i3-t3-1][2*i2-t2-1][2*i1-t1-1] +0.125*(z[i3][i2][i1]+z[i3][i2-1][i1] +z[i3][i2][i1-1]+z[i3][i2-1][i1-1] +z[i3-1][i2][i1]+z[i3-1][i2-1][i1] +z[i3-1][i2][i1-1]+z[i3-1][i2-1][i1-1]); } } } } #pragma omp single { if (debug_vec[0] >= 1 ) { rep_nrm(z,mm1,mm2,mm3,"z: inter",k-1); rep_nrm(u,n1,n2,n3,"u: inter",k); } if ( debug_vec[5] >= k ) { showall(z,mm1,mm2,mm3); showall(u,n1,n2,n3); } } /* pragma omp single */ } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void norm2u3(double ***r, int n1, int n2, int n3, double *rnm2, double *rnmu, int nx, int ny, int nz) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c norm2u3 evaluates approximations to the L2 norm and the c uniform (or L-infinity or Chebyshev) norm, under the c assumption that the boundaries are periodic or zero. Add the c boundaries in with half weight (quarter weight on the edges c and eighth weight at the corners) for inhomogeneous boundaries. c-------------------------------------------------------------------*/ static double s = 0.0; double tmp; int i3, i2, i1, n; double p_s = 0.0, p_a = 0.0; n = nx*ny*nz; #pragma omp for for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 1; i1 < n1-1; i1++) { p_s = p_s + r[i3][i2][i1] * r[i3][i2][i1]; tmp = fabs(r[i3][i2][i1]); if (tmp > p_a) p_a = tmp; } } } #pragma omp critical { s += p_s; if (p_a > *rnmu) *rnmu = p_a; } #pragma omp barrier #pragma omp single { *rnm2 = sqrt(s/(double)n); s = 0.0; } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void rep_nrm(double ***u, int n1, int n2, int n3, char *title, int kk) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c report on norm c-------------------------------------------------------------------*/ double rnm2, rnmu; norm2u3(u,n1,n2,n3,&rnm2,&rnmu,nx[kk],ny[kk],nz[kk]); printf(" Level%2d in %8s: norms =%21.14e%21.14e\n", kk, title, rnm2, rnmu); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /* Exchange boundary information */ static void comm3(double ***u, int n1, int n2, int n3, int kk) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c comm3 organizes the communication on all borders c-------------------------------------------------------------------*/ int i1, i2, i3; /* axis = 1 */ #pragma omp for for ( i3 = 1; i3 < n3-1; i3++) { for ( i2 = 1; i2 < n2-1; i2++) { u[i3][i2][n1-1] = u[i3][i2][1]; u[i3][i2][0] = u[i3][i2][n1-2]; } } /* axis = 2 */ #pragma omp for for ( i3 = 1; i3 < n3-1; i3++) { for ( i1 = 0; i1 < n1; i1++) { u[i3][n2-1][i1] = u[i3][1][i1]; u[i3][0][i1] = u[i3][n2-2][i1]; } } /* axis = 3 */ #pragma omp for for ( i2 = 0; i2 < n2; i2++) { for ( i1 = 0; i1 < n1; i1++) { u[n3-1][i2][i1] = u[1][i2][i1]; u[0][i2][i1] = u[n3-2][i2][i1]; } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void zran3(double ***z, int n1, int n2, int n3, int nx, int ny, int k) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c zran3 loads +1 at ten randomly chosen points, c loads -1 at a different ten random points, c and zero elsewhere. c-------------------------------------------------------------------*/ #define MM 10 #define A pow(5.0,13) #define X 314159265.e0 int i0, m0, m1; int i1, i2, i3, d1, e1, e2, e3; double xx, x0, x1, a1, a2, ai; double ten[MM][2], best; int i, j1[MM][2], j2[MM][2], j3[MM][2]; int jg[4][MM][2]; double rdummy; a1 = power( A, nx ); a2 = power( A, nx*ny ); #pragma omp parallel { zero3(z,n1,n2,n3); } i = is1-1+nx*(is2-1+ny*(is3-1)); ai = power( A, i ); d1 = ie1 - is1 + 1; e1 = ie1 - is1 + 2; e2 = ie2 - is2 + 2; e3 = ie3 - is3 + 2; x0 = X; rdummy = randlc( &x0, ai ); for (i3 = 1; i3 < e3; i3++) { x1 = x0; for (i2 = 1; i2 < e2; i2++) { xx = x1; vranlc( d1, &xx, A, &(z[i3][i2][0])); rdummy = randlc( &x1, a1 ); } rdummy = randlc( &x0, a2 ); } /*-------------------------------------------------------------------- c call comm3(z,n1,n2,n3) c call showall(z,n1,n2,n3) c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c each processor looks for twenty candidates c-------------------------------------------------------------------*/ for (i = 0; i < MM; i++) { ten[i][1] = 0.0; j1[i][1] = 0; j2[i][1] = 0; j3[i][1] = 0; ten[i][0] = 1.0; j1[i][0] = 0; j2[i][0] = 0; j3[i][0] = 0; } for (i3 = 1; i3 < n3-1; i3++) { for (i2 = 1; i2 < n2-1; i2++) { for (i1 = 1; i1 < n1-1; i1++) { if ( z[i3][i2][i1] > ten[0][1] ) { ten[0][1] = z[i3][i2][i1]; j1[0][1] = i1; j2[0][1] = i2; j3[0][1] = i3; bubble( ten, j1, j2, j3, MM, 1 ); } if ( z[i3][i2][i1] < ten[0][0] ) { ten[0][0] = z[i3][i2][i1]; j1[0][0] = i1; j2[0][0] = i2; j3[0][0] = i3; bubble( ten, j1, j2, j3, MM, 0 ); } } } } /*-------------------------------------------------------------------- c Now which of these are globally best? c-------------------------------------------------------------------*/ i1 = MM - 1; i0 = MM - 1; for (i = MM - 1 ; i >= 0; i--) { best = z[j3[i1][1]][j2[i1][1]][j1[i1][1]]; if (best == z[j3[i1][1]][j2[i1][1]][j1[i1][1]]) { jg[0][i][1] = 0; jg[1][i][1] = is1 - 1 + j1[i1][1]; jg[2][i][1] = is2 - 1 + j2[i1][1]; jg[3][i][1] = is3 - 1 + j3[i1][1]; i1 = i1-1; } else { jg[0][i][1] = 0; jg[1][i][1] = 0; jg[2][i][1] = 0; jg[3][i][1] = 0; } ten[i][1] = best; best = z[j3[i0][0]][j2[i0][0]][j1[i0][0]]; if (best == z[j3[i0][0]][j2[i0][0]][j1[i0][0]]) { jg[0][i][0] = 0; jg[1][i][0] = is1 - 1 + j1[i0][0]; jg[2][i][0] = is2 - 1 + j2[i0][0]; jg[3][i][0] = is3 - 1 + j3[i0][0]; i0 = i0-1; } else { jg[0][i][0] = 0; jg[1][i][0] = 0; jg[2][i][0] = 0; jg[3][i][0] = 0; } ten[i][0] = best; } m1 = i1+1; m0 = i0+1; /* printf(" negative charges at"); for (i = 0; i < MM; i++) { if (i%5 == 0) printf("\n"); printf(" (%3d,%3d,%3d)", jg[1][i][0], jg[2][i][0], jg[3][i][0]); } printf("\n positive charges at"); for (i = 0; i < MM; i++) { if (i%5 == 0) printf("\n"); printf(" (%3d,%3d,%3d)", jg[1][i][1], jg[2][i][1], jg[3][i][1]); } printf("\n small random numbers were\n"); for (i = MM-1; i >= 0; i--) { printf(" %15.8e", ten[i][0]); } printf("\n and they were found on processor number\n"); for (i = MM-1; i >= 0; i--) { printf(" %4d", jg[0][i][0]); } printf("\n large random numbers were\n"); for (i = MM-1; i >= 0; i--) { printf(" %15.8e", ten[i][1]); } printf("\n and they were found on processor number\n"); for (i = MM-1; i >= 0; i--) { printf(" %4d", jg[0][i][1]); } printf("\n");*/ #pragma omp parallel for private(i2, i1) for (i3 = 0; i3 < n3; i3++) { for (i2 = 0; i2 < n2; i2++) { for (i1 = 0; i1 < n1; i1++) { z[i3][i2][i1] = 0.0; } } } for (i = MM-1; i >= m0; i--) { z[j3[i][0]][j2[i][0]][j1[i][0]] = -1.0; } for (i = MM-1; i >= m1; i--) { z[j3[i][1]][j2[i][1]][j1[i][1]] = 1.0; } #pragma omp parallel comm3(z,n1,n2,n3,k); /*-------------------------------------------------------------------- c call showall(z,n1,n2,n3) c-------------------------------------------------------------------*/ } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void showall(double ***z, int n1, int n2, int n3) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i1,i2,i3; int m1, m2, m3; m1 = min(n1,18); m2 = min(n2,14); m3 = min(n3,18); printf("\n"); for (i3 = 0; i3 < m3; i3++) { for (i1 = 0; i1 < m1; i1++) { for (i2 = 0; i2 < m2; i2++) { printf("%6.3f", z[i3][i2][i1]); } printf("\n"); } printf(" - - - - - - - \n"); } printf("\n"); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static double power( double a, int n ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c power raises an integer, disguised as a double c precision real, to an integer power c-------------------------------------------------------------------*/ double aj; int nj; double rdummy; double power; power = 1.0; nj = n; aj = a; while (nj != 0) { if( (nj%2) == 1 ) rdummy = randlc( &power, aj ); rdummy = randlc( &aj, aj ); nj = nj/2; } return (power); } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void bubble( double ten[M][2], int j1[M][2], int j2[M][2], int j3[M][2], int m, int ind ) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ /*-------------------------------------------------------------------- c bubble does a bubble sort in direction dir c-------------------------------------------------------------------*/ double temp; int i, j_temp; if ( ind == 1 ) { for (i = 0; i < m-1; i++) { if ( ten[i][ind] > ten[i+1][ind] ) { temp = ten[i+1][ind]; ten[i+1][ind] = ten[i][ind]; ten[i][ind] = temp; j_temp = j1[i+1][ind]; j1[i+1][ind] = j1[i][ind]; j1[i][ind] = j_temp; j_temp = j2[i+1][ind]; j2[i+1][ind] = j2[i][ind]; j2[i][ind] = j_temp; j_temp = j3[i+1][ind]; j3[i+1][ind] = j3[i][ind]; j3[i][ind] = j_temp; } else { return; } } } else { for (i = 0; i < m-1; i++) { if ( ten[i][ind] < ten[i+1][ind] ) { temp = ten[i+1][ind]; ten[i+1][ind] = ten[i][ind]; ten[i][ind] = temp; j_temp = j1[i+1][ind]; j1[i+1][ind] = j1[i][ind]; j1[i][ind] = j_temp; j_temp = j2[i+1][ind]; j2[i+1][ind] = j2[i][ind]; j2[i][ind] = j_temp; j_temp = j3[i+1][ind]; j3[i+1][ind] = j3[i][ind]; j3[i][ind] = j_temp; } else { return; } } } } /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ static void zero3(double ***z, int n1, int n2, int n3) { /*-------------------------------------------------------------------- c-------------------------------------------------------------------*/ int i1, i2, i3; #pragma omp for for (i3 = 0;i3 < n3; i3++) { for (i2 = 0; i2 < n2; i2++) { for (i1 = 0; i1 < n1; i1++) { z[i3][i2][i1] = 0.0; } } } } /*---- end of program ------------------------------------------------*/ /* cat ./common/c_print_results.c */ /*****************************************************************/ /****** C _ P R I N T _ R E S U L T S ******/ /*****************************************************************/ void c_print_results( char *name, char cclass, int n1, int n2, int n3, int niter, int nthreads, double t, double mops, char *optype, int passed_verification, char *npbversion, char *compiletime, char *cc, char *clink, char *c_lib, char *c_inc, char *cflags, char *clinkflags, char *rand) { char *evalue="1000"; printf( "\n\n %s Benchmark Completed\n", name ); printf( " Class = %c\n", cclass ); if( n2 == 0 && n3 == 0 ) printf( " Size = %12d\n", n1 ); /* as in IS */ else printf( " Size = %3dx%3dx%3d\n", n1,n2,n3 ); printf( " Iterations = %12d\n", niter ); printf( " Threads = %12d\n", nthreads ); printf( " Time in seconds = %12.2f\n", t ); printf( " Mop/s total = %12.2f\n", mops ); printf( " Operation type = %24s\n", optype); if( passed_verification ) printf( " Verification = SUCCESSFUL\n" ); else printf( " Verification = UNSUCCESSFUL\n" ); printf( " Version = %12s\n", npbversion ); printf( " Compile date = %12s\n", compiletime ); printf( "\n Compile options:\n" ); printf( " CC = %s\n", cc ); printf( " CLINK = %s\n", clink ); printf( " C_LIB = %s\n", c_lib ); printf( " C_INC = %s\n", c_inc ); printf( " CFLAGS = %s\n", cflags ); printf( " CLINKFLAGS = %s\n", clinkflags ); printf( " RAND = %s\n", rand ); #ifdef SMP evalue = getenv("MP_SET_NUMTHREADS"); printf( " MULTICPUS = %s\n", evalue ); #endif /* printf( "\n\n" ); printf( " Please send the results of this run to:\n\n" ); printf( " NPB Development Team\n" ); printf( " Internet: npb@nas.nasa.gov\n \n" ); printf( " If email is not available, send this to:\n\n" ); printf( " MS T27A-1\n" ); printf( " NASA Ames Research Center\n" ); printf( " Moffett Field, CA 94035-1000\n\n" ); printf( " Fax: 415-604-3957\n\n" );*/ } /* cat ./common/c_randdp.c */ #if defined(USE_POW) #define r23 pow(0.5, 23.0) #define r46 (r23*r23) #define t23 pow(2.0, 23.0) #define t46 (t23*t23) #else #define r23 (0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5*0.5) #define r46 (r23*r23) #define t23 (2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0*2.0) #define t46 (t23*t23) #endif /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ double randlc (double *x, double a) { /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ /*c--------------------------------------------------------------------- c c This routine returns a uniform pseudorandom double precision number in the c range (0, 1) by using the linear congruential generator c c x_{k+1} = a x_k (mod 2^46) c c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers c before repeating. The argument A is the same as 'a' in the above formula, c and X is the same as x_0. A and X must be odd double precision integers c in the range (1, 2^46). The returned value RANDLC is normalized to be c between 0 and 1, i.e. RANDLC = 2^(-46) * x_1. X is updated to contain c the new seed x_1, so that subsequent calls to RANDLC using the same c arguments will generate a continuous sequence. c c This routine should produce the same results on any computer with at least c 48 mantissa bits in double precision floating point data. On 64 bit c systems, double precision should be disabled. c c David H. Bailey October 26, 1990 c c---------------------------------------------------------------------*/ double t1,t2,t3,t4,a1,a2,x1,x2,z; /*c--------------------------------------------------------------------- c Break A into two parts such that A = 2^23 * A1 + A2. c---------------------------------------------------------------------*/ t1 = r23 * a; a1 = (int)t1; a2 = a - t23 * a1; /*c--------------------------------------------------------------------- c Break X into two parts such that X = 2^23 * X1 + X2, compute c Z = A1 * X2 + A2 * X1 (mod 2^23), and then c X = 2^23 * Z + A2 * X2 (mod 2^46). c---------------------------------------------------------------------*/ t1 = r23 * (*x); x1 = (int)t1; x2 = (*x) - t23 * x1; t1 = a1 * x2 + a2 * x1; t2 = (int)(r23 * t1); z = t1 - t23 * t2; t3 = t23 * z + a2 * x2; t4 = (int)(r46 * t3); (*x) = t3 - t46 * t4; return (r46 * (*x)); } /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ void vranlc (int n, double *x_seed, double a, double* y) { /* void vranlc (int n, double *x_seed, double a, double y[]) { */ /*c--------------------------------------------------------------------- c---------------------------------------------------------------------*/ /*c--------------------------------------------------------------------- c c This routine generates N uniform pseudorandom double precision numbers in c the range (0, 1) by using the linear congruential generator c c x_{k+1} = a x_k (mod 2^46) c c where 0 < x_k < 2^46 and 0 < a < 2^46. This scheme generates 2^44 numbers c before repeating. The argument A is the same as 'a' in the above formula, c and X is the same as x_0. A and X must be odd double precision integers c in the range (1, 2^46). The N results are placed in Y and are normalized c to be between 0 and 1. X is updated to contain the new seed, so that c subsequent calls to VRANLC using the same arguments will generate a c continuous sequence. If N is zero, only initialization is performed, and c the variables X, A and Y are ignored. c c This routine is the standard version designed for scalar or RISC systems. c However, it should produce the same results on any single processor c computer with at least 48 mantissa bits in double precision floating point c data. On 64 bit systems, double precision should be disabled. c c---------------------------------------------------------------------*/ int i; double x,t1,t2,t3,t4,a1,a2,x1,x2,z; /*c--------------------------------------------------------------------- c Break A into two parts such that A = 2^23 * A1 + A2. c---------------------------------------------------------------------*/ t1 = r23 * a; a1 = (int)t1; a2 = a - t23 * a1; x = *x_seed; /*c--------------------------------------------------------------------- c Generate N results. This loop is not vectorizable. c---------------------------------------------------------------------*/ for (i = 1; i <= n; i++) { /*c--------------------------------------------------------------------- c Break X into two parts such that X = 2^23 * X1 + X2, compute c Z = A1 * X2 + A2 * X1 (mod 2^23), and then c X = 2^23 * Z + A2 * X2 (mod 2^46). c---------------------------------------------------------------------*/ t1 = r23 * x; x1 = (int)t1; x2 = x - t23 * x1; t1 = a1 * x2 + a2 * x1; t2 = (int)(r23 * t1); z = t1 - t23 * t2; t3 = t23 * z + a2 * x2; t4 = (int)(r46 * t3); x = t3 - t46 * t4; y[i] = r46 * x; } *x_seed = x; } /* cat ./common/c_timers.c */ /* #include "wtime.h" #if defined(IBM) #define wtime wtime #elif defined(CRAY) #define wtime WTIME #else #define wtime wtime_ #endif */ /* Prototype */ void wtime( double * ); /*****************************************************************/ /****** E L A P S E D _ T I M E ******/ /*****************************************************************/ double elapsed_time( void ) { double t; wtime( &t ); return( t ); } double start[64], elapsed[64]; /*****************************************************************/ /****** T I M E R _ C L E A R ******/ /*****************************************************************/ void timer_clear( int n ) { elapsed[n] = 0.0; } /*****************************************************************/ /****** T I M E R _ S T A R T ******/ /*****************************************************************/ void timer_start( int n ) { start[n] = elapsed_time(); } /*****************************************************************/ /****** T I M E R _ S T O P ******/ /*****************************************************************/ void timer_stop( int n ) { double t, now; now = elapsed_time(); t = now - start[n]; elapsed[n] += t; } /*****************************************************************/ /****** T I M E R _ R E A D ******/ /*****************************************************************/ double timer_read( int n ) { return( elapsed[n] ); } void wtime(double *t) { static int sec = -1; struct timeval tv; gettimeofday(&tv, (void *)0); // gettimeofday(&tv, (struct timezone *)0); if (sec < 0) sec = tv.tv_sec; *t = (tv.tv_sec - sec) + 1.0e-6*tv.tv_usec; }
tree-dependencias.c
#include <malloc.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "omp.h" #include <sys/time.h> double getusec_() { struct timeval time; gettimeofday(&time, NULL); return ((double)time.tv_sec * (double)1e6 + (double)time.tv_usec); } #define START_COUNT_TIME stamp = getusec_(); #define STOP_COUNT_TIME(_m) stamp = getusec_() - stamp;\ stamp = stamp/1e6;\ printf ("%s: %0.6f\n",(_m), stamp); // N and MIN must be powers of 2 long N; long MIN_SORT_SIZE; long MIN_MERGE_SIZE; int CUTOFF; #define T int void basicsort(long n, T data[n]); void basicmerge(long n, T left[n], T right[n], T result[n*2], long start, long length); void merge(long n, T left[n], T right[n], T result[n*2], long start, long length,int i) { if (length < MIN_MERGE_SIZE*2L || omp_in_final()) { // Base case basicmerge(n, left, right, result, start, length); } else { // Recursive decomposition #pragma omp task final(i == CUTOFF) depend(in: left[0], right[0]) merge(n, left, right, result, start, length/2,i+1); #pragma omp task final(i == CUTOFF) depend(in: left[length/2], right[length/2]) merge(n, left, right, result, start + length/2, length/2,i+1); #pragma omp taskwait } } void multisort(long n, T data[n], T tmp[n],int i) { //if(omp_in_final()) printf ("\na\n"); if (n >= MIN_SORT_SIZE*4L && !omp_in_final()) { // Recursive decomposition #pragma omp task final(i == CUTOFF) depend(out: data[0]) multisort(n/4L, &data[0], &tmp[0],i+1); #pragma omp task final(i == CUTOFF) depend(out: data[n/4L]) multisort(n/4L, &data[n/4L], &tmp[n/4L],i+1); #pragma omp task final(i == CUTOFF) depend(out: data[n/2L]) multisort(n/4L, &data[n/2L], &tmp[n/2L],i+1); #pragma omp task final(i == CUTOFF) depend(out: data[3L*n/4L]) multisort(n/4L, &data[3L*n/4L], &tmp[3L*n/4L],i+1); #pragma omp task final(i == CUTOFF) depend(in: data[0], data[n/4L]) depend(out: tmp[0]) merge(n/4L, &data[0], &data[n/4L], &tmp[0], 0, n/2L,i+1); #pragma omp task final(i == CUTOFF) depend(in: data[N/2L], data[3L*n/4L]) depend(out: tmp[n/2L]) merge(n/4L, &data[n/2L], &data[3L*n/4L], &tmp[n/2L], 0, n/2L,i+1); #pragma omp task final(i == CUTOFF) depend(in: tmp[0], tmp[n/2L]) merge(n/2L, &tmp[0], &tmp[n/2L], &data[0], 0, n,i+1); #pragma omp taskwait } else { // Base case basicsort(n, data); } } static void initialize(long length, T data[length]) { long i; for (i = 0; i < length; i++) { if (i==0) { data[i] = rand(); } else { data[i] = ((data[i-1]+1) * i * 104723L) % N; } } } static void clear(long length, T data[length]) { long i; for (i = 0; i < length; i++) { data[i] = 0; } } void check_sorted(long n, T data[n]) { int unsorted=0; for (int i=1; i<n; i++) if (data[i-1] > data[i]) unsorted++; if (unsorted > 0) printf ("\nERROR: data is NOT properly sorted. There are %d unordered positions\n\n",unsorted); } int main(int argc, char **argv) { /* Defaults for command line arguments */ /* Important: all of them should be powers of two */ N = 32768 * 1024; MIN_SORT_SIZE = 1024; MIN_MERGE_SIZE = 1024; CUTOFF = 4; /* Process command-line arguments */ for (int i=1; i<argc; i++) { if (strcmp(argv[i], "-n")==0) { N = atol(argv[++i]) * 1024; } else if (strcmp(argv[i], "-s")==0) { MIN_SORT_SIZE = atol(argv[++i]); } else if (strcmp(argv[i], "-m")==0) { MIN_MERGE_SIZE = atol(argv[++i]); } #ifdef _OPENMP else if (strcmp(argv[i], "-c")==0) { CUTOFF = atoi(argv[++i]); } #endif else { #ifdef _OPENMP fprintf(stderr, "Usage: %s [-n vector_size -s MIN_SORT_SIZE -m MIN_MERGE_SIZE] -c CUTOFF\n", argv[0]); #else fprintf(stderr, "Usage: %s [-n vector_size -s MIN_SORT_SIZE -m MIN_MERGE_SIZE]\n", argv[0]); #endif fprintf(stderr, " -n to specify the size of the vector (in Kelements) to sort (default 32768)\n"); fprintf(stderr, " -s to specify the size of the vector (in elements) that breaks recursion in the sort phase (default 1024)\n"); fprintf(stderr, " -m to specify the size of the vector (in elements) that breaks recursion in the merge phase (default 1024)\n"); #ifdef _OPENMP fprintf(stderr, " -c to specify the cut off recursion level to stop task generation in OpenMP (default 16)\n"); #endif return EXIT_FAILURE; } } fprintf(stdout, "*****************************************************************************************\n"); fprintf(stdout, "Problem size (in number of elements): N=%ld, MIN_SORT_SIZE=%ld, MIN_MERGE_SIZE=%ld\n", N/1024, MIN_SORT_SIZE, MIN_MERGE_SIZE); #ifdef _OPENMP fprintf(stdout, "Cut-off level: CUTOFF=%d\n", CUTOFF); fprintf(stdout, "Number of threads in OpenMP: OMP_NUM_THREADS=%d\n", omp_get_max_threads()); #endif fprintf(stdout, "*****************************************************************************************\n"); T *data = malloc(N*sizeof(T)); T *tmp = malloc(N*sizeof(T)); double stamp; START_COUNT_TIME; initialize(N, data); clear(N, tmp); STOP_COUNT_TIME("Initialization time in seconds"); START_COUNT_TIME; #pragma omp parallel #pragma omp single multisort(N, data, tmp,0); STOP_COUNT_TIME("Multisort execution time"); START_COUNT_TIME; check_sorted (N, data); STOP_COUNT_TIME("Check sorted data execution time"); fprintf(stdout, "Multisort program finished\n"); fprintf(stdout, "*****************************************************************************************\n"); return 0; }
DRB104-nowait-barrier-orig-no.c
/* Copyright (c) 2017, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory Written by Chunhua Liao, Pei-Hung Lin, Joshua Asplund, Markus Schordan, and Ian Karlin (email: liao6@llnl.gov, lin32@llnl.gov, asplund1@llnl.gov, schordan1@llnl.gov, karlin1@llnl.gov) LLNL-CODE-732144 All rights reserved. This file is part of DataRaceBench. For details, see https://github.com/LLNL/dataracebench. Please also see the LICENSE file for our additional BSD notice. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer below. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer (as noted below) in the documentation and/or other materials provided with the distribution. * Neither the name of the LLNS/LLNL nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL LAWRENCE LIVERMORE NATIONAL SECURITY, LLC, THE U.S. DEPARTMENT OF ENERGY OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* This example is based on one code snippet extracted from a paper: Ma etc. Symbolic Analysis of Concurrency Errors in OpenMP Programs, ICPP 2013 Explicit barrier to counteract nowait */ #include <stdio.h> #include <assert.h> #include <omp.h> int main() { int i; int error; int len = 1000; int a[len]; int b = 5; #pragma omp parallel for private (i) for (i = 0; i <= len - 1; i += 1) { a[i] = i; } { #pragma omp parallel for private (i) firstprivate (len,b) for (i = 0; i <= len - 1; i += 1) { a[i] = b + a[i] * 5; } } error = a[9] + 1; (((void )(sizeof(((error == 51?1 : 0))))) , (( { if (error == 51) ; else __assert_fail("error == 51","DRB104-nowait-barrier-orig-no.c",70,__PRETTY_FUNCTION__); }))); printf("error = %d\n",error); return 0; }
CPUMatrixImpl.h
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.md file in the project root for full license information. // // CPUMatrix.h : template implementation of all matrix functions on the CPU side // #pragma once #include "Basics.h" #include "File.h" #include "CPUMatrix.h" #include "TensorOps.h" #include <assert.h> #include <stdexcept> #include <omp.h> #include <math.h> #include <random> #include <chrono> #include <exception> #include <thread> #include <iostream> #include <algorithm> #include <numeric> #pragma warning(push) #pragma warning(disable:4244) // 'conversion' conversion from 'type1' to 'type2', possible loss of data #include <boost/random/normal_distribution.hpp> #pragma warning(pop) #include <boost/random/uniform_real_distribution.hpp> #ifdef _WIN32 #define NOMINMAX #include "Windows.h" #else #include <cfloat> #endif #ifdef LEAKDETECT #include <vld.h> #endif #pragma warning(disable : 4100) // unreferenced formal parameter; "struct TensorOpReduction<ElemType, OPFN, typename ReductionOp, N, -1>" trigger this #pragma warning(disable : 4127) // conditional expression is constant; "if (sizeof(ElemType)==sizeof(float))" triggers this #pragma warning(disable : 4244) // unreachable code; triggered for unknown reasons #pragma warning(disable : 4702) // conversion from 'double' to 'float' #ifdef USE_MKL // requires MKLML 0.11 and above #include <mkl_cblas.h> #include <mkl_lapacke.h> #include <mkl_service.h> #else #ifdef _MSC_VER // Visual Studio doesn't define standard complex types properly #define HAVE_LAPACK_CONFIG_H #define LAPACK_COMPLEX_STRUCTURE #endif #include <cblas.h> #include <lapacke.h> #endif #define SWAP(a, b) \ { \ (a) ^= (b); \ (b) ^= (a); \ (a) ^= (b); \ } #define IDX2C(i, j, ld) (((j) * (ld)) + (i)) // 0 based indexing namespace Microsoft { namespace MSR { namespace CNTK { #pragma region Helpful Enum Definitions enum class MatrixOrder { RowMajor = 101, // row-major arrays ColMajor = 102 // column-major arrays }; enum class MatrixTranspose : char { NoTrans = 'N', // trans='N' Trans = 'T', // trans='T' ConjTrans = 'C' // trans='C' }; enum class SymMatrixType : char { Up = 'U', // symmetric matrix is stored in the upper part Low = 'L', // symmetric matrix is stored in the lower part Full = 'F', // full populated NotSymmetric = 'N' // not a symmetric matrix }; enum class MatrixOpSide : char { Left = 'L', // left multiply Right = 'R', // right multiply }; #pragma endregion Helpful Enum Definitions #pragma region Constructors and Destructor template <class ElemType> CPUMatrix<ElemType>::CPUMatrix() { ZeroInit(); } // helper to allocate an array of ElemType // Use this instead of new[] to get NaN initialization for debugging. template <class ElemType> static ElemType* NewArray(size_t n) { // We need to allocate possibly one more element for the following reason. // At some point we might want to fill a buffer with the result of a random // number generator. The RNG is oblivious to whether the buffer is on the // CPU or GPU but it needs to keep an accurate tally of how many numbers it // has generated. The trouble stems from the fact that generating an odd // number gaussians on the GPU is not supported so we must always // generate an even number. So since we wouldn't know how to update the tally // we are making this allocate one more element in the worst case. ElemType* p = new ElemType[AsMultipleOf(n, 2)](); #if 0 // _DEBUG ElemType nan = Matrix<ElemType>::MakeNan(__LINE__); for (size_t i = 0; i < n; i++) p[i] = nan; #endif return p; } template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols) { ZeroInit(); m_numRows = numRows; m_numCols = numCols; SetSizeAllocated(GetNumElements()); if (GetNumElements() != 0) { SetBuffer(NewArray<ElemType>(GetNumElements()), GetNumElements() * sizeof(ElemType)); } } template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags) { ZeroInit(); SetValue(numRows, numCols, pArray, matrixFlags); } //copy constructor, deep copy template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& deepCopyFrom) { ZeroInit(); SetValue(deepCopyFrom); } //assignment operator, deep copy template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(const CPUMatrix<ElemType>& deepCopyFrom) { SetValue(deepCopyFrom); return *this; } //move constructor, shallow copy template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(CPUMatrix<ElemType>&& moveFrom) : Base(/* shallow */ true) { ShallowCopyFrom(moveFrom); moveFrom.ZeroValues(); } // Shortcut of default constructor + shallow copy, to avoid one initialization template <class ElemType> CPUMatrix<ElemType>::CPUMatrix(const CPUMatrix<ElemType>& shallowCopyFrom, bool shallow) : Base(shallow) { ShallowCopyFrom(shallowCopyFrom); } //move assignment operator, shallow copy template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator=(CPUMatrix<ElemType>&& moveFrom) { if (this != &moveFrom) { ShallowCopyFrom(moveFrom); // release the pointer from the source object so that the destructor won't release it twice moveFrom.ZeroValues(); } return *this; } template <class ElemType> void CPUMatrix<ElemType>::Clear() { ZeroInit(); } #pragma endregion Constructors and Destructor #pragma region Basic Operators template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::ColumnSlice(size_t startColumn, size_t numCols) const { if (startColumn + numCols > m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) m_numCols); CPUMatrix<ElemType> slice(*this, /* shallow= */ true); slice.m_numCols = numCols; slice.m_sliceViewOffset = m_sliceViewOffset + startColumn * m_numRows; return slice; } // set this(:, 0:numCols-1) = fromMatrix(:, startColumn : startColumn+numCols-1) // TODO: why not say *this = ColumnSlice()? template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols) { if (startColumn + numCols > fromMatrix.m_numCols) InvalidArgument("The slice (%d+%d) is out of range of the source matrix (%d).", (int) startColumn, (int) numCols, (int) fromMatrix.m_numCols); Clear(); ShallowCopyFrom(fromMatrix); m_numCols = numCols; m_sliceViewOffset = fromMatrix.m_sliceViewOffset + startColumn * m_numRows; return *this; } // set this(: , startColumn:startColumn+numCols-1)= fromMatrix; template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::SetColumnSlice(const CPUMatrix<ElemType>& fromMatrix, size_t startColumn, size_t numCols) { if (startColumn + numCols > m_numCols) LogicError("The slice is out of range of the destination matrix."); if (numCols > fromMatrix.GetNumCols()) InvalidArgument("The slice (%d) is out of range of the source matrix (%d).", (int) numCols, (int) fromMatrix.GetNumCols()); if (m_numRows != fromMatrix.m_numRows) LogicError("The number of rows in source and destination matrices do not match"); memcpy(Data() + startColumn * m_numRows, fromMatrix.Data(), numCols * m_numRows * sizeof(ElemType)); return *this; } template <class ElemType> void CPUMatrix<ElemType>::CopyColumnsStrided(const CPUMatrix<ElemType>& fromMatrix, size_t numCols, size_t srcNumColsStride, size_t destNumColsStride) { if ((((numCols - 1) * srcNumColsStride) + 1) > fromMatrix.m_numCols) LogicError("The numCols to copy and srcNumColsStride specified is out of range of the source matrix."); if ((((numCols - 1) * destNumColsStride) + 1) > m_numCols) LogicError("The numCols to copy and srcNumColsStride specified is out of range of the destination matrix."); if (m_numRows != fromMatrix.m_numRows) LogicError("The number of rows in source and destination matrices do not match"); long n = (long) numCols, m = (long) m_numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (size_t i = 0; i < (m & ~3); i += 4) { us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride); us(i + 1, j * destNumColsStride) = fromMatrix(i + 1, j * srcNumColsStride); us(i + 2, j * destNumColsStride) = fromMatrix(i + 2, j * srcNumColsStride); us(i + 3, j * destNumColsStride) = fromMatrix(i + 3, j * srcNumColsStride); } // handle remaining for (size_t i = m & ~3; i < m; i++) { us(i, j * destNumColsStride) = fromMatrix(i, j * srcNumColsStride); } } } //for each column of a, we add all rows of a to this starting from startIndex template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.GetNumRows() != numRows) LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddToRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (size_t i = 0, startRow = startIndex; i < (m & ~3); i += 4, startRow += 4) { us(startRow, j) = a(i, j); us(startRow + 1, j) = a(i + 1, j); us(startRow + 2, j) = a(i + 2, j); us(startRow + 3, j) = a(i + 3, j); } // handle remaining stuffs for (size_t i = m & ~3, startRow = startIndex + (m & ~3); i < m; i++, startRow++) { us(startRow, j) = a(i, j); } } return *this; } //for each column of a, we assign numRows starting from startIndex to this template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (startIndex + numRows > a.GetNumRows()) LogicError("AssignRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); RequireSize(numRows, a.GetNumCols()); long n = (long) a.GetNumCols(); // note: OpenMP requires loop indices to be long, not size_t long k = (long) a.GetNumRows(); #pragma omp parallel for for (long j = 0; j < n; j++) { // memory copy might be faster? memcpy(Data() + j * numRows, a.Data() + j * k + startIndex, sizeof(ElemType) * numRows); // //four-way unrolling // for (long i=0, startRow = startIndex; i<(m & ~3); i+=4, startRow+=4) // { // us(i,j) = a(startRow,j); // us(i+1,j) = a(startRow+1,j); // us(i+2,j) = a(startRow+2,j); // us(i+3,j) = a(startRow+3,j); // } // //handle remaining stuffs // for (long i=m & ~3, startRow = startIndex+(m & ~3); i<m; i++, startRow++) // { // us(i,j) = a(startRow,j); // } } return *this; } //for the row slice of this starting from startIndex we add a to it. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) LogicError("AddToRowSliceValuesOf: input matrix a is empty."); if (a.GetNumRows() != numRows) LogicError("AddToRowSliceValuesOf: a.GetNumRows() != numRows."); if (startIndex + numRows > GetNumRows()) LogicError("AddToRowSliceValuesOf: startIndex + numRows exceeds GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddToRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4) { us(startRow, j) += a(i, j); us(startRow + 1, j) += a(i + 1, j); us(startRow + 2, j) += a(i + 2, j); us(startRow + 3, j) += a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++) { us(startRow, j) += a(i, j); } } return *this; } //for each column of this, we add row slice of a starting from startIndex template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithRowSliceValuesOf(const CPUMatrix<ElemType>& a, const size_t startIndex, const size_t numRows) { if (a.IsEmpty()) LogicError("AddWithRowSliceValuesOf: input matrix a is empty."); if (GetNumRows() != numRows) LogicError("AddWithRowSliceValuesOf: GetNumRows() != numRows."); if (startIndex + numRows > a.GetNumRows()) LogicError("AddWithRowSliceValuesOf: startIndex + numRows exceeds a.GetNumRows()."); if (a.GetNumCols() != GetNumCols()) LogicError("AddWithRowSliceValuesOf: columns does not match."); long n = (long) a.GetNumCols(), m = (long) numRows; auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0, startRow = (long) startIndex; i < (m & ~3); i += 4, startRow += 4) { us(i, j) += a(startRow, j); us(i + 1, j) += a(startRow + 1, j); us(i + 2, j) += a(startRow + 2, j); us(i + 3, j) += a(startRow + 3, j); } // handle remaining stuffs for (long i = m & ~3, startRow = (long) startIndex + (m & ~3); i < m; i++, startRow++) { us(i, j) += a(startRow, j); } } return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Diagonal() const { if (m_numRows != m_numCols) LogicError("Diagonal can be called only for square matrix. (rows=%d, cols=%d)", (int) m_numRows, (int) m_numCols); CPUMatrix<ElemType> diag(1, m_numCols); auto& us = *this; #pragma omp parallel for for (long i = 0; i < m_numRows; i++) { diag(0, (size_t) i) = us(i, i); } return diag; } template <class ElemType> void CPUMatrix<ElemType>::MinusOneAt(CPUMatrix<ElemType>& c, const size_t position) { if (position < c.GetNumElements()) c.Data()[position] -= 1.0; else RuntimeError("MinusOneAt: position is out of CPU matrix size"); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignRepeatOf(const CPUMatrix<ElemType>& a, const size_t numRowRepeats, const size_t numColRepeats) { if (this == &a) LogicError("AssignRepeatOf: a is the same as [this]. Does not support inplace repeat."); if (a.IsEmpty()) LogicError("AssignRepeatOf: Matrix a is empty."); RequireSize(a.GetNumRows() * numRowRepeats, a.GetNumCols() * numColRepeats); long n = (long) a.GetNumCols(), m = (long) a.GetNumRows(); auto& us = *this; #pragma omp parallel for for (long q = 0; q < numColRepeats; q++) { for (long p = 0; p < numRowRepeats; p++) { long colOffset = q * n; for (long j = 0; j < n; j++, colOffset++) { long rowOffset = p * m; // four-way unrolling for (long i = 0; i < (m & ~3); i += 4, rowOffset += 4) { us(rowOffset, colOffset) = a(i, j); us(rowOffset + 1, colOffset) = a(i + 1, j); us(rowOffset + 2, colOffset) = a(i + 2, j); us(rowOffset + 3, colOffset) = a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++, rowOffset++) { us(rowOffset, colOffset) = a(i, j); } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddToRowRepeatValuesOf(const CPUMatrix<ElemType>& a, const size_t numRepeats) { if (a.IsEmpty()) LogicError("AddToRowRepeatValuesOf: input matrix a is empty."); if (a.GetNumRows() != GetNumRows() * numRepeats) LogicError("AddToRowRepeatValuesOf: a.GetNumRows() != GetNumRows() * numRepeats."); long n = (long) a.GetNumCols(), m = (long) GetNumRows(); auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { for (long k = 0; k < numRepeats; k++) { us(i, j) += a(k * m + i, j); us(i + 1, j) += a(k * m + i + 1, j); us(i + 2, j) += a(k * m + i + 2, j); us(i + 3, j) += a(k * m + i + 3, j); } } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { for (long k = 0; k < numRepeats; k++) { us(i, j) += a(k * m + i, j); } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { a; posNumber; negNumber; shiftNumber; NOT_IMPLEMENTED; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddFoldedPositiveAndShiftedNegSample(const CPUMatrix<ElemType>& a, const size_t posNumber, const size_t negNumber, const size_t shiftNumber) { a; posNumber; negNumber; shiftNumber; NOT_IMPLEMENTED; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Transpose() { if (IsEmpty()) LogicError("Transpose: Matrix is empty."); CPUMatrix<ElemType> c; c.AssignTransposeOf(*this); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTransposeOf(const CPUMatrix<ElemType>& a) { if (this == &a) LogicError("AssignTransposeOf: a is the same as [this]. Does not support inplace transpose."); if (a.IsEmpty()) LogicError("AssignTransposeOf: Matrix a is empty."); RequireSize(a.GetNumCols(), a.GetNumRows()); long n = (long) a.GetNumCols(), m = (long) a.GetNumRows(); auto& us = *this; #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(j, i) = a(i, j); us(j, i + 1) = a(i + 1, j); us(j, i + 2) = a(i + 2, j); us(j, i + 3) = a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(j, i) = a(i, j); } } return *this; } // dst[i] = src[i] * alpha + dst[i] * beta // scale a column vector and add it to another // The usual special case: If beta = 0, then dst[] is not read, and may be uninitialized or NaN. template <class ElemType> static void ScaleAndAddColumn(ElemType beta, ElemType* dst, const ElemType* src, size_t numRows, ElemType alpha) { if (alpha != 1) // rare case: just do the full thing for (size_t i = 0; i < numRows; i++) dst[i] = beta * dst[i] + alpha * src[i]; else if (beta == 1) // used in backprop for (size_t i = 0; i < numRows; i++) dst[i] += src[i]; else if (beta == 0) // plain assignment memcpy(dst, src, sizeof(ElemType) * numRows); else // alpha=1, arbitrary beta: also rare case for (size_t i = 0; i < numRows; i++) dst[i] = beta * dst[i] + src[i]; } // *this[:,j] = a[:,idx[j]] * alpha + *this[:,j] * beta template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DoGatherColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha) { if (idx.GetNumRows() != 1) // index is 1-dimensional only InvalidArgument("DoGatherColumnsOf: Map must be a row vector."); if (beta) VerifySize(a.GetNumRows(), idx.GetNumCols()); else Resize(a.GetNumRows(), idx.GetNumCols()); auto& us = *this; // race-condition consideration: Since this loops over independent output columns, this has no race condition. Cf. DoScatterColumnsOf(). #pragma omp parallel for // TODO: Depending in circumstance, it may be more efficient to parallelize over rows. foreach_column(jOut, us) { auto jInF = idx(0, jOut); // this is the column we need to get if (std::isnan(jInF) || jInF < 0) // negative index means gap continue; size_t jIn = (size_t)jInF; if (jIn >= a.GetNumCols()) InvalidArgument("DoGatherColumnsOf: Map out of bounds. %ld >= %ld", (long int)jIn, (long int)a.GetNumCols()); ScaleAndAddColumn(beta, &us(0,jOut), &a(0,jIn), us.GetNumRows(), alpha); } return *this; } // *this[:,idx[j]] = a[:,j] * alpha + *this[:,idx[j]] * beta template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DoScatterColumnsOf(ElemType beta, const CPUMatrix<ElemType>& idx, const CPUMatrix<ElemType>& a, ElemType alpha) { if (idx.GetNumRows() != 1) // index is 1-dimensional only InvalidArgument("DoScatterColumnsOf: Map must be a row vector."); if (idx.GetNumCols() != a.GetNumCols()) InvalidArgument("DoScatterColumnsOf: Map must have width of input vector."); if (a.GetNumRows() != GetNumRows()) InvalidArgument("DoScatterColumnsOf: Output must have same height as input vector."); auto& us = *this; // pre-scale with beta upfront // Scatter may add more than one source column to the same target, so we must pre-scale with beta, and then just keep adding. Scale(beta, us); // if beta is 0, then this will be a memset() ScatterValues(idx.Data(), a.Data(), us.Data(), alpha, idx.GetNumCols(), a.GetNumRows(), GetNumCols(), idx.GetNumRows()); return *this; } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const ElemType v) { if (IsEmpty()) LogicError("SetValue: Matrix is empty."); bool isFinite = std::numeric_limits<ElemType>::is_integer || std::isfinite((double) v); if (isFinite && v == 0) { memset(Data(), 0, sizeof(ElemType) * GetNumElements()); } else { ElemType* bufPtr = Data(); long m = (long) GetNumElements(); // 2-way thread parallelism is sufficient for the memory bound // operation of just setting the values of an array. const unsigned SETVALUE_NUM_THREADS = 2; UNUSED(SETVALUE_NUM_THREADS); // in case OMP is turned off. #pragma omp parallel for num_threads(SETVALUE_NUM_THREADS) // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { bufPtr[i] = v; bufPtr[i + 1] = v; bufPtr[i + 2] = v; bufPtr[i + 3] = v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { bufPtr[i] = v; } } } template <class ElemType> void CPUMatrix<ElemType>::MaskColumnsValue(const CPUMatrix<char>& columnsMask, ElemType val, size_t numColsPerMaskEntry) { if (GetNumCols() != (columnsMask.GetNumCols() * numColsPerMaskEntry)) RuntimeError("MaskColumnsValue: Matrix number of columns must equal 'column mask number of columns * numColsPerMaskEntry'."); auto& us = *this; long n = (long)columnsMask.GetNumCols(), m = (long) GetNumRows(); #pragma omp parallel for for (long j = 0; j < n; j++) { if (columnsMask(0, j) == 1) continue; for (long k = 0; k < numColsPerMaskEntry; ++k) { // four-way unrolling for (size_t i = 0; i < (m & ~3); i += 4) { us(i, (j * numColsPerMaskEntry) + k) = val; us(i + 1, (j * numColsPerMaskEntry) + k) = val; us(i + 2, (j * numColsPerMaskEntry) + k) = val; us(i + 3, (j * numColsPerMaskEntry) + k) = val; } // handle remaining for (size_t i = m & ~3; i < m; i++) { us(i, (j * numColsPerMaskEntry) + k) = val; } } } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const ElemType* colPointer, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); if (colPointer == NULL) return; auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = colPointer[i]; us(i + 1, j) = colPointer[i + 1]; us(i + 2, j) = colPointer[i + 2]; us(i + 3, j) = colPointer[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = colPointer[i]; } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const ElemType val, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = val; us(i + 1, j) = val; us(i + 2, j) = val; us(i + 3, j) = val; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = val; } } template <class ElemType> void CPUMatrix<ElemType>::SetColumn(const CPUMatrix<ElemType>& valMat, size_t j) { if (IsEmpty()) LogicError("SetColumn: Matrix is empty."); if (valMat.GetNumRows() != GetNumRows() || valMat.GetNumCols() != 1) LogicError("The valMat matrix has incorrect number of rows or columns."); auto& us = *this; long m = (long) GetNumRows(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = valMat(i, 0); us(i + 1, j) = valMat(i + 1, 0); us(i + 2, j) = valMat(i + 2, 0); us(i + 3, j) = valMat(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = valMat(i, 0); } } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const CPUMatrix<ElemType>& deepCopyFrom) { if (this == &deepCopyFrom) return; SetValue(deepCopyFrom.GetNumRows(), deepCopyFrom.GetNumCols(), deepCopyFrom.Data(), 0); } #if 0 template <class ElemType> void CPUMatrix<ElemType>::SetValue(const GPUMatrix<ElemType>& /*deepCopyFrom*/) { NOT_IMPLEMENTED; } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const CPUSparseMatrix<ElemType>& deepCopyFrom) { deepCopyFrom.AssignColumnSliceToDense(*this, 0, deepCopyFrom.GetNumCols()); } template <class ElemType> void CPUMatrix<ElemType>::SetValue(const GPUSparseMatrix<ElemType>& /*deepCopyFrom*/) { NOT_IMPLEMENTED; } #endif template <class ElemType> void CPUMatrix<ElemType>::SetValue(const size_t numRows, const size_t numCols, ElemType* pArray, const size_t matrixFlags) { if (pArray == nullptr && numRows * numCols > 0) InvalidArgument("Invalid pArray. pArray == nullptr, but matrix is of size %d * %d = %d.", (int)numRows, (int)numCols, (int)(numRows * numCols)); SetFormat(matrixFormatDense); SetComputeDeviceId(CPUDEVICE); // if it's externally managed, then populate the structure if (matrixFlags & matrixFlagDontOwnBuffer) { // free previous array allocation if any before overwriting delete[] Buffer(); m_numRows = numRows; m_numCols = numCols; SetBuffer(pArray, GetNumElements() * sizeof(ElemType), true); SetSizeAllocated(GetNumElements()); } else { RequireSize(numRows, numCols); if (!IsEmpty()) { if (!(matrixFlags & matrixFormatRowMajor)) // compatible to internal structure memcpy(Data(), pArray, GetNumElements() * sizeof(ElemType)); else // need to transpose { ElemType* bufPtr = Data(); auto& us = *this; if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_column (j, us) { cblas_dcopy((int) numRows, reinterpret_cast<double*>(pArray + j), (int) numCols, reinterpret_cast<double*>(bufPtr + LocateColumn(j)), 1); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_column (j, us) { { #pragma warning(suppress : 4244) cblas_scopy((int) numRows, reinterpret_cast<float*>(pArray + j), (int) numCols, reinterpret_cast<float*>(bufPtr + LocateColumn(j)), 1); } } } else { RuntimeError("Unsupported data format"); } } } } } template <class ElemType> void CPUMatrix<ElemType>::SetDiagonalValue(const ElemType v) { auto& us = *this; long m = static_cast<long>(GetDiagSize()); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = v; us(i + 1, i + 1) = v; us(i + 2, i + 2) = v; us(i + 3, i + 3) = v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = v; } } template <class ElemType> void CPUMatrix<ElemType>::SetDiagonalValue(const CPUMatrix<ElemType>& vector) { if (IsEmpty() || vector.IsEmpty()) LogicError("SetDiagonalValue: Matrix is empty."); if (vector.GetNumRows() != 1 && vector.GetNumCols() != 1) LogicError("SetDiagonalValue: input vector must be a vector."); if (vector.GetNumElements() == 1) // reduce to simple form SetDiagonalValue(vector(0, 0)); else if (vector.GetNumRows() != GetDiagSize() && vector.GetNumCols() != GetDiagSize()) LogicError("SetDiagonalValue: input vector's dimension does not agree with [this]."); else { auto& us = *this; long m = (long) GetDiagSize(); if (vector.GetNumRows() == 1) // row vector { #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = vector(0, i); us(i + 1, i + 1) = vector(0, i + 1); us(i + 2, i + 2) = vector(0, i + 2); us(i + 3, i + 3) = vector(0, i + 3); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = vector(0, i); } } else { #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, i) = vector(i, 0); us(i + 1, i + 1) = vector(i + 1, 0); us(i + 2, i + 2) = vector(i + 2, 0); us(i + 3, i + 3) = vector(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, i) = vector(i, 0); } } } } template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomValue(const ElemType low, const ElemType high, unsigned long seed) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); std::mt19937_64 generator; generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::uniform_real_distribution<double> r((double)low, (double)high); ElemType* bufPtr = Data(); long m = (long) GetNumElements(); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { bufPtr[i] = (ElemType)r(generator); bufPtr[i + 1] = (ElemType)r(generator); bufPtr[i + 2] = (ElemType)r(generator); bufPtr[i + 3] = (ElemType)r(generator); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { bufPtr[i] = (ElemType)r(generator); } } template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomValue(RNGHandle& rngHandle, const ElemType low, const ElemType high) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::uniform_real_distribution<double> r((double)low, (double)high); std::generate(Data(), Data() + GetNumElements(), [&cpuRNGHandle, &r]() {return (ElemType)r(cpuRNGHandle->Generator()); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGaussianRandomValue(RNGHandle& rngHandle, const ElemType mean, const ElemType stdev) { if (IsEmpty()) LogicError("SetGaussianRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::normal_distribution<double> r((double)mean, (double)stdev); auto n = AsMultipleOf(GetNumElements(), 2); std::generate(Data(), Data() + n, [&cpuRNGHandle, &r]() {return (ElemType)r(cpuRNGHandle->Generator()); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGumbelRandomValue(RNGHandle& rngHandle, const ElemType loc, const ElemType scale) { if (IsEmpty()) LogicError("SetGumbelRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); boost::random::uniform_real_distribution<double> r(0, 1); std::generate(Data(), Data() + GetNumElements(), [&cpuRNGHandle, &r, loc, scale]() {return (ElemType)(loc - scale * log(-log1p(-r(cpuRNGHandle->Generator())))); }); } template <class ElemType> void CPUMatrix<ElemType>::SetGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetGaussianRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetGaussianRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::normal_distribution<double> r((double)mean, (double)sigma); // #pragma omp parallel for is not thread safe. Also the results would not be deterministic foreach_coord (i, j, us) { us(i, j) = (ElemType)r(generator); } } template <class ElemType> void CPUMatrix<ElemType>::SetTruncatedNormalRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetTruncatedNormalRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetTruncatedNormalRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator(seed == USE_TIME_BASED_SEED ? (unsigned long)time(NULL) : seed); boost::random::normal_distribution<double> r((double)mean, (double)sigma); const ElemType high = mean + 2 * sigma; const ElemType low = mean - 2 * sigma; // #pragma omp parallel for is not thread safe. Also the results would not be deterministic foreach_coord(i, j, us) { ElemType tmp = 0; do tmp = (ElemType)r(generator); while (tmp < low || tmp > high ); // Rejection sampling is fine here because the acceptance probability is about 0.9545 us(i, j) = tmp; } } template <class ElemType> void CPUMatrix<ElemType>::AddGaussianRandomValue(const ElemType mean, const ElemType sigma, unsigned long seed) { if (sigma <= 0) InvalidArgument("SetUniformRandomValue: sigma must be a positive value."); if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); auto& us = *this; std::mt19937_64 generator; generator.seed(seed == USE_TIME_BASED_SEED ? (unsigned long) time(NULL) : seed); boost::random::normal_distribution<double> r((double)mean, (double)sigma); long m = (long) GetNumRows(), n = (long) GetNumCols(); for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = (ElemType)r(generator); us(i + 1, j) = (ElemType)r(generator); us(i + 2, j) = (ElemType)r(generator); us(i + 3, j) = (ElemType)r(generator); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = r(generator); } } } //maskRate: percentage of values masked out (similar to dropout rate) //scaleValue: which scale value to set to the left ones (unmasked items). template <class ElemType> void CPUMatrix<ElemType>::SetUniformRandomMask(const ElemType maskRate, const ElemType scaleValue, RNGHandle& rngHandle) { if (IsEmpty()) LogicError("SetUniformRandomValue: Matrix is empty."); CPURNGHandle* cpuRNGHandle = dynamic_cast<CPURNGHandle*>(&rngHandle); if (cpuRNGHandle == nullptr) LogicError("rngHandle must be a CPURNGHandle."); auto& us = *this; boost::random::uniform_real_distribution<double> r(0, 1); long m = (long) GetNumRows(), n = (long) GetNumCols(); ElemType v; for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { v = (ElemType)r(cpuRNGHandle->Generator()); us(i, j) = v <= maskRate ? (ElemType)0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 1, j) = v <= maskRate ? (ElemType)0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 2, j) = v <= maskRate ? (ElemType)0 : scaleValue; v = r(cpuRNGHandle->Generator()); us(i + 3, j) = v <= maskRate ? (ElemType)0 : scaleValue; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { v = (ElemType)r(cpuRNGHandle->Generator()); us(i, j) = v <= maskRate ? (ElemType)0 : scaleValue; } } } template <class ElemType> ElemType CPUMatrix<ElemType>::Adagrad(CPUMatrix<ElemType>& gradients, const bool needAveMultiplier) { ElemType aveMultiplier = 0; if (IsEmpty() || gradients.GetNumCols() != GetNumCols() || gradients.GetNumRows() != GetNumRows()) { RequireSize(gradients.GetNumRows(), gradients.GetNumCols()); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols()) LogicError("The matrix gradients must have the same rows and columns as this matrix."); ElemType *a = Data(), *d_v = gradients.Data(); size_t n = GetNumElements(); const ElemType floor = 1e-16f; ElemType a0, a1, a2, a3; // disable omp here because aveMultiper needs to be added atomically. however, it seems the result is incorrect even if rmp atomic and amp critical are used. // #pragma omp parallel for for (long i = 0; i < (n & ~3); i += 4) // four-way unrolling { a[i] += d_v[i] * d_v[i]; a[i + 1] += d_v[i + 1] * d_v[i + 1]; a[i + 2] += d_v[i + 2] * d_v[i + 2]; a[i + 3] += d_v[i + 3] * d_v[i + 3]; a0 = sqrt(a[i] + floor); a1 = sqrt(a[i + 1] + floor); a2 = sqrt(a[i + 2] + floor); a3 = sqrt(a[i + 3] + floor); d_v[i] /= a0; d_v[i + 1] /= a1; d_v[i + 2] /= a2; d_v[i + 3] /= a3; if (needAveMultiplier) { aveMultiplier += 1 / a0 + 1 / a1 + 1 / a2 + 1 / a3; } } // get the last few elements if any for (long i = n & ~3; i < n; i++) { a[i] += d_v[i] * d_v[i]; a0 = sqrt(a[i] + floor); d_v[i] /= a0; if (needAveMultiplier) { aveMultiplier += 1 / a0; } } if (needAveMultiplier && n > 0) return aveMultiplier / n; else return 1; } template <class ElemType> void CPUMatrix<ElemType>::FSAdagrad(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learnRatePerSample, ElemType momentum, ElemType adaWeight, ElemType adaMul, ElemType unitGainFactor) { size_t numColsNeeded = 2 * gradients.GetNumCols(); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); ElemType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothMom = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = grad[i]; ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g; smoothAda[i] = adaSqr; if (adaSqr != 0.0f) { ElemType ada = sqrt(adaSqr); ElemType w = adaMul * ((ElemType) 1.0 / ada); if (w > 10.0f) w = 10.0f; g *= w; } if (momentum > 0.0f) { g = momentum * smoothMom[i] + unitGainFactor * g; smoothMom[i] = g; } g *= learnRatePerSample; val[i] -= g; } } template <class ElemType> void CPUMatrix<ElemType>::Adam(CPUMatrix<ElemType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learnRatePerSample, ElemType momentum, ElemType adaWeight, ElemType adaMul, ElemType epsilon, ElemType unitGainFactor, bool adamax) { size_t numColsNeeded = 2 * gradients.GetNumCols(); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); ElemType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothMom = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = grad[i]; ElemType ada; if (!adamax) { ElemType adaSqr = adaWeight * smoothAda[i] + (1.0f - adaWeight) * g * g; smoothAda[i] = adaSqr; ada = sqrt(adaSqr); } else ada = smoothAda[i] = std::max(adaWeight * smoothAda[i], fabs_(g)); ElemType w = adaMul * (ElemType)( 1.0 / (ada + epsilon)); g = momentum * smoothMom[i] + unitGainFactor * g; smoothMom[i] = g; val[i] -= g * w * learnRatePerSample; } } template <class ElemType> ElemType CPUMatrix<ElemType>::RmsProp(CPUMatrix<ElemType>& gradients, ElemType RMS_GAMMA, ElemType RMS_WGT_INC, ElemType RMS_WGT_MAX, ElemType RMS_WGT_DEC, ElemType RMS_WGT_MIN, const bool needAveMultiplier, const bool initialized) { const ElemType floor = 1e-6f; size_t n = gradients.GetNumElements(); ElemType* curr_grad = gradients.Data(); if (IsEmpty() || GetNumCols() < gradients.GetNumCols() * 3 || !initialized) { RequireSize(gradients.GetNumRows(), gradients.GetNumCols() * 3); SetValue(0.0); ElemType* avars = Data(); // accumulated variances for RMS scaling ElemType* steps = Data() + 2 * n; // current step size // initialize moving average of gradient-squared for (long i = 0; i < n; i++) avars[i] = curr_grad[i] * curr_grad[i]; // initialize starting step size for (long i = 0; i < n; i++) steps[i] = ElemType(0.02); } ElemType* avars = Data(); // accumulated variances for RMS scaling ElemType* signs = Data() + n; // sign of previous gradient ElemType* steps = Data() + 2 * n; // current step size if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != gradients.GetNumCols() * 3) LogicError("The matrix gradients does not have expected dimensions."); ElemType ONE_MINUS_GAMMA = ElemType(1.0) - RMS_GAMMA; // int upd[] = { // 2,2,0, // 2,2,0, // 1,1,1, // 2,2,0, // 1,2,1, // 0,2,2, // 1,1,1, // 0,2,2, // 0,2,2, // }; // for (long i=0; i<n; i++) // { // avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]); // // grad sign base 3: 0->neg, 1->zero, 2->pos // const int grad_sign = 1 + (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0)); // // signs[i] contains three consecutive grad_sign // signs[i] = 3*(int(signs[i]) % 9) + grad_sign; // switch(upd[int(signs[i])]) // { // case 0: // steps[i] = max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN); // break; // case 2: // steps[i] = min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX); // break; // } // curr_grad[i] *= steps[i] / sqrt(avars[i] + floor); // } ElemType aveMultiplier = 0, a; for (long i = 0; i < n; i++) { avars[i] = RMS_GAMMA * avars[i] + ONE_MINUS_GAMMA * (curr_grad[i] * curr_grad[i]); const int grad_sign = (ElemType(0) < curr_grad[i]) - (curr_grad[i] < ElemType(0)); if (signs[i] * grad_sign > 0) steps[i] = std::min(steps[i] * RMS_WGT_INC, RMS_WGT_MAX); else steps[i] = std::max(steps[i] * RMS_WGT_DEC, RMS_WGT_MIN); a = steps[i] / sqrt(avars[i] + floor); curr_grad[i] *= a; signs[i] = (ElemType) grad_sign; if (needAveMultiplier) aveMultiplier += a; } if (needAveMultiplier) return aveMultiplier / n; else return 1; } template <class ElemType> template <typename GradType> void CPUMatrix<ElemType>::AdaDelta(CPUMatrix<GradType>& gradients, CPUMatrix<ElemType>& functionValues, ElemType learningRate, ElemType rho, ElemType epsilon) { size_t numColsNeeded = 2 * gradients.GetNumCols(); if (IsEmpty() || (GetNumCols() < numColsNeeded)) { RequireSize(gradients.GetNumRows(), numColsNeeded); SetValue(0.0); } if (GetNumRows() != gradients.GetNumRows() || GetNumCols() != numColsNeeded) LogicError("The matrix gradients does not have expected dimensions."); size_t n = gradients.GetNumElements(); GradType* grad = gradients.Data(); ElemType* smoothAda = Data(); ElemType* smoothX2 = Data() + n; ElemType* val = functionValues.Data(); #pragma omp parallel for // TODO: Unroll 4-times for better performance leveraging vectorization for (long i = 0; i < n; i++) { ElemType g = (ElemType)grad[i]; ElemType adaSqr = rho * smoothAda[i] + (1 - rho) * g * g; smoothAda[i] = adaSqr; ElemType x2 = smoothX2[i]; ElemType deltaX = -sqrt(x2 + epsilon) / sqrt(adaSqr + epsilon) * g; smoothX2[i] = rho * smoothX2[i] + (1 - rho) * deltaX * deltaX; val[i] += learningRate * deltaX; } } template <class ElemType> void CPUMatrix<ElemType>::AdaDeltaFlushTimestamps(size_t cols, ElemType rho, int* timestamps, int currentTimestamp) { // Sets all timestamps to 0 and updates the two logical buffers that this object holds // so that their values are the same as if a dense implementation of adadelta had been used. // This basically means that the values of these buffers are set to decay * original value // where decay is rho ** (currentTimestamp - timestamp for that column) auto rows = GetNumRows(); auto smoothAda = Data(); auto smoothX2 = Data() + cols * rows; #pragma omp parallel for for (auto col = 0; col < cols; ++col) { ElemType decay = std::pow(rho, ElemType(currentTimestamp - timestamps[col])); auto offset = rows * col; timestamps[col] = 0; for (auto row = 0; row < rows; ++row) { smoothAda[offset + row] *= decay; smoothX2[offset + row] *= decay; } } } template <class ElemType> void CPUMatrix<ElemType>::Reshape(const size_t numRows, const size_t numCols) { if (numRows * numCols != GetNumElements()) InvalidArgument("Reshape: Total number of elements does not match."); m_numRows = numRows; m_numCols = numCols; } // RequireSize() -- Tests if the matrix is the right size. If not, resizes the matrix. This avoids the VerifyResizable check if we're already the right size. template <class ElemType> void CPUMatrix<ElemType>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/) { if (GetNumRows() != numRows || GetNumCols() != numCols) Resize(numRows, numCols, growOnly); } // Resize() -- change matrix size // This function is cheap if the matrix size does not change. // Current content is not preserved. // If growOnly is true, resize will not reallocate memory if the current memory is large enough (i.e., will not shrink). // If this object does not own its memory then new memory cannot be allocated (one can still shrink and/or reshape). template <class ElemType> void CPUMatrix<ElemType>::Resize(const size_t numRows, const size_t numCols, bool growOnly /*=true*/) { if (GetNumRows() == numRows && GetNumCols() == numCols) return; VerifyResizable(__func__); size_t numElements = numRows * numCols; if (numElements > GetSizeAllocated() || // grow allocation (!growOnly && (numElements != GetSizeAllocated()))) // shrink allocation (not if 'growOnly') { // reallocate buffer ElemType* pArray = nullptr; if (numElements > 0) { pArray = NewArray<ElemType>(numElements); } // success: update the object delete[] Buffer(); SetBuffer(pArray, numElements * sizeof(ElemType)); SetSizeAllocated(numElements); } // success m_sliceViewOffset = 0; m_numRows = numRows; m_numCols = numCols; } // allocated by the callee but should be deleted by the caller // TODO: change to use STL vector instead template <class ElemType> ElemType* CPUMatrix<ElemType>::CopyToArray() const { size_t numElements = GetNumElements(); if (numElements != 0) { ElemType* arrayCopyTo = NewArray<ElemType>(numElements); memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements); return arrayCopyTo; } else { return nullptr; } } //memory will be allocated by the callee if not enough but need to be deleted by the caller after it's done //return number of elements copied template <class ElemType> size_t CPUMatrix<ElemType>::CopyToArray(ElemType*& arrayCopyTo, size_t& currentArraySize) const { size_t numElements = GetNumElements(); if (numElements > currentArraySize) { delete arrayCopyTo; arrayCopyTo = NewArray<ElemType>(numElements); currentArraySize = numElements; } if (numElements != 0) { memcpy(arrayCopyTo, Data(), sizeof(ElemType) * numElements); } return numElements; } template <typename ElemType> void CPUMatrix<ElemType>::CopySection(size_t /*numRows*/, size_t /*numCols*/, ElemType* /*dst*/, size_t /*colStride*/) const { // REVIEW alexeyk: currently not used by CPU, but implement when possible. RuntimeError("Not implemented."); } template <class ElemType> inline size_t CPUMatrix<ElemType>::LocateColumn(const size_t col) const { // For performance reason avoid extra validation in release. assert(col == 0 || col < GetNumCols()); return col * m_numRows; // matrix in column-wise storage } template <class ElemType> inline size_t CPUMatrix<ElemType>::LocateElement(const size_t row, const size_t col) const { // For performance reason avoid extra validation in release. assert(row < m_numRows); return LocateColumn(col) + row; // matrix in column-wise storage } #pragma endregion Basic Operators #pragma region Member BLAS Functions template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(ElemType alpha) { return AssignSumOf(alpha, *this); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); c.AssignSumOf(alpha, *this); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSumOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = alpha + a(i, j); us(i + 1, j) = alpha + a(i + 1, j); us(i + 2, j) = alpha + a(i + 2, j); us(i + 3, j) = alpha + a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = alpha + a(i, j); } } return *this; } //if [this] and a have same dimension then [this]=[this]+a //if a is a column vector, add to all columns of [this] //if a is a row vector, add to all rows of [this] //if a is a scalar, add it to all elements. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator+=(const CPUMatrix<ElemType>& a) { // if (a.GetNumElements() == 1) // *this += a(0,0); // else ScaleAndAdd(1, a, *this); return *this; } //if [this] and a have same dimension then OUTPUT=[this]+a //if a is a column vector, add to all columns of [this] //if a is a row vector, add to all rows of [this] template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator+(const CPUMatrix<ElemType>& a) const { if (GetNumElements() == 1) { CPUMatrix<ElemType> c(a); c += (*this)(0, 0); return c; } else if (a.GetNumElements() == 1) { CPUMatrix<ElemType> c(*this); c += a(0, 0); return c; } else { CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code c += a; return c; } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.GetNumElements() == 1) { SetValue(b); (*this) += a; } else { SetValue(a); (*this) += b; } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(ElemType alpha) { return AssignDifferenceOf(*this, alpha); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); c.AssignDifferenceOf(*this, alpha); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = alpha - a(i, j); us(i + 1, j) = alpha - a(i + 1, j); us(i + 2, j) = alpha - a(i + 2, j); us(i + 3, j) = alpha - a(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = alpha - a(i, j); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const ElemType alpha) { auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) - alpha; us(i + 1, j) = a(i + 1, j) - alpha; us(i + 2, j) = a(i + 2, j) - alpha; us(i + 3, j) = a(i + 3, j) - alpha; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) - alpha; } } return *this; } //if [this] and a have same dimension then [this]=[this]-a //if a is a column vector, minus it from all columns of [this] //if a is a row vector, minus it from all rows of [this] template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator-=(const CPUMatrix<ElemType>& a) { ScaleAndAdd(-1, a, *this); return *this; } //if [this] and a have same dimension then output=[this]-a //if a is a column vector, minus it from all columns of [this] //if a is a row vector, minus it from all rows of [this] template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator-(const CPUMatrix<ElemType>& a) const { CPUMatrix<ElemType> c(*this); // this implementation will introduce a copy overhead. but make resue of the code c -= a; return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignDifferenceOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (this != &a) { RequireSize(a.GetNumRows(), a.GetNumCols()); SetValue(a); } (*this) -= b; return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator*=(ElemType alpha) { Scale(alpha, *this); return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); Scale(alpha, *this, c); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const ElemType alpha, const CPUMatrix<ElemType>& a) { Scale(alpha, a, *this); return *this; } // [this]=a*b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignProductOf(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB) { if (a.GetNumElements() == 1) { if (transposeB) AssignTransposeOf(b); (*this) *= a(0, 0); } else if (b.GetNumElements() == 1) { if (transposeA) AssignTransposeOf(a); (*this) *= b(0, 0); } else Multiply(a, transposeA, b, transposeB, *this); return *this; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator*(const CPUMatrix<ElemType>& a) const { auto& us = *this; if (GetNumElements() == 1) { CPUMatrix<ElemType> c; c.AssignProductOf(us(0, 0), a); return c; } else if (a.GetNumElements() == 1) { CPUMatrix<ElemType> c; c.AssignProductOf(a(0, 0), us); return c; } else { CPUMatrix<ElemType> c; Multiply(*this, a, c); return c; } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator/=(ElemType alpha) { (*this) *= 1 / alpha; return (*this); } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator/(ElemType alpha) const { return ((*this) * (1 / alpha)); } //element-wise power template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::operator^=(ElemType alpha) { auto& us = *this; ElementWisePower(alpha, us, us); return us; } //element-wise power template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::operator^(ElemType alpha) const { CPUMatrix<ElemType> c(GetNumRows(), GetNumCols()); ElementWisePower(alpha, *this, c); return c; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementPowerOf(const CPUMatrix<ElemType>& a, const ElemType power) { ElementWisePower(power, a, *this); return *this; } //[this]=[this] .* a (we cannot override operator .* in c++) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementMultiplyWith(const CPUMatrix<ElemType>& a) { return AssignElementProductOf(*this, a); } //[this]=[this] .* a (we cannot override operator .* in c++) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementDivideBy(const CPUMatrix<ElemType>& a) { return AssignElementDivisionOf(*this, a); } //[this]=a .* b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementProductOf: The input matrix dimensions do not match."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) * b(i, j); us(i + 1, j) = a(i + 1, j) * b(i + 1, j); us(i + 2, j) = a(i + 2, j) * b(i + 2, j); us(i + 3, j) = a(i + 3, j) * b(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) * b(i, j); } } return *this; } //[this] +=a .* b template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddElementProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AddElementProductOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AddElementProductOf : The input matrix dimensions do not match."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == GetNumCols())) InvalidArgument("AddElementProductOf : The input matrix dimensions do not match [this]."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) += a(i, j) * b(i, j); us(i + 1, j) += a(i + 1, j) * b(i + 1, j); us(i + 2, j) += a(i + 2, j) * b(i + 2, j); us(i + 3, j) += a(i + 3, j) * b(i + 3, j); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) += a(i, j) * b(i, j); } } return *this; } //[this]=a ./ b // TODO: This clips the divisor by a small value. Is that really what one would want? template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementDivisionOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementDivisionOf: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementDivisionOf : The input matrix dimensions do not match."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); ElemType smallValue = EPS_IN_INVERSE; #pragma omp parallel for foreach_coord (i, j, us) { ElemType v = b(i, j); if (v >= 0 && v < smallValue) us(i, j) = a(i, j) / smallValue; else if (v < 0 && v > -smallValue) us(i, j) = a(i, j) / (-smallValue); else us(i, j) = a(i, j) / v; } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementMultiplyWith(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("ColumnElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) InvalidArgument("ColumnElementMultiplyWith: The input matrix should be a col vector and match [this]'s rows."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) *= a(i, 0); us(i + 1, j) *= a(i + 1, 0); us(i + 2, j) *= a(i + 2, 0); us(i + 3, j) *= a(i + 3, 0); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) *= a(i, 0); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementMultiplyWith(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("RowElementMultiplyWith: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) InvalidArgument("RowElementMultiplyWith: The input matrix should be a row vector and match [this]'s columns."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { ElemType v = a(0, j); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) *= v; us(i + 1, j) *= v; us(i + 2, j) *= v; us(i + 3, j) *= v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) *= v; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::RowElementDivideBy(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("RowElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == 1 && a.GetNumCols() == GetNumCols())) InvalidArgument("RowElementDivideBy: The input matrix should be a row vector and match [this]'s columns."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { ElemType v = a(0, j); if (v >= 0 && v < EPS_IN_INVERSE) v = EPS_IN_INVERSE; else if (v < 0 && v > -EPS_IN_INVERSE) v = (-EPS_IN_INVERSE); // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) /= v; us(i + 1, j) /= v; us(i + 2, j) /= v; us(i + 3, j) /= v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) /= v; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ColumnElementDivideBy(const CPUMatrix<ElemType>& a) { if (a.IsEmpty() || IsEmpty()) LogicError("ColumnElementDivideBy: Matrix is empty."); if (!(a.GetNumRows() == GetNumRows() && a.GetNumCols() == 1)) InvalidArgument("ColumnElementDivideBy: The input matrix should be a col vector and match [this]'s rows."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); ElemType smallValue = EPS_IN_INVERSE; #pragma omp parallel for for (long j = 0; j < n; j++) { for (long i = 0; i < m; i++) { ElemType v = a(i, 0); if (v >= 0 && v < smallValue) us(i, j) /= smallValue; else if (v < 0 && v > -smallValue) us(i, j) /= (-smallValue); else us(i, j) /= v; } } return *this; } //[this]=1 ./ a template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ElementInverse() { return AssignElementInverseOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementInverseOf(const CPUMatrix<ElemType>& a) { ElemType smallValue = EPS_IN_INVERSE; if (a.IsEmpty()) LogicError("AssignElementInverseOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, us) { if (a(i, j) < 0 && a(i, j) > -smallValue) us(i, j) = 1 / (-smallValue); else if (a(i, j) >= 0 && a(i, j) < smallValue) us(i, j) = 1 / smallValue; else us(i, j) = 1 / a(i, j); } return *this; } //[this]=sigmoid([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoid() { return AssignSigmoidOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSigmoidOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, us) { if (a(i, j) >= 0) us(i, j) = 1 / (1 + exp(-a(i, j))); else { ElemType v = exp(a(i, j)); us(i, j) = v / (1 + v); } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLinearRectifierDerivative() { return AssignLinearRectifierDerivativeOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLinearRectifierDerivativeOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLinearRectifierDerivativeOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f; us(i + 1, j) = a(i + 1, j) > 0.0f ? 1.0f : 0.0f; us(i + 2, j) = a(i + 2, j) > 0.0f ? 1.0f : 0.0f; us(i + 3, j) = a(i + 3, j) > 0.0f ? 1.0f : 0.0f; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = a(i, j) > 0.0f ? 1.0f : 0.0f; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSigmoidDerivative() { return AssignSigmoidDerivativeOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSigmoidDerivativeOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSigmoidDerivativeOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { ElemType v = a(i, j); us(i, j) = v * (1 - v); ElemType v1 = a(i + 1, j); us(i + 1, j) = v1 * (1 - v1); ElemType v2 = a(i + 2, j); us(i + 2, j) = v2 * (1 - v2); ElemType v3 = a(i + 3, j); us(i + 3, j) = v3 * (1 - v3); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { ElemType v = a(i, j); us(i, j) = v * (1 - v); } } return *this; } //[this]=tanh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTanh() { return AssignTanhOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTanhOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignTanhOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = tanh(a(i, j)); us(i + 1, j) = tanh(a(i + 1, j)); us(i + 2, j) = tanh(a(i + 2, j)); us(i + 3, j) = tanh(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = tanh(a(i, j)); } } return *this; } //[this]=atanh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAtanh() { return AssignAtanhOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAtanhOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAtanhOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = atanh(a(i, j)); us(i + 1, j) = atanh(a(i + 1, j)); us(i + 2, j) = atanh(a(i + 2, j)); us(i + 3, j) = atanh(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = atanh(a(i, j)); } } return *this; } //[this]=softmax([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLogSoftmax(const bool isColWise) { return AssignLogSoftmaxOf(*this, isColWise); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogSoftmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise) { if (a.IsEmpty()) LogicError("AssignLogSoftmaxOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); if (isColWise) { #pragma omp parallel for foreach_column (j, a) { // we need to extract max before applying exp to avoid overflow ElemType maxV = a(0, j); foreach_row (i, a) maxV = std::max(maxV, a(i, j)); ElemType sum = 0; foreach_row (i, a) sum += exp(us(i, j) = a(i, j) - maxV); sum = log(sum); foreach_row (i, us) us(i, j) -= sum; } } else { #pragma omp parallel for foreach_row (i, a) { // we need to extract max before applying exp to avoid overflow ElemType maxV = a(i, 0); foreach_column (j, a) maxV = std::max(maxV, a(i, j)); ElemType sum = 0; foreach_column (j, a) sum += exp(us(i, j) = a(i, j) - maxV); sum = log(sum); foreach_column (j, us) us(i, j) -= sum; } } return *this; } //[this]=hardmax([this]) //the max element is 1 else is 0 template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceHardmax(const bool isColWise) { return AssignHardmaxOf(*this, isColWise); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignHardmaxOf(const CPUMatrix<ElemType>& a, const bool isColWise) { if (a.IsEmpty()) LogicError("AssignHardmaxOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); bool isInplace = (us.Data() == a.Data()); if (!isInplace) memset(us.Data(), 0, a.GetNumElements() * sizeof(ElemType)); if (isColWise) { foreach_column (j, a) { // we need to extract max ElemType maxV = a(0, j); long maxI = 0; foreach_row (i, a) { if (maxV < a(i, j)) { maxV = a(i, j); maxI = i; } } if (isInplace) memset(us.Data() + j * a.GetNumRows(), 0, a.GetNumRows() * sizeof(ElemType)); us(maxI, j) = 1.0f; } } else { foreach_row (i, a) { // we need to extract max ElemType maxV = a(i, 0); long maxJ = 0; foreach_column (j, a) { if (maxV < a(i, j)) { maxV = a(i, j); maxJ = j; } } if (isInplace) { foreach_column(j, us) us(i, j) = (j == maxJ) ? 1.0f : 0.0f; } else us(i, maxJ) = 1.0f; } } return *this; } //[this]=sqrt([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSqrt() { return AssignSqrtOf(*this); } //to prevent negative values caused by floating operations, we force inputs to be >=0 //this may, however, hide problems in the caller. template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSqrtOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSqrtOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = sqrt(max((ElemType)0, a(i, j))); us(i + 1, j) = sqrt(max((ElemType)0, a(i + 1, j))); us(i + 2, j) = sqrt(max((ElemType)0, a(i + 2, j))); us(i + 3, j) = sqrt(max((ElemType)0, a(i + 3, j))); } // remaining for (long i = m & ~3; i < m; i++) { us(i, j) = sqrt(max((ElemType)0, a(i, j))); } } return *this; } //[this]=exp([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceExp() { return AssignExpOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignExpOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignExpOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = exp(a(i, j)); us(i + 1, j) = exp(a(i + 1, j)); us(i + 2, j) = exp(a(i + 2, j)); us(i + 3, j) = exp(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = exp(a(i, j)); } } return *this; } //[this]=exp([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAbs() { return AssignAbsOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAbsOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAbsOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { us(i, j) = abs(a(i, j)); us(i + 1, j) = abs(a(i + 1, j)); us(i + 2, j) = abs(a(i + 2, j)); us(i + 3, j) = abs(a(i + 3, j)); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { us(i, j) = abs(a(i, j)); } } return *this; } //[this]=log([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog() { return AssignLogOf(*this); } //[this]=log([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceLog10() { return AssignLog10Of(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLogOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLogOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); if (v < EPS_IN_LOG) { us(i, j) = LOG_OF_EPS_IN_LOG; } else us(i, j) = log(v); } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignLog10Of(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignLogOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); if (v <= 0) LogicError("AssignLogOf: Log can only applied to numbers larger than 0."); else if (v < EPS_IN_LOG) { us(i, j) = LOG10_OF_EPS_IN_LOG; } else us(i, j) = log10(v); } return *this; } //[this]=cos([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceCosine() { return AssignCosineOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCosineOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignCosineOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = cos(v); } return *this; } //[this]=-sin([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceNegativeSine() { return AssignNegativeSineOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNegativeSineOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignNegativeSineOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = -sin(v); } return *this; } //[this]=tan([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTan() { return AssignTanOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTanOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignTanOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord(i, j, a) { const ElemType v = a(i, j); us(i, j) = tan(v); } return *this; } //[this]=acos([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAcos() { return AssignAcosOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAcosOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAcosOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = acos(v); } return *this; } //[this]=asin([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAsin() { return AssignAsinOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAsinOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAsinOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = asin(v); } return *this; } //[this]=atan([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAtan() { return AssignAtanOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAtanOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAtanOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord(i, j, a) { const ElemType v = a(i, j); us(i, j) = atan(v); } return *this; } //[this]=cosh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceCosh() { return AssignCoshOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCoshOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignCoshOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = cosh(v); } return *this; } //[this]=sinh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSinh() { return AssignSinhOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSinhOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSinhOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = sinh(v); } return *this; } //[this]=asinh([this]) element wise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceAsinh() { return AssignAsinhOf(*this); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAsinhOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignAsinhOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { const ElemType v = a(i, j); us(i, j) = asinh(v); } return *this; } //Threshold truncating: this[i] = max( this[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateBottom(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncateBottom: Matrix is empty."); auto& us = *this; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { if (us(i, j) < threshold) us(i, j) = threshold; if (us(i + 1, j) < threshold) us(i + 1, j) = threshold; if (us(i + 2, j) < threshold) us(i + 2, j) = threshold; if (us(i + 3, j) < threshold) us(i + 3, j) = threshold; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (us(i, j) < threshold) us(i, j) = threshold; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncate(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncate: Matrix is empty."); auto& us = *this; ElemType locThresholdPos = abs(threshold); ElemType locTHresholdNeg = -locThresholdPos; long m = (long) GetNumRows(), n = (long) GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { if (us(i, j) > locThresholdPos) us(i, j) = locThresholdPos; else if (us(i, j) < locTHresholdNeg) us(i, j) = locTHresholdNeg; if (us(i + 1, j) > locThresholdPos) us(i + 1, j) = locThresholdPos; else if (us(i + 1, j) < locTHresholdNeg) us(i + 1, j) = locTHresholdNeg; if (us(i + 2, j) > locThresholdPos) us(i + 2, j) = locThresholdPos; else if (us(i + 2, j) < locTHresholdNeg) us(i + 2, j) = locTHresholdNeg; if (us(i + 3, j) > locThresholdPos) us(i + 3, j) = locThresholdPos; else if (us(i + 3, j) < locTHresholdNeg) us(i + 3, j) = locTHresholdNeg; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (us(i, j) > locThresholdPos) us(i, j) = locThresholdPos; else if (us(i, j) < locTHresholdNeg) us(i, j) = locTHresholdNeg; } } return *this; } //x= x-threshold if x>threshold, x+threshold if x<-threshold, 0 otherwise template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceSoftThreshold(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncate: Matrix is empty."); long m = (long) GetNumElements(); ElemType* bufPtr = Data(); #pragma omp parallel for for (long i = 0; i < (m & ~3); i += 4) // four-way unrolling { if (bufPtr[i] > threshold) bufPtr[i] -= threshold; else if (bufPtr[i] < -threshold) bufPtr[i] += threshold; else bufPtr[i] = 0; if (bufPtr[i + 1] > threshold) bufPtr[i + 1] -= threshold; else if (bufPtr[i + 1] < -threshold) bufPtr[i + 1] += threshold; else bufPtr[i + 1] = 0; if (bufPtr[i + 2] > threshold) bufPtr[i + 2] -= threshold; else if (bufPtr[i + 2] < -threshold) bufPtr[i + 2] += threshold; else bufPtr[i + 2] = 0; if (bufPtr[i + 3] > threshold) bufPtr[i + 3] -= threshold; else if (bufPtr[i + 3] < -threshold) bufPtr[i + 3] += threshold; else bufPtr[i + 3] = 0; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { if (bufPtr[i] > threshold) bufPtr[i] -= threshold; else if (bufPtr[i] < -threshold) bufPtr[i] += threshold; else bufPtr[i] = 0; } return *this; } //Threshold truncating: this[i] = max( a[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateBottomOf(const CPUMatrix<ElemType>& a, const ElemType threshold) { if (a.IsEmpty()) LogicError("AssignTruncateBottomOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { if (a(i, j) < threshold) us(i, j) = threshold; else us(i, j) = a(i, j); } return *this; } //Threshold truncating: this[i] = min( this[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::InplaceTruncateTop(const ElemType threshold) { if (IsEmpty()) LogicError("InplaceTruncateTop: Matrix is empty."); auto& us = *this; #pragma omp parallel for foreach_coord (i, j, us) { if (us(i, j) > threshold) us(i, j) = threshold; } return *this; } //Threshold truncating: this[i] = min( a[i], threshold ) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignTruncateTopOf(const CPUMatrix<ElemType>& a, const ElemType threshold) { if (a.IsEmpty()) LogicError("AssignTruncateTopOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_coord (i, j, a) { if (a(i, j) > threshold) us(i, j) = threshold; else us(i, j) = a(i, j); } return *this; } //Threshold truncating: this[i] = 0 if abs(this[i]<threshold). template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::SetToZeroIfAbsLessThan(const ElemType threshold) { if (IsEmpty()) LogicError("SetToZeroIfAbsLessThan: Matrix is empty."); auto& us = *this; #pragma omp parallel for foreach_coord (i, j, us) { if (abs(us(i, j)) < threshold) us(i, j) = 0; } return *this; } //sum of all abs(elements) template <class ElemType> ElemType CPUMatrix<ElemType>::SumOfAbsElements() const { if (IsEmpty()) LogicError("SumOfAbsElements: Matrix is empty."); if (std::is_same<ElemType, double>::value) { return (ElemType) cblas_dasum((int) GetNumElements(), reinterpret_cast<double*>(Data()), 1); } else if (std::is_same<ElemType, float>::value) { #pragma warning(suppress : 4244) return cblas_sasum((int) GetNumElements(), reinterpret_cast<float*>(Data()), 1); } else { RuntimeError("Unsupported data format"); } } //sum of all elements template <class ElemType> ElemType CPUMatrix<ElemType>::SumOfElements() const { if (IsEmpty()) LogicError("SumOfElements: Matrix is empty."); ElemType sum = 0; long m = (long) GetNumElements(); // note: OpenMP requires loop indices to be long, not size_t ElemType* bufPtr = Data(); //four-way unrolling #pragma omp parallel for reduction(+ : sum) for (long i = 0; i < (m & ~3); i += 4) { sum += bufPtr[i] + bufPtr[i + 1] + bufPtr[i + 2] + bufPtr[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { sum += bufPtr[i]; } return sum; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSumOfElements(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSumOfElements: Matrix a is empty."); auto& us = *this; us.RequireSize(1, 1); us(0, 0) = a.SumOfElements(); return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignOneHot(const CPUMatrix<ElemType>& a, vector<size_t>& shape, size_t axis) { if (a.IsEmpty()) LogicError("AssignOneHot: Matrix a is empty."); if (axis >= shape.size()) LogicError("AssignOneHot: axis is not correct"); size_t item_size = 1; for (size_t i = 0; i < shape.size() && i < axis; i++) item_size *= shape[i]; size_t num_class = shape[axis]; auto& us = *this; auto nCols = a.GetNumCols(); auto nRows = num_class * a.GetNumRows(); us.RequireSize(nRows, nCols); ElemType* bufPtr = Data(); ElemType* aBufPtr = a.Data(); memset(bufPtr, 0, sizeof(ElemType) * nRows *nCols); #pragma omp parallel for for (long i = 0; i < a.GetNumElements(); i++) { if (aBufPtr[i] >= 0 && aBufPtr[i] < num_class) { size_t block_id = i / item_size; size_t item_id = i % item_size; bufPtr[block_id * num_class * item_size + item_id + item_size * (size_t)aBufPtr[i]] = 1; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::GatherFromTarget(const CPUMatrix<ElemType>& indices, const CPUMatrix<ElemType>& target, size_t row_elements) { if (indices.IsEmpty() || target.IsEmpty()) LogicError("GatherFromTarget: input matrix is empty."); if (row_elements == 0) LogicError("GatherFromTarget: target matrix at least need 1 dim."); auto nCols = indices.GetNumCols(); auto nRows = indices.GetNumRows() * row_elements; this->RequireSize(nRows, nCols); ElemType* indicesBufPtr = indices.Data(); ElemType* targetBufPtr = target.Data(); ElemType* buffer = Data(); #pragma omp parallel for for (int i = 0; i < indices.GetNumElements(); i++) { memcpy(buffer + i * row_elements, targetBufPtr + ((size_t)indicesBufPtr[i] * row_elements), sizeof(ElemType) * row_elements); } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::ScatterToIndices(const CPUMatrix<ElemType>& values, const CPUMatrix<ElemType>& indices, size_t row_elements, const CPUMatrix<char>* mask/*= nullptr*/) { if (indices.IsEmpty() || values.IsEmpty() || (mask && mask->IsEmpty())) LogicError("ScatterToIndices: input matrix is empty."); if (mask && (indices.GetNumCols() % mask->GetNumCols() != 0)) LogicError("ScatterAccordingIndices: The number of columns(%zu) of the matrix slice to be masked is not a multiple of the number of columns(%zu) of the mask slice.", indices.GetNumCols(), mask->GetNumCols()); ElemType* indicesBufPtr = indices.Data(); ElemType* valueBufPtr = values.Data(); char* maskBufPtr = mask ? mask->Data() : nullptr; ElemType* buffer = Data(); size_t numElemsPerMaskEntry = mask ? indices.GetNumCols() / mask->GetNumCols() * indices.GetNumRows() : 0; ScatterValues(indicesBufPtr, valueBufPtr, buffer, static_cast<ElemType>(1), indices.GetNumElements(), row_elements, this->GetNumCols(), maskBufPtr, numElemsPerMaskEntry); return *this; } template <class ElemType> bool CPUMatrix<ElemType>::IsEqualTo(const CPUMatrix<ElemType>& a, const ElemType threshold /*= 1e-8*/) const { return AreEqual(*this, a, threshold); } template <class ElemType> void CPUMatrix<ElemType>::VectorSum(const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c, const bool isColWise) { if (a.IsEmpty()) LogicError("VectorSum: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); #pragma omp parallel for foreach_column (j, a) { ElemType v = 0; foreach_row (i, a) { #pragma omp atomic v += a(i, j); } c(0, j) = v; } } else { c.RequireSize(m, 1); #pragma omp parallel for foreach_row (i, a) { ElemType v = 0; foreach_column (j, a) { #pragma omp atomic v += a(i, j); } c(i, 0) = v; } } } template <class ElemType> void CPUMatrix<ElemType>::VectorNorm1(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNorm1: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); #pragma omp parallel for foreach_column (j, us) { ElemType v = 0; foreach_row (i, us) { #pragma omp atomic v += abs(us(i, j)); } c(0, j) = v; } } else { c.RequireSize(m, 1); #pragma omp parallel for foreach_row (i, us) { ElemType v = 0; foreach_column (j, us) { #pragma omp atomic v += abs(us(i, j)); } c(i, 0) = v; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm1Of(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNorm1(*this, isColWise); return *this; } template <class ElemType> void CPUMatrix<ElemType>::VectorNorm2(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNorm2: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow ElemType* bufPtr = us.Data(); if (isColWise) // col-wise { c.RequireSize(1, n); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_column (j, c) { c(0, j) = (ElemType) cblas_dnrm2(m, reinterpret_cast<double*>(bufPtr + us.LocateColumn(j)), 1); } } else if(std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) c(0, j) = cblas_snrm2(m, reinterpret_cast<float*>(bufPtr + us.LocateColumn(j)), 1); } } else { RuntimeError("Unsupported data format"); } } else { c.RequireSize(m, 1); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = cblas_dnrm2(n, reinterpret_cast<double*>(bufPtr + i), m); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_snrm2(n, reinterpret_cast<float*>(bufPtr + i), m); } } else { RuntimeError("Unsupported data format"); } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNorm2Of(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNorm2(*this, isColWise); return *this; } template <class ElemType> void CPUMatrix<ElemType>::VectorNormInf(CPUMatrix<ElemType>& c, const bool isColWise) const { if (IsEmpty()) LogicError("VectorNormInf: Matrix is empty."); auto& us = *this; const int m = (int) us.GetNumRows(); const int n = (int) us.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { c.RequireSize(1, n); // #pragma omp parallel for foreach_column (j, us) { ElemType v = 0; foreach_row (i, us) { v = std::max(v, fabs_(us(i, j))); } c(0, j) = v; } } else { c.RequireSize(m, 1); // #pragma omp parallel for foreach_row (i, us) { ElemType v = 0; foreach_column (j, us) { v = std::max(v, fabs_(us(i, j))); } c(i, 0) = v; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignVectorNormInfOf(CPUMatrix<ElemType>& a, const bool isColWise) { a.VectorNormInf(*this, isColWise); return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignInnerProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool isColWise) { InnerProduct(a, b, *this, isColWise); return *this; } //column-wise crossproduct template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignKhatriRaoProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignKhatriRaoProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); if (cols != b.GetNumCols()) InvalidArgument("a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); RequireSize(rowsA * rowsB, cols); #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for for (long k = 0; k < cols; k++) { long jj = 0; for (long j = 0; j < rowsB; j++) { for (long i = 0; i < rowsA; i++) { (*this)(jj++, k) = a(i, k) * b(j, k); } } } return *this; } //column-wise reshaped product. Used to compute KhatriRaoProduct Gradient // this = reshape each column of a from (K1xK2,1) to (K1, K2) // if each column of a is not transposed, each (K1, K2) times each column of b (K2, frames). // the output is a (K1, frames) matrix // if each column of a is tranposed, each (K1, K2)^T times each column of b(K1, frames) and output is (K2, frames) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddColumnReshapeProductOf(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const bool transposeAColumn) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AddColumnReshapeProductOf: Matrix is empty."); long cols = (long) a.GetNumCols(); if (cols != b.GetNumCols()) InvalidArgument("AddColumnReshapeProductOf: a.GetNumCols() != b.GetNumCols()"); long rowsA = (long) a.GetNumRows(); long rowsB = (long) b.GetNumRows(); if (rowsA % rowsB != 0) InvalidArgument("AddColumnReshapeProductOf: number of rows in a should be multiples of that in b."); long rowsC = rowsA / rowsB; if (rowsC != GetNumRows() || cols != GetNumCols()) InvalidArgument("AddColumnReshapeProductOf: This matrix does not have the right size."); auto& us = *this; if (transposeAColumn) { // find nrows and ncols of tbe reshaped a long nrows = rowsB; long ncols = rowsC; #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for foreach_column (t, a) { size_t k = 0; for (size_t j = 0; j < ncols; j++) // row and col is transposed { ElemType v = 0; for (size_t i = 0; i < nrows; i++) { v += a(k, t) * b(i, t); k++; } us(j, t) += v; } } } else { size_t ncols = rowsB; size_t nrows = rowsC; #ifdef __INTEL_COMPILER // TODO: check this #pragma simd statement #endif #pragma omp parallel for foreach_column (t, a) { size_t k = 0; for (size_t j = 0; j < ncols; j++) { for (size_t i = 0; i < nrows; i++) { us(i, t) += a(k, t) * b(j, t); k++; } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddWithScaleOf(ElemType alpha, const CPUMatrix<ElemType>& a) { ScaleAndAdd(alpha, a, *this); return *this; } template <class ElemType> ElemType CPUMatrix<ElemType>::FrobeniusNorm() const { if (IsEmpty()) LogicError("FrobeniusNorm: Matrix is empty."); ElemType v = 0; long m = (long) GetNumElements(); ElemType* bufPtr = Data(); //four-way unrolling #pragma omp parallel for reduction(+ : v) for (long i = 0; i < (m & ~3); i += 4) { v += bufPtr[i] * bufPtr[i] + bufPtr[i + 1] * bufPtr[i + 1] + bufPtr[i + 2] * bufPtr[i + 2] + bufPtr[i + 3] * bufPtr[i + 3]; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { v += bufPtr[i] * bufPtr[i]; } return sqrt(v); } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignFrobeniusNormOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignFrobeniusNormOf: Matrix a is empty."); auto& us = *this; us.RequireSize(1, 1); us(0, 0) = a.FrobeniusNorm(); return us; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNormInf() const { if (IsEmpty()) LogicError("MatrixNormInf: Matrix is empty."); auto& us = *this; ElemType v = 0; #pragma omp parallel for foreach_coord (i, j, us) { #pragma omp critical { v = std::max(v, fabs_(us(i, j))); } } return v; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNorm0() const { if (IsEmpty()) LogicError("MatrixNorm0: Matrix is empty."); auto& us = *this; ElemType v = 0; #pragma omp parallel for foreach_coord (i, j, us) { if (us(i, j) != 0) { #pragma omp critical { ++v; } } } return v; } template <class ElemType> ElemType CPUMatrix<ElemType>::MatrixNorm1() const { if (IsEmpty()) LogicError("MatrixNorm1: Matrix is empty."); auto& us = *this; ElemType sum = 0; #pragma omp parallel for reduction(+ : sum) foreach_coord (i, j, us) { sum += abs(us(i, j)); } return sum; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSignOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AssignSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_column (j, us) { foreach_row (i, us) { ElemType v = a(i, j); if (!std::isnan(v)) us(i, j) = (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1))); else us(i, j) = v; } } return us; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddSignOf(const CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("AddSignOf: Matrix a is empty."); auto& us = *this; if (this != &a) RequireSize(a.GetNumRows(), a.GetNumCols()); #pragma omp parallel for foreach_column (j, us) { foreach_row (i, us) { ElemType v = a(i, j); if (!std::isnan(v)) us(i, j) += (v == (ElemType) 0 ? (ElemType) 0 : (v > 0 ? (ElemType) 1 : (ElemType)(-1))); else us(i, j) = v; } } return us; } //I decided to use CPUMatrix<ElemType>& maxIndexes instead of integer vector because the result may be used to do additional calculation template <class ElemType> void CPUMatrix<ElemType>::VectorMax(CPUMatrix<ElemType>& maxIndexes, CPUMatrix<ElemType>& maxValues, const bool isColWise, int topK) const { if (IsEmpty()) LogicError("VectorMax: Matrix is empty."); auto& us = *this; const int m = (int) GetNumRows(); const int n = (int) GetNumCols(); if (topK > m) InvalidArgument("VectorMax: TopK must be less or equal than the number of rows"); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { maxValues.RequireSize(topK, n); maxIndexes.RequireSize(topK, n); if (topK == 1) { #pragma omp parallel for for (int j = 0; j < n; j++) { ElemType v = us(0, j); size_t index = 0; foreach_row (i, us) { if (v < us(i, j)) { index = i; v = us(i, j); } } maxValues(0, j) = v; maxIndexes(0, j) = (ElemType) index; } } else { std::vector<int> indices(m); const ElemType* curVal = Data(); ElemType* curIdx = maxIndexes.Data(); ElemType* curMax = maxValues.Data(); for (int icol = 0; icol < n; icol++, curVal += m, curIdx += topK, curMax += topK) { std::iota(indices.begin(), indices.end(), 0); // Partial sort, descending order. std::partial_sort(indices.begin(), indices.begin() + topK, indices.end(), [curVal](const int& a, const int& b) { return curVal[a] > curVal[b]; }); // REVIEW alexeyk: the following produces warning (see SCL_SECURE_NO_WARNINGS) so use loop instead. // std::transform(indices.begin(), indices.begin() + topK, curIdx, [](const int& a) { return static_cast<ElemType>(a); }); for (int i2 = 0; i2 < topK; i2++) { curIdx[i2] = static_cast<ElemType>(indices[i2]); curMax[i2] = curVal[indices[i2]]; } } } } else { if (topK > 1) RuntimeError("Row-wise TopK max is not supported."); maxValues.RequireSize(m, 1); maxIndexes.RequireSize(m, 1); #pragma omp parallel for for (int i = 0; i < m; i++) { ElemType v = us(i, 0); size_t index = 0; foreach_column (j, us) { if (v < us(i, j)) { index = j; v = us(i, j); } } maxValues(i, 0) = v; maxIndexes(i, 0) = (ElemType) index; } } } template <class ElemType> void CPUMatrix<ElemType>::VectorMin(CPUMatrix<ElemType>& minIndexes, CPUMatrix<ElemType>& minValues, const bool isColWise) const { if (IsEmpty()) LogicError("VectorMin: Matrix is empty."); auto& us = *this; const int m = (int) GetNumRows(); const int n = (int) GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow if (isColWise) // col-wise { minValues.RequireSize(1, n); minIndexes.RequireSize(1, n); #pragma omp parallel for for (int j = 0; j < n; j++) { ElemType v = us(0, j); size_t index = 0; foreach_row (i, us) { if (v > us(i, j)) { index = i; v = us(i, j); } } minValues(0, j) = v; minIndexes(0, j) = (ElemType) index; } } else { minValues.RequireSize(m, 1); minIndexes.RequireSize(m, 1); #pragma omp parallel for for (int i = 0; i < m; i++) { ElemType v = us(i, 0); size_t index = 0; foreach_column (j, us) { if (v > us(i, j)) { index = j; v = us(i, j); } } minValues(i, 0) = v; minIndexes(i, 0) = (ElemType) index; } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNumOfDiff(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, bool searchInCol) { if (a.GetNumCols() != b.GetNumCols()) throw std::invalid_argument("AssignNumOfDiff: a and b must have the same number of columns."); if (!searchInCol && a.GetNumRows() != b.GetNumRows()) throw std::invalid_argument("AssignNumOfDiff: a and b must have the same number of rows."); ElemType n = 0; if (!searchInCol) { foreach_coord (i, j, a) { n += (a(i, j) != b(i, j)); } } else { size_t crow = b.GetNumRows(); const ElemType* curCol = b.Data(); for (size_t icol = 0; icol < a.GetNumCols(); icol++, curCol += crow) { auto res = std::find(curCol, curCol + crow, a(0, icol)); if (res == curCol + crow) n++; } } RequireSize(1, 1); // result should be one element (*this)(0, 0) = n; return *this; } #pragma endregion Member BLAS Functions #pragma region Other helper Functions struct PrintRange { // print from begin to skipBegin, then from skipEnd to end // skipBegin = end if no split size_t begin; size_t skipBegin; size_t skipEnd; size_t end; bool IsEmpty() const { return end <= begin; } // examples: // * 3..10 // * -3..-3: include end-3..end and 0..3 PrintRange(ptrdiff_t first, ptrdiff_t last, size_t total) { if (first >= 0 && last >= 0) { begin = (size_t)first; end = (size_t)last + 1; if (end > total) // allow INT_MAX, meaning to end end = total; skipBegin = end; skipEnd = end; } else if (first < 0 && last < 0) { begin = 0; skipBegin = (size_t)(-last); skipEnd = (size_t)(total + first); if (skipEnd <= skipBegin) skipBegin = skipEnd = total; end = total; } else // if other combinations are ever of interest then implement them here LogicError("Print: Bounds must be either both positive or both negative."); } }; // use negative ranges to print corners, e.g. Print("name", -3, -3, -3, -3) will print the first 3 and last 3 rows/cols template <class ElemType> void CPUMatrix<ElemType>::Print(const char* matrixName, ptrdiff_t rowFirst, ptrdiff_t rowLast, ptrdiff_t colFirst, ptrdiff_t colLast) const { fprintf(stderr, "\n###### "); if (matrixName != nullptr) fprintf(stderr, "%s ", matrixName); fprintf(stderr, "(%lu, %lu)", (unsigned long)GetNumRows(), (unsigned long)GetNumCols()); if (rowFirst != 0 || colFirst != 0 || (size_t)(rowLast + 1) != GetNumRows() || (size_t)(colLast + 1) != GetNumCols()) fprintf(stderr, " [%ld:%ld, %ld:%ld]", (long)rowFirst, (long)rowLast, (long)colFirst, (long)colLast); fprintf(stderr, " ######\n\n"); if (IsEmpty()) { fprintf(stderr, "(empty)\n"); return; } PrintRange rowRange(rowFirst, rowLast, GetNumRows()); PrintRange colRange(colFirst, colLast, GetNumCols()); if (rowRange.IsEmpty() || colRange.IsEmpty()) { fprintf(stderr, "(empty)\n"); return; } const auto& us = *this; if (rowRange.begin > 0) fprintf(stderr, "...\n"); for (size_t i = rowRange.begin; i < rowRange.end; i++) { if (i == rowRange.skipBegin) // insert ... between the two blocks if any { fprintf(stderr, "...\n"); i = rowRange.skipEnd; } if (colRange.begin > 0) // ... at line start fprintf(stderr, "...\t"); for (size_t j = colRange.begin; j < colRange.end; j++) { if (j == colRange.skipBegin) { fprintf(stderr, "...\t"); j = colRange.skipEnd; } fprintf(stderr, "%.10f\t", (double)us(i, j)); } if (colRange.end < GetNumCols()) // ... at line end fprintf(stderr, "..."); fprintf(stderr, "\n"); } if (rowRange.end < GetNumRows()) fprintf(stderr, "...\n"); } template <class ElemType> void CPUMatrix<ElemType>::Print(const char* matrixName /*=nullptr*/) const { Print(matrixName, 0, GetNumRows() - 1, 0, GetNumCols() - 1); } // file I/O //matrixName is used to verify that correct matrix is read. template <class ElemType> void CPUMatrix<ElemType>::ReadFromFile(FILE*, const char* /*matrixName*/) { RuntimeError("not implemented."); } //matrixName is used to verify that correct matrix is read. template <class ElemType> void CPUMatrix<ElemType>::WriteToFile(FILE*, const char* /*matrixName*/) { RuntimeError("not implemented."); } //assume each column is an input sample. Each sample is stored in [channel, row, col] (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignPackedConvolutionInput(const CPUMatrix<ElemType>& inputSubBatch, const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/, const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample, const bool zeroPadding) { if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth) LogicError("Arguments verticalSubsample (or horitzontalSubsample) must be less or equal than kernelHeight (or kernelWidth)."); const size_t packedInputRows = kernelWidth * kernelHeight * inputChannels; const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel const size_t inputDim = inputWidth * inputHeight * inputChannels; const size_t smallBatchSize = inputSubBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * inputChannels); RequireSize(packedInputRows, packedInputColsPerSample * smallBatchSize); if (zeroPadding) SetValue((ElemType) 0); const long halfKernelWidth = (long) kernelWidth / 2; const long halfKernelHeight = (long) kernelHeight / 2; #pragma omp parallel for // each input element is copied to many places for (long sample = 0; sample < smallBatchSize; sample++) { for (long id = 0; id < inputDim; id++) { // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels) // IN_ELEM_COLPOS = sample const long y = id / inputHeightTimesChannel; // inputCol const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels const long x = nXC / (long) inputChannels; // inputRow const long c = nXC % (long) inputChannels; // channel long x0 = 0, y0 = 0, x1 = 0, y1 = 0; if (zeroPadding) { x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1.0f + halfKernelHeight) / (ElemType)verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1.0f + halfKernelWidth) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample); // first posyInKernel } else { x0 = (long) max((ElemType)0, ceil((x - (ElemType)kernelHeight + 1) / (ElemType)verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType)kernelWidth + 1) / (ElemType)horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y - y0 * horizontalSubsample); // first posyInKernel } assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth); // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight) // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow ElemType currentInputValue = inputSubBatch(id, sample); long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight); for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample) { long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight); for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample) { const long packRow = packRowBase + posxInKernel; const long packCol = packColBase + wrow; (*this)(packRow, packCol) = currentInputValue; } packColBase += (long) outputHeight; } } } return *this; } //assume each column is an input sample. Each sample is stored in [channel, row, col] (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::UnpackConvolutionInput(CPUMatrix<ElemType>& inputSubBatch, const size_t inputWidth, const size_t inputHeight, const size_t inputChannels, const size_t outputWidth, const size_t outputHeight, const size_t /*outputChannels*/, const size_t kernelWidth, const size_t kernelHeight, const size_t horizontalSubsample, const size_t verticalSubsample, const bool zeroPadding) const { if (verticalSubsample > kernelHeight || horizontalSubsample > kernelWidth) LogicError("Arguments verticalSubsample (or horizonSubsample) must be less than or equal to kernelHeight (or kernelWidth)."); const size_t packedInputColsPerSample = outputWidth * outputHeight; // output size per channel const size_t inputDim = inputWidth * inputHeight * inputChannels; const size_t smallBatchSize = inputSubBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * inputChannels); const long halfKernelWidth = (long) kernelWidth / 2; const long halfKernelHeight = (long) kernelHeight / 2; #pragma omp parallel for // each input element is copied to many places for (long sample = 0; sample < smallBatchSize; sample++) { for (long id = 0; id < inputDim; id++) { // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * inputChannels) // IN_ELEM_COLPOS = sample const long y = id / inputHeightTimesChannel; // inputCol const long nXC = id % inputHeightTimesChannel; // channel + inputRow*inputChannels const long x = nXC / (long) inputChannels; // inputRow const long c = nXC % (long) inputChannels; // channel long x0 = 0, y0 = 0, x1 = 0, y1 = 0; if (zeroPadding) { x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1.0f + halfKernelHeight) / (ElemType) verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x + halfKernelHeight - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1.0f + halfKernelWidth) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y + halfKernelWidth - y0 * horizontalSubsample); // first posyInKernel } else { x0 = (long) max((ElemType)0, ceil((x - (ElemType) kernelHeight + 1) / (ElemType) verticalSubsample)); // row : first wrow in which x is in x1 = (long) (x - x0 * verticalSubsample); // first posxInKernel y0 = (long) max((ElemType)0, ceil((y - (ElemType) kernelWidth + 1) / (ElemType) horizontalSubsample)); // col : first wcol in which y is in y1 = (long) (y - y0 * horizontalSubsample); // first posyInKernel } assert(x1 >= 0 && x1 < kernelHeight && y1 >= 0 && y1 < kernelWidth); // PACK_ELEM_ROWPOS(channel, posxInKernel, posyInKernel) = (channel * kernelWidth * kernelHeight + posxInKernel + posyInKernel * kernelHeight) // PACK_ELEM_COLPOS(sample, wrow, wcol) = (sample*packedInputColsPerSample + outputHeight*wcol + wrow ElemType currentInputValue = inputSubBatch(id, sample); long packColBase = (long) (sample * packedInputColsPerSample + y0 * outputHeight); for (long wcol = y0, posyInKernel = y1; wcol < (long) outputWidth && posyInKernel >= 0; wcol++, posyInKernel -= (long) horizontalSubsample) { long packRowBase = (long) (c * kernelWidth * kernelHeight + posyInKernel * kernelHeight); for (long wrow = x0, posxInKernel = x1; wrow < (long) outputHeight && posxInKernel >= 0; wrow++, posxInKernel -= (long) verticalSubsample) { const long packRow = packRowBase + posxInKernel; const long packCol = packColBase + wrow; currentInputValue += (*this)(packRow, packCol); } packColBase += (long) outputHeight; } inputSubBatch(id, sample) = currentInputValue; } } return inputSubBatch; } //assume each column is an input sample. Each sample is stored in (r00, g00, b00, r01, g01, b01, r10, g10, b10, r11, g11, b11) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignMaxPoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/, const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const size_t batchSize = inputBatch.GetNumCols(); RequireSize(outputSizePerSample, batchSize); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < (long) batchSize; sample++) { for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++) { const long y = outputIndexWithinSample / outputHeightTimesChannel; // wcol const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels const long x = (long) (nXC / channels); // wrow const long c = (long) (nXC % channels); // channel ElemType maxVal = -FLT_MAX; ElemType minVal = FLT_MAX; const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c); for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++) { long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel; for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++) { const ElemType val = inputBatch(rowInInput, sample); // pf[rowInWindow*channels]; maxVal = std::max(maxVal, val); minVal = std::min(minVal, val); rowInInput += (long) channels; } } (*this)(outputIndexWithinSample, sample) = maxVal; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddMaxPoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch, const CPUMatrix<ElemType>& inputBatch, const CPUMatrix<ElemType>& outputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample, const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { size_t batchSize = inputBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++) { const long y = inputIndexWithinSample / inputHeightTimesChannel; // col in input const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels const long x = (long) (nXC / channels); // row in input const long c = (long) (nXC % channels); // channel long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample)); // inclusive start long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / verticalSubsample : outputHeight - 1); // inclusive end long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample)); // inclusive start long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1); // inclusive end ElemType inputValue = inputBatch(inputIndexWithinSample, sample); for (long outY = startOutY; outY <= endOutY; outY++) { for (long outX = startOutX; outX <= endOutX; outX++) { long outputIndex = (long) (outY * outputHeightTimesChannel + outX * channels + c); if (inputValue == outputBatch(outputIndex, sample)) (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample); } } } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignAveragePoolingResult(const CPUMatrix<ElemType>& inputBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t /*inputSizePerSample*/, const size_t /*outputWidth*/, const size_t outputHeight, const size_t outputSizePerSample, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const size_t batchSize = inputBatch.GetNumCols(); const size_t windowSize = windowWidth * windowHeight; RequireSize(outputSizePerSample, batchSize); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long outputIndexWithinSample = 0; outputIndexWithinSample < outputSizePerSample; outputIndexWithinSample++) { const long y = outputIndexWithinSample / outputHeightTimesChannel; // wcol const long nXC = outputIndexWithinSample % outputHeightTimesChannel; // channel + wrow*channels const long x = (long) (nXC / channels); // wrow const long c = (long) (nXC % channels); // channel ElemType sum = 0; const long rowInWindowBase = (long) ((x * verticalSubsample + y * horizontalSubsample * inputHeight) * channels + c); for (long colInWindow = 0; colInWindow < windowWidth; colInWindow++) { long rowInInput = rowInWindowBase + colInWindow * inputHeightTimesChannel; for (long rowInWindow = 0; rowInWindow < windowHeight; rowInWindow++) { sum += inputBatch(rowInInput, sample); rowInInput += (long) channels; } } (*this)(outputIndexWithinSample, sample) = sum / windowSize; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AddAveragePoolingGradient(const CPUMatrix<ElemType>& outputGradientBatch, const size_t channels, const size_t /*inputWidth*/, const size_t inputHeight, const size_t inputSizePerSample, const size_t outputWidth, const size_t outputHeight, const size_t /*outputSizePerSample*/, const size_t windowWidth, const size_t windowHeight, const size_t horizontalSubsample, const size_t verticalSubsample) { size_t batchSize = outputGradientBatch.GetNumCols(); const long inputHeightTimesChannel = (long) (inputHeight * channels); const long outputHeightTimesChannel = (long) (outputHeight * channels); const long windowSize = (long) (windowWidth * windowHeight); // IN_ELEM_ROWPOS(channel, row, col) = (channel + (row + col * inputHeight) * channels) // IN_ELEM_COLPOS = sample // OUT_ELEM_ROWPOS(channel, wrow, wcol) = (channel + (wrow + wcol * outputHeight) * channels) // OUT_ELEM_COLPOS = sample #pragma omp parallel for for (long sample = 0; sample < batchSize; sample++) { for (long inputIndexWithinSample = 0; inputIndexWithinSample < inputSizePerSample; inputIndexWithinSample++) { const long y = inputIndexWithinSample / inputHeightTimesChannel; // col in input const long nXC = inputIndexWithinSample % inputHeightTimesChannel; // channel + row*chanels const long x = nXC / (long) channels; // row in input const long c = nXC % (long) channels; // channel long startOutX = (long) max((ElemType)0, ceil((x - (ElemType) windowHeight + 1) / (ElemType) verticalSubsample)); // inclusive start long endOutX = (long) ((x / verticalSubsample < outputHeight - 1) ? x / (long) verticalSubsample : outputHeight - 1); // inclusive end long startOutY = (long) max((ElemType)0, ceil((y - (ElemType) windowWidth + 1) / (ElemType) horizontalSubsample)); // inclusive start long endOutY = (long) ((y / horizontalSubsample < outputWidth - 1) ? y / horizontalSubsample : outputWidth - 1); // inclusive end for (long outY = startOutY; outY <= endOutY; outY++) { for (long outX = startOutX; outX <= endOutX; outX++) { long outputIndex = outY * outputHeightTimesChannel + outX * (long) channels + c; (*this)(inputIndexWithinSample, sample) += outputGradientBatch(outputIndex, sample) / windowSize; } } } } return *this; } #pragma endregion Other Helper Functions template <class ElemType> void CPUMatrix<ElemType>::ConvolutionForward(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < GetNumRows()); ElemType sum = 0; int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); sum += kernel.Data()[ivBase + skip + i] * (*this)(colBase + dcol, sample); } output(row, sample) = sum; } } } template <class ElemType> void CPUMatrix<ElemType>::ConvolutionBackwardData(const CPUMatrix<ElemType>& kernel, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& grad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); ElemType curGrad = (*this)(row, sample); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); grad(colBase + dcol, sample) += curGrad * kernel.Data()[ivBase + skip + i]; } } } } template <class ElemType> void CPUMatrix<ElemType>::ConvolutionBackwardKernel(const CPUMatrix<ElemType>& in, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIwht, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& kernelGrad) const { // Do NOT parallelize these loops! for (size_t sample = 0; sample < GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); int ivBase = mpRowIwht(row, 0); assert(0 <= colBase && colBase < in.GetNumRows()); ElemType curGrad = (*this)(row, sample); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < in.GetNumRows()); kernelGrad.Data()[ivBase + skip + i] += curGrad * in(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionInput(size_t unrollCols, size_t mapOutSize, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { size_t batchSize = GetNumCols(); #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)batchSize; sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); output.Data()[(row * batchSize + sample) * unrollCols + skip + i] = (*this)(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionOutput(size_t unrollCols, size_t mapInCount, size_t mapOutCount, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { if (mpRowCol.GetNumRows() % mapOutCount != 0) InvalidArgument("The number of rows in mpRowCol must be multiple of mapOutCount."); size_t mapOutSize = mpRowCol.GetNumRows() / mapOutCount; size_t batchSize = GetNumCols(); size_t kernelSize = runs(1, 0); if (kernelSize % mapInCount != 0) InvalidArgument("kernelSize must be multiple of mapInCount."); size_t kernelMapSize = kernelSize / mapInCount; #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < std::min(size, (int)kernelMapSize); i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); size_t isrc = row; size_t idst = ((colBase + dcol) * batchSize + sample) * unrollCols + ((skip + i) % kernelMapSize) * mapOutCount; for (size_t outMap = 0; outMap < mapOutCount; outMap++, isrc += mapOutSize) { assert(isrc < GetNumElements()); assert(idst + outMap < output.GetNumElements()); output.Data()[idst + outMap] = (*this)(isrc, sample); } } } } } template <class ElemType> void CPUMatrix<ElemType>::UnrollConvolutionInputForKernelBackprop(size_t mapOutSize, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowRun, const CPUMatrix<int>& runs, CPUMatrix<ElemType>& output) const { size_t batchSize = GetNumCols(); size_t unrollCols = mapOutSize * batchSize; #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)batchSize; sample++) { for (size_t row = 0; row < mapOutSize; row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); int i0 = mpRowRun(row, 0); int skip = runs(i0++, 0); int size = runs(i0++, 0); int imask = i0 + size; for (int i = 0; i < size; i++) { if (runs(imask + i, 0) == 0) continue; int dcol = runs(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); size_t idst = (skip + i) * unrollCols + row * batchSize + sample; assert(idst < output.GetNumElements()); output.Data()[idst] = (*this)(colBase + dcol, sample); } } } } template <class ElemType> void CPUMatrix<ElemType>::MaxPoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); assert(std::numeric_limits<ElemType>::has_infinity); ElemType res = -std::numeric_limits<ElemType>::infinity(); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); res = std::max(res, (*this)(colBase + dcol, sample)); } output(row, sample) = res; } } } template <class ElemType> void CPUMatrix<ElemType>::MaxPoolingBackward(const CPUMatrix<ElemType>& out, const CPUMatrix<ElemType>& in, const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& grad, bool accumulateGradient) const { if (!accumulateGradient) grad.SetValue((ElemType)0); #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); ElemType g = (*this)(row, sample); ElemType m = out(row, sample); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); if (in(colBase + dcol, sample) >= m) { #pragma omp atomic grad(colBase + dcol, sample) += g; break; } } } } } // For each image, for each ROI, this function treats that ROI as an image // and does max pooling so that it has output size pooledHeight x pooledWidth. // It loops over each location in the output tensor, computes which ROI // and image should populate that location, computes the subset of the image // corresponding to the ROI and which pixels in that subset should go into the // output location, then takes the max value over that window. // src: Images [W x H x C x N] // roiData: ROIs [4 x numROIs x N], // dst: Pooled ROIs [PW x PH x C x numROIs x N] // argmax: max positions [PW x PH x C x numROIs x N] // spatialScale ratio of input feature map to the original image. // where PW = Pooled Width, PH = Pooled Height, C = Channels, N = Batch Size template <class ElemType> void CPUMatrix<ElemType>::MaxROIPoolingForward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height, const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& output, CPUMatrix<ElemType>& argmax, double spatialScale) const { size_t roiOutputSize = pooledHeight * pooledWidth * channels; #pragma omp parallel for for (int imgIdx = 0; imgIdx < numImg; imgIdx++) { auto img = ColumnSlice(imgIdx, 1); auto rois = roiData.ColumnSlice(imgIdx, 1); #pragma omp parallel for for (int roiIdx = 0; roiIdx < numRois; roiIdx++) { // each ROI is 4 elements: (x, y, w, h). int base = roiIdx * 4; // roi points represent the absolute location of the roi // in the original image. ElemType scX1 = rois(base, (ElemType)0); ElemType scY1 = rois(base + (ElemType)1, (ElemType)0); ElemType scX2 = rois(base + (ElemType)2, (ElemType)0); ElemType scY2 = rois(base + (ElemType)3, (ElemType)0); // compute actual spatial location of the ROI in our featuremap. size_t x1 = (size_t)round(scX1 * spatialScale); size_t y1 = (size_t)round(scY1 * spatialScale); size_t x2 = (size_t)round(scX2 * spatialScale); size_t y2 = (size_t)round(scY2 * spatialScale); ElemType roiW = (ElemType)max(x2 - x1 + 1, (size_t)1); ElemType roiH = (ElemType)max(y2 - y1 + 1, (size_t)1); const ElemType winW = roiW / (ElemType)pooledWidth; const ElemType winH = roiH / (ElemType)pooledHeight; // inspired by Ross Girshick fast-rcnn caffe cpu: https://github.com/rbgirshick/fast-rcnn // loop over spatial locations in output. #pragma omp parallel for for (int outw = 0; outw < pooledWidth; outw++) { for (int outh = 0; outh < pooledHeight; outh++) { // compute the top left corner of the input // spatial window corresponding to this output unit size_t hstart = (size_t)floor(outh * winH); size_t wstart = (size_t)floor(outw * winW); // compute bottom right corner (not included) size_t hend = (size_t)ceil((outh + 1) * winH); size_t wend = (size_t)ceil((outw + 1) * winW); // offset window based on ROI top left corner. // these indices are into the input slice. hstart = min(max(hstart + y1, (size_t)0), height); wstart = min(max(wstart + x1, (size_t)0), width); hend = min(max(hend + y1, (size_t)0), height); wend = min(max(wend + x1, (size_t)0), width); bool isempty = (hend <= hstart) || (wend <= wstart); for (size_t c = 0; c < channels; c++) { // [W x H x C x R x N]; R = ROIs per image size_t outputIdx = roiIdx * roiOutputSize + outw + outh * pooledWidth + c * pooledHeight * pooledWidth; size_t maxidx = 0; ElemType maxval = isempty ? (ElemType)0 : (ElemType)-FLT_MAX; size_t baseIdx = c * height * width; for (size_t h = hstart; h < hend; h++) { for (size_t w = wstart; w < wend; w++) { // stored argmax indices are relative to the current channel. size_t dataIdx = w + h * width; if (img(baseIdx + dataIdx, 0) > maxval) { maxval = img(baseIdx + dataIdx, 0); maxidx = dataIdx; } } } output(outputIdx, imgIdx) = maxval; argmax(outputIdx, imgIdx) = maxidx; } } } } } } // This function loops over locations in the input to the ROIPoolingNode (image locations). // It loops over the ROIs corresponding to that image, seeing which ones could contain the current location // in their output. For each ROI, it checks the argmax data to see if that ROI indeed chose // this pixel location as the maximum. If so, it increments the gradient term for the input location. template <class ElemType> void CPUMatrix<ElemType>::MaxROIPoolingBackward(const size_t numRois, const size_t numImg, const size_t channels, const size_t width, const size_t height, const size_t pooledWidth, const size_t pooledHeight, const CPUMatrix<ElemType>& roiData, CPUMatrix<ElemType>& grad, CPUMatrix<ElemType>& argmax, double spatialScale) const { // loop over images in the batch. #pragma omp parallel for for (int imgIdx = 0; imgIdx < numImg; imgIdx++) { // ROIs for this image. length 4*numRois; auto rois = roiData.ColumnSlice(imgIdx, 1).Data(); // gradient values for all ROIs from this image. length numRois*pooledHeight*pooledWidth*channels; auto pooledGrad = ColumnSlice(imgIdx, 1).Data(); auto argmaxCol = argmax.ColumnSlice(imgIdx, 1).Data(); // loop over spatial locations in the image. #pragma omp parallel for for (int w = 0; w < width; w++) { #pragma omp parallel for for (int h = 0; h < width; h++) { // loop over the ROIs seeing which ones contain this location. for (int roiN = 0; roiN < numRois; roiN++) { // each ROI is 4 elements: (x, y, w, h). int roiOffset = roiN * 4; // ROI data points represent the absolute location of the roi // in the original image. size_t roiStartW = (size_t)round(rois[roiOffset + 0] * spatialScale); size_t roiStartH = (size_t)round(rois[roiOffset + 1] * spatialScale); size_t roiEndW = (size_t)round(rois[roiOffset + 2] * spatialScale); size_t roiEndH = (size_t)round(rois[roiOffset + 3] * spatialScale); size_t roiWidth = max(roiEndW - roiStartW + 1, (size_t)1); size_t roiHeight = max(roiEndH - roiStartH + 1, (size_t)1); // skip this ROI if it doesn't contain the current input location. const bool inROI = (w >= roiStartW && w < roiStartW + roiWidth && h >= roiStartH && h < roiStartH + roiHeight); if (!inROI) continue; ElemType winH = (ElemType)roiHeight / (ElemType)pooledHeight; ElemType winW = (ElemType)roiWidth / (ElemType)pooledWidth; // what pooled nodes in the output for this ROI could have pooled this input location? size_t phstart = (size_t)((h - roiStartH) / winH); size_t pwstart = (size_t)((w - roiStartW) / winW); size_t phend = (size_t)(ceil((h - roiStartH + 1) / winH)); size_t pwend = (size_t)(ceil((w - roiStartW + 1) / winW)); phstart = min(max(phstart, (size_t)0), pooledHeight); phend = min(max(phend, (size_t)0), pooledHeight); pwstart = min(max(pwstart, (size_t)0), pooledWidth); pwend = min(max(pwend, (size_t)0), pooledWidth); for (size_t c = 0; c < channels; c++) { ElemType gradient = 0; // [W x H x C x N] size_t index = w + h*width + c*height*width; // go right up to channel c of the current ROI. size_t offset = (roiN * channels + c) * pooledWidth * pooledHeight; const ElemType* offsetPoolGrad = pooledGrad + offset; const ElemType* offsetArgmax = argmaxCol + offset; for (size_t ph = phstart; ph < phend; ph++) { for (size_t pw = pwstart; pw < pwend; pw++) { if ((size_t)offsetArgmax[ph * pooledWidth + pw] == (w + h * width)) { gradient += offsetPoolGrad[ph * pooledWidth + pw]; } } } #pragma omp atomic grad(index, imgIdx) += gradient; } } } } } } template <class ElemType> void CPUMatrix<ElemType>::MaxUnpooling(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, const CPUMatrix<ElemType>& poolInput, CPUMatrix<ElemType>& input) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < input.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); ElemType curMax = poolInput(colBase + indices(i0, 0), sample); ElemType prevMax = curMax; int imax = 0; for (int i = 1; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < poolInput.GetNumRows()); curMax = std::max(curMax, poolInput(colBase + dcol, sample)); if (curMax > prevMax) { prevMax = curMax; imax = i; } } int dcol = indices(i0 + imax, 0); assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows()); input(colBase + dcol, sample) = (*this)(row, sample); //int i = (int)poolIn(row, sample); //assert(0 <= i && i < size); //int dcol = indices(i0 + i, 0); //assert(0 <= colBase + dcol && colBase + dcol < input.GetNumRows()); //input(colBase + dcol, sample) = (*this)(row, sample); } } } template <class ElemType> void CPUMatrix<ElemType>::AveragePoolingForward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& output, const bool poolIncludePad) const { #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)output.GetNumCols(); sample++) { for (size_t row = 0; row < output.GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < GetNumRows()); ElemType sum = 0; int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); assert(size > 0); for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < GetNumRows()); sum += (*this)(colBase + dcol, sample); } // Note that we divide by size which is the number of actual elements (does not include padding). // if poolIncludePad == true, use avg_pool_include_pad if (poolIncludePad) size = indices(0, 0); output(row, sample) = sum / size; } } } template <class ElemType> void CPUMatrix<ElemType>::AveragePoolingBackward(const CPUMatrix<int>& mpRowCol, const CPUMatrix<int>& mpRowIndices, const CPUMatrix<int>& indices, CPUMatrix<ElemType>& grad, const bool poolIncludePad, bool accumulateGradient) const { if (!accumulateGradient) grad.SetValue((ElemType)0); #pragma omp parallel for for (int64_t sample = 0; sample < (int64_t)GetNumCols(); sample++) { for (size_t row = 0; row < GetNumRows(); row++) { int colBase = mpRowCol(row, 0); assert(0 <= colBase && colBase < grad.GetNumRows()); int i0 = mpRowIndices(row, 0); int size = indices(i0++, 0); int tmp = size; if (poolIncludePad) size = indices(0, 0); assert(size > 0); ElemType g = (*this)(row, sample) / size; size = tmp; for (int i = 0; i < size; i++) { int dcol = indices(i0 + i, 0); assert(0 <= colBase + dcol && colBase + dcol < grad.GetNumRows()); #pragma omp atomic grad(colBase + dcol, sample) += g; } } } } template <class ElemType> template <class StatType> void CPUMatrix<ElemType>::BatchNormalizationForward(const CPUMatrix<StatType>& scale, const CPUMatrix<StatType>& bias, bool inferenceOnly, double expAvgFactor, double blendFactor, CPUMatrix<StatType>& runMean, CPUMatrix<StatType>& runVariance, CPUMatrix<ElemType>& out, double epsilon, CPUMatrix<StatType>& saveMean, CPUMatrix<StatType>& saveInvStdDev) const { if (GetNumRows() % scale.GetNumRows() != 0) LogicError("The number of rows of this matrx must be multiple of the number of rows of the scale matrix."); if (!inferenceOnly || expAvgFactor != 0 || blendFactor != 1) RuntimeError("Batch normalization training on CPU is not yet implemented."); saveMean.Resize(0, 0); // only doing inference: these two are not produced saveInvStdDev.Resize(0, 0); bool spatial = GetNumRows() != scale.GetNumRows(); if (spatial) { size_t spatialSize = GetNumRows() / scale.GetNumRows(); #pragma omp parallel for for (long icol = 0; icol < out.GetNumCols(); icol++) { for (long irow = 0; irow < out.GetNumRows(); irow++) { size_t imap = irow / spatialSize; ElemType stdDev = sqrt(runVariance(imap, 0) + epsilon); out(irow, icol) = (ElemType)(scale(imap, 0) * ((*this)(irow, icol) - runMean(imap, 0)) / stdDev + bias(imap, 0)); } } } else { #pragma omp parallel for for (long icol = 0; icol < out.GetNumCols(); icol++) { for (long irow = 0; irow < out.GetNumRows(); irow++) { ElemType stdDev = sqrt(runVariance(irow, 0) + epsilon); out(irow, icol) = (ElemType)(scale(irow, 0) * ((*this)(irow, icol) - runMean(irow, 0)) / stdDev + bias(irow, 0)); } } } } template <class ElemType> template <class StatType> void CPUMatrix<ElemType>::BatchNormalizationBackward(const CPUMatrix<ElemType>& in, CPUMatrix<ElemType>& grad, const CPUMatrix<StatType>& scale, double blendFactor, const CPUMatrix<StatType>& saveMean, const CPUMatrix<StatType>& saveInvStdDev, CPUMatrix<StatType>& scaleGrad, CPUMatrix<StatType>& biasGrad) const { UNUSED(in); UNUSED(grad); UNUSED(scale); UNUSED(blendFactor), UNUSED(saveMean); UNUSED(saveInvStdDev); UNUSED(scaleGrad); UNUSED(biasGrad); RuntimeError("Batch normalization training on CPU is not yet implemented."); } #pragma region Static BLAS Functions /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = alpha * op(a) * op(b) + beta*c</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="beta">Scalar</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::MultiplyAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, ElemType beta, CPUMatrix<ElemType>& c, shared_ptr<QuantizedMultiplier<ElemType>> pQuantizedMultiplier) { if (a.IsEmpty() || b.IsEmpty()) return; int m, n, k, l; int lda, ldb, ldc; CBLAS_TRANSPOSE mklTransA; CBLAS_TRANSPOSE mklTransB; if (transposeA) { m = (int) a.GetNumCols(); k = (int) a.GetNumRows(); lda = k; mklTransA = CBLAS_TRANSPOSE::CblasTrans; } else { m = (int) a.GetNumRows(); k = (int) a.GetNumCols(); lda = m; mklTransA = CBLAS_TRANSPOSE::CblasNoTrans; } if (transposeB) { l = (int) b.GetNumCols(); n = (int) b.GetNumRows(); ldb = n; mklTransB = CBLAS_TRANSPOSE::CblasTrans; } else { l = (int) b.GetNumRows(); n = (int) b.GetNumCols(); ldb = l; mklTransB = CBLAS_TRANSPOSE::CblasNoTrans; } assert(m > 0 && k > 0 && l > 0 && n > 0); // converting from size_t to int may cause overflow if (k != l) InvalidArgument("CPUMatrix<ElemType>::MultiplyAndWeightedAdd : The inner dimensions of a and b must match."); if (beta == 0) c.RequireSize(m, n); else c.VerifySize(m, n); // Can't resize if beta != 0 ldc = (int) c.GetNumRows(); if (pQuantizedMultiplier == nullptr) { if (std::is_same<ElemType, double>::value) { cblas_dgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<double*>(a.Data()), lda, reinterpret_cast<double*>(b.Data()), ldb, beta, reinterpret_cast<double*>(c.Data()), ldc); } else if (std::is_same<ElemType, float>::value) { #pragma warning(suppress : 4244) cblas_sgemm((CBLAS_ORDER) (int)MatrixOrder::ColMajor, mklTransA, mklTransB, m, n, k, alpha, reinterpret_cast<float*>(a.Data()), lda, reinterpret_cast<float*>(b.Data()), ldb, beta, reinterpret_cast<float*>(c.Data()), ldc); } else { RuntimeError("Unsupported data format"); } } else { // TODO: support transpose product if (mklTransA == CBLAS_TRANSPOSE::CblasTrans || mklTransB == CBLAS_TRANSPOSE::CblasTrans) LogicError("Quantized multiplier currently doesn't support transpose."); pQuantizedMultiplier->Multiply(m, n, k, a.Data(), b.Data(), c.Data()); } } template <class ElemType> void CPUMatrix<ElemType>::Multiply1x1AndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, ElemType beta, CPUMatrix<ElemType>& c) { if (a.GetNumElements() != 1) InvalidArgument("the argument a must be a scalar"); // a is a scalar ElemType f = alpha * a.Get00Element(); if (beta == 0) // don't even read the memory if beta is 0 #pragma omp parallel for foreach_coord (i, j, c) c(i, j) = b(i, j) * f; else #pragma omp parallel for foreach_coord (i, j, c) c(i, j) = b(i, j) * f + c(i, j) * beta; } template <class ElemType> void CPUMatrix<ElemType>::ColumnwiseScaleAndWeightedAdd(ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& v, ElemType beta, CPUMatrix<ElemType>& c) { if (v.GetNumRows() != 1 && v.GetNumCols() != 1) InvalidArgument("the argument v must be a vector"); // v is a vector if (beta == 0) c.RequireSize(a.GetNumRows(), a.GetNumCols()); else c.VerifySize(a.GetNumRows(), a.GetNumCols()); // Can't resize if beta != 0 const ElemType* vd = v.Data(); if (beta == 0) // don't even read the memory if beta is 0 #pragma omp parallel for foreach_coord(i, j, c) c(i, j) = alpha * a(i, j) * vd[j]; else #pragma omp parallel for foreach_coord(i, j, c) c(i, j) = alpha * a(i, j) * vd[j] + c(i, j) * beta; } /* compute singular value decomposition as A = U*SIGMA*VT W is used as temp working memory */ template <class ElemType> void CPUMatrix<ElemType>::SVD(const CPUMatrix<ElemType>& A, CPUMatrix<ElemType>& SIGMA, CPUMatrix<ElemType>& U, CPUMatrix<ElemType>& VT, CPUMatrix<ElemType>& W) { if (A.IsEmpty()) LogicError("SVD: input matrix is empty."); int info; int m, n, lda, ldu, ldvt; m = (int) A.GetNumRows(); n = (int) A.GetNumCols(); W.GetNumRows(); // W is used as temp working memory lda = m; ldu = m; ldvt = n; U.RequireSize(m, m); SIGMA.RequireSize(std::min(m, n), 1); VT.RequireSize(n, n); #if CNTK_UWP RuntimeError("Error, LAPACKE_*gesvd is not supported for UWP.\n"); #else if (std::is_same<ElemType, double>::value) { std::vector<double> superb(std::max(std::min(m, n) - 1, 1)); info = LAPACKE_dgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<double*>(A.Data()), (int) lda, reinterpret_cast<double*>(SIGMA.Data()), reinterpret_cast<double*>(U.Data()), (int) ldu, reinterpret_cast<double*>(VT.Data()), (int) ldvt, &superb[0]); } else if (std::is_same<ElemType, float>::value) { std::vector<float> superb(std::max(std::min(m, n) - 1, 1)); info = LAPACKE_sgesvd((int) MatrixOrder::ColMajor, 'A', 'A', (int) m, (int) n, reinterpret_cast<float*>(A.Data()), (int) lda, reinterpret_cast<float*>(SIGMA.Data()), reinterpret_cast<float*>(U.Data()), (int) ldu, reinterpret_cast<float*>(VT.Data()), (int) ldvt, &superb[0]); } else { RuntimeError("Unsupported data format"); } #endif if (info > 0) { RuntimeError("The algorithm computing SVD failed to converge.\n"); } } /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = op(a) * op(b) + c</summary> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::MultiplyAndAdd(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 1.0, c); } template <class ElemType> void CPUMatrix<ElemType>::AssignSoftmaxSum(const CPUMatrix<ElemType>& softmax, CPUMatrix<ElemType>& c) { ElemType log_likelihood = 0.0; size_t batch_size = GetNumCols(); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) { int sample = (int) (*this)(0, instance_id); log_likelihood += softmax(instance_id, sample); } c(0, 0) = -log_likelihood; } template <class ElemType> void CPUMatrix<ElemType>::AssignNCEUnnormalizedEval(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& c) //this: samples+probs // a: hidden // b: embedding // tmp: softmax // c: loglikelihood { ElemType log_likelihood = 0.0; size_t batch_size = GetNumCols(); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) { int sample = -(int) (*this)(0, instance_id); ElemType score = bias(sample, 0); for (int dim = 0; dim < b.GetNumRows(); dim++) score += b(dim, sample) * a(dim, instance_id); log_likelihood += score; } c(0, 0) = -log_likelihood; } //samples+prob gradient hidden embedding embedding/hidden //a.m_CPUMatrix->AssignNCEDerivative(*tmp.m_CPUMatrix, *a.m_CPUMatrix, *b.m_CPUMatrix, inputIndex, *c.m_CPUMatrix); template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignNCEDerivative(const CPUMatrix<ElemType>& tmp, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t inputIndex, CPUMatrix<ElemType>& c) { size_t sample_size = GetNumRows() / 2; size_t batch_size = GetNumCols(); if (inputIndex == 1) { #pragma omp parallel for for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); for (int dim = 0; dim < b.GetNumRows(); dim++) c(dim, instance_id) -= b(dim, sample) * tmp(sample_id, instance_id); } } else if (inputIndex == 2) { int i_blocks = omp_get_num_threads() * 16; // Assume only one block in k direction. // We don't need to explicitly block in the j direction. #pragma omp parallel for for (int ib = 0; ib < i_blocks; ib++) for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); if (sample % i_blocks == ib) for (int dim = 0; dim < b.GetNumRows(); dim++) c(dim, sample) -= a(dim, instance_id) * tmp(sample_id, instance_id); } } else if (inputIndex == 3) { // Assume only one block in k direction. // We don't need to explicitly block in the j direction. for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); c(0, sample) -= tmp(sample_id, instance_id); } } else InvalidArgument("The argument inputIndex must be 1 or 2 or 3."); return *this; } template <class ElemType> void CPUMatrix<ElemType>::AssignNoiseContrastiveEstimation(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& bias, CPUMatrix<ElemType>& tmp, CPUMatrix<ElemType>& c) //this: samples+probs // a: hidden // b: embedding // tmp: softmax // c: loglikelihood { double log_likelihood = 0.0; size_t sample_size = GetNumRows() / 2; size_t batch_size = GetNumCols(); size_t num_noise_samples = sample_size - 1; double log_num_noise_samples = std::log(num_noise_samples); #pragma omp parallel for reduction(+ : log_likelihood) for (int instance_id = 0; instance_id < batch_size; instance_id++) for (int sample_id = 0; sample_id < sample_size; sample_id++) { int sample = (int) (*this)(2 * sample_id, instance_id); double score = bias(0, sample); for (int dim = 0; dim < b.GetNumRows(); dim++) score += (double)(a(dim, instance_id) * b(dim, sample)); double sample_prob = -(*this)(2 * sample_id + 1, instance_id); if (sample_id == 0) sample_prob = -sample_prob; double score_noise = log_num_noise_samples + sample_prob; double z = LogAdd(score, score_noise); double logprob = score - z; double logprob_noise = score_noise - z; tmp(sample_id, instance_id) = (ElemType) -std::exp(logprob); if (sample_id == 0) tmp(sample_id, instance_id) += 1; log_likelihood += sample_id == 0 ? logprob : logprob_noise; } c(0, 0) = (ElemType) -log_likelihood; } /// <summary>Matrix-matrix multiply with col-major matrices (a and b may be transposed): c = op(a) * op(b)</summary> /// <param name="a">Input matrix</param> /// <param name="transposeA">Whether matrix a is transposed</param> /// <param name="b">Input matrix</param> /// <param name="transposeB">Whether matrix b is transposed</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const bool transposeA, const CPUMatrix<ElemType>& b, const bool transposeB, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, transposeA, b, transposeB, 0.0, c); } /// <summary>Matrix-matrix multiply with col-major matrices (a and b are not transposed): c = a * b</summary> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::Multiply(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { return CPUMatrix<ElemType>::MultiplyAndWeightedAdd(1.0, a, false, b, false, 0.0, c); } /// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a + c</summary> /// if a is a column vector, add to all columns of c /// if a is a row vector, add to all rows of c /// if a is a scalar, add to all rows of c /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::ScaleAndAdd(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty() || c.IsEmpty()) LogicError("ScaleAndAdd: one of the input matrices is empty."); if (a.GetNumRows() != 1 && a.GetNumCols() != 1) // a is not a col or row vector { const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int len = m * n; const int incx = 1; const int incy = 1; assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow if ((int) c.GetNumRows() != m || (int) c.GetNumCols() != n) InvalidArgument("Dimension of matrix c does not match dimension of matrix a."); if (std::is_same<ElemType, double>::value) { cblas_daxpy(len, alpha, reinterpret_cast<double*>(a.Data()), incx, reinterpret_cast<double*>(c.Data()), incy); } else if (std::is_same<ElemType, float>::value) { #pragma warning(suppress : 4244) cblas_saxpy(len, alpha, reinterpret_cast<float*>(a.Data()), incx, reinterpret_cast<float*>(c.Data()), incy); } else { RuntimeError("Unsupported data format"); } } else if (a.GetNumElements() == 1) // scalar, add to all elements { ElemType v = alpha * a(0, 0); long m = (long) c.GetNumRows(), n = (long) c.GetNumCols(); #pragma omp parallel for for (long j = 0; j < n; j++) { // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { c(i, j) += v; c(i + 1, j) += v; c(i + 2, j) += v; c(i + 3, j) += v; } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { c(i, j) += v; } } } else if (a.GetNumCols() == 1) // col vector, add it to all columns { int m = (int) c.GetNumRows(); if (m != (int) a.GetNumRows()) InvalidArgument("To add column vector, rows should match."); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_column (j, c) { cblas_daxpy(m, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + c.LocateColumn(j)), 1); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) cblas_saxpy(m, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + c.LocateColumn(j)), 1); } } else { RuntimeError("Unsupported data format"); } } else // row vector, add it to all rows { int m = (int) c.GetNumRows(); int n = (int) c.GetNumCols(); if (n != (int) a.GetNumCols()) InvalidArgument("To add row vector, cols should match."); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_row (i, c) { cblas_daxpy(n, alpha, reinterpret_cast<double*>(aBufPtr), 1, reinterpret_cast<double*>(cBufPtr + i), m); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) cblas_saxpy(n, alpha, reinterpret_cast<float*>(aBufPtr), 1, reinterpret_cast<float*>(cBufPtr + i), m); } } else { RuntimeError("Unsupported data format"); } } } /// <summary>c += alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AddScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumRows() == c.GetNumRows() && a.GetNumCols() == b.GetNumCols() && a.GetNumCols() == c.GetNumCols())) { InvalidArgument("AddScaledDifference: a, b, and c must have same dimension."); } if (a.IsEmpty()) LogicError("AddScaledDifference: Input matrix a is empty."); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); long m = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]); cBufPtr[i + 1] += alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]); cBufPtr[i + 2] += alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]); cBufPtr[i + 3] += alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { cBufPtr[i] += alpha * (aBufPtr[i] - bBufPtr[i]); } } /// <summary> c = alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AssignScaledDifference(const ElemType alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) { InvalidArgument("AssignScaledDifference: a, b must have same dimension."); } if (a.IsEmpty()) LogicError("AssignScaledDifference: Input matrix a is empty."); if (&c != &a && &c != &b) c.RequireSize(a.GetNumRows(), a.GetNumCols()); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); long m = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (m & ~3); i += 4) { cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]); cBufPtr[i + 1] = alpha * (aBufPtr[i + 1] - bBufPtr[i + 1]); cBufPtr[i + 2] = alpha * (aBufPtr[i + 2] - bBufPtr[i + 2]); cBufPtr[i + 3] = alpha * (aBufPtr[i + 3] - bBufPtr[i + 3]); } // handle remaining stuffs for (long i = m & ~3; i < m; i++) { cBufPtr[i] = alpha * (aBufPtr[i] - bBufPtr[i]); } } // c[ci,cj] += a[ai,aj] template <class ElemType> void CPUMatrix<ElemType>::AddElementToElement(ElemType beta, const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) { if (ai >= a.GetNumRows() || aj >= a.GetNumCols() || ci >= c.GetNumRows() || cj >= c.GetNumCols()) InvalidArgument("AddElementToElement: index out of range."); ElemType us = beta ? beta * c(ci, cj) : (ElemType)0; // do not multiply if beta is 0, could be a NaN us += a(ai, aj); c(ci, cj) = us; } ////c[ci,cj] += a[ai,aj] //template<class ElemType> //void CPUMatrix<ElemType>::AddLogElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) //{ // if (ai >= a.GetNumRows() || aj >=a.GetNumCols() || // ci >= c.GetNumRows() || cj >=c.GetNumCols()) // InvalidArgument("AddElementToElement: index out of range."); // // ElemType v = a(ai,aj); // c(ci, cj) += ((v < EPS_IN_LOG) ? LOG_OF_EPS_IN_LOG : log(v)); //} #if 0 // now done as AddElementToElement (beta=0) // c[ci,cj] = a[ai,aj] template <class ElemType> void CPUMatrix<ElemType>::AssignElementToElement(const CPUMatrix<ElemType>& a, const size_t ai, const size_t aj, CPUMatrix<ElemType>& c, const size_t ci, const size_t cj) { if (ai >= a.GetNumRows() || aj >= a.GetNumCols() || ci >= c.GetNumRows() || cj >= c.GetNumCols()) InvalidArgument("AssignElementToElement: index out of range."); c(ci, cj) = a(ai, aj); } #endif /// <summary>c += alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">1X1 matrix</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AddScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (alpha.GetNumElements() != 1) InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AddScaledDifference(alpha(0, 0), a, b, c); } /// <summary> c = alpha * (a-b)</summary> /// if a, b, c must have same dim /// <param name="alpha">1X1 matrix</param> /// <param name="a">Input matrix</param> /// <param name="b">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> void CPUMatrix<ElemType>::AssignScaledDifference(const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { if (alpha.GetNumElements() != 1) InvalidArgument("AddScaledDifference: alpha must be a 1X1 matrix."); AssignScaledDifference(alpha(0, 0), a, b, c); } /// <summary>Matrix-scalar multiply with col-major matrices: c = alpha * a</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> /// <param name="c">Resulting matrix, user is responsible for allocating this</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow c.RequireSize(m, n); ElemType* aBufPtr = a.Data(); ElemType* cBufPtr = c.Data(); if (alpha == 0) { memset(cBufPtr, 0, sizeof(ElemType) * c.GetNumElements()); return; } long size = (long) c.GetNumElements(); #pragma omp parallel for // four-way unrolling for (long i = 0; i < (size & ~3); i += 4) { cBufPtr[i] = alpha * aBufPtr[i]; cBufPtr[i + 1] = alpha * aBufPtr[i + 1]; cBufPtr[i + 2] = alpha * aBufPtr[i + 2]; cBufPtr[i + 3] = alpha * aBufPtr[i + 3]; } // remaining elements for (long i = size & ~3; i < size; i++) { cBufPtr[i] = alpha * aBufPtr[i]; } } /// <summary>Matrix-scalar multiply with col-major matrices: a = alpha * a</summary> /// <param name="alpha">Scalar</param> /// <param name="a">Input matrix</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(ElemType alpha, CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int len = m * n; const int incx = 1; assert(m > 0 && n > 0 && len > 0); // converting from size_t to int may cause overflow if (alpha == 0 && incx == 1) { memset(a.Data(), 0, sizeof(ElemType) * len); } else if (std::is_same<ElemType, double>::value) { cblas_dscal(len, alpha, reinterpret_cast<double*>(a.Data()), incx); } else if (std::is_same<ElemType, float>::value) { #pragma warning(suppress : 4244) cblas_sscal(len, alpha, reinterpret_cast<float*>(a.Data()), incx); } else { RuntimeError("Unsupported data format"); } } /// <summary>Matrix multiply with col-major matrices: a = alpha[1,1] * a</summary> /// <param name="alpha">1x1 matrix</param> /// <param name="a">Input matrix</param> template <class ElemType> /*static*/ void CPUMatrix<ElemType>::Scale(CPUMatrix<ElemType> alpha, CPUMatrix<ElemType>& a) { if (a.IsEmpty()) LogicError("Scale: Input matrix a is empty."); if (alpha.GetNumElements() != 1) LogicError("Matrix alpha must be 1x1"); CPUMatrix<ElemType>::Scale(alpha(0, 0), a); } template <class ElemType> void CPUMatrix<ElemType>::InnerProduct(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product { c.AssignElementProductOf(a, b); } else if (isColWise) // col-wise { c.RequireSize(1, n); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_column (j, c) { c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_column (j, c) { #pragma warning(suppress : 4244) c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1); } } else { RuntimeError("Unsupported data format"); } } else { c.RequireSize(m, 1); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m); } } else { RuntimeError("Unsupported data format"); } } } // treat matrices as vectors. do vec(a)^T vec(b) template <class ElemType> ElemType CPUMatrix<ElemType>::InnerProductOfMatrices(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProductOfMatrices: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProductOfMatrices: Matrices a and b should have same dimension."); if (std::is_same<ElemType, double>::value) { return (ElemType) cblas_ddot((int) a.GetNumElements(), reinterpret_cast<double*>(a.Data()), 1, reinterpret_cast<double*>(b.Data()), 1); } else if (std::is_same<ElemType, float>::value) { #pragma warning(suppress : 4244) return (ElemType) cblas_sdot((int) a.GetNumElements(), reinterpret_cast<float*>(a.Data()), 1, reinterpret_cast<float*>(b.Data()), 1); } else { RuntimeError("Unsupported data format"); } } template <class ElemType> void CPUMatrix<ElemType>::ElementWisePower(ElemType alpha, const CPUMatrix<ElemType>& a, CPUMatrix<ElemType>& c) { if (a.IsEmpty()) LogicError("Scale: The input matrix a is empty."); c.RequireSize(a.GetNumRows(), a.GetNumCols()); if (alpha == 2) { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = a(i, j) * a(i, j); } } else if (alpha == 3) { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = a(i, j) * a(i, j) * a(i, j); } } else { #pragma omp parallel for foreach_coord (i, j, c) { c(i, j) = pow(a(i, j), alpha); } } } template <class ElemType> void CPUMatrix<ElemType>::BatchMatMul(ElemType beta, const CPUMatrix<ElemType>& a, const bool transposeA, const int m, const CPUMatrix<ElemType>& b, const bool transposeB, const int n, CPUMatrix<ElemType>& c, const bool isColWise) { if (a.IsEmpty() || b.IsEmpty()) LogicError("BatchMatMul: one of the input matrices is empty."); if (!isColWise) LogicError("Only column wise is supported."); const int aSampleElemNum = (int)a.GetNumRows(); const int aBatchSize = (int)a.GetNumCols(); const int bSampleElemNum = (int)b.GetNumRows(); const int bBatchSize = (int)b.GetNumCols(); assert(aSampleElemNum > 0 && aBatchSize > 0 && bSampleElemNum > 0 && bBatchSize > 0); if (aBatchSize != bBatchSize) InvalidArgument("BatchMatMul: Matrices a and b should have same batch size."); int k = aSampleElemNum / m; int kb = bSampleElemNum / n; if (k != kb) InvalidArgument("BatchMatMul: Matrices a's cols number should match Matrices b's rows number."); size_t cSampleElemNum = m * n; if (beta == 0) c.RequireSize(cSampleElemNum, aBatchSize); else c.VerifySize(cSampleElemNum, aBatchSize); // Can't resize if beta != 0 #ifdef USE_OPENBLAS int lda, ldb, ldc; CBLAS_TRANSPOSE blasTransA; CBLAS_TRANSPOSE blasTransB; lda = transposeA ? k : m; ldb = transposeB ? n : k; blasTransA = transposeA ? CblasTrans : CblasNoTrans; blasTransB = transposeB ? CblasTrans : CblasNoTrans; ldc = m; std::vector<const ElemType *> a_array; std::vector<const ElemType *> b_array; std::vector<ElemType *> c_array; a_array.reserve(aBatchSize); b_array.reserve(aBatchSize); c_array.reserve(aBatchSize); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); for (size_t i = 0; i < aBatchSize; i++) { a_array.push_back(aBufPtr + a.LocateColumn(i)); b_array.push_back(bBufPtr + b.LocateColumn(i)); c_array.push_back(cBufPtr + c.LocateColumn(i)); } for (size_t i = 0; i < aBatchSize; i++) { if (sizeof(ElemType) == sizeof(double)) { double alpha = 1.0; cblas_dgemm((CBLAS_ORDER)(int)MatrixOrder::ColMajor, blasTransA, blasTransB, m, n, k, alpha, reinterpret_cast<const double*>(a_array[i]), lda, reinterpret_cast<const double*>(b_array[i]), ldb, double(beta), reinterpret_cast<double*>(c_array[i]), ldc); } else { float alpha = 1.0f; cblas_sgemm((CBLAS_ORDER)(int)MatrixOrder::ColMajor, blasTransA, blasTransB, m, n, k, alpha, reinterpret_cast<const float*>(a_array[i]), lda, reinterpret_cast<const float*>(b_array[i]), ldb, float(beta), reinterpret_cast<float*>(c_array[i]), ldc); } } #else std::vector<int> m_array(aBatchSize, m); std::vector<int> n_array(aBatchSize, n); std::vector<int> k_array(aBatchSize, k); std::vector<int> lda_array(aBatchSize, transposeA ? k : m); std::vector<int> ldb_array(aBatchSize, transposeB ? n : k); std::vector<int> ldc_array(aBatchSize, m); std::vector<int> group_size(1, aBatchSize); std::vector<CBLAS_TRANSPOSE> transa_array(aBatchSize, transposeA ? CblasTrans : CblasNoTrans); std::vector<CBLAS_TRANSPOSE> transb_array(aBatchSize, transposeB ? CblasTrans : CblasNoTrans); std::vector<const ElemType *> a_array; std::vector<const ElemType *> b_array; std::vector<ElemType *> c_array; a_array.reserve(aBatchSize); b_array.reserve(aBatchSize); c_array.reserve(aBatchSize); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); ElemType* cBufPtr = c.Data(); for (size_t i = 0; i < aBatchSize; i++) { a_array.push_back(aBufPtr + a.LocateColumn(i)); b_array.push_back(bBufPtr + b.LocateColumn(i)); c_array.push_back(cBufPtr + c.LocateColumn(i)); } if (sizeof(ElemType) == sizeof(double)) { std::vector<double> alpha_array(group_size[0], 1.0); std::vector<double> beta_array(group_size[0], double(beta)); cblas_dgemm_batch(CblasColMajor, &transa_array[0], &transb_array[0], &m_array[0], &n_array[0], &k_array[0], &alpha_array[0], reinterpret_cast<const double**>(&a_array[0]), &lda_array[0], reinterpret_cast<const double**>(&b_array[0]), &ldb_array[0], &beta_array[0], reinterpret_cast<double**>(&c_array[0]), &ldc_array[0], 1, &group_size[0]); } else { std::vector<float> alpha_array(group_size[0], 1.0f); std::vector<float> beta_array(group_size[0], float(beta)); cblas_sgemm_batch(CblasColMajor, &transa_array[0], &transb_array[0], &m_array[0], &n_array[0], &k_array[0], &alpha_array[0], reinterpret_cast<const float**>(&a_array[0]), &lda_array[0], reinterpret_cast<const float**>(&b_array[0]), &ldb_array[0], &beta_array[0], reinterpret_cast<float**>(&c_array[0]), &ldc_array[0], 1, &group_size[0]); } #endif } template <class ElemType> bool CPUMatrix<ElemType>::AreEqual(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const ElemType threshold /*= 1e-8*/) { if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) return false; bool result = true; #pragma omp parallel for foreach_coord (i, j, a) { if (abs(a(i, j) - b(i, j)) > threshold) { result = false; break; } } return result; } // see Matrix<ElemType>::TensorShuffleScaleAndAdd() for comments template <class ElemType> void CPUMatrix<ElemType>::TensorShuffleScaleAndAdd(ElemType keepWeight, const CPUMatrix<ElemType>& a, size_t D, size_t S, size_t M, size_t K, size_t T, ElemType scaleFactor, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c) { size_t N = D * S * M * K * T; const auto pa = a.Data(); const auto pb = b.Data(); auto pc = c.Data(); // Note: This code is written to match a GPU implementation. It is not super-efficient on the CPU. for (size_t na = 0; na < N; na++) // loop over all elements { // recover the 5 indices from the loop counter size_t d = na % D; size_t s = (na / D) % S; size_t m = (na / D / S) % M; size_t k = (na / D / S / M) % K; size_t t = (na / D / S / M / K) % T; // compute index for the a and b/c tensors assert(na == (((t * K + k) * M + m) * S + s) * D + d); // input tensor of dimension (D x S x M x K x T) size_t nb = (((t * S + s) * M + m) * K + k) * D + d; // output tensor of dimension (D x K x M x S x T): k/K and s/S swapped assert(nb < N); // perform the computation ElemType cval = keepWeight ? keepWeight * pb[nb] : (ElemType)0; // if weight is 0 then don't bother to read memory (efficiency) or to multiply (NaN-safe) cval += scaleFactor * pa[na]; pc[nb] = cval; } } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Ones(const size_t rows, const size_t cols) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetValue(1); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Zeros(const size_t rows, const size_t cols) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetValue(0); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::Eye(const size_t rows) { CPUMatrix<ElemType> c(rows, rows); // will initialize to 0 c.SetDiagonalValue(1); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::RandomUniform(const size_t rows, const size_t cols, const ElemType low, const ElemType high, unsigned long seed) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetUniformRandomValue(low, high, seed); return c; } template <class ElemType> CPUMatrix<ElemType> CPUMatrix<ElemType>::RandomGaussian(const size_t rows, const size_t cols, const ElemType mean, const ElemType sigma, unsigned long seed) { CPUMatrix<ElemType> c(rows, cols); // will initialize to 0 c.SetGaussianRandomValue(mean, sigma, seed); return c; } template <class ElemType> bool CPUMatrix<ElemType>::HasElement(const CPUMatrix<ElemType>& mat, const ElemType v) { bool bHas = false; bool isvFinite = std::isfinite(v); #pragma omp parallel for for (long j = 0; j < mat.GetNumElements(); j++) { #pragma omp flush(bHas) if (!bHas) { ElemType cur = mat.Data()[j]; if (isvFinite && std::isfinite(cur)) { if (cur == v) bHas = true; } else if (std::isnan(v) && std::isnan(cur)) bHas = true; else if (std::isinf(v) && std::isinf(cur) && std::signbit(v) == std::signbit(cur)) bHas = true; } } return bHas; } // CPUMatrix<ElemType>& AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber); //[this]=a .* b // here, a and b must be two row vectors of the same size, i.e. [1,m] // the inputs are two rwo vectors // the output is a matrix of size(neg+1, col) template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); if (!(a.GetNumRows() == b.GetNumRows() && a.GetNumCols() == b.GetNumCols())) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) { RequireSize(negnumber + 1, a.GetNumCols()); // RequireSize(a.GetNumRows(), a.GetNumCols()); } long m = (long) GetNumRows(), n = (long) GetNumCols(); // a and b are of size (1,n) // #pragma omp parallel for for (long j = 0; j < n; j++) { us(0, j) = a(0, j) * b(0, j); } for (long j = 0; j < n; j++) { for (long i = 1; i < m; i++) { us(i, j) = a(0, j) * b(0, (j + shift + i - 1) % n); } } return *this; } template <class ElemType> void CPUMatrix<ElemType>::InnerProductWithShiftNeg(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, const bool isColWise, size_t shift, size_t negnumber) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != k || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); if ((isColWise && m == 1) || !isColWise && n == 1) // in this case it's equivalent to element-wise product { InvalidArgument("InnerProduct: Both matrices should be normal ones, not vectors"); // c.AssignElementProductOf(a, b); } else if (isColWise) // col-wise { c.RequireSize(negnumber + 1, n); // this line ischanged ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (std::is_same<ElemType, double>::value) { for (long j = 0; j < n; j++) { c(0, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn(j)), 1); } for (long j = 0; j < n; j++) { for (long i = 1; i < negnumber + 1; i++) { c(i, j) = (ElemType) cblas_ddot(m, reinterpret_cast<double*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<double*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1); } } } else if (std::is_same<ElemType, float>::value) { for (long j = 0; j < n; j++) { c(0, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn(j)), 1); } for (long j = 0; j < n; j++) { for (long i = 1; i < negnumber + 1; i++) { c(i, j) = (ElemType) cblas_sdot(m, reinterpret_cast<float*>(aBufPtr + a.LocateColumn(j)), 1, reinterpret_cast<float*>(bBufPtr + b.LocateColumn((j + shift + i - 1) % n)), 1); } } } else { RuntimeError("Unsupported data format"); } } else { InvalidArgument("InnerProduct: Rowwise is not supported yet"); c.RequireSize(m, 1); ElemType* aBufPtr = a.Data(); ElemType* bBufPtr = b.Data(); if (std::is_same<ElemType, double>::value) { #pragma omp parallel for foreach_row (i, c) { c(i, 0) = (ElemType) cblas_ddot(n, reinterpret_cast<double*>(aBufPtr + i), m, reinterpret_cast<double*>(bBufPtr + i), m); } } else if (std::is_same<ElemType, float>::value) { #pragma omp parallel for foreach_row (i, c) { #pragma warning(suppress : 4244) c(i, 0) = cblas_sdot(n, reinterpret_cast<float*>(aBufPtr + i), m, reinterpret_cast<float*>(bBufPtr + i), m); } } else { RuntimeError("Unsupported data format"); } } } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::GetARowByIndex(const CPUMatrix<ElemType>& a, size_t index) { if (a.IsEmpty()) LogicError("GetARowByIndex: the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); if (index < 0 || index >= m) LogicError("GetARowByIndex: the row index is out of range."); assert(m > 0 && n > 0); // converting from size_t to int may cause overflow auto& us = *this; RequireSize(1, n); for (long j = 0; j < n; j++) { us(0, j) = a(index, j); } return *this; } // input: a, a row vector // input: b, a matrix. b.col == a.col // input firstmatrixfixed: If true, keep a's order. Otherwise, keep b's order // output: c, a matrix. c.size == b.size /* Example, a = [a1 a2 a3] b = [b11 b12 b13; b21 b22 b23 ] if true: shift = 1 then c = [a1*b12 a2*b13 a3*b11 a1*b22 a2*b23 a3*b21] if shift = 2 then c = [ a1*b13 a2*b11 a3*b12 a1*b23 a2*b21 a3*b22] i.e. we do column-wise shift if false: shift = 1 then c = [a2*b11 a3*b12 a1*b13 a2*b21 a3*b22 a1*b23] shift = 2 then c = [ a3*b11 a1*b12 a2*b13 a3*b21 a1*b22 a2*b23] */ template <class ElemType> void CPUMatrix<ElemType>::ConductRowElementMultiplyWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, CPUMatrix<ElemType>& c, size_t shift, bool bFirstmatrixfixed) { if (a.IsEmpty() || b.IsEmpty()) LogicError("InnerProduct: one of the input matrices is empty."); const int m = (int) a.GetNumRows(); const int n = (int) a.GetNumCols(); const int k = (int) b.GetNumRows(); const int l = (int) b.GetNumCols(); assert(m > 0 && n > 0 && k > 0 && l > 0); // converting from size_t to int may cause overflow if (m != 1 || n != l) InvalidArgument("InnerProduct: Matrices a and b should have same dimension."); c.RequireSize(k, l); // c must the same size of b if (bFirstmatrixfixed) { for (long j = 0; j < l; j++) { for (long i = 0; i < k; i++) { c(i, j) = a(0, j) * b(i, (j + shift) % l); } } } else { for (long j = 0; j < l; j++) { for (long i = 0; i < k; i++) { c(i, j) = a(0, (j + shift) % l) * b(i, j); } } } } // CPUMatrix<ElemType>& AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift); //[this]=a .* b // here, a and b must be two row vectors of the same size, i.e. [1,m]. We will do element product with shift. // inputs are 2 row vectors // output is a row vector template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignElementProductOfWithShift(const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, size_t shift) { if (a.IsEmpty() || b.IsEmpty()) LogicError("AssignElementProductOfWithShiftNeg: Matrix is empty."); if (a.GetNumRows() != b.GetNumRows() || a.GetNumCols() != b.GetNumCols()) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix dimensions do not match."); if (a.GetNumRows() != 1) InvalidArgument("AssignElementProductOfWithShiftNeg: The input matrix must be a row vector."); auto& us = *this; if (this != &a) { RequireSize(1, a.GetNumCols()); // RequireSize(a.GetNumRows(), a.GetNumCols()); } // long m = (long)GetNumRows(), n = (long)GetNumCols(); // a and b are of size (1,n) long n = (long) GetNumCols(); // a and b are of size (1,n) #pragma omp parallel for for (long j = 0; j < n; j++) { us(0, j) = a(0, j) * b(0, (j + shift) % n); } return *this; } #pragma endregion Static BLAS Functions // 'double' version of LogAdd inline double LogAddD(double x, double y) { return LogAdd(x, y); } template <class ElemType> ElemType CPUMatrix<ElemType>::LogSumOfElements() const { ElemType fAlpha = (ElemType) LZERO; ElemType* bufPtr = Data(); for (int k = 0; k < GetNumElements(); k++) fAlpha = (ElemType) LogAddD(fAlpha, bufPtr[k]); return fAlpha; } template <class ElemType> void CPUMatrix<ElemType>::RCRFBackwardCompute(const CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& pair_scores) { int iNumPos = (int) lbls.GetNumCols(); int iNumLab = (int) lbls.GetNumRows(); int lastLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, iNumPos - 1) != 0) { lastLbl = ik; break; } beta.RequireSize(iNumLab, iNumPos); for (int t = iNumPos - 1; t >= 0; t--) { #pragma omp parallel for for (int k = 0; k < iNumLab; k++) { _rcrfBackwardCompute(t, k, alpha, beta, pair_scores); } } }; // Calculate alpha in forward-backward calculation. equation (6), (7) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // GPU x dimension corresponds to utterances, y dimension corresponds to phone sequence in each utterance // prob (input): the posterior output from the network // alpha (output): alpha for forward-backward calculation. // phoneSeq (input): phone ID sequence for each utterance in this minibatch, each col is one utterance // phoneBound (input): phone boundary (frame index) of each phone for each utterance in this minibatch, each col is one utterance // uttToChanInd (input): map from utterance ID to minibatch channel ID. We need this because each channel may contain more than one utterance. // uttFrameNum (input): the frame number of each utterance. The size of this vector = the number of all utterances in this minibatch // uttBeginFrame(input): the position of the first frame of each utterance in the minibatch channel. We need this because each channel may contain more than one utterance. // uttPhoneNum (input): the phone number of each utterance. The size of this vector = the number of all utterances in this minibatch // numChannels (input): channel number in this minibatch // uttNum (input): number of utterances // t (input): time stamp to process // maxPhoneNum (input): the max number of phones between utterances // totalPhoneNum (input): the total number of phones of all utterances // blankTokenId (input): id of the CTC blank token // delayConstraint -- label output delay constraint introduced during training that allows to have shorter delay during inference. // Alpha and Beta scores outside of the delay boundary are set to zero. // Setting this parameter smaller will result in shorted delay between label output during decoding. // delayConstraint=-1 means no constraint template<class ElemType> void _assignAlphaScore( const ElemType *prob, ElemType *alphaScore, ElemType *phoneSeq, ElemType *phoneBound, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttFrameNum, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, size_t numChannels, const size_t uttNum, const size_t t, const size_t maxPhoneNum, // Maximum length of utterance in this MB const size_t totalPhoneNum, // Total number of phones const size_t blankTokenId, const int delayConstraint) { for (size_t uttId = 0;uttId < uttNum;uttId++) { // Number of phones and frames in this utterance size_t frameNum = uttFrameNum[uttId]; if (t >= frameNum) continue; size_t phoneNum = uttPhoneNum[uttId]; #pragma omp parallel for for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) { // Index of the label in the sequence // Current and previous phone indices in phoneSeq matrix size_t labelid = uttId*maxPhoneNum + phoneSeqId; // Actual current phone label size_t phoneId = (size_t)(phoneSeq[labelid]); // Index of the current frame in minibatch size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; // Index of probability of observing phoneId at frame timeId size_t probId = timeId*totalPhoneNum + phoneId; size_t alphaId = maxPhoneNum* timeId + phoneSeqId; // alpha_t(s) if (t == 0) { // Initialize recursion if (phoneSeqId == 1 || phoneSeqId == 2) { alphaScore[alphaId] = prob[probId]; } } else { if (phoneSeqId >= 1) { size_t timeId_1 = timeId - numChannels; // Index corresponding to (t-1) size_t alphaId_0 = maxPhoneNum* timeId_1 + phoneSeqId; // alpha_{t-1}(s) size_t alphaId_1 = alphaId_0 - 1; // alpha_{t-1}(s-1) size_t alphaId_2 = alphaId_0 - 2; // alpha_{t-1}(s-2) ElemType x = LZERO; ElemType ascore; if (phoneSeqId > 2) { size_t labelid_2 = labelid - 2; // if current label is not blank and not equal prev non-blank label if ((size_t)(phoneSeq[labelid]) != blankTokenId && phoneId != (size_t)(phoneSeq[labelid_2])) { x = LogAdd(x, alphaScore[alphaId_2]); } } if (phoneSeqId > 1) { x = LogAdd(x, alphaScore[alphaId_1]); } x = LogAdd(x, alphaScore[alphaId_0]); if (phoneId != SIZE_MAX) ascore = prob[probId]; // Probability of observing given label at given time else ascore = 0; alphaScore[alphaId] = (ElemType)x + ascore; if (delayConstraint != -1) { size_t labelid_r = labelid + 2; size_t phoneBoundId_r = (size_t)(phoneBound[labelid_r]); if (phoneId == blankTokenId) { // only constraint right side if (t > phoneBoundId_r + delayConstraint - 1) alphaScore[alphaId] = LZERO; } else if (phoneId != blankTokenId) { if (t > phoneBoundId_r + delayConstraint) alphaScore[alphaId] = LZERO; } } } } } } } // Calculate beta in forward-backward calculation, equation (10), (11) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // See _assignAlphaScore for the explanation of parameters template<class ElemType> void _assignBetaScore( const ElemType *prob, ElemType *betaScore, ElemType *phoneSeq, ElemType *phoneBound, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttFrameNum, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, const size_t numChannels, const size_t uttNum, const long t, const size_t maxPhoneNum, const size_t totalPhoneNum, const size_t blankTokenId, const int delayConstraint) { for (size_t uttId = 0;uttId < uttNum;uttId++) { // Number of phones and frames in this utterance size_t frameNum = uttFrameNum[uttId]; if (t >= frameNum) continue; size_t phoneNum = uttPhoneNum[uttId]; #pragma omp parallel for for (int phoneSeqId = 1;phoneSeqId < phoneNum - 1;phoneSeqId++) { size_t labelid = uttId*maxPhoneNum + phoneSeqId; size_t labelid_2 = labelid + 2; size_t phoneId = (LONG64)(phoneSeq[labelid]); size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; size_t probId = timeId*totalPhoneNum + phoneId; size_t betaid = maxPhoneNum* timeId + phoneSeqId; size_t timeId_1 = timeId + numChannels; size_t betaid_0 = maxPhoneNum* timeId_1 + phoneSeqId; size_t betaid_1 = betaid_0 + 1; size_t betaid_2 = betaid_0 + 2; if (t == frameNum - 1) { if (phoneSeqId == phoneNum - 3 || phoneSeqId == phoneNum - 2) { betaScore[betaid] = prob[probId]; } } else { if (phoneSeqId >= 1) { ElemType x = LZERO; ElemType ascore; if (phoneSeqId < phoneNum - 3) { if (phoneSeq[labelid] != blankTokenId && phoneId != phoneSeq[labelid_2]) { x = LogAdd(x, betaScore[betaid_2]); } } if (phoneSeqId < phoneNum - 2) { x = LogAdd(x, betaScore[betaid_1]); } x = LogAdd(x, betaScore[betaid_0]); if (phoneId != SIZE_MAX) ascore = prob[probId]; else ascore = 0; betaScore[betaid] = (ElemType)x + ascore; if (delayConstraint != -1) { size_t phoneBoundId_r = (size_t)(phoneBound[labelid_2]); if (phoneId == blankTokenId) { if (t > phoneBoundId_r + delayConstraint - 1) betaScore[betaid] = LZERO; } else if (phoneId != blankTokenId) { if (t > phoneBoundId_r + delayConstraint) betaScore[betaid] = LZERO; } } } } } } } // Calculate CTC score. equation (8) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf template<class ElemType> void _assignTotalScore(ElemType *betaScore, std::vector<ElemType>& totalScore, const size_t uttNum, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttBeginFrame, const size_t numChannels, const size_t maxPhoneNum) { #pragma omp parallel for for (int uttId = 0; uttId < uttNum; uttId++) { if (uttId < uttNum) { LONG64 alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum; betaScore[alphaId_0] = LogAdd(betaScore[alphaId_0 + 1], betaScore[alphaId_0 + 2]); totalScore[uttId] = betaScore[alphaId_0]; } } } // Calculate derivative, equation (15) in ftp://ftp.idsia.ch/pub/juergen/icml2006.pdf // See _assignAlphaScore for the explanation of parameters template<class ElemType> void _assignCTCScore( ElemType *CTCscore, ElemType *prob, ElemType *alphaScore, ElemType *betaScore, ElemType *phoneSeq, const size_t uttNum, const std::vector<size_t>& uttToChanInd, const std::vector<size_t>& uttBeginFrame, const std::vector<size_t>& uttPhoneNum, const std::vector<size_t>& uttFrameNum, const size_t numChannels, const size_t maxPhoneNum, const size_t totalPhoneNum) { for (size_t uttId = 0;uttId < uttNum;uttId++) { #pragma omp parallel for for (int t = 0; t < uttFrameNum[uttId]; t++) { size_t phoneNum = uttPhoneNum[uttId]; size_t alphaId_0 = (uttBeginFrame[uttId] * numChannels + uttToChanInd[uttId]) * maxPhoneNum; size_t timeId = (t + uttBeginFrame[uttId])*numChannels + uttToChanInd[uttId]; ElemType P_lx = betaScore[alphaId_0]; for (int s = 1; s < phoneNum - 1; s++) { long phoneId = phoneSeq[uttId*maxPhoneNum + s]; size_t alphaId = maxPhoneNum* timeId + s; size_t probId = timeId*totalPhoneNum + phoneId; if (phoneId != SIZE_MAX) { ElemType logoccu = alphaScore[alphaId] + betaScore[alphaId] - prob[probId] - (ElemType)P_lx; CTCscore[probId] = LogAdd(CTCscore[probId], logoccu); } } for (int s = 0; s < totalPhoneNum; s++) { size_t probId = timeId*totalPhoneNum + s; ElemType logoccu = CTCscore[probId]; if (logoccu < LZERO) CTCscore[probId] = 0.0f; else CTCscore[probId] = exp(logoccu); } } } } template<class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignCTCScore( const CPUMatrix<ElemType>& prob, CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& phoneSeq, const CPUMatrix<ElemType>& phoneBoundary, CPUMatrix<ElemType> & totalScore, const std::vector<size_t>& uttToChanInd, const std::vector<size_t> & uttBeginFrame, const std::vector<size_t> & uttFrameNum, const std::vector<size_t> & uttPhoneNum, const size_t numParallelSequences, const size_t maxFrameNum, const size_t blankTokenId, const int delayConstraint, const bool isColWise) { // Column wise representation of sequences in input matrices (each column is one sequence/utterance) if (isColWise) { // Total number of phones size_t totalPhoneNum = prob.GetNumRows(); size_t uttNum = uttFrameNum.size(); // Max number of phones in utterances in this minibatch size_t maxPhoneNum = phoneSeq.GetNumRows(); for (size_t t = 0; t < maxFrameNum; t++) { _assignAlphaScore(prob.Data(), alpha.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd, uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint); } for (LONG64 t = maxFrameNum - 1; t >= 0; t--) { _assignBetaScore(prob.Data(), beta.Data(), phoneSeq.Data(), phoneBoundary.Data(), uttToChanInd, uttFrameNum, uttBeginFrame, uttPhoneNum, numParallelSequences, uttNum, t, maxPhoneNum, totalPhoneNum, blankTokenId, delayConstraint); } std::vector<ElemType> scores(uttNum); _assignTotalScore(beta.Data(), scores, uttNum, uttToChanInd, uttBeginFrame, numParallelSequences, maxPhoneNum); _assignCTCScore(Data(), prob.Data(), alpha.Data(), beta.Data(), phoneSeq.Data(), uttNum, uttToChanInd, uttBeginFrame, uttPhoneNum, uttFrameNum, numParallelSequences, maxPhoneNum, totalPhoneNum); totalScore(0, 0) = 0.0; for (size_t utt = 0; utt < uttNum; utt++) { totalScore(0,0) -= scores[utt]; } return *this; } else { LogicError("Only ColWise minibatch layout is supported."); } return *this; } /// the kernel function for RCRF backward computation template <class ElemType> void CPUMatrix<ElemType>::_rcrfBackwardCompute(size_t t, size_t k, const CPUMatrix<ElemType>& alpha, CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores) { size_t iNumLab = alpha.GetNumRows(); size_t iNumPos = alpha.GetNumCols(); ElemType fSum; ElemType fTmp = (ElemType) LZERO; if (t == iNumPos - 1) { fSum = (ElemType) LZERO; for (int j = 0; j < iNumLab; j++) { fSum = (ElemType) LogAddD(fSum, alpha(j, t)); } fTmp = alpha(k, t) - fSum; beta(k, t) = fTmp; } else { for (int j = 0; j < iNumLab; j++) { fSum = (ElemType) LZERO; for (int m = 0; m < iNumLab; m++) { fSum = (ElemType) LogAddD(fSum, alpha(m, t) + pair_scores(j, m)); } fTmp = (ElemType) LogAddD(fTmp, beta(j, t + 1) + alpha(k, t) + pair_scores(j, k) - fSum); } beta(k, t) = fTmp; } } template <class ElemType> void CPUMatrix<ElemType>::RCRFTransGrdCompute(const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores, CPUMatrix<ElemType>& grd) { int iNumPos = (int) alpha.GetNumCols(); int iNumLab = (int) alpha.GetNumRows(); int firstLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, 0) != 0) { firstLbl = ik; break; } for (size_t tPos = 0; tPos < iNumPos; tPos++) { CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1); CPUMatrix<ElemType> a; if (tPos > 0) a = alpha.ColumnSlice(tPos - 1, 1); #pragma omp parallel for for (int i = 0; i < iNumLab; i++) { _rcrfTransGrdCompute(i, lbls, alpha, beta, pair_scores, grd, tPos); } // transition score int i = -1; if (tPos == 0) i = firstLbl; else { for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, tPos - 1) != 0) { i = ik; break; } } int j = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) { if (lbls(ik, tPos) != 0) { j = ik; break; } } grd(j, i) -= 1.0; } }; template <class ElemType> void CPUMatrix<ElemType>::_rcrfTransGrdCompute(size_t i, const CPUMatrix<ElemType>& lbls, const CPUMatrix<ElemType>& alpha, const CPUMatrix<ElemType>& beta, const CPUMatrix<ElemType>& pair_scores, CPUMatrix<ElemType>& grd, const size_t tPos // position ) { int iNumLab = (int) alpha.GetNumRows(); int firstLbl = -1; for (int ik = 0; ik < lbls.GetNumRows(); ik++) if (lbls(ik, 0) != 0) { firstLbl = ik; break; } CPUMatrix<ElemType> b = beta.ColumnSlice(tPos, 1); CPUMatrix<ElemType> a; if (tPos > 0) a = alpha.ColumnSlice(tPos - 1, 1); { ElemType fTmp = (ElemType) LZERO; for (int j = 0; j < iNumLab; j++) { if (tPos == 0) { if (i == firstLbl) { fTmp = 0; } else { fTmp = (ElemType) LZERO; } } else { fTmp = a(i, 0); } fTmp += pair_scores(j, i); ElemType fSum = (ElemType) LZERO; for (int k = 0; k < iNumLab; k++) { ElemType fTmp2; if (tPos == 0) { if (k == firstLbl) { fTmp2 = 0; } else { fTmp2 = (ElemType) LZERO; } } else { fTmp2 = a(k, 0); } fSum = (ElemType) LogAddD(fSum, fTmp2 + pair_scores(j, k)); } fTmp -= fSum; fTmp += b(j, 0); grd(j, i) += exp(fTmp); } } }; template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::DropFrame(const CPUMatrix<ElemType>& label, const CPUMatrix<ElemType>& gamma, const ElemType& threshhold) { auto& us = *this; if (us.GetNumCols() != gamma.GetNumCols() || us.GetNumRows() != gamma.GetNumRows()) LogicError("DropFrame: target matrix is not in the same size as gamm matrix."); #pragma omp parallel for foreach_column (j, label) { bool dropframe = false; foreach_row (i, label) { if (fabs(label(i, j) - 1.0f) < 0.1) { if (gamma(i, j) < threshhold) dropframe = true; break; } } foreach_row (i, label) { us(i, j) = 0.0f; } } return *this; } template <class ElemType> CPUMatrix<ElemType>& CPUMatrix<ElemType>::AssignSequenceError(const ElemType hsmoothingWeight, const CPUMatrix<ElemType>& label, const CPUMatrix<ElemType>& dnnoutput, const CPUMatrix<ElemType>& gamma, ElemType alpha) { auto& us = *this; foreach_coord (i, j, us) us(i, j) += alpha * (label(i, j) - (1 - hsmoothingWeight) * dnnoutput(i, j) - hsmoothingWeight * gamma(i, j)); return *this; } // note: this function does not depend on the <ElemType> parameter template <class ElemType> int CPUMatrix<ElemType>::SetNumThreads(int numThreads) { if (numThreads == 0) // use default return numThreads; int mthreads = (int) std::thread::hardware_concurrency(); if (numThreads <= 0) numThreads = std::max(1, mthreads + numThreads); if (numThreads > mthreads) numThreads = mthreads; #ifdef _OPENMP omp_set_num_threads(numThreads); numThreads = omp_get_max_threads(); #ifdef USE_MKL mkl_set_num_threads(numThreads); #elif defined(USE_OPENBLAS) openblas_set_num_threads(numThreads); #endif #endif return numThreads; } template <class ElemType> int CPUMatrix<ElemType>::GetMaxNumThreads() { int numThreads = (int)std::thread::hardware_concurrency(); #ifdef _OPENMP numThreads = omp_get_max_threads(); #endif return numThreads; } // To ensure Intel MKL calls return the same results on all Intel or Intel compatible CPUs, // the function set CBWR compatible mode. template <class ElemType> void CPUMatrix<ElemType>::SetCompatibleMode() { // mkl_cbwr_set not supported in MKLML yet // Explanation on numeric diff: https://software.intel.com/en-us/articles/introduction-to-the-conditional-numerical-reproducibility-cnr // #ifdef USE_MKL // if (mkl_cbwr_set(MKL_CBWR_COMPATIBLE) != MKL_CBWR_SUCCESS) // RuntimeError("Could not set MKL compatible mode."); // #endif } template <class ElemType> void CPUMatrix<ElemType>::SetOptimizationFlags(int flags) { m_optimizationFlags = flags; } template <class ElemType> int CPUMatrix<ElemType>::GetOptimizationFlags() { return m_optimizationFlags; } // ----------------------------------------------------------------------- // entry points from Matrix.cpp; calls into CPUMatrixTensorOpImpl // ----------------------------------------------------------------------- // perform unary operation 'op' on a giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 2>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides) { CPUMatrixTensorOpImpl<ElemType>(beta, a, *this, alpha, op, reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } // perform binary operation 'op' on a and b giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 3>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 3>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 3>& reducingStrides) { CPUMatrixTensorOpImpl<ElemType>(beta, a, b, *this, alpha, op, reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } // perform ternary operation 'op' on a, and c giving 'this', reinterpreting the matrices as tensors as specified by the dims and strides // This maps 'op' to a lambda. template <class ElemType> void CPUMatrix<ElemType>::TensorOp(ElemType beta, const CPUMatrix<ElemType>& a, const CPUMatrix<ElemType>& b, const CPUMatrix<ElemType>& c, ElemType alpha, ElementWiseOperator op, ElementWiseOperator reductionOp, const array<size_t, 4>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 4>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 4>& reducingStrides) { CPUMatrixTensorOpImpl<ElemType>(beta, a, b, c, *this, alpha, op, reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } template <class ElemType> int CPUMatrix<ElemType>::Argmin() const { int minArg = -1; ElemType minValue = std::numeric_limits<ElemType>::max(); #pragma omp parallel { int localMinArg = -1; ElemType localMinValue = std::numeric_limits<ElemType>::max(); #pragma omp for for (int index = 0; index < (int)GetNumElements(); ++index) { if (localMinValue > Data()[index]) { localMinArg = index; localMinValue = Data()[index]; } // If we have more then one min value, select the one with lower index. else if ((localMinValue == Data()[index]) && (localMinArg > index)) { localMinArg = index; } } #pragma omp critical { if (minValue > localMinValue) { minArg = localMinArg; minValue = localMinValue; } // If we have more then one min value, select the one with lower index. else if ((minValue == localMinValue) && (minArg > localMinArg)) { minArg = localMinArg; } } } return minArg; } template <class ElemType> int CPUMatrix<ElemType>::Argmax() const { int maxArg = -1; ElemType maxValue = std::numeric_limits<ElemType>::lowest(); #pragma omp parallel { int localMaxArg = -1; ElemType localMaxValue = std::numeric_limits<ElemType>::lowest(); #pragma omp for for (int index = 0; index < (int)GetNumElements(); ++index) { if (localMaxValue < Data()[index]) { localMaxArg = index; localMaxValue = Data()[index]; } // If we have more then one max value, select the one with lower index. else if ((localMaxValue == Data()[index]) && (localMaxArg > index)) { localMaxArg = index; } } #pragma omp critical { if (maxValue < localMaxValue) { maxArg = localMaxArg; maxValue = localMaxValue; } // If we have more then one max value, select the one with lower index. else if ((maxValue == localMaxValue) && (maxArg > localMaxArg)) { maxArg = localMaxArg; } } } return maxArg; } template <class ElemType> int CPUMatrix<ElemType>::ArgOp(ElementWiseOperator reductionOp) const { switch (reductionOp) { case ElementWiseOperator::opArgmin: return Argmin(); break; case ElementWiseOperator::opArgmax: return Argmax(); break; } InvalidArgument("ArgOp: Arg reduction operations other than opArgmax, and opArgmin are not implemented."); return -1; } template <class ElemType> void CPUMatrix<ElemType>::TensorArgOp(const CPUMatrix<ElemType>& a, ElementWiseOperator reductionOp, const array<size_t, 2>& offsets, const SmallVector<size_t>& regularOpDims, const array<SmallVector<ptrdiff_t>, 2>& regularStrides, const SmallVector<size_t>& reducingOpDims, const array<SmallVector<ptrdiff_t>, 2>& reducingStrides) { CPUMatrixTensorArgOpImpl<ElemType>(a, *this, reductionOp, offsets, regularOpDims, regularStrides, reducingOpDims, reducingStrides); } template <class ElemType> void CPUMatrix<ElemType>::ScatterValues(ElemType* indices, ElemType* value, ElemType* data, ElemType alpha, size_t num_indices, size_t rows, size_t cols, size_t indices_step/*=1*/) { ScatterValues(indices, value, data, alpha, num_indices, rows, cols, /*mask*/nullptr, /*numElemsPerMaskEntry*/0, indices_step); } template <class ElemType> void CPUMatrix<ElemType>::ScatterValues(ElemType* indices, ElemType* value, ElemType* data, ElemType alpha, size_t num_indices, size_t rows, size_t cols, char* mask, size_t numElemsPerMaskEntry, size_t indices_step/*=1*/) { if (!indices || !value || !data) LogicError("ScatterValues: input data is null."); if (mask && (numElemsPerMaskEntry == 0)) RuntimeError("ScatterValues: numElemsPerMaskEntry must not be 0 when a mask is provided."); #pragma omp parallel { int ithread = omp_get_thread_num(); int nthread = omp_get_num_threads(); for (auto i = 0; i < num_indices; i++) { auto col_r = indices[i * indices_step]; if (std::isnan(col_r) || col_r < 0) continue; auto col = (size_t)col_r; //ignore the elements that is not partitioned into this thread if (col % nthread != ithread) continue; //check if colMask is invalid if (mask && mask[i * indices_step / numElemsPerMaskEntry] == 0) continue; if (col >= cols) InvalidArgument("ScatterValues: Indices map out of bounds. %ld >= %ld", (long int)col, (long int)cols); auto index = col * rows; auto offset = i * rows; for (auto j = 0; j < rows; j++) data[index + j] = data[index + j] + alpha * value[offset + j]; } } } // We use Matrix<char> as the backing store for QuantizedMatrix // Let's explicitly instantiate the methods we need for that purpose template CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols); template CPUMatrix<char>::CPUMatrix(const size_t numRows, const size_t numCols, char* pArray, const size_t matrixFlags); template CPUMatrix<char>::CPUMatrix(); template CPUMatrix<char>::CPUMatrix(CPUMatrix<char> const&); template CPUMatrix<char>::CPUMatrix(CPUMatrix<char>&&); template size_t CPUMatrix<char>::LocateElement(size_t, size_t) const; template CPUMatrix<char> CPUMatrix<char>::ColumnSlice(size_t startColumn, size_t numCols) const; template CPUMatrix<char>& CPUMatrix<char>::operator=(CPUMatrix<char>&&); template void CPUMatrix<char>::SetValue(const char); template void CPUMatrix<char>::SetValue(const size_t numRows, const size_t numCols, char* pArray, size_t matrixFlags); template void CPUMatrix<char>::SetValue(CPUMatrix<char> const&); template bool CPUMatrix<char>::IsEqualTo(const CPUMatrix<char>& a, const char threshold) const; //template void CPUMatrix<char>::SetValue(GPUMatrix<char> const&); //template void CPUMatrix<char>::SetValue(CPUSparseMatrix<char> const&); //template void CPUMatrix<char>::SetValue(GPUSparseMatrix<char> const&); template void CPUMatrix<char>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly); template void CPUMatrix<char>::Resize(const size_t numRows, const size_t numCols, bool growOnly); template char* CPUMatrix<char>::CopyToArray(void) const; template void CPUMatrix<char>::CopySection(size_t numRows, size_t numCols, char* dst, size_t colStride) const; template void CPUMatrix<char>::Reshape(const size_t, const size_t); template void CPUMatrix<char>::SetUniformRandomValue(const char low, const char high, unsigned long seed); template void CPUMatrix<char>::SetUniformRandomValue(RNGHandle& rngHandle, const char low, const char high); template void CPUMatrix<char>::SetGaussianRandomValue(const char mean, const char sigma, unsigned long seed); // Support <short> template CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols); template CPUMatrix<short>::CPUMatrix(const size_t numRows, const size_t numCols, short* pArray, const size_t matrixFlags); template CPUMatrix<short>::CPUMatrix(); template CPUMatrix<short>::CPUMatrix(CPUMatrix<short> const&); template CPUMatrix<short>::CPUMatrix(CPUMatrix<short>&&); template size_t CPUMatrix<short>::LocateElement(size_t, size_t) const; template CPUMatrix<short> CPUMatrix<short>::ColumnSlice(size_t startColumn, size_t numCols) const; template CPUMatrix<short>& CPUMatrix<short>::operator=(CPUMatrix<short>&&); template void CPUMatrix<short>::SetValue(const short); template void CPUMatrix<short>::SetValue(const size_t numRows, const size_t numCols, short* pArray, size_t matrixFlags); template void CPUMatrix<short>::SetValue(CPUMatrix<short> const&); template bool CPUMatrix<short>::IsEqualTo(const CPUMatrix<short>& a, const short threshold) const; //template void CPUMatrix<short>::SetValue(GPUMatrix<short> const&); //template void CPUMatrix<short>::SetValue(CPUSparseMatrix<short> const&); //template void CPUMatrix<short>::SetValue(GPUSparseMatrix<short> const&); template void CPUMatrix<short>::RequireSize(const size_t numRows, const size_t numCols, bool growOnly); template void CPUMatrix<short>::Resize(const size_t numRows, const size_t numCols, bool growOnly); template short* CPUMatrix<short>::CopyToArray(void) const; template void CPUMatrix<short>::CopySection(size_t numRows, size_t numCols, short* dst, size_t colStride) const; template void CPUMatrix<short>::Reshape(const size_t, const size_t); template void CPUMatrix<short>::SetUniformRandomValue(const short low, const short high, unsigned long seed); template void CPUMatrix<short>::SetUniformRandomValue(RNGHandle& rngHandle, const short low, const short high); template void CPUMatrix<short>::SetGaussianRandomValue(const short mean, const short sigma, unsigned long seed); template CPUMatrix<int>::CPUMatrix(const size_t, const size_t, int*, const size_t); }}}
deconv_kernel_arm.c
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * License); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * AS IS BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /* * Copyright (c) 2021, OPEN AI LAB * Author: haoluo@openailab.com */ #include "deconv_kernel_arm.h" #include <stdint.h> #include <stdlib.h> #include <math.h> #ifdef __aarch64__ #define PER_OUT_CHAN 16 void sgemm_4x16_deconv_a72(float* input, float* kernel, long kernel_size, float* output, long weight_size); void sgemm_4x4_deconv_a72(float* input, float* kernel, long kernel_size, float* output, long weight_size); void sgemm_4x16_deconv_a53(float* input, float* kernel, long kernel_size, float* output, long weight_size); void sgemm_4x4_deconv_a53(float* input, float* kernel, long kernel_size, float* output, long weight_size); #else #define PER_OUT_CHAN 12 void sgemm_4x12_deconv_a17(float* input, float* kernel, int kernel_size, float* output, int weight_size); void sgemm_4x4_deconv_a17(float* input, float* kernel, int kernel_size, float* output, int weight_size); void sgemm_4x12_deconv_a7(float* input, float* kernel, int kernel_size, float* output, int weight_size); void sgemm_4x4_deconv_a7(float* input, float* kernel, int kernel_size, float* output, int weight_size); #endif static double get_current_time() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec * 1000.0 + tv.tv_usec / 1000.0; } static void interleave_kernel(float* kernel, float* kernel_interleaved, int kernel_chan, int kernel_size) { int i, j, k; float* cur_kernel_interleaved = kernel_interleaved; // interleave PER_OUT_CHAN kernels for (i = 0; i + PER_OUT_CHAN - 1 < kernel_size; i += PER_OUT_CHAN) { for (j = 0; j < kernel_chan; j++) { for (k = 0; k < PER_OUT_CHAN; k++) *(cur_kernel_interleaved++) = kernel[j * kernel_size + i + k]; } } for (; i < (kernel_size & -4); i += 4) { for (j = 0; j < kernel_chan; j++) { for (k = 0; k < 4; k++) *(cur_kernel_interleaved++) = kernel[j * kernel_size + i + k]; } } // last 4 kernel int kernel_size3 = kernel_chan & 0x3; if (kernel_size3) { for (j = 0; j < kernel_chan; j++) { for (k = 0; k < kernel_size3; k++) *(cur_kernel_interleaved++) = kernel[j * kernel_size + i + k]; for (; k < 4; k++) *(cur_kernel_interleaved++) = 0.0; } } } static void interleave(struct tensor* filter, struct deconv_priv_info* priv_info, struct deconv_param* param) { int group = param->group; int out_chan = filter->dims[0] / group; int kernel_size = out_chan * filter->dims[2] * filter->dims[3]; int in_chan = filter->dims[1]; int kernel_size_algin = in_chan * ((kernel_size + 3) & -4); float* kernel = filter->data; float* interleave_buf = priv_info->interleave_buffer; for (int g = 0; g < group; g++) { float* cur_kernel = kernel + g * kernel_size * in_chan; float* cur_interleave = interleave_buf + g * kernel_size_algin; interleave_kernel(cur_kernel, cur_interleave, in_chan, kernel_size); } } static void transpose_input(float* input, float* inputT, int input_w, int input_h) { int i, j, k; int input_w3 = input_w & 0x3; float* cur_input = inputT; for (i = 0; i < (input_w & -4); i += 4) for (j = 0; j < input_h; j++) for (k = 0; k < 4; k++) *cur_input++ = *(input + j * input_w + i + k); if (input_w3) { for (j = 0; j < input_h; j++) { for (k = 0; k < input_w3; k++) *cur_input++ = *(input + j * input_w + i + k); for (; k < 4; k++) *cur_input++ = 0; } } } static void col2im(float* col, float* im, float* bias, int output_ch, int output_x, int output_y, int kernel_x, int kernel_y, int stride_x, int stride_y, int dilation_x, int dilation_y, int pad_x, int pad_y, int input_x, int input_y) { float* cur_col; int imx_start, imy_start, ix, iy, kch, kx, ky, imx, imy; int output_xy = output_x * output_y; int kernel_xy = kernel_x * kernel_y; int weight_size = output_ch * kernel_x * kernel_y; int is_nodilation = (dilation_x == 1 && dilation_y == 1); int is_4x4 = (kernel_x == 4 && kernel_y == 4 && is_nodilation); int is_8x8 = (kernel_x == 8 && kernel_y == 8 && is_nodilation); /* init bias */ if (bias == NULL) { for (int i = 0; i < (output_xy * output_ch); i++) im[i] = 0; } else { float* cur_im = im; for (int i = 0; i < output_ch; i++) for (int j = 0; j < output_xy; j++) *cur_im++ = bias[i]; } if (is_4x4) { for (iy = 0; iy < input_y; iy++) { imy_start = iy * stride_y - pad_y; for (ix = 0; ix < input_x; ix++) { imx_start = ix * stride_x - pad_x; cur_col = col + (iy * input_x + ix) * weight_size; if (iy != 0 && iy != (input_y - 1) && ix != 0 && ix != (input_x - 1)) { for (kch = 0; kch < output_ch; kch++) for (ky = 0; ky < 4; ky++) { imy = imy_start + ky; for (kx = 0; kx < 4; kx++) *(im + output_xy * kch + output_x * imy + imx_start + kx) += *cur_col++; } } else { for (kch = 0; kch < output_ch; kch++) { for (ky = 0; ky < 4; ky++) { imy = imy_start + ky; for (kx = 0; kx < 4; kx++) { imx = imx_start + kx; if (imx >= 0 && imx < output_x && imy >= 0 && imy < output_y) *(im + output_xy * kch + output_x * imy + imx) += *cur_col; cur_col++; } } } } } } } else if (is_8x8) { for (iy = 0; iy < input_y; iy++) { imy_start = iy * stride_y - pad_y; for (ix = 0; ix < input_x; ix++) { imx_start = ix * stride_x - pad_x; cur_col = col + (iy * input_x + ix) * weight_size; if (iy != 0 && iy != (input_y - 1) && ix != 0 && ix != (input_x - 1)) { for (kch = 0; kch < output_ch; kch++) for (ky = 0; ky < 8; ky++) { imy = imy_start + ky; for (kx = 0; kx < 8; kx++) *(im + output_xy * kch + output_x * imy + imx_start + kx) += *cur_col++; } } else { for (kch = 0; kch < output_ch; kch++) for (ky = 0; ky < 8; ky++) { imy = imy_start + ky; for (kx = 0; kx < 8; kx++) { imx = imx_start + kx; if (imx >= 0 && imx < output_x && imy >= 0 && imy < output_y) *(im + output_xy * kch + output_x * imy + imx) += *cur_col; cur_col++; } } } } } } // general case else { for (iy = 0; iy < input_y; iy++) { imy_start = iy * stride_y - pad_y; for (ix = 0; ix < input_x; ix++) { imx_start = ix * stride_x - pad_x; cur_col = col + (iy * input_x + ix) * weight_size; if (iy != 0 && iy != (input_y - 1) && ix != 0 && ix != (input_x - 1)) { for (kch = 0; kch < output_ch; kch++) for (ky = 0; ky < kernel_y; ky++) { imy = imy_start + ky * dilation_y; for (kx = 0; kx < kernel_x; kx++) { imx = imx_start + kx * dilation_x; *(im + output_xy * kch + output_x * imy + imx) += *cur_col++; } } } else { for (kch = 0; kch < output_ch; kch++) { for (ky = 0; ky < kernel_y; ky++) { imy = imy_start + ky * dilation_y; for (kx = 0; kx < kernel_x; kx++) { imx = imx_start + kx * dilation_x; float out = bias[kch]; if (imx >= 0 && imx < output_x && imy >= 0 && imy < output_y) *(im + output_xy * kch + output_x * imy + imx) += *cur_col; cur_col++; } } } } } } } } static void sgemm_set(float* input, float* kernel, float* col, int in_ch, int in_hw, int kernel_size, int kernel_start, int kernel_end, int num_thread, int cpu_affinity) { int nn_kernel = (kernel_end - kernel_start) / PER_OUT_CHAN; int input_end3 = in_hw & 0x3; if (input_end3) { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_kernel; pp++) { int p = kernel_start + pp * PER_OUT_CHAN; float* cur_kernel = (float*)(kernel + p * in_ch); int i = 0; for (i = 0; i + 3 < in_hw; i += 4) #ifdef __aarch64__ { float* cur_input = (float*)(input + i * in_ch); float* cur_col = (float*)(col + i * kernel_size + p); if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x16_deconv_a53(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x16_deconv_a72(cur_input, cur_kernel, in_ch, cur_col, kernel_size); } { float result[64]; float* cur_input = (float*)(input + i * in_ch); if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x16_deconv_a53(cur_input, cur_kernel, in_ch, result, 16); else sgemm_4x16_deconv_a72(cur_input, cur_kernel, in_ch, result, 16); for (int j = 0; j < (input_end3); j++) { for (int k = 0; k < 16; k++) *(col + (i + j) * kernel_size + p + k) = result[(j << 4) + k]; } } #else { float* cur_input = (float*)(input + i * in_ch); float* cur_col = (float*)(col + i * kernel_size + p); if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x12_deconv_a7(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x12_deconv_a17(cur_input, cur_kernel, in_ch, cur_col, kernel_size); } { float result[48]; float* cur_input = (float*)(input + i * in_ch); if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x12_deconv_a7(cur_input, cur_kernel, in_ch, result, 12); else sgemm_4x12_deconv_a17(cur_input, cur_kernel, in_ch, result, 12); for (int j = 0; j < (input_end3); j++) { for (int k = 0; k < 12; k++) *(col + (i + j) * kernel_size + p + k) = result[j * 12 + k]; } } #endif } } else { #pragma omp parallel for num_threads(num_thread) for (int pp = 0; pp < nn_kernel; pp++) { int p = kernel_start + pp * PER_OUT_CHAN; float* cur_kernel = (float*)(kernel + p * in_ch); int i = 0; for (; i + 3 < in_hw; i += 4) { float* cur_input = (float*)(input + i * in_ch); float* cur_col = (float*)(col + i * kernel_size + p); #ifdef __aarch64__ if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x16_deconv_a53(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x16_deconv_a72(cur_input, cur_kernel, in_ch, cur_col, kernel_size); #else if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x12_deconv_a7(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x12_deconv_a17(cur_input, cur_kernel, in_ch, cur_col, kernel_size); #endif } } } } static void sgemm4x4(float* input, float* kernel, float* col, int in_ch, int in_hw, int kernel_size, int kernel_start, int kernel_end, int num_thread, int cpu_affinity) { float result[16]; int input_line, kernel_num; float *cur_col, *cur_kernel, *cur_input; int i, j; int input_end3 = in_hw & 0x3; int kernel_end3 = kernel_end & 0x3; for (kernel_num = kernel_start; kernel_num + 3 < (kernel_end & -4); kernel_num += 4) { cur_kernel = (float*)(kernel + kernel_num * in_ch); for (input_line = 0; input_line < (in_hw & -4); input_line += 4) { cur_input = (float*)(input + input_line * in_ch); cur_col = (float*)(col + input_line * kernel_size + kernel_num); #ifdef __aarch64__ if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a53(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x4_deconv_a72(cur_input, cur_kernel, in_ch, cur_col, kernel_size); #else if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a7(cur_input, cur_kernel, in_ch, cur_col, kernel_size); else sgemm_4x4_deconv_a17(cur_input, cur_kernel, in_ch, cur_col, kernel_size); #endif } if (input_end3) { cur_input = (float*)(input + input_line * in_ch); #ifdef __aarch64__ if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a53(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a72(cur_input, cur_kernel, in_ch, result, 4); #else if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a7(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a17(cur_input, cur_kernel, in_ch, result, 4); #endif for (j = 0; j < (input_end3); j++) for (i = 0; i < 4; i++) *(col + (input_line + j) * kernel_size + kernel_num + i) = result[(j << 2) + i]; } } if (kernel_end3) { cur_kernel = (float*)(kernel + kernel_num * in_ch); for (input_line = 0; input_line < (in_hw & -4); input_line += 4) { cur_input = (float*)(input + input_line * in_ch); #ifdef __aarch64__ if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a53(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a72(cur_input, cur_kernel, in_ch, result, 4); #else if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a7(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a17(cur_input, cur_kernel, in_ch, result, 4); #endif for (j = 0; j < 4; j++) for (i = 0; i < kernel_end3; i++) *(col + (input_line + j) * kernel_size + kernel_num + i) = result[(j << 2) + i]; } if (input_end3) { cur_input = (float*)(input + input_line * in_ch); #ifdef __aarch64__ if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a53(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a72(cur_input, cur_kernel, in_ch, result, 4); #else if (cpu_affinity == TENGINE_CLUSTER_LITTLE) sgemm_4x4_deconv_a7(cur_input, cur_kernel, in_ch, result, 4); else sgemm_4x4_deconv_a17(cur_input, cur_kernel, in_ch, result, 4); #endif for (j = 0; j < input_end3; j++) for (i = 0; i < kernel_end3; i++) *(col + (input_line + j) * kernel_size + kernel_num + i) = result[(j << 2) + i]; } } } int deconv_hcl_prerun(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* output_tensor, struct deconv_priv_info* priv_info, struct deconv_param* param) { int group = param->group; int kernel_h = param->kernel_h; int kernel_w = param->kernel_w; int out_ch = output_tensor->dims[1] / group; int in_ch = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int input_size = in_ch * ((in_h * in_w + 3) & -4); int kernel_size = kernel_h * kernel_w * out_ch; int kernel_size_g = ((kernel_size + 3) & -4) * in_ch; { int trans_input_size = sizeof(float) * input_size + 128; priv_info->trans_input_buffer = (float*)sys_malloc(trans_input_size); priv_info->trans_input_size = trans_input_size; int interleave_size = sizeof(float) * kernel_size_g * group + 128; priv_info->interleave_buffer = (float*)sys_malloc(interleave_size); priv_info->interleave_buffer_size = interleave_size; int col_size = sizeof(float) * in_h * in_w * kernel_size + 128; priv_info->col_buffer = (float*)sys_malloc(col_size); priv_info->col_buffer_size = col_size; } interleave(filter_tensor, priv_info, param); return 0; } int deconv_hcl_postrun(struct deconv_priv_info* priv_info) { if (priv_info->interleave_buffer != NULL) { sys_free(priv_info->interleave_buffer); priv_info->interleave_buffer = NULL; } if (priv_info->trans_input_buffer != NULL) { sys_free(priv_info->trans_input_buffer); priv_info->trans_input_buffer = NULL; } if (priv_info->col_buffer != NULL) { sys_free(priv_info->col_buffer); priv_info->col_buffer = NULL; } return 0; } int deconv_hcl_run(struct tensor* input_tensor, struct tensor* filter_tensor, struct tensor* bias_tensor, struct tensor* output_tensor, struct deconv_priv_info* priv_info, struct deconv_param* param, int num_thread, int cpu_affinity) { /* param */ int group = param->group; int ksize = param->kernel_h; int stride = param->stride_h; int dilation = param->dilation_h; int pad = param->pad_w0; int act_type = param->activation; int batch = input_tensor->dims[0]; int in_c = input_tensor->dims[1] / group; int in_h = input_tensor->dims[2]; int in_w = input_tensor->dims[3]; int in_hw = in_h * in_w; int input_size = in_c * in_h * in_w; int out_c = output_tensor->dims[1] / group; int out_h = output_tensor->dims[2]; int out_w = output_tensor->dims[3]; int out_hw = out_h * out_w; int output_size = out_c * out_h * out_w; int kernel_size = out_c * ksize * ksize; int kernel_size_g = ((kernel_size + 3) & -4) * in_c; /* buffer addr */ float* input_buf = (float*)input_tensor->data; float* output_buf = (float*)output_tensor->data; float* biases_buf = (float*)bias_tensor->data; float* trans_input_buf = (float*)priv_info->trans_input_buffer; float* col_buf = (float*)priv_info->col_buffer; float* interleave_buf = (float*)priv_info->interleave_buffer; int sgemm_set_num = kernel_size / PER_OUT_CHAN * PER_OUT_CHAN; int sgemm_set_remain = kernel_size % PER_OUT_CHAN; for (int n = 0; n < batch; n++) // batch size { for (int g = 0; g < group; g++) { /* im2col */ float* cur_input = input_buf + (n * group + g) * input_size; float* cur_output = output_buf + (n * group + g) * output_size; float* cur_kernel = interleave_buf + g * kernel_size_g; transpose_input(cur_input, trans_input_buf, in_hw, in_c); /* gemm */ sgemm_set(trans_input_buf, cur_kernel, col_buf, in_c, in_hw, kernel_size, 0, sgemm_set_num, num_thread, cpu_affinity); if (sgemm_set_remain) sgemm4x4(trans_input_buf, cur_kernel, col_buf, in_c, in_hw, kernel_size, sgemm_set_num, kernel_size, num_thread, cpu_affinity); float* cur_bias = biases_buf ? (biases_buf + g * out_c) : NULL; col2im(col_buf, cur_output, cur_bias, out_c, out_w, out_h, ksize, ksize, stride, stride, dilation, dilation, pad, pad, in_w, in_h); } } return 0; }
pfmg3_setup_rap.c
/*BHEADER********************************************************************** * Copyright (c) 2008, Lawrence Livermore National Security, LLC. * Produced at the Lawrence Livermore National Laboratory. * This file is part of HYPRE. See file COPYRIGHT for details. * * HYPRE is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License (as published by the Free * Software Foundation) version 2.1 dated February 1999. * * $Revision$ ***********************************************************************EHEADER*/ #include "_hypre_struct_ls.h" #include "pfmg.h" /*-------------------------------------------------------------------------- * Macro to "change coordinates". This routine is written as though * coarsening is being done in the z-direction. This macro is used to * allow for coarsening to be done in the x- and y-directions also. *--------------------------------------------------------------------------*/ #define MapIndex(in_index, cdir, out_index) \ hypre_IndexD(out_index, cdir) = hypre_IndexD(in_index, 2); \ cdir = (cdir + 1) % 3; \ hypre_IndexD(out_index, cdir) = hypre_IndexD(in_index, 0); \ cdir = (cdir + 1) % 3; \ hypre_IndexD(out_index, cdir) = hypre_IndexD(in_index, 1); \ cdir = (cdir + 1) % 3; /*-------------------------------------------------------------------------- * Sets up new coarse grid operator stucture. *--------------------------------------------------------------------------*/ hypre_StructMatrix * hypre_PFMG3CreateRAPOp( hypre_StructMatrix *R, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructGrid *coarse_grid, HYPRE_Int cdir ) { hypre_StructMatrix *RAP; hypre_Index *RAP_stencil_shape; hypre_StructStencil *RAP_stencil; HYPRE_Int RAP_stencil_size; HYPRE_Int RAP_stencil_dim; HYPRE_Int RAP_num_ghost[] = {1, 1, 1, 1, 1, 1}; hypre_StructStencil *A_stencil; HYPRE_Int A_stencil_size; hypre_Index index_temp; HYPRE_Int k, j, i; HYPRE_Int stencil_rank; RAP_stencil_dim = 3; A_stencil = hypre_StructMatrixStencil(A); A_stencil_size = hypre_StructStencilSize(A_stencil); /*----------------------------------------------------------------------- * Define RAP_stencil *-----------------------------------------------------------------------*/ stencil_rank = 0; /*----------------------------------------------------------------------- * non-symmetric case *-----------------------------------------------------------------------*/ /*----------------------------------------------------------------------- * 7-point fine grid stencil produces 19 point RAP * * Store all 27 elements except for the corners. * * For symmetric A, only store the lower triangular part, where * lower triangular means the lower triangular part on the matrix * in the standard lexicographic ordering. *-----------------------------------------------------------------------*/ if( A_stencil_size == 7) { RAP_stencil_size = 19; if (hypre_StructMatrixSymmetric(A)) { RAP_stencil_size = (RAP_stencil_size + 1) / 2; } RAP_stencil_shape = hypre_CTAlloc(hypre_Index, RAP_stencil_size); for (k = -1; k < 2; k++) { for (j = -1; j < 2; j++) { for (i = -1; i < 2; i++) { if ((i*j*k == 0) && (stencil_rank < RAP_stencil_size)) { hypre_SetIndex3(index_temp,i,j,k); MapIndex(index_temp, cdir, RAP_stencil_shape[stencil_rank]); stencil_rank++; } } } } } /*----------------------------------------------------------------------- * 19 or 27 point fine grid stencil produces 27 point RAP * * Store all 27 elements * * For symmetric A, only store the lower triangular part, where * lower triangular means the lower triangular part on the matrix * in the standard lexicographic ordering. *-----------------------------------------------------------------------*/ else { RAP_stencil_size = 27; if (hypre_StructMatrixSymmetric(A)) { RAP_stencil_size = (RAP_stencil_size + 1) / 2; } RAP_stencil_shape = hypre_CTAlloc(hypre_Index, RAP_stencil_size); for (k = -1; k < 2; k++) { for (j = -1; j < 2; j++) { for (i = -1; i < 2; i++) { if (stencil_rank < RAP_stencil_size) { hypre_SetIndex3(index_temp,i,j,k); MapIndex(index_temp, cdir, RAP_stencil_shape[stencil_rank]); stencil_rank++; } } } } } RAP_stencil = hypre_StructStencilCreate(RAP_stencil_dim, RAP_stencil_size, RAP_stencil_shape); RAP = hypre_StructMatrixCreate(hypre_StructMatrixComm(A), coarse_grid, RAP_stencil); hypre_StructStencilDestroy(RAP_stencil); /*----------------------------------------------------------------------- * Coarse operator in symmetric iff fine operator is *-----------------------------------------------------------------------*/ hypre_StructMatrixSymmetric(RAP) = hypre_StructMatrixSymmetric(A); /*----------------------------------------------------------------------- * Set number of ghost points - one one each boundary *-----------------------------------------------------------------------*/ hypre_StructMatrixSetNumGhost(RAP, RAP_num_ghost); return RAP; } /*-------------------------------------------------------------------------- * Routines to build RAP. These routines are fairly general * 1) No assumptions about symmetry of A * 2) No assumption that R = transpose(P) * 3) 7, 19 or 27-point fine grid A * * I am, however, assuming that the c-to-c interpolation is the identity. * * I've written a two routines - hypre_PFMG3BuildRAPSym to build the lower * triangular part of RAP (including the diagonal) and * hypre_PFMG3BuildRAPNoSym to build the upper triangular part of RAP * (excluding the diagonal). So using symmetric storage, only the first * routine would be called. With full storage both would need to be called. * *--------------------------------------------------------------------------*/ HYPRE_Int hypre_PFMG3BuildRAPSym( hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_StructStencil *fine_stencil; HYPRE_Int fine_stencil_size; hypre_StructGrid *fgrid; HYPRE_Int *fgrid_ids; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; HYPRE_Int *cgrid_ids; HYPRE_Int fi, ci; HYPRE_Int constant_coefficient; HYPRE_Int constant_coefficient_A; fine_stencil = hypre_StructMatrixStencil(A); fine_stencil_size = hypre_StructStencilSize(fine_stencil); fgrid = hypre_StructMatrixGrid(A); fgrid_ids = hypre_StructGridIDs(fgrid); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_ids = hypre_StructGridIDs(cgrid); constant_coefficient = hypre_StructMatrixConstantCoefficient(RAP); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); hypre_assert( constant_coefficient==0 || constant_coefficient==1 ); hypre_assert( hypre_StructMatrixConstantCoefficient(R) == constant_coefficient ); hypre_assert( hypre_StructMatrixConstantCoefficient(P) == constant_coefficient ); if (constant_coefficient==1 ) { hypre_assert( constant_coefficient_A==1 ); } else { hypre_assert( constant_coefficient_A==0 || constant_coefficient_A==2 ); } fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ switch (fine_stencil_size) { /*-------------------------------------------------------------- * Loop for symmetric 7-point fine grid operator; produces a * symmetric 19-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-south, below-west, * below-center, below-east, below-north, center-south, * center-west, and center-center). *--------------------------------------------------------------*/ case 7: if ( constant_coefficient==1 ) { hypre_PFMG3BuildRAPSym_onebox_FSS07_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPSym_onebox_FSS07_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; /*-------------------------------------------------------------- * Loop for symmetric 19-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ case 19: if ( constant_coefficient==1 ) { hypre_PFMG3BuildRAPSym_onebox_FSS19_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPSym_onebox_FSS19_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; /*-------------------------------------------------------------- * Loop for symmetric 27-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ default: if ( constant_coefficient==1 ) { hypre_PFMG3BuildRAPSym_onebox_FSS27_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPSym_onebox_FSS27_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; } /* end switch statement */ } /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (7) and one value of constant_coefficient (0). Within this function there is a test on constant_coefficient_A as well. */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS07_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac; HYPRE_Real *a_bc; HYPRE_Real a_cs_offd, a_cs_offdm1, a_cs_offdp1; HYPRE_Real a_cn_offdm1; HYPRE_Real a_cw_offd, a_cw_offdm1, a_cw_offdp1; HYPRE_Real a_ce_offdm1; HYPRE_Real a_ac_offd, a_ac_offdm1; HYPRE_Real a_bc_offd, a_bc_offdm1, a_bc_offdp1; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 7-point fine grid operator; produces a * symmetric 19-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-south, below-west, * below-center, below-east, below-north, center-south, * center-west, and center-center). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A == 0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1]; rap_csw[iAc] = 0.0; rap_cse[iAc] = 0.0; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cs_offd = a_cs[iA_offd]; a_cs_offdm1 = a_cs[iA_offdm1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cw_offd = a_cw[iA_offd]; a_cw_offdm1 = a_cw[iA_offdm1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_ce_offdm1 = a_ce[iA_offdm1]; a_cn_offdm1 = a_cn[iA_offdm1]; a_bc_offd = a_bc[iA_offd]; a_bc_offdm1 = a_bc[iA_offdm1]; a_bc_offdp1 = a_bc[iA_offdp1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdm1 = a_ac[iA_offdm1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs_offdm1 * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw_offdm1 * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc_offd * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc_offdm1; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce_offdm1 * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn_offdm1 * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs_offd + rb[iR] * a_cs_offdm1 * pb[iP1] + ra[iR] * a_cs_offdp1 * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw_offd + rb[iR] * a_cw_offdm1 * pb[iP1] + ra[iR] * a_cw_offdp1 * pa[iP1]; rap_csw[iAc] = 0.0; rap_cse[iAc] = 0.0; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac_offdm1 + ra[iR] * a_bc_offdp1 + a_bc_offd * pb[iP] + a_ac_offd * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (7) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS07_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac; HYPRE_Real *a_bc; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 7-point fine grid operator; produces a * symmetric 19-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-south, below-west, * below-center, below-east, below-north, center-south, * center-west, and center-center). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1]; rap_csw[iAc] = 0.0; rap_cse[iAc] = 0.0; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (19) and one value of constant_coefficient (0). Within this functions there is a test on constant_coefficient_A as well. */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS19_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_as; HYPRE_Real *a_bc, *a_bw, *a_be, *a_bs, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real a_cs_offd, a_cs_offdm1, a_cs_offdp1; HYPRE_Real a_csw_offd, a_csw_offdm1, a_csw_offdp1; HYPRE_Real a_cse_offd, a_cse_offdm1, a_cse_offdp1; HYPRE_Real a_cn_offdm1, a_cne_offdm1, a_cnw_offdm1; HYPRE_Real a_cw_offd, a_cw_offdm1, a_cw_offdp1; HYPRE_Real a_ce_offdm1; HYPRE_Real a_ac_offd, a_ac_offdm1; HYPRE_Real a_aw_offd, a_aw_offdm1; HYPRE_Real a_as_offd, a_as_offdm1; HYPRE_Real a_bc_offd, a_bc_offdm1, a_bc_offdp1; HYPRE_Real a_be_offd, a_be_offdm1; HYPRE_Real a_bn_offd, a_bn_offdm1; HYPRE_Real a_bw_offd, a_bw_offdm1, a_bw_offdp1; HYPRE_Real a_bs_offd, a_bs_offdm1, a_bs_offdp1; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Real *rap_bsw, *rap_bse, *rap_bnw, *rap_bne; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); a_bw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); a_bs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the lower triangular part. * * rap_csw is pointer for southwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); rap_bsw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); rap_bse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); rap_bnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); rap_bne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 19-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A==0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1] + rb[iR] * a_bs[iAm1] + a_bs[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1] + rb[iR] * a_bw[iAm1] + a_bw[iA] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1] + rb[iR] * a_be[iAm1] + a_be[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1] + rb[iR] * a_bn[iAm1] + a_bn[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne[iAm1] * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw[iA] + rb[iR] * a_csw[iAm1] * pb[iP1] + ra[iR] * a_csw[iAp1] * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1] + a_bs[iA] * pb[iP1] + a_as[iA] * pa[iP1] + rb[iR] * a_as[iAm1] + ra[iR] * a_bs[iAp1]; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse[iA] + rb[iR] * a_cse[iAm1] * pb[iP1] + ra[iR] * a_cse[iAp1] * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1] + a_bw[iA] * pb[iP1] + a_aw[iA] * pa[iP1] + rb[iR] * a_aw[iAm1] + ra[iR] * a_bw[iAp1]; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cs_offd = a_cs[iA_offd]; a_cs_offdm1 = a_cs[iA_offdm1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cw_offd = a_cw[iA_offd]; a_cw_offdm1 = a_cw[iA_offdm1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_ce_offdm1 = a_ce[iA_offdm1]; a_csw_offd = a_csw[iA_offd]; a_csw_offdm1 = a_csw[iA_offdm1]; a_csw_offdp1 = a_csw[iA_offdp1]; a_cse_offd = a_cse[iA_offd]; a_cse_offdm1 = a_cse[iA_offdm1]; a_cse_offdp1 = a_cse[iA_offdp1]; a_cn_offdm1 = a_cn[iA_offdm1]; a_cne_offdm1 = a_cne[iA_offdm1]; a_cnw_offdm1 = a_cnw[iA_offdm1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdm1 = a_ac[iA_offdm1]; a_aw_offd = a_aw[iA_offd]; a_aw_offdm1 = a_aw[iA_offdm1]; a_as_offd = a_as[iA_offd]; a_as_offdm1 = a_as[iA_offdm1]; a_bc_offd = a_bc[iA_offd]; a_bc_offdm1 = a_bc[iA_offdm1]; a_bc_offdp1 = a_bc[iA_offdp1]; a_be_offd = a_be[iA_offd]; a_be_offdm1 = a_be[iA_offdm1]; a_bn_offd = a_bn[iA_offd]; a_bn_offdm1 = a_bn[iA_offdm1]; a_bw_offd = a_bw[iA_offd]; a_bw_offdm1 = a_bw[iA_offdm1]; a_bw_offdp1 = a_bw[iA_offdp1]; a_bs_offd = a_bs[iA_offd]; a_bs_offdm1 = a_bs[iA_offdm1]; a_bs_offdp1 = a_bs[iA_offdp1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw_offdm1 * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs_offdm1 * pa[iP1] + rb[iR] * a_bs_offdm1 + a_bs_offd * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse_offdm1 * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw_offdm1 * pa[iP1] + rb[iR] * a_bw_offdm1 + a_bw_offd * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc_offd * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc_offdm1; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce_offdm1 * pa[iP1] + rb[iR] * a_be_offdm1 + a_be_offd * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw_offdm1 * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn_offdm1 * pa[iP1] + rb[iR] * a_bn_offdm1 + a_bn_offd * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne_offdm1 * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw_offd + rb[iR] * a_csw_offdm1 * pb[iP1] + ra[iR] * a_csw_offdp1 * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs_offd + rb[iR] * a_cs_offdm1 * pb[iP1] + ra[iR] * a_cs_offdp1 * pa[iP1] + a_bs_offd * pb[iP1] + a_as_offd * pa[iP1] + rb[iR] * a_as_offdm1 + ra[iR] * a_bs_offdp1; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse_offd + rb[iR] * a_cse_offdm1 * pb[iP1] + ra[iR] * a_cse_offdp1 * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw_offd + rb[iR] * a_cw_offdm1 * pb[iP1] + ra[iR] * a_cw_offdp1 * pa[iP1] + a_bw_offd * pb[iP1] + a_aw_offd * pa[iP1] + rb[iR] * a_aw_offdm1 + ra[iR] * a_bw_offdp1; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac_offdm1 + ra[iR] * a_bc_offdp1 + a_bc_offd * pb[iP] + a_ac_offd * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (19) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS19_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_as; HYPRE_Real *a_bc, *a_bw, *a_be, *a_bs, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Real *rap_bsw, *rap_bse, *rap_bnw, *rap_bne; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); a_bw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); a_bs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the lower triangular part. * * rap_csw is pointer for southwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); rap_bsw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); rap_bse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); rap_bnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); rap_bne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 19-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1] + rb[iR] * a_bs[iAm1] + a_bs[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse[iAm1] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1] + rb[iR] * a_bw[iAm1] + a_bw[iA] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1] + rb[iR] * a_be[iAm1] + a_be[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw[iAm1] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1] + rb[iR] * a_bn[iAm1] + a_bn[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne[iAm1] * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw[iA] + rb[iR] * a_csw[iAm1] * pb[iP1] + ra[iR] * a_csw[iAp1] * pa[iP1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1] + a_bs[iA] * pb[iP1] + a_as[iA] * pa[iP1] + rb[iR] * a_as[iAm1] + ra[iR] * a_bs[iAp1]; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse[iA] + rb[iR] * a_cse[iAm1] * pb[iP1] + ra[iR] * a_cse[iAp1] * pa[iP1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1] + a_bw[iA] * pb[iP1] + a_aw[iA] * pa[iP1] + rb[iR] * a_aw[iAm1] + ra[iR] * a_bw[iAp1]; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (27) and one value of constant_coefficient (0). Within this functions there is a test on constant_coefficient_A as well. */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS27_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_as; HYPRE_Real *a_bc, *a_bw, *a_be, *a_bs, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *a_asw, *a_ase; HYPRE_Real *a_bsw, *a_bse, *a_bnw, *a_bne; HYPRE_Real a_cs_offd, a_cs_offdm1, a_cs_offdp1; HYPRE_Real a_csw_offd, a_csw_offdm1, a_csw_offdp1; HYPRE_Real a_cse_offd, a_cse_offdm1, a_cse_offdp1; HYPRE_Real a_cn_offdm1, a_cne_offdm1, a_cnw_offdm1; HYPRE_Real a_cw_offd, a_cw_offdm1, a_cw_offdp1; HYPRE_Real a_ce_offdm1; HYPRE_Real a_ac_offd, a_ac_offdm1; HYPRE_Real a_aw_offd, a_aw_offdm1; HYPRE_Real a_as_offd, a_as_offdm1; HYPRE_Real a_asw_offd, a_asw_offdm1; HYPRE_Real a_ase_offd, a_ase_offdm1; HYPRE_Real a_bc_offd, a_bc_offdm1, a_bc_offdp1; HYPRE_Real a_be_offd, a_be_offdm1; HYPRE_Real a_bn_offd, a_bn_offdm1; HYPRE_Real a_bw_offd, a_bw_offdm1, a_bw_offdp1; HYPRE_Real a_bs_offd, a_bs_offdm1, a_bs_offdp1; HYPRE_Real a_bsw_offd, a_bsw_offdm1, a_bsw_offdp1; HYPRE_Real a_bse_offd, a_bse_offdm1, a_bse_offdp1; HYPRE_Real a_bnw_offd, a_bnw_offdm1; HYPRE_Real a_bne_offd, a_bne_offdm1; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Real *rap_bsw, *rap_bse, *rap_bnw, *rap_bne; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); a_bw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); a_bs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point fine grid operator: * * a_asw is pointer for southwest coefficient in plane above * a_ase is pointer for southeast coefficient in plane above * a_anw is pointer for northwest coefficient in plane above * a_ane is pointer for northeast coefficient in plane above * a_bsw is pointer for southwest coefficient in plane below * a_bse is pointer for southeast coefficient in plane below * a_bnw is pointer for northwest coefficient in plane below * a_bne is pointer for northeast coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); a_asw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); a_ase = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); a_bsw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); a_bse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); a_bnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); a_bne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the lower triangular part. * * rap_csw is pointer for southwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); rap_bsw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); rap_bse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); rap_bnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); rap_bne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 27-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A == 0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw[iAm1] * pa[iP1] + rb[iR] * a_bsw[iAm1] + a_bsw[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1] + rb[iR] * a_bs[iAm1] + a_bs[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse[iAm1] * pa[iP1] + rb[iR] * a_bse[iAm1] + a_bse[iA] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1] + rb[iR] * a_bw[iAm1] + a_bw[iA] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1] + rb[iR] * a_be[iAm1] + a_be[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw[iAm1] * pa[iP1] + rb[iR] * a_bnw[iAm1] + a_bnw[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1] + rb[iR] * a_bn[iAm1] + a_bn[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne[iAm1] * pa[iP1] + rb[iR] * a_bne[iAm1] + a_bne[iA] * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw[iA] + rb[iR] * a_csw[iAm1] * pb[iP1] + ra[iR] * a_csw[iAp1] * pa[iP1] + a_bsw[iA] * pb[iP1] + a_asw[iA] * pa[iP1] + rb[iR] * a_asw[iAm1] + ra[iR] * a_bsw[iAp1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1] + a_bs[iA] * pb[iP1] + a_as[iA] * pa[iP1] + rb[iR] * a_as[iAm1] + ra[iR] * a_bs[iAp1]; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse[iA] + rb[iR] * a_cse[iAm1] * pb[iP1] + ra[iR] * a_cse[iAp1] * pa[iP1] + a_bse[iA] * pb[iP1] + a_ase[iA] * pa[iP1] + rb[iR] * a_ase[iAm1] + ra[iR] * a_bse[iAp1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1] + a_bw[iA] * pb[iP1] + a_aw[iA] * pa[iP1] + rb[iR] * a_aw[iAm1] + ra[iR] * a_bw[iAp1]; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cs_offd = a_cs[iA_offd]; a_cs_offdm1 = a_cs[iA_offdm1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cse_offd = a_cse[iA_offd]; a_cse_offdm1 = a_cse[iA_offdm1]; a_cse_offdp1 = a_cse[iA_offdp1]; a_csw_offd = a_csw[iA_offd]; a_csw_offdm1 = a_csw[iA_offdm1]; a_csw_offdp1 = a_csw[iA_offdp1]; a_cw_offd = a_cw[iA_offd]; a_cw_offdm1 = a_cw[iA_offdm1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_cn_offdm1 = a_cn[iA_offdm1]; a_cne_offdm1 = a_cne[iA_offdm1]; a_cnw_offdm1 = a_cnw[iA_offdm1]; a_ce_offdm1 = a_ce[iA_offdm1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdm1 = a_ac[iA_offdm1]; a_as_offd = a_as[iA_offd]; a_as_offdm1 = a_as[iA_offdm1]; a_aw_offd = a_aw[iA_offd]; a_aw_offdm1 = a_aw[iA_offdm1]; a_asw_offd = a_asw[iA_offd]; a_asw_offdm1 = a_asw[iA_offdm1]; a_ase_offd = a_ase[iA_offd]; a_ase_offdm1 = a_ase[iA_offdm1]; a_bc_offd = a_bc[iA_offd]; a_bc_offdm1 = a_bc[iA_offdm1]; a_bc_offdp1 = a_bc[iA_offdp1]; a_bs_offd = a_bs[iA_offd]; a_bs_offdm1 = a_bs[iA_offdm1]; a_bs_offdp1 = a_bs[iA_offdp1]; a_bsw_offd = a_bsw[iA_offd]; a_bsw_offdm1 = a_bsw[iA_offdm1]; a_bsw_offdp1 = a_bsw[iA_offdp1]; a_bse_offd = a_bse[iA_offd]; a_bse_offdm1 = a_bse[iA_offdm1]; a_bse_offdp1 = a_bse[iA_offdp1]; a_be_offd = a_be[iA_offd]; a_be_offdm1 = a_be[iA_offdm1]; a_bw_offd = a_bw[iA_offd]; a_bw_offdm1 = a_bw[iA_offdm1]; a_bw_offdp1 = a_bw[iA_offdp1]; a_bn_offd = a_bn[iA_offd]; a_bn_offdm1 = a_bn[iA_offdm1]; a_bnw_offd = a_bnw[iA_offd]; a_bnw_offdm1 = a_bnw[iA_offdm1]; a_bne_offd = a_bne[iA_offd]; a_bne_offdm1 = a_bne[iA_offdm1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw_offdm1 * pa[iP1] + rb[iR] * a_bsw_offdm1 + a_bsw_offd * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs_offdm1 * pa[iP1] + rb[iR] * a_bs_offdm1 + a_bs_offd * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse_offdm1 * pa[iP1] + rb[iR] * a_bse_offdm1 + a_bse_offd * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw_offdm1 * pa[iP1] + rb[iR] * a_bw_offdm1 + a_bw_offd * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc_offd * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc_offdm1; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce_offdm1 * pa[iP1] + rb[iR] * a_be_offdm1 + a_be_offd * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw_offdm1 * pa[iP1] + rb[iR] * a_bnw_offdm1 + a_bnw_offd * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn_offdm1 * pa[iP1] + rb[iR] * a_bn_offdm1 + a_bn_offd * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne_offdm1 * pa[iP1] + rb[iR] * a_bne_offdm1 + a_bne_offd * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw_offd + rb[iR] * a_csw_offdm1 * pb[iP1] + ra[iR] * a_csw_offdp1 * pa[iP1] + a_bsw_offd * pb[iP1] + a_asw_offd * pa[iP1] + rb[iR] * a_asw_offdm1 + ra[iR] * a_bsw_offdp1; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs_offd + rb[iR] * a_cs_offdm1 * pb[iP1] + ra[iR] * a_cs_offdp1 * pa[iP1] + a_bs_offd * pb[iP1] + a_as_offd * pa[iP1] + rb[iR] * a_as_offdm1 + ra[iR] * a_bs_offdp1; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse_offd + rb[iR] * a_cse_offdm1 * pb[iP1] + ra[iR] * a_cse_offdp1 * pa[iP1] + a_bse_offd * pb[iP1] + a_ase_offd * pa[iP1] + rb[iR] * a_ase_offdm1 + ra[iR] * a_bse_offdp1; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw_offd + rb[iR] * a_cw_offdm1 * pb[iP1] + ra[iR] * a_cw_offdp1 * pa[iP1] + a_bw_offd * pb[iP1] + a_aw_offd * pa[iP1] + rb[iR] * a_aw_offdm1 + ra[iR] * a_bw_offdp1; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac_offdm1 + ra[iR] * a_bc_offdp1 + a_bc_offd * pb[iP] + a_ac_offd * pa[iP]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPSym, for one box, one value of fine_stencil_size (27) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPSym_onebox_FSS27_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_as; HYPRE_Real *a_bc, *a_bw, *a_be, *a_bs, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *a_asw, *a_ase; HYPRE_Real *a_bsw, *a_bse, *a_bnw, *a_bne; HYPRE_Real *rap_cc, *rap_cw, *rap_cs; HYPRE_Real *rap_bc, *rap_bw, *rap_be, *rap_bs, *rap_bn; HYPRE_Real *rap_csw, *rap_cse; HYPRE_Real *rap_bsw, *rap_bse, *rap_bnw, *rap_bne; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); a_bc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); a_bw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); a_bs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point fine grid operator: * * a_asw is pointer for southwest coefficient in plane above * a_ase is pointer for southeast coefficient in plane above * a_anw is pointer for northwest coefficient in plane above * a_ane is pointer for northeast coefficient in plane above * a_bsw is pointer for southwest coefficient in plane below * a_bse is pointer for southeast coefficient in plane below * a_bnw is pointer for northwest coefficient in plane below * a_bne is pointer for northeast coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); a_asw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); a_ase = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); a_bsw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); a_bse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); a_bnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); a_bne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the lower triangular part (plus diagonal). * * rap_cc is pointer for center coefficient (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); rap_cc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); rap_cw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); rap_cs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); rap_bc = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,-1); MapIndex(index_temp, cdir, index); rap_bw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); rap_be = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,-1); MapIndex(index_temp, cdir, index); rap_bs = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); rap_bn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); rap_csw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); rap_cse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the lower triangular part. * * rap_csw is pointer for southwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,-1); MapIndex(index_temp, cdir, index); rap_bsw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,-1); MapIndex(index_temp, cdir, index); rap_bse = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); rap_bnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); rap_bne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*-------------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for symmetric 27-point fine grid operator; produces a * symmetric 27-point coarse grid operator. We calculate only the * lower triangular stencil entries: (below-southwest, below-south, * below-southeast, below-west, below-center, below-east, * below-northwest, below-north, below-northeast, center-southwest, * center-south, center-southeast, center-west, and center-center). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP - zOffsetP - yOffsetP - xOffsetP; rap_bsw[iAc] = rb[iR] * a_csw[iAm1] * pa[iP1] + rb[iR] * a_bsw[iAm1] + a_bsw[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP; rap_bs[iAc] = rb[iR] * a_cs[iAm1] * pa[iP1] + rb[iR] * a_bs[iAm1] + a_bs[iA] * pa[iP1]; iP1 = iP - zOffsetP - yOffsetP + xOffsetP; rap_bse[iAc] = rb[iR] * a_cse[iAm1] * pa[iP1] + rb[iR] * a_bse[iAm1] + a_bse[iA] * pa[iP1]; iP1 = iP - zOffsetP - xOffsetP; rap_bw[iAc] = rb[iR] * a_cw[iAm1] * pa[iP1] + rb[iR] * a_bw[iAm1] + a_bw[iA] * pa[iP1]; iP1 = iP - zOffsetP; rap_bc[iAc] = a_bc[iA] * pa[iP1] + rb[iR] * a_cc[iAm1] * pa[iP1] + rb[iR] * a_bc[iAm1]; iP1 = iP - zOffsetP + xOffsetP; rap_be[iAc] = rb[iR] * a_ce[iAm1] * pa[iP1] + rb[iR] * a_be[iAm1] + a_be[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP - xOffsetP; rap_bnw[iAc] = rb[iR] * a_cnw[iAm1] * pa[iP1] + rb[iR] * a_bnw[iAm1] + a_bnw[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP; rap_bn[iAc] = rb[iR] * a_cn[iAm1] * pa[iP1] + rb[iR] * a_bn[iAm1] + a_bn[iA] * pa[iP1]; iP1 = iP - zOffsetP + yOffsetP + xOffsetP; rap_bne[iAc] = rb[iR] * a_cne[iAm1] * pa[iP1] + rb[iR] * a_bne[iAm1] + a_bne[iA] * pa[iP1]; iP1 = iP - yOffsetP - xOffsetP; rap_csw[iAc] = a_csw[iA] + rb[iR] * a_csw[iAm1] * pb[iP1] + ra[iR] * a_csw[iAp1] * pa[iP1] + a_bsw[iA] * pb[iP1] + a_asw[iA] * pa[iP1] + rb[iR] * a_asw[iAm1] + ra[iR] * a_bsw[iAp1]; iP1 = iP - yOffsetP; rap_cs[iAc] = a_cs[iA] + rb[iR] * a_cs[iAm1] * pb[iP1] + ra[iR] * a_cs[iAp1] * pa[iP1] + a_bs[iA] * pb[iP1] + a_as[iA] * pa[iP1] + rb[iR] * a_as[iAm1] + ra[iR] * a_bs[iAp1]; iP1 = iP - yOffsetP + xOffsetP; rap_cse[iAc] = a_cse[iA] + rb[iR] * a_cse[iAm1] * pb[iP1] + ra[iR] * a_cse[iAp1] * pa[iP1] + a_bse[iA] * pb[iP1] + a_ase[iA] * pa[iP1] + rb[iR] * a_ase[iAm1] + ra[iR] * a_bse[iAp1]; iP1 = iP - xOffsetP; rap_cw[iAc] = a_cw[iA] + rb[iR] * a_cw[iAm1] * pb[iP1] + ra[iR] * a_cw[iAp1] * pa[iP1] + a_bw[iA] * pb[iP1] + a_aw[iA] * pa[iP1] + rb[iR] * a_aw[iAm1] + ra[iR] * a_bw[iAp1]; rap_cc[iAc] = a_cc[iA] + rb[iR] * a_cc[iAm1] * pb[iP] + ra[iR] * a_cc[iAp1] * pa[iP] + rb[iR] * a_ac[iAm1] + ra[iR] * a_bc[iAp1] + a_bc[iA] * pb[iP] + a_ac[iA] * pa[iP]; /* }*/ /* end ForBoxI */ return hypre_error_flag; } /*-------------------------------------------------------------------------- *--------------------------------------------------------------------------*/ HYPRE_Int hypre_PFMG3BuildRAPNoSym( hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_StructStencil *fine_stencil; HYPRE_Int fine_stencil_size; hypre_StructGrid *fgrid; HYPRE_Int *fgrid_ids; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; HYPRE_Int *cgrid_ids; HYPRE_Int fi, ci; HYPRE_Int constant_coefficient; HYPRE_Int constant_coefficient_A; fine_stencil = hypre_StructMatrixStencil(A); fine_stencil_size = hypre_StructStencilSize(fine_stencil); fgrid = hypre_StructMatrixGrid(A); fgrid_ids = hypre_StructGridIDs(fgrid); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_ids = hypre_StructGridIDs(cgrid); constant_coefficient = hypre_StructMatrixConstantCoefficient(RAP); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); hypre_assert( constant_coefficient==0 || constant_coefficient==1 ); hypre_assert( hypre_StructMatrixConstantCoefficient(R) == constant_coefficient ); hypre_assert( hypre_StructMatrixConstantCoefficient(P) == constant_coefficient ); if (constant_coefficient==1 ) { hypre_assert( constant_coefficient_A==1 ); } else { hypre_assert( constant_coefficient_A==0 || constant_coefficient_A==2 ); } fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } switch (fine_stencil_size) { /*-------------------------------------------------------------- * Loop for 7-point fine grid operator; produces upper triangular * part of 19-point coarse grid operator. stencil entries: * (above-north, above-east, above-center, above-west, * above-south, center-north, and center-east). *--------------------------------------------------------------*/ case 7: if ( constant_coefficient == 1 ) { hypre_PFMG3BuildRAPNoSym_onebox_FSS07_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPNoSym_onebox_FSS07_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; /*-------------------------------------------------------------- * Loop for 19-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ case 19: if ( constant_coefficient == 1 ) { hypre_PFMG3BuildRAPNoSym_onebox_FSS19_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPNoSym_onebox_FSS19_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; /*-------------------------------------------------------------- * Loop for 27-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ default: if ( constant_coefficient == 1 ) { hypre_PFMG3BuildRAPNoSym_onebox_FSS27_CC1( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } else { hypre_PFMG3BuildRAPNoSym_onebox_FSS27_CC0( ci, fi, A, P, R, cdir, cindex, cstride, RAP ); } break; } /* end switch statement */ } /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (07) and one value of constant_coefficient (0). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS07_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac; HYPRE_Real a_cn_offd, a_cn_offdm1, a_cn_offdp1; HYPRE_Real a_ce_offd, a_ce_offdm1, a_ce_offdp1; HYPRE_Real a_cs_offdp1, a_cw_offdp1; HYPRE_Real a_ac_offd, a_ac_offdp1; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); /* fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } */ cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 7-point fine grid operator; produces upper triangular * part of 19-point coarse grid operator. stencil entries: * (above-north, above-east, above-center, above-west, * above-south, center-north, and center-east). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A == 0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1]; rap_cnw[iAc] = 0.0; rap_cne[iAc] = 0.0; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cn_offd = a_cn[iA_offd]; a_cn_offdm1 = a_cn[iA_offdm1]; a_cn_offdp1 = a_cn[iA_offdp1]; a_ce_offd = a_ce[iA_offd]; a_ce_offdm1 = a_ce[iA_offdm1]; a_ce_offdp1 = a_ce[iA_offdp1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdp1 = a_ac[iA_offdp1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn_offdp1 * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce_offdp1 * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac_offd * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac_offdp1; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw_offdp1 * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs_offdp1 * pb[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn_offd + rb[iR] * a_cn_offdm1 * pb[iP1] + ra[iR] * a_cn_offdp1 * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce_offd + rb[iR] * a_ce_offdm1 * pb[iP1] + ra[iR] * a_ce_offdp1 * pa[iP1]; rap_cnw[iAc] = 0.0; rap_cne[iAc] = 0.0; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (07) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS07_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 7-point fine grid operator; produces upper triangular * part of 19-point coarse grid operator. stencil entries: * (above-north, above-east, above-center, above-west, * above-south, center-north, and center-east). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1]; rap_cnw[iAc] = 0.0; rap_cne[iAc] = 0.0; /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (19) and one value of constant_coefficient (0). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS19_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_ae, *a_as, *a_an; HYPRE_Real *a_be, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real a_cn_offd, a_cn_offdm1, a_cn_offdp1; HYPRE_Real a_ce_offd, a_ce_offdm1, a_ce_offdp1; HYPRE_Real a_cs_offdp1, a_cw_offdp1, a_cse_offdp1, a_csw_offdp1; HYPRE_Real a_cne_offd, a_cne_offdm1, a_cne_offdp1; HYPRE_Real a_cnw_offd, a_cnw_offdm1, a_cnw_offdp1; HYPRE_Real a_ac_offd, a_ac_offdp1; HYPRE_Real a_an_offd, a_an_offdm1, a_an_offdp1; HYPRE_Real a_as_offd, a_as_offdp1; HYPRE_Real a_aw_offd, a_aw_offdp1; HYPRE_Real a_ae_offd, a_ae_offdm1, a_ae_offdp1; HYPRE_Real a_be_offd, a_be_offdp1; HYPRE_Real a_bn_offd, a_bn_offdp1; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Real *rap_asw, *rap_ase, *rap_anw, *rap_ane; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); /* fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } */ cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); a_ae = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); a_an = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the upper triangular part. * * rap_cnw is pointer for northwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); rap_asw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); rap_ase = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); rap_anw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); rap_ane = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 19-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A == 0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1] + ra[iR] * a_an[iAp1] + a_an[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1] + ra[iR] * a_ae[iAp1] + a_ae[iA] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1] + ra[iR] * a_aw[iAp1] + a_aw[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse[iAp1] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1] + ra[iR] * a_as[iAp1] + a_as[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw[iAp1] * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne[iA] + rb[iR] * a_cne[iAm1] * pb[iP1] + ra[iR] * a_cne[iAp1] * pa[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1] + a_bn[iA] * pb[iP1] + a_an[iA] * pa[iP1] + rb[iR] * a_an[iAm1] + ra[iR] * a_bn[iAp1]; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw[iA] + rb[iR] * a_cnw[iAm1] * pb[iP1] + ra[iR] * a_cnw[iAp1] * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1] + a_be[iA] * pb[iP1] + a_ae[iA] * pa[iP1] + rb[iR] * a_ae[iAm1] + ra[iR] * a_be[iAp1]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cn_offd = a_cn[iA_offd]; a_cn_offdm1 = a_cn[iA_offdm1]; a_cn_offdp1 = a_cn[iA_offdp1]; a_cne_offd = a_cne[iA_offd]; a_cne_offdm1 = a_cne[iA_offdm1]; a_cne_offdp1 = a_cne[iA_offdp1]; a_cnw_offd = a_cnw[iA_offd]; a_cnw_offdm1 = a_cnw[iA_offdm1]; a_cnw_offdp1 = a_cnw[iA_offdp1]; a_ce_offd = a_ce[iA_offd]; a_ce_offdm1 = a_ce[iA_offdm1]; a_ce_offdp1 = a_ce[iA_offdp1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cse_offdp1 = a_cse[iA_offdp1]; a_csw_offdp1 = a_csw[iA_offdp1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdp1 = a_ac[iA_offdp1]; a_an_offd = a_an[iA_offd]; a_an_offdm1 = a_an[iA_offdm1]; a_an_offdp1 = a_an[iA_offdp1]; a_as_offd = a_as[iA_offd]; a_as_offdp1 = a_as[iA_offdp1]; a_aw_offd = a_aw[iA_offd]; a_aw_offdp1 = a_aw[iA_offdp1]; a_ae_offd = a_ae[iA_offd]; a_ae_offdm1 = a_ae[iA_offdm1]; a_ae_offdp1 = a_ae[iA_offdp1]; a_be_offd = a_be[iA_offd]; a_be_offdp1 = a_be[iA_offdp1]; a_bn_offd = a_bn[iA_offd]; a_bn_offdp1 = a_bn[iA_offdp1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne_offdp1 * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn_offdp1 * pb[iP1] + ra[iR] * a_an_offdp1 + a_an_offd * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw_offdp1 * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce_offdp1 * pb[iP1] + ra[iR] * a_ae_offdp1 + a_ae_offd * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac_offd * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac_offdp1; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw_offdp1 * pb[iP1] + ra[iR] * a_aw_offdp1 + a_aw_offd * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse_offdp1 * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs_offdp1 * pb[iP1] + ra[iR] * a_as_offdp1 + a_as_offd * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw_offdp1 * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne_offd + rb[iR] * a_cne_offdm1 * pb[iP1] + ra[iR] * a_cne_offdp1 * pa[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn_offd + rb[iR] * a_cn_offdm1 * pb[iP1] + ra[iR] * a_cn_offdp1 * pa[iP1] + a_bn_offd * pb[iP1] + a_an_offd * pa[iP1] + rb[iR] * a_an_offdm1 + ra[iR] * a_bn_offdp1; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw_offd + rb[iR] * a_cnw_offdm1 * pb[iP1] + ra[iR] * a_cnw_offdp1 * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce_offd + rb[iR] * a_ce_offdm1 * pb[iP1] + ra[iR] * a_ce_offdp1 * pa[iP1] + a_be_offd * pb[iP1] + a_ae_offd * pa[iP1] + rb[iR] * a_ae_offdm1 + ra[iR] * a_be_offdp1; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (19) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS19_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_ae, *a_as, *a_an; HYPRE_Real *a_be, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Real *rap_asw, *rap_ase, *rap_anw, *rap_ane; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); a_ae = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); a_an = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the upper triangular part. * * rap_cnw is pointer for northwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); rap_asw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); rap_ase = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); rap_anw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); rap_ane = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 19-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1] + ra[iR] * a_an[iAp1] + a_an[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw[iAp1] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1] + ra[iR] * a_ae[iAp1] + a_ae[iA] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1] + ra[iR] * a_aw[iAp1] + a_aw[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse[iAp1] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1] + ra[iR] * a_as[iAp1] + a_as[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw[iAp1] * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne[iA] + rb[iR] * a_cne[iAm1] * pb[iP1] + ra[iR] * a_cne[iAp1] * pa[iP1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1] + a_bn[iA] * pb[iP1] + a_an[iA] * pa[iP1] + rb[iR] * a_an[iAm1] + ra[iR] * a_bn[iAp1]; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw[iA] + rb[iR] * a_cnw[iAm1] * pb[iP1] + ra[iR] * a_cnw[iAp1] * pa[iP1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1] + a_be[iA] * pb[iP1] + a_ae[iA] * pa[iP1] + rb[iR] * a_ae[iAm1] + ra[iR] * a_be[iAp1]; /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (27) and one value of constant_coefficient (0). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS27_CC0( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index stridec; hypre_Index fstart; hypre_IndexRef stridef; hypre_Index loop_size; HYPRE_Int constant_coefficient_A; hypre_Box *A_dbox; hypre_Box *P_dbox; hypre_Box *R_dbox; hypre_Box *RAP_dbox; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_ae, *a_as, *a_an; HYPRE_Real *a_be, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *a_asw, *a_ase, *a_anw, *a_ane; HYPRE_Real *a_bnw, *a_bne; HYPRE_Real a_cn_offd, a_cn_offdm1, a_cn_offdp1; HYPRE_Real a_ce_offd, a_ce_offdm1, a_ce_offdp1; HYPRE_Real a_cs_offdp1, a_cw_offdp1, a_cse_offdp1, a_csw_offdp1; HYPRE_Real a_cne_offd, a_cne_offdm1, a_cne_offdp1; HYPRE_Real a_cnw_offd, a_cnw_offdm1, a_cnw_offdp1; HYPRE_Real a_ac_offd, a_ac_offdp1; HYPRE_Real a_an_offd, a_an_offdm1, a_an_offdp1; HYPRE_Real a_ane_offd, a_ane_offdm1, a_ane_offdp1; HYPRE_Real a_anw_offd, a_anw_offdm1, a_anw_offdp1; HYPRE_Real a_as_offd, a_as_offdp1; HYPRE_Real a_ase_offd, a_ase_offdp1, a_asw_offd, a_asw_offdp1; HYPRE_Real a_aw_offd, a_aw_offdp1; HYPRE_Real a_ae_offd, a_ae_offdm1, a_ae_offdp1; HYPRE_Real a_be_offd, a_be_offdp1; HYPRE_Real a_bn_offd, a_bn_offdp1; HYPRE_Real a_bne_offd, a_bne_offdp1, a_bnw_offd, a_bnw_offdp1; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Real *rap_asw, *rap_ase, *rap_anw, *rap_ane; HYPRE_Int iA, iAm1, iAp1, iA_offd, iA_offdm1, iA_offdp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int zOffsetA_diag; HYPRE_Int zOffsetA_offd; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; stridef = cstride; hypre_SetIndex3(stridec, 1, 1, 1); cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); constant_coefficient_A = hypre_StructMatrixConstantCoefficient(A); /* fi = 0; hypre_ForBoxI(ci, cgrid_boxes) { while (fgrid_ids[fi] != cgrid_ids[ci]) { fi++; } */ cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); A_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(A), fi); P_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(P), fi); R_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(R), fi); RAP_dbox = hypre_BoxArrayBox(hypre_StructMatrixDataSpace(RAP), ci); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index) - hypre_BoxOffsetDistance(P_dbox, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index) - hypre_BoxOffsetDistance(R_dbox, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); a_ae = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); a_an = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point fine grid operator: * * a_asw is pointer for southwest coefficient in plane above * a_ase is pointer for southeast coefficient in plane above * a_anw is pointer for northwest coefficient in plane above * a_ane is pointer for northeast coefficient in plane above * a_bsw is pointer for southwest coefficient in plane below * a_bse is pointer for southeast coefficient in plane below * a_bnw is pointer for northwest coefficient in plane below * a_bne is pointer for northeast coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); a_asw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); a_ase = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); a_anw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); a_ane = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); a_bnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); a_bne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the upper triangular part. * * rap_cnw is pointer for northwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); rap_asw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); rap_ase = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); rap_anw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); rap_ane = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetP = hypre_BoxOffsetDistance(P_dbox,index); if ( constant_coefficient_A == 0 ) { zOffsetA = hypre_BoxOffsetDistance(A_dbox,index); } else { zOffsetA_diag = hypre_BoxOffsetDistance(A_dbox,index); zOffsetA_offd = 0; } hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = hypre_BoxOffsetDistance(P_dbox,index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = hypre_BoxOffsetDistance(P_dbox,index); /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 27-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ hypre_BoxGetSize(cgrid_box, loop_size); if ( constant_coefficient_A == 0 ) { hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne[iAp1] * pb[iP1] + ra[iR] * a_ane[iAp1] + a_ane[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1] + ra[iR] * a_an[iAp1] + a_an[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw[iAp1] * pb[iP1] + ra[iR] * a_anw[iAp1] + a_anw[iA] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1] + ra[iR] * a_ae[iAp1] + a_ae[iA] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1] + ra[iR] * a_aw[iAp1] + a_aw[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse[iAp1] * pb[iP1] + ra[iR] * a_ase[iAp1] + a_ase[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1] + ra[iR] * a_as[iAp1] + a_as[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw[iAp1] * pb[iP1] + ra[iR] * a_asw[iAp1] + a_asw[iA] * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne[iA] + rb[iR] * a_cne[iAm1] * pb[iP1] + ra[iR] * a_cne[iAp1] * pa[iP1] + a_bne[iA] * pb[iP1] + a_ane[iA] * pa[iP1] + rb[iR] * a_ane[iAm1] + ra[iR] * a_bne[iAp1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1] + a_bn[iA] * pb[iP1] + a_an[iA] * pa[iP1] + rb[iR] * a_an[iAm1] + ra[iR] * a_bn[iAp1]; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw[iA] + rb[iR] * a_cnw[iAm1] * pb[iP1] + ra[iR] * a_cnw[iAp1] * pa[iP1] + a_bnw[iA] * pb[iP1] + a_anw[iA] * pa[iP1] + rb[iR] * a_anw[iAm1] + ra[iR] * a_bnw[iAp1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1] + a_be[iA] * pb[iP1] + a_ae[iA] * pa[iP1] + rb[iR] * a_ae[iAm1] + ra[iR] * a_be[iAp1]; } hypre_BoxLoop4End(iP, iR, iA, iAc); } else { iA_offd = 0; iA_offdm1 = iA_offd - zOffsetA_offd; iA_offdp1 = iA_offd + zOffsetA_offd; a_cn_offd = a_cn[iA_offd]; a_cn_offdm1 = a_cn[iA_offdm1]; a_cn_offdp1 = a_cn[iA_offdp1]; a_cne_offd = a_cne[iA_offd]; a_cne_offdm1 = a_cne[iA_offdm1]; a_cne_offdp1 = a_cne[iA_offdp1]; a_cnw_offd = a_cnw[iA_offd]; a_cnw_offdm1 = a_cnw[iA_offdm1]; a_cnw_offdp1 = a_cnw[iA_offdp1]; a_ce_offd = a_ce[iA_offd]; a_ce_offdm1 = a_ce[iA_offdm1]; a_ce_offdp1 = a_ce[iA_offdp1]; a_cs_offdp1 = a_cs[iA_offdp1]; a_cse_offdp1 = a_cse[iA_offdp1]; a_csw_offdp1 = a_csw[iA_offdp1]; a_cw_offdp1 = a_cw[iA_offdp1]; a_ac_offd = a_ac[iA_offd]; a_ac_offdp1 = a_ac[iA_offdp1]; a_an_offd = a_an[iA_offd]; a_an_offdm1 = a_an[iA_offdm1]; a_an_offdp1 = a_an[iA_offdp1]; a_ane_offd = a_ane[iA_offd]; a_ane_offdm1 = a_ane[iA_offdm1]; a_ane_offdp1 = a_ane[iA_offdp1]; a_anw_offd = a_anw[iA_offd]; a_anw_offdm1 = a_anw[iA_offdm1]; a_anw_offdp1 = a_anw[iA_offdp1]; a_ae_offd = a_ae[iA_offd]; a_ae_offdm1 = a_ae[iA_offdm1]; a_ae_offdp1 = a_ae[iA_offdp1]; a_aw_offd = a_aw[iA_offd]; a_aw_offdp1 = a_aw[iA_offdp1]; a_as_offd = a_as[iA_offd]; a_as_offdp1 = a_as[iA_offdp1]; a_ase_offd = a_ase[iA_offd]; a_ase_offdp1 = a_ase[iA_offdp1]; a_asw_offd = a_asw[iA_offd]; a_asw_offdp1 = a_asw[iA_offdp1]; a_bn_offd = a_bn[iA_offd]; a_bn_offdp1 = a_bn[iA_offdp1]; a_bne_offd = a_bne[iA_offd]; a_bne_offdp1 = a_bne[iA_offdp1]; a_bnw_offd = a_bnw[iA_offd]; a_bnw_offdp1 = a_bnw[iA_offdp1]; a_be_offd = a_be[iA_offd]; a_be_offdp1 = a_be[iA_offdp1]; hypre_BoxLoop4Begin(hypre_StructMatrixNDim(A), loop_size, P_dbox, cstart, stridec, iP, R_dbox, cstart, stridec, iR, A_dbox, fstart, stridef, iA, RAP_dbox, cstart, stridec, iAc); #ifdef HYPRE_USING_OPENMP #pragma omp parallel for private(HYPRE_BOX_PRIVATE,iP,iR,iA,iAc,iAm1,iAp1,iP1) HYPRE_SMP_SCHEDULE #endif hypre_BoxLoop4For(iP, iR, iA, iAc) { iAm1 = iA - zOffsetA_diag; iAp1 = iA + zOffsetA_diag; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne_offdp1 * pb[iP1] + ra[iR] * a_ane_offdp1 + a_ane_offd * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn_offdp1 * pb[iP1] + ra[iR] * a_an_offdp1 + a_an_offd * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw_offdp1 * pb[iP1] + ra[iR] * a_anw_offdp1 + a_anw_offd * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce_offdp1 * pb[iP1] + ra[iR] * a_ae_offdp1 + a_ae_offd * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac_offd * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac_offdp1; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw_offdp1 * pb[iP1] + ra[iR] * a_aw_offdp1 + a_aw_offd * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse_offdp1 * pb[iP1] + ra[iR] * a_ase_offdp1 + a_ase_offd * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs_offdp1 * pb[iP1] + ra[iR] * a_as_offdp1 + a_as_offd * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw_offdp1 * pb[iP1] + ra[iR] * a_asw_offdp1 + a_asw_offd * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne_offd + rb[iR] * a_cne_offdm1 * pb[iP1] + ra[iR] * a_cne_offdp1 * pa[iP1] + a_bne_offd * pb[iP1] + a_ane_offd * pa[iP1] + rb[iR] * a_ane_offdm1 + ra[iR] * a_bne_offdp1; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn_offd + rb[iR] * a_cn_offdm1 * pb[iP1] + ra[iR] * a_cn_offdp1 * pa[iP1] + a_bn_offd * pb[iP1] + a_an_offd * pa[iP1] + rb[iR] * a_an_offdm1 + ra[iR] * a_bn_offdp1; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw_offd + rb[iR] * a_cnw_offdm1 * pb[iP1] + ra[iR] * a_cnw_offdp1 * pa[iP1] + a_bnw_offd * pb[iP1] + a_anw_offd * pa[iP1] + rb[iR] * a_anw_offdm1 + ra[iR] * a_bnw_offdp1; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce_offd + rb[iR] * a_ce_offdm1 * pb[iP1] + ra[iR] * a_ce_offdp1 * pa[iP1] + a_be_offd * pb[iP1] + a_ae_offd * pa[iP1] + rb[iR] * a_ae_offdm1 + ra[iR] * a_be_offdp1; } hypre_BoxLoop4End(iP, iR, iA, iAc); } /* }*/ /* end ForBoxI */ return hypre_error_flag; } /* core part of hypre_PFMG3BuildRAPNoSym, for one box, one value of fine_stencil_size (27) and one value of constant_coefficient (1). */ HYPRE_Int hypre_PFMG3BuildRAPNoSym_onebox_FSS27_CC1( HYPRE_Int ci, HYPRE_Int fi, hypre_StructMatrix *A, hypre_StructMatrix *P, hypre_StructMatrix *R, HYPRE_Int cdir, hypre_Index cindex, hypre_Index cstride, hypre_StructMatrix *RAP ) { hypre_Index index; hypre_Index index_temp; hypre_StructGrid *cgrid; hypre_BoxArray *cgrid_boxes; hypre_Box *cgrid_box; hypre_IndexRef cstart; hypre_Index fstart; HYPRE_Real *pa, *pb; HYPRE_Real *ra, *rb; HYPRE_Real *a_cc, *a_cw, *a_ce, *a_cs, *a_cn; HYPRE_Real *a_ac, *a_aw, *a_ae, *a_as, *a_an; HYPRE_Real *a_be, *a_bn; HYPRE_Real *a_csw, *a_cse, *a_cnw, *a_cne; HYPRE_Real *a_asw, *a_ase, *a_anw, *a_ane; HYPRE_Real *a_bnw, *a_bne; HYPRE_Real *rap_ce, *rap_cn; HYPRE_Real *rap_ac, *rap_aw, *rap_ae, *rap_as, *rap_an; HYPRE_Real *rap_cnw, *rap_cne; HYPRE_Real *rap_asw, *rap_ase, *rap_anw, *rap_ane; HYPRE_Int iA, iAm1, iAp1; HYPRE_Int iAc; HYPRE_Int iP, iP1; HYPRE_Int iR; HYPRE_Int zOffsetA; HYPRE_Int xOffsetP; HYPRE_Int yOffsetP; HYPRE_Int zOffsetP; cgrid = hypre_StructMatrixGrid(RAP); cgrid_boxes = hypre_StructGridBoxes(cgrid); cgrid_box = hypre_BoxArrayBox(cgrid_boxes, ci); cstart = hypre_BoxIMin(cgrid_box); hypre_StructMapCoarseToFine(cstart, cindex, cstride, fstart); /*----------------------------------------------------------------- * Extract pointers for interpolation operator: * pa is pointer for weight for f-point above c-point * pb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); pa = hypre_StructMatrixExtractPointerByIndex(P, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); pb = hypre_StructMatrixExtractPointerByIndex(P, fi, index); /*----------------------------------------------------------------- * Extract pointers for restriction operator: * ra is pointer for weight for f-point above c-point * rb is pointer for weight for f-point below c-point *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,-1); MapIndex(index_temp, cdir, index); ra = hypre_StructMatrixExtractPointerByIndex(R, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rb = hypre_StructMatrixExtractPointerByIndex(R, fi, index); /*----------------------------------------------------------------- * Extract pointers for 7-point fine grid operator: * * a_cc is pointer for center coefficient * a_cw is pointer for west coefficient in same plane * a_ce is pointer for east coefficient in same plane * a_cs is pointer for south coefficient in same plane * a_cn is pointer for north coefficient in same plane * a_ac is pointer for center coefficient in plane above * a_bc is pointer for center coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,0); MapIndex(index_temp, cdir, index); a_cc = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,0,0); MapIndex(index_temp, cdir, index); a_cw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); a_ce = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,0); MapIndex(index_temp, cdir, index); a_cs = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); a_cn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); a_ac = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 19-point fine grid operator: * * a_aw is pointer for west coefficient in plane above * a_ae is pointer for east coefficient in plane above * a_as is pointer for south coefficient in plane above * a_an is pointer for north coefficient in plane above * a_bw is pointer for west coefficient in plane below * a_be is pointer for east coefficient in plane below * a_bs is pointer for south coefficient in plane below * a_bn is pointer for north coefficient in plane below * a_csw is pointer for southwest coefficient in same plane * a_cse is pointer for southeast coefficient in same plane * a_cnw is pointer for northwest coefficient in same plane * a_cne is pointer for northeast coefficient in same plane *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); a_aw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); a_ae = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); a_as = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); a_an = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,0,-1); MapIndex(index_temp, cdir, index); a_be = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,0,1,-1); MapIndex(index_temp, cdir, index); a_bn = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,-1,0); MapIndex(index_temp, cdir, index); a_csw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,0); MapIndex(index_temp, cdir, index); a_cse = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); a_cnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); a_cne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point fine grid operator: * * a_asw is pointer for southwest coefficient in plane above * a_ase is pointer for southeast coefficient in plane above * a_anw is pointer for northwest coefficient in plane above * a_ane is pointer for northeast coefficient in plane above * a_bsw is pointer for southwest coefficient in plane below * a_bse is pointer for southeast coefficient in plane below * a_bnw is pointer for northwest coefficient in plane below * a_bne is pointer for northeast coefficient in plane below *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); a_asw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); a_ase = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); a_anw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); a_ane = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,-1,1,-1); MapIndex(index_temp, cdir, index); a_bnw = hypre_StructMatrixExtractPointerByIndex(A, fi, index); hypre_SetIndex3(index_temp,1,1,-1); MapIndex(index_temp, cdir, index); a_bne = hypre_StructMatrixExtractPointerByIndex(A, fi, index); /*----------------------------------------------------------------- * Extract pointers for 19-point coarse grid operator: * * We build only the upper triangular part (excluding diagonal). * * rap_ce is pointer for east coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); rap_ce = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); rap_cn = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); rap_ac = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,0,1); MapIndex(index_temp, cdir, index); rap_aw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,0,1); MapIndex(index_temp, cdir, index); rap_ae = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,-1,1); MapIndex(index_temp, cdir, index); rap_as = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,0,1,1); MapIndex(index_temp, cdir, index); rap_an = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,0); MapIndex(index_temp, cdir, index); rap_cnw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,0); MapIndex(index_temp, cdir, index); rap_cne = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Extract additional pointers for 27-point coarse grid operator: * * A 27-point coarse grid operator is produced when the fine grid * stencil is 19 or 27 point. * * We build only the upper triangular part. * * rap_cnw is pointer for northwest coefficient in same plane (etc.) *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,-1,-1,1); MapIndex(index_temp, cdir, index); rap_asw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,-1,1); MapIndex(index_temp, cdir, index); rap_ase = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,-1,1,1); MapIndex(index_temp, cdir, index); rap_anw = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); hypre_SetIndex3(index_temp,1,1,1); MapIndex(index_temp, cdir, index); rap_ane = hypre_StructMatrixExtractPointerByIndex(RAP, ci, index); /*----------------------------------------------------------------- * Define offsets for fine grid stencil and interpolation * * In the BoxLoop below I assume iA and iP refer to data associated * with the point which we are building the stencil for. The below * Offsets are used in refering to data associated with other points. *-----------------------------------------------------------------*/ hypre_SetIndex3(index_temp,0,0,1); MapIndex(index_temp, cdir, index); zOffsetA = 0; zOffsetP = 0; hypre_SetIndex3(index_temp,0,1,0); MapIndex(index_temp, cdir, index); yOffsetP = 0; hypre_SetIndex3(index_temp,1,0,0); MapIndex(index_temp, cdir, index); xOffsetP = 0; /*----------------------------------------------------------------- * Switch statement to direct control to apropriate BoxLoop depending * on stencil size. Default is full 27-point. *-----------------------------------------------------------------*/ /*-------------------------------------------------------------- * Loop for 27-point fine grid operator; produces upper triangular * part of 27-point coarse grid operator. stencil entries: * (above-northeast, above-north, above-northwest, above-east, * above-center, above-west, above-southeast, above-south, * above-southwest, center-northeast, center-north, * center-northwest, and center-east). *--------------------------------------------------------------*/ iP = 0; iR = 0; iA = 0; iAc = 0; iAm1 = iA - zOffsetA; iAp1 = iA + zOffsetA; iP1 = iP + zOffsetP + yOffsetP + xOffsetP; rap_ane[iAc] = ra[iR] * a_cne[iAp1] * pb[iP1] + ra[iR] * a_ane[iAp1] + a_ane[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP; rap_an[iAc] = ra[iR] * a_cn[iAp1] * pb[iP1] + ra[iR] * a_an[iAp1] + a_an[iA] * pb[iP1]; iP1 = iP + zOffsetP + yOffsetP - xOffsetP; rap_anw[iAc] = ra[iR] * a_cnw[iAp1] * pb[iP1] + ra[iR] * a_anw[iAp1] + a_anw[iA] * pb[iP1]; iP1 = iP + zOffsetP + xOffsetP; rap_ae[iAc] = ra[iR] * a_ce[iAp1] * pb[iP1] + ra[iR] * a_ae[iAp1] + a_ae[iA] * pb[iP1]; iP1 = iP + zOffsetP; rap_ac[iAc] = a_ac[iA] * pb[iP1] + ra[iR] * a_cc[iAp1] * pb[iP1] + ra[iR] * a_ac[iAp1]; iP1 = iP + zOffsetP - xOffsetP; rap_aw[iAc] = ra[iR] * a_cw[iAp1] * pb[iP1] + ra[iR] * a_aw[iAp1] + a_aw[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP + xOffsetP; rap_ase[iAc] = ra[iR] * a_cse[iAp1] * pb[iP1] + ra[iR] * a_ase[iAp1] + a_ase[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP; rap_as[iAc] = ra[iR] * a_cs[iAp1] * pb[iP1] + ra[iR] * a_as[iAp1] + a_as[iA] * pb[iP1]; iP1 = iP + zOffsetP - yOffsetP - xOffsetP; rap_asw[iAc] = ra[iR] * a_csw[iAp1] * pb[iP1] + ra[iR] * a_asw[iAp1] + a_asw[iA] * pb[iP1]; iP1 = iP + yOffsetP + xOffsetP; rap_cne[iAc] = a_cne[iA] + rb[iR] * a_cne[iAm1] * pb[iP1] + ra[iR] * a_cne[iAp1] * pa[iP1] + a_bne[iA] * pb[iP1] + a_ane[iA] * pa[iP1] + rb[iR] * a_ane[iAm1] + ra[iR] * a_bne[iAp1]; iP1 = iP + yOffsetP; rap_cn[iAc] = a_cn[iA] + rb[iR] * a_cn[iAm1] * pb[iP1] + ra[iR] * a_cn[iAp1] * pa[iP1] + a_bn[iA] * pb[iP1] + a_an[iA] * pa[iP1] + rb[iR] * a_an[iAm1] + ra[iR] * a_bn[iAp1]; iP1 = iP + yOffsetP - xOffsetP; rap_cnw[iAc] = a_cnw[iA] + rb[iR] * a_cnw[iAm1] * pb[iP1] + ra[iR] * a_cnw[iAp1] * pa[iP1] + a_bnw[iA] * pb[iP1] + a_anw[iA] * pa[iP1] + rb[iR] * a_anw[iAm1] + ra[iR] * a_bnw[iAp1]; iP1 = iP + xOffsetP; rap_ce[iAc] = a_ce[iA] + rb[iR] * a_ce[iAm1] * pb[iP1] + ra[iR] * a_ce[iAp1] * pa[iP1] + a_be[iA] * pb[iP1] + a_ae[iA] * pa[iP1] + rb[iR] * a_ae[iAm1] + ra[iR] * a_be[iAp1]; /* }*/ /* end ForBoxI */ return hypre_error_flag; }
Stencil_par4.c
#include <stdio.h> #include <stdlib.h> #include <sys/time.h> #include "malloc2D.h" #include "timer.h" int main(int argc, char *argv[]) { struct timespec tstart_cpu, tstop_cpu; double cpu_time; int imax=2002, jmax = 2002; int niter=1000, nburst=100; double** restrict x = malloc2D(jmax, imax); double** restrict xnew = malloc2D(jmax, imax); #pragma omp target enter data map(to:x[0:jmax][0:imax], xnew[0:jmax][0:imax]) #pragma omp target teams { #pragma omp distribute for (int j = 0; j < jmax; j++){ #pragma omp parallel for simd for (int i = 0; i < imax; i++){ xnew[j][i] = 0.0; x[j][i] = 5.0; } } #pragma omp distribute for (int j = jmax/2 - 5; j < jmax/2 + 5; j++){ #pragma omp parallel for simd for (int i = imax/2 - 5; i < imax/2 -1; i++){ x[j][i] = 400.0; } } } for (int iter = 0; iter < niter; iter+=nburst){ for (int ib = 0; ib < nburst; ib++){ cpu_timer_start(&tstart_cpu); #pragma omp target teams distribute for (int j = 1; j < jmax-1; j++){ #pragma omp parallel for simd for (int i = 1; i < imax-1; i++){ xnew[j][i] = ( x[j][i] + x[j][i-1] + x[j][i+1] + x[j-1][i] + x[j+1][i] )/5.0; } } #pragma omp target teams distribute for (int j = 0; j < jmax; j++){ #pragma omp parallel for simd for (int i = 0; i < imax; i++){ x[j][i] = xnew[j][i]; } } cpu_time += cpu_timer_stop(tstart_cpu); } printf("Iter %d\n",iter+nburst); } #pragma omp target exit data map(from:x[0:jmax][0:imax], xnew[0:jmax][0:imax]) free(x); free(xnew); printf("Timing is %lf\n",cpu_time); }
TRPO_Lightweight.c
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <sys/time.h> #include "omp.h" #include "TRPO.h" #include "lbfgs.h" double TRPO_Lightweight (TRPOparam param, const int NumIter, const size_t NumThreads) { //////////////////// Read Parameters //////////////////// // OpenMP Settings omp_set_num_threads(NumThreads); // Assign Parameters const size_t NumLayers = param.NumLayers; char * AcFunc = param.AcFunc; size_t * LayerSize = param.LayerSize; char * ModelFile = param.ModelFile; char * BaselineFile = param.BaselineFile; char * ResultFile = param.ResultFile; const double CG_Damping = param.CG_Damping; double ResidualTh = 1e-10; size_t MaxIter = 10; double MaxKL = 0.01; double MaxBackTracks = 10; double AcceptRatio = 0.1; double gamma = 0.995; double lam = 0.98; // Layer Size of Baseline size_t LayerSizeBase[4] = {16, 16, 16, 1}; // Dimension of Observation Space and Action Space const size_t ObservSpaceDim = LayerSize[0]; const size_t ActionSpaceDim = LayerSize[NumLayers-1]; // Number of Policy Parameters size_t NumParams = NumParamsCalc(param.LayerSize, param.NumLayers); size_t NumParamsBase = NumParamsCalc(LayerSizeBase, NumLayers) - 1; int PaddedParamsBase = (int)ceil((double)NumParamsBase/16.0)*16; // iterator when traversing through input vector and result vector size_t pos; // Number of Episodes per Batch const int NumEpBatch = 20; // Length of Each Episode - timestep_limit const int EpLen = 150; // Number of Samples size_t NumSamples = NumEpBatch * EpLen; // Length of Each TimeStep (s) const double TimeStepLen = 0.02; // Angular Speed = coeff * Activation double coeff = 1; // Random Seed srand(0); // pi - for Gaussian Random Number generation const double pi = 3.1415926535897931; //////////////////// Memory Allocation - Model //////////////////// // W[i]: Weight Matrix from Layer[i] to Layer[i+1] // B[i]: Bias Vector from Layer[i] to Layer[i+1] // Item (j,k) in W[i] refers to the weight from Neuron #j in Layer[i] to Neuron #k in Layer[i+1] // Item B[k] is the bias of Neuron #k in Layer[i+1] double * W [NumLayers-1]; double * B [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { W[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); B[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // LogStd[i] is the log of std[i] in the policy double * LogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Policy Gradient //////////////////// // The Policy Gradient Vector (PG) is the gradient of Surrogate Loss w.r.t. to policy parameters // -PG is the input to the Conjugate Gradient (CG) function // There is one-to-one correspondence between PG and policy parameters (W and B of neural network, LogStd) double * PGW [NumLayers-1]; double * PGB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { PGW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); PGB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // Allocate Memory for Policy Gradient corresponding to LogStd double * PGLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Simulation Data //////////////////// // Allocate Memory for Observation and Probability Mean // Observ: list of observations - corresponds to ob_no in modular_rl // Mean: list of probablity mean values - corresponds to the 'mean' part of prob_np in modular_rl // Remarks: due to the specific setting of the experienments in the TRPO paper, // Std is the same for all samples in each simulation iteration, // so we just allocate Std memory space for one sample and use it for all samples. // The general case should be another vector of Std with size NumSamples*ActionSpaceDim double * Observ = (double *) calloc(NumSamples*ObservSpaceDim, sizeof(double)); double * Mean = (double *) calloc(NumSamples*ActionSpaceDim, sizeof(double)); double * Std = (double *) calloc(ActionSpaceDim, sizeof(double)); double * Action = (double *) calloc(NumSamples*ActionSpaceDim, sizeof(double)); double * Reward = (double *) calloc(NumSamples, sizeof(double)); double * Return = (double *) calloc(NumSamples, sizeof(double)); double * Baseline = (double *) calloc(NumSamples, sizeof(double)); double * Advantage = (double *) calloc(NumSamples, sizeof(double)); //////////////////// Memory Allocation - Ordinary Forward and Backward Propagation //////////////////// // Layer[i] : Memory of each layer's outputs, i.e. y_i // GLayer[i]: Gradient of Loss Function w.r.t. the pre-activation values in Layer[i], i.e. d(Loss)/d(x_i) double * Layer [NumLayers]; double * GLayer [NumLayers]; for (size_t i=0; i<NumLayers; ++i) { Layer[i] = (double *) calloc(LayerSize[i], sizeof(double)); GLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); } // GW[i]: Gradient of Loss Function w.r.t to Neural Network Weight W[i] // GB[i]: Gradient of Loss Function w.r.t to Neural Network Bias B[i] // There is one-to-one correspondence between: GW[i] and W[i], GB[i] and B[i], GStd[i] and Std[i] double * GW [NumLayers-1]; double * GB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { GW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); GB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // GLogStd[i]: Gradient of Loss Function w.r.t LogStd[i] double * GLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Pearlmutter Forward and Backward Propagation //////////////////// // RyLayer[i]: R{} of each layer's outputs, i.e. R{y_i} // RxLayer[i]: R{} of each layer's pre-activated outputs, i.e. R{x_i} // RGLayer[I]: R{} Gradient of KL w.r.t. the pre-activation values in Layer[i], i.e. R{d(KL)/d(x_i)} double * RyLayer [NumLayers]; double * RxLayer [NumLayers]; double * RGLayer [NumLayers]; for (size_t i=0; i<NumLayers; ++i) { RyLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); RxLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); RGLayer[i] = (double *) calloc(LayerSize[i], sizeof(double)); } // RGW[i]: R{} Gradient of KL w.r.t. to Neural Network Weight W[i], i.e. R{d(KL)/d(W[i])} // RGB[i]: R{} Gradient of KL w.r.t. to Neural Network Bias B[i], i.e. R{d(KL)/d(B[i])} // There is one-to-one correspondence between: RGW[i] and W[i], RGB[i] and B[i] double * RGW [NumLayers-1]; double * RGB [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { RGW[i] = (double *) calloc(LayerSize[i]*LayerSize[i+1], sizeof(double)); RGB[i] = (double *) calloc(LayerSize[i+1], sizeof(double)); } // RGLogStd[i]: R{} Gradient of KL w.r.t LogStd[i] double * RGLogStd = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Memory Allocation - Conjugate Gradient (CG) //////////////////// // These names correspond to the names in the TRPO Python code double * b = (double *) calloc(NumParams, sizeof(double)); double * p = (double *) calloc(NumParams, sizeof(double)); double * r = (double *) calloc(NumParams, sizeof(double)); double * x = (double *) calloc(NumParams, sizeof(double)); double * z = (double *) calloc(NumParams, sizeof(double)); //////////////////// Memory Allocation - Line Search //////////////////// // These names correspond to the names in the TRPO Python code // Note: In Line Search we also need a vector called x // Here we just use the x declared for Conjugate Gradient for simlicity // The x used in Line Search has nothing to do with the x used in CG // They just have the same type and size double * fullstep = (double *) calloc(NumParams, sizeof(double)); double * theta = (double *) calloc(NumParams, sizeof(double)); double * xnew = (double *) calloc(NumParams, sizeof(double)); //////////////////// Memory Allocation - Baseline //////////////////// // WBase[i]: Weight Matrix from Layer[i] to Layer[i+1] // BBase[i]: Bias Vector from Layer[i] to Layer[i+1] // Item (j,k) in WBase[i] refers to the weight from Neuron #j in Layer[i] to Neuron #k in Layer[i+1] // Item BBase[k] is the bias of Neuron #k in Layer[i+1] double * WBase [NumLayers-1]; double * BBase [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { WBase[i] = (double *) calloc(LayerSizeBase[i]*LayerSizeBase[i+1], sizeof(double)); BBase[i] = (double *) calloc(LayerSizeBase[i+1], sizeof(double)); } // GW[i]: Gradient of Loss Function w.r.t to Neural Network Weight W[i] // GB[i]: Gradient of Loss Function w.r.t to Neural Network Bias B[i] // There is one-to-one correspondence between: GW[i] and W[i], GB[i] and B[i], GStd[i] and Std[i] double * GWBase [NumLayers-1]; double * GBBase [NumLayers-1]; for (size_t i=0; i<NumLayers-1; ++i) { GWBase[i] = (double *) calloc(LayerSizeBase[i]*LayerSizeBase[i+1], sizeof(double)); GBBase[i] = (double *) calloc(LayerSizeBase[i+1], sizeof(double)); } // Layer[i] : Memory of each layer's outputs, i.e. y_i // GLayer[i]: Gradient of Loss Function w.r.t. the pre-activation values in Layer[i], i.e. d(Loss)/d(x_i)s double * LayerBase [NumLayers]; double * GLayerBase [NumLayers]; for (size_t i=0; i<NumLayers; ++i) { LayerBase[i] = (double *) calloc(LayerSizeBase[i], sizeof(double)); GLayerBase[i] = (double *) calloc(LayerSizeBase[i], sizeof(double)); } // Pamameters Vector for L-BFGS Optimisation lbfgsfloatval_t * LBFGS_x = lbfgs_malloc(PaddedParamsBase); // Objection Function Value lbfgsfloatval_t LBFGS_fx; //////////////////// Memory Allocation - MuJoCo Simulation //////////////////// // Observation Vector and it Mean and Variance (for Filter) double * ob = (double *) calloc(ObservSpaceDim, sizeof(double)); double * obMean = (double *) calloc(ObservSpaceDim, sizeof(double)); double * obVar = (double *) calloc(ObservSpaceDim, sizeof(double)); // Action Vector (for MuJoCo) double * ac = (double *) calloc(ActionSpaceDim, sizeof(double)); //////////////////// Parameters for Baseline //////////////////// TRPOBaselineParam BaselineParam; // Paramaters BaselineParam.NumLayers = NumLayers; BaselineParam.ObservSpaceDim = ObservSpaceDim; BaselineParam.NumEpBatch = NumEpBatch; BaselineParam.EpLen = EpLen; BaselineParam.NumSamples = NumSamples; BaselineParam.NumParams = NumParamsBase; BaselineParam.PaddedParams = PaddedParamsBase; BaselineParam.LayerSizeBase = LayerSizeBase; BaselineParam.AcFunc = AcFunc; // For Forward Propagation and Back Propagation BaselineParam.WBase = WBase; BaselineParam.BBase = BBase; BaselineParam.LayerBase = LayerBase; BaselineParam.GWBase = GWBase; BaselineParam.GBBase = GBBase; BaselineParam.GLayerBase = GLayerBase; // Training Data BaselineParam.Observ = Observ; BaselineParam.Target = Return; // The prediction target BaselineParam.Predict = Baseline; // The prediction //////////////////// Initialisation - Neural Network //////////////////// // Note: Here we just initialise the Neural Network from a Datafile // which is the initialisation given by the Python ML Libraries. // We can also initialise the Neural Network ourselves // Open Model File that contains Weights, Bias and std FILE *ModelFilePointer = fopen(ModelFile, "r"); if (ModelFilePointer==NULL) { fprintf(stderr, "[ERROR] Cannot open Model File [%s]. \n", ModelFile); return -1; } // Read Weights and Bias from file for (size_t i=0; i<NumLayers-1; ++i) { // Reading Weights W[i]: from Layer[i] to Layer[i+1] size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { fscanf(ModelFilePointer, "%lf", &W[i][j*nextLayerDim+k]); } } // Reading Bias B[i]: from Layer[i] to Layer[i+1] for (size_t k=0; k<nextLayerDim; ++k) { fscanf(ModelFilePointer, "%lf", &B[i][k]); } } // Read LogStd from file for (size_t k=0; k<ActionSpaceDim; ++k) { fscanf(ModelFilePointer, "%lf", &LogStd[k]); } // Close Model File fclose(ModelFilePointer); //////////////////// Initialisation - Baseline //////////////////// // Note: Here we just initialise the Neural Network from a Datafile // which is the initialisation given by the Python ML Libraries. // We can also initialise the Neural Network ourselves // Open Model File that contains Weights, Bias and std FILE *BaselineFilePointer = fopen(BaselineFile, "r"); if (BaselineFilePointer==NULL) { fprintf(stderr, "[ERROR] Cannot open BaselineFile [%s]. \n", BaselineFile); return -1; } // Read Weights and Bias from file for (size_t i=0; i<NumLayers-1; ++i) { // Reading Weights W[i]: from Layer[i] to Layer[i+1] size_t curLayerDim = LayerSizeBase[i]; size_t nextLayerDim = LayerSizeBase[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { fscanf(BaselineFilePointer, "%lf", &WBase[i][j*nextLayerDim+k]); } } // Reading Bias B[i]: from Layer[i] to Layer[i+1] for (size_t k=0; k<nextLayerDim; ++k) { fscanf(BaselineFilePointer, "%lf", &BBase[i][k]); } } // Close Baseline Model File fclose(BaselineFilePointer); // L-BFGS Optimisation for Baseline Fitting lbfgs_parameter_t LBFGS_Param; lbfgs_parameter_init(&LBFGS_Param); LBFGS_Param.max_iterations = 25; //////////////////// Main Loop //////////////////// // Tic struct timeval tv1, tv2; gettimeofday(&tv1, NULL); // Run Training for NumIter Iterations for (int iter=0; iter<NumIter; ++iter) { // Run Training for several Episodes in each Iteration - can be parallelised for (int ep=0; ep<NumEpBatch; ++ep) { ///////// Reset Environment ///////// // Theta double theta_1 = 0; double theta_2 = -pi/2.0; double theta_3 = pi/2.0; // DOF1 - Fixed double DOF1_x = 0; double DOF1_y = 0; double DOF1_z = 0.01768; // DOF2 double DOF2_x = 0; double DOF2_y = 0; double DOF2_z = 0.07518; // Wrist double Wrist_x = 0.07375; double Wrist_y = 0; double Wrist_z = 0.07518; // Grip double Grip_x = 0.11315; double Grip_y = 0; double Grip_z = 0.06268; // Object - Random Position fixed for each Episode double Object_x = ((double)rand()/(double)RAND_MAX) * 0.076 + 0.084; double Object_y = ((double)rand()/(double)RAND_MAX) * 0.100 - 0.05; double Object_z = ((double)rand()/(double)RAND_MAX) * 0.100; ///////// Rollout Several Time Steps in Each Episode ///////// for(int timeStep=0; timeStep<EpLen; ++timeStep) { // Row Address of the Simulation Data int RowAddr = ep * EpLen + timeStep; // Get Raw Observation Vector: DOF1 DOF2 Wrist Grip Object ob[0] = DOF1_x; ob[1] = DOF1_y; ob[2] = DOF1_z; ob[3] = DOF2_x; ob[4] = DOF2_y; ob[5] = DOF2_z; ob[6] = Wrist_x; ob[7] = Wrist_y; ob[8] = Wrist_z; ob[9] = Grip_x; ob[10] = Grip_y; ob[11] = Grip_z; ob[12] = Object_x; ob[13] = Object_y; ob[14] = Object_z; // Save Data to Observation Matrix for (int i=0; i<ObservSpaceDim; ++i) Observ[RowAddr*ObservSpaceDim+i] = ob[i]; ///////// Forward Propagation ///////// // Assign Input Values for (size_t i=0; i<ObservSpaceDim; ++i) Layer[0][i] = ob[i]; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSize[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer Layer[i+1][j] = B[i][j]; for (size_t k=0; k<LayerSize[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*LayerSize[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {Layer[i+1][j] = tanh(Layer[i+1][j]); break;} // 0.1x Activation Function case 'o': {Layer[i+1][j] = 0.1*Layer[i+1][j]; break;} // sigmoid Activation Function case 's': {Layer[i+1][j] = 1.0/(1+exp(-Layer[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } // Save Data to Mean Matrix for (int i=0; i<ActionSpaceDim; ++i) Mean[RowAddr*ActionSpaceDim+i] = Layer[NumLayers-1][i]; // Save Data to Std Vector for (int i=0; i<ActionSpaceDim; ++i) Std[i] = exp(LogStd[i]); // Get Action from Mean - Sample from the distribution for (int i=0; i<ActionSpaceDim; ++i) { // Box-Muller double u1 = ((double)rand() + 1.0) / ((double)RAND_MAX + 1.0); double u2 = ((double)rand() + 1.0) / ((double)RAND_MAX + 1.0); double z0 = sqrt(-2.0 * log(u1)) * cos(2*pi*u2); //double z1 = sqrt(-2.0 * log(u1)) * sin(2*pi*u2); // N(mu, sigma^2) = N(0,1) * sigma + mu ac[i] = z0 * Std[i] + Layer[NumLayers-1][i]; } // Save Data to Action Matrix for (int i=0; i<ActionSpaceDim; ++i) Action[RowAddr*ActionSpaceDim+i] = ac[i]; ///////// Lightweight Simulator ///////// // Update Theta theta_1 += ac[0] * coeff * TimeStepLen; theta_2 += ac[1] * coeff * TimeStepLen; theta_3 += ac[2] * coeff * TimeStepLen; double s1 = sin(theta_1); double c1 = cos(theta_1); double s2 = sin(theta_2); double c2 = cos(theta_2); double s3 = sin(theta_3); double c3 = cos(theta_3); double c2c3 = c2 * c3; double s2s3 = s2 * s3; double c2s3 = c2 * s3; double s2c3 = s2 * c3; // DOF1 and Object positions are fixed // DOF2 DOF2_x = 0.0575 * c1 * c2; DOF2_y = 0.0575 * s1 * c2; DOF2_z = 0.01768 - 0.0575 * s2; // Wrist Wrist_x = DOF2_x + 0.07375 * c1 * (c2c3 - s2s3); Wrist_y = DOF2_y + 0.07375 * s1 * (c2c3 - s2s3); Wrist_z = DOF2_z - 0.07375 * (c2s3 + s2c3); // Grip Grip_x = DOF2_x + 0.11315 * c1 * (c2c3 - s2s3) - 0.0125 * c1 * (c2s3 + s2c3); Grip_y = DOF2_y + 0.11315 * s1 * (c2c3 - s2s3) - 0.0125 * s1 * (c2s3 + s2c3); Grip_z = DOF2_z - 0.11315 * (c2s3 + s2c3) + 0.0125 * (s2s3 - c2c3); // Get Position of the Grip and the Object double gripPos[3] = {Grip_x, Grip_y, Grip_z}; double objectPos[3] = {Object_x, Object_y, Object_z}; ///////// Calculating Reward ///////// // Reward Function TODO Modify Reward Function with -Eculidean Distance - Action Norm? double re = 0; for (int i=0; i<3; ++i) { re -= 100 * (objectPos[i] - gripPos[i]) * (objectPos[i] - gripPos[i]); re -= ac[i] * ac[i]; } // Save Reward to Reward Vector Reward[RowAddr] = re; } // End of Episode } // End of the Lightweight Simulation ///////// Calculate Reward Statistics ///////// double EpRewMean = 0; for (int i=0; i<NumSamples; ++i) EpRewMean += Reward[i]; EpRewMean = EpRewMean / (double) NumEpBatch; double EpRewStd = 0; for (int i=0; i<NumEpBatch; ++i){ double thisEpReward = 0; for (int j=0; j<EpLen; ++j) { thisEpReward += Reward[i*EpLen+j]; } EpRewStd += (thisEpReward-EpRewMean)*(thisEpReward-EpRewMean); } EpRewStd = sqrt(EpRewStd / (double) (NumEpBatch)); printf("[INFO] Iteration %d, Episode Rewards Mean = %f, Std = %f\n", iter, EpRewMean, EpRewStd); ///////// Calculate Advantage ///////// // Discount Reward to get Return for (int ep=0; ep<NumEpBatch; ++ep) { // Calculate Return for (int currentStep=0; currentStep<EpLen; ++currentStep) { // Reward in the current step pos = ep*EpLen + currentStep; double thisStepReturn = Reward[pos]; // Discounted future Reward for (int futureStep=currentStep+1; futureStep<EpLen; ++futureStep) { thisStepReturn += Reward[ep*EpLen+futureStep] * pow(gamma, futureStep-currentStep); } Return[pos] = thisStepReturn; } // Using Value Function to estimate return // For each step in each episode for (int currentStep=0; currentStep<EpLen; ++currentStep) { // Obsevation Vector and Normalised Time Step pos = ep*EpLen + currentStep; for (int i=0; i<ObservSpaceDim; ++i) { LayerBase[0][i] = Observ[pos*ObservSpaceDim+i]; } LayerBase[0][ObservSpaceDim] = (double) currentStep / (double) EpLen; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSizeBase[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer LayerBase[i+1][j] = BBase[i][j]; for (size_t k=0; k<LayerSizeBase[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] LayerBase[i+1][j] += LayerBase[i][k] * WBase[i][k*LayerSizeBase[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {LayerBase[i+1][j] = tanh(LayerBase[i+1][j]); break;} // sigmoid Activation Function case 's': {LayerBase[i+1][j] = 1.0/(1+exp(-LayerBase[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } // Write result to Baseline Baseline[pos] = LayerBase[NumLayers-1][0]; } // Using Reward to temporarily hold 'deltas' for (int currentStep=0; currentStep<EpLen-1; ++currentStep) { Reward[ep*EpLen+currentStep] += gamma * Baseline[ep*EpLen+currentStep+1] - Baseline[ep*EpLen+currentStep]; } Reward[ep*EpLen+EpLen-1] += (-1) * Baseline[ep*EpLen+EpLen-1]; // Calculate the Advantage of this episode for (int currentStep=0; currentStep<EpLen; ++currentStep) { pos = ep*EpLen + currentStep; double thisStepAdvantage = Reward[pos]; for (int futureStep=currentStep+1; futureStep<EpLen; ++futureStep) { thisStepAdvantage += Reward[ep*EpLen+futureStep] * pow(gamma*lam, futureStep-currentStep); } Advantage[pos] = thisStepAdvantage; } } // Standarise Advantage double AdvantageMean = 0; for (int i=0; i<NumSamples; ++i) AdvantageMean += Advantage[i]; AdvantageMean = AdvantageMean / (double) NumSamples; double AdvantageStd = 0; for (int i=0; i<NumSamples; ++i) AdvantageStd += (Advantage[i] - AdvantageMean)*(Advantage[i] - AdvantageMean); AdvantageStd = sqrt(AdvantageStd / (double) (NumSamples)); for (int i=0; i<NumSamples; ++i) Advantage[i] = (Advantage[i] - AdvantageMean) / AdvantageStd; ///////// Baseline Update ///////// TODO: Can be executed concurrently with TRPO Update // Write Weight and Bias of the Baseline to LBFGS_x pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSizeBase[i]; size_t nextLayerDim = LayerSizeBase[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { LBFGS_x[pos] = WBase[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { LBFGS_x[pos] = BBase[i][k]; pos++; } } // Run L-BFGS Algorithm to optimise the Baseline lbfgs(BaselineParam.PaddedParams, LBFGS_x, &LBFGS_fx, evaluate, NULL, &BaselineParam, &LBFGS_Param); // Update Baseline Weight and Bias from LBFGS_x pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSizeBase[i]; size_t nextLayerDim = LayerSizeBase[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { WBase[i][j*nextLayerDim+k] = LBFGS_x[pos]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { BBase[i][k] = LBFGS_x[pos]; pos++; } } //////////////////// TRPO Update //////////////////// ///////// Computing Policy Gradient ///////// // reset Policy Gradient to 0 for (size_t i=0; i<NumParams; ++i) b[i] = 0; // Processing all training samples for (size_t iter=0; iter<NumSamples; iter++) { ///////// Ordinary Forward Propagation ///////// // Assign Input Values for (size_t i=0; i<ObservSpaceDim; ++i) Layer[0][i] = Observ[iter*ObservSpaceDim+i]; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSize[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer Layer[i+1][j] = B[i][j]; for (size_t k=0; k<LayerSize[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*LayerSize[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {Layer[i+1][j] = tanh(Layer[i+1][j]); break;} // 0.1x Activation Function case 'o': {Layer[i+1][j] = 0.1*Layer[i+1][j]; break;} // sigmoid Activation Function case 's': {Layer[i+1][j] = 1.0/(1+exp(-Layer[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } ///////// Ordinary Backward Propagation ///////// // Gradient Initialisation // Assign the derivative of Surrogate Loss w.r.t. Mean (output values from the final layer) and LogStd for (size_t i=0; i<ActionSpaceDim; ++i) { double temp = (Action[iter*ActionSpaceDim+i] - Mean[iter*ActionSpaceDim+i]) / exp(LogStd[i]); GLayer[NumLayers-1][i] = Advantage[iter] * temp / exp(LogStd[i]); GLogStd[i] = Advantage[iter] * (temp * temp - 1); } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { // Propagate from Layer[i] to Layer[i-1] for (size_t j=0; j<LayerSize[i]; ++j) { // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {GLayer[i][j] = GLayer[i][j] * (1- Layer[i][j] * Layer[i][j]); break;} // 0.1x Activation Function case 'o': {GLayer[i][j] = 0.1 * GLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {GLayer[i][j] = GLayer[i][j] * Layer[i][j] * (1- Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] Activation Function for Layer[%zu] is %c. Unsupported.\n", i, AcFunc[i]); return -1; } } // The derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value GB[i-1][j] = GLayer[i][j]; } // Calculate the derivative w.r.t. to Weight for (size_t j=0; j<LayerSize[i-1]; ++j) { for (size_t k=0; k<LayerSize[i]; ++k) { // The Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] GW[i-1][j*LayerSize[i]+k] = GLayer[i][k] * Layer[i-1][j]; } } // Calculate the derivative w.r.t. the output values from Layer[i] for (size_t j=0; j<LayerSize[i-1]; ++j) { GLayer[i-1][j] = 0; for (size_t k=0; k<LayerSize[i]; ++k) { // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] GLayer[i-1][j] += GLayer[i][k] * W[i-1][j*LayerSize[i]+k]; } } } // Accumulate the Policy Gradient to b pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { b[pos] += GW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { b[pos] += GB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { b[pos] += GLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Policy Gradient over the samples - Policy Gradient is held in b // Note this corresponds to -g in the Python code: b = -g #pragma omp parallel for for (size_t i=0; i<pos; ++i) { b[i] = b[i] / (double)NumSamples; } //////////////////// Computing Search Direction //////////////////// ///////// Conjugate Gradient ///////// // This function implements Conjugate Gradient algorithm to solve linear equation Ax=b // x: The Conjugate Gradient Result, i.e. solution x to Ax=b // In TRPO context, x is the Step Direction of the line search (stepdir in the Python code) // b: Vector b in the equation Ax=b // Initialisation double rdotr = 0; for (size_t i=0; i<NumParams; ++i) { x[i] = 0; p[i] = b[i]; r[i] = b[i]; rdotr += r[i] * r[i]; } // Iterative Solver for (size_t it=0; it<=MaxIter; ++it) { // Calculate Frobenius Norm of x double FrobNorm = 0; #pragma omp parallel for reduction (+:FrobNorm) for (size_t i=0; i<NumParams; ++i) { FrobNorm += x[i] * x[i]; } FrobNorm = sqrt(FrobNorm); printf("CG Iter[%zu] Residual Norm=%.12e, Soln Norm=%.12e\n", it, rdotr, FrobNorm); // Check Termination Condition if (rdotr<ResidualTh || it==MaxIter) { for (size_t i=0; i<NumParams; ++i) z[i] = x[i]; break; } ///////// Fisher Vector Product Computation z = FVP(p) ///////// // Init PGW, PGB, PGLogStd from p // Init z to 0 pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { PGW[i][j*nextLayerDim+k] = p[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { PGB[i][k] = p[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { PGLogStd[k] = p[pos]; z[pos] = 0; pos++; } for (size_t iter=0; iter<NumSamples; iter++) { ///////// Combined Forward Propagation ///////// // Initialise the Input Layer for (size_t i=0; i<ObservSpaceDim; ++i) { Layer[0][i] = Observ[iter*ObservSpaceDim+i]; RxLayer[0][i] = 0; RyLayer[0][i] = 0; } // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { size_t CurrLayerSize = LayerSize[i]; size_t NextLayerSize = LayerSize[i+1]; size_t j, k; // Propagate from Layer[i] to Layer[i+1] #pragma omp parallel for private(j,k) shared(Layer, RxLayer, RyLayer, W, PGW, B, PGB, AcFunc) schedule(static) for (j=0; j<NextLayerSize; ++j) { // Initialise x_j and R{x_j} in next layer // Here we just use y_j's memory space to store x_j temoporarily Layer[i+1][j] = B[i][j]; RxLayer[i+1][j] = PGB[i][j]; for (k=0; k<CurrLayerSize; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += RyLayer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += Layer[i][k] * PGW[i][k*NextLayerSize+j]; } // Calculate y_j and R{y_j} in next layer. Note that R{y_j} depends on y_j switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': { RyLayer[i+1][j] = RxLayer[i+1][j]; break; } // tanh() Activation Function case 't': { Layer[i+1][j] = tanh(Layer[i+1][j]); RyLayer[i+1][j] = RxLayer[i+1][j] * (1 - Layer[i+1][j] * Layer[i+1][j]); break; } // sigmoid Activation Function case 's': { Layer[i+1][j] = 1.0 / ( 1 + exp(-Layer[i+1][j]) ); RyLayer[i+1][j] = RxLayer[i+1][j] * Layer[i+1][j] * (1 - Layer[i+1][j]); break; } // Default: Activation Function not supported default: { printf("[ERROR] AC Function for Layer[%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); } } } } ///////// Pearlmutter Backward Propagation ///////// // Gradient Initialisation // Calculating R{} Gradient of KL w.r.t. output values from the final layer, i.e. R{d(KL)/d(mean_i)} for (size_t i=0; i<ActionSpaceDim; ++i) { RGLayer[NumLayers-1][i] = RyLayer[NumLayers-1][i] / Std[i] / Std[i]; } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { size_t CurrLayerSize = LayerSize[i]; size_t PrevLayerSize = LayerSize[i-1]; size_t j, k; // Propagate from Layer[i] to Layer[i-1] #pragma omp parallel for private(j) shared(Layer, RGLayer, RGB) schedule(static) for (j=0; j<CurrLayerSize; ++j) { // Calculating R{} Gradient of KL w.r.t. pre-activated values in Layer[i], i.e. R{d(KL)/d(x_i)} // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {RGLayer[i][j] = (1-Layer[i][j]*Layer[i][j])*RGLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {RGLayer[i][j] = RGLayer[i][j]*Layer[i][j]*(1-Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] AC Function for Layer [%zu] is %c. Unsupported.\n", i, AcFunc[i]); } } // The R{} derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value RGB[i-1][j] = RGLayer[i][j]; } // Calculate the R{} derivative w.r.t. to Weight and the output values from Layer[i] #pragma omp parallel for private(j,k) shared(Layer, RGLayer, W, RGW) schedule(static) for (j=0; j<PrevLayerSize; ++j) { double temp = 0; for (k=0; k<CurrLayerSize; ++k) { // The R{} Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] RGW[i-1][j*CurrLayerSize+k] = Layer[i-1][j] * RGLayer[i][k]; // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] temp += W[i-1][j*CurrLayerSize+k] * RGLayer[i][k]; } RGLayer[i-1][j] = temp; } } // Accumulate the Fisher-Vector Product to z pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { z[pos] += 2 * PGLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Fisher Vector Product over the samples and apply CG Damping #pragma omp parallel for for (size_t i=0; i<pos; ++i) { z[i] = z[i] / (double)NumSamples + CG_Damping * p[i]; } //////////////// FVP Finish // Update x and r double pdotz = 0; #pragma omp parallel for reduction (+:pdotz) for (size_t i=0; i<NumParams; ++i) { pdotz += p[i] * z[i]; } double v = rdotr / pdotz; #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { x[i] += v * p[i]; r[i] -= v * z[i]; } // Update p double newrdotr = 0; #pragma omp parallel for reduction (+:newrdotr) for (size_t i=0; i<NumParams; ++i) { newrdotr += r[i] * r[i]; } double mu = newrdotr / rdotr; #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { p[i] = r[i] + mu * p[i]; } // Update rdotr rdotr = newrdotr; } // Calculate another Fisher Vector Product - code reuse opportunity ///////// Fisher Vector Product Computation z = FVP(x) ///////// // Init PGW, PGB, PGLogStd from x // Init z to 0 pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { PGW[i][j*nextLayerDim+k] = x[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { PGB[i][k] = x[pos]; z[pos] = 0; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { PGLogStd[k] = x[pos]; z[pos] = 0; pos++; } for (size_t iter=0; iter<NumSamples; iter++) { ///////// Combined Forward Propagation ///////// // Initialise the Input Layer for (size_t i=0; i<ObservSpaceDim; ++i) { Layer[0][i] = Observ[iter*ObservSpaceDim+i]; RxLayer[0][i] = 0; RyLayer[0][i] = 0; } // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { size_t CurrLayerSize = LayerSize[i]; size_t NextLayerSize = LayerSize[i+1]; size_t j, k; // Propagate from Layer[i] to Layer[i+1] #pragma omp parallel for private(j,k) shared(Layer, RxLayer, RyLayer, W, PGW, B, PGB, AcFunc) schedule(static) for (j=0; j<NextLayerSize; ++j) { // Initialise x_j and R{x_j} in next layer // Here we just use y_j's memory space to store x_j temoporarily Layer[i+1][j] = B[i][j]; RxLayer[i+1][j] = PGB[i][j]; for (k=0; k<CurrLayerSize; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += RyLayer[i][k] * W[i][k*NextLayerSize+j]; RxLayer[i+1][j] += Layer[i][k] * PGW[i][k*NextLayerSize+j]; } // Calculate y_j and R{y_j} in next layer. Note that R{y_j} depends on y_j switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': { RyLayer[i+1][j] = RxLayer[i+1][j]; break; } // tanh() Activation Function case 't': { Layer[i+1][j] = tanh(Layer[i+1][j]); RyLayer[i+1][j] = RxLayer[i+1][j] * (1 - Layer[i+1][j] * Layer[i+1][j]); break; } // sigmoid Activation Function case 's': { Layer[i+1][j] = 1.0 / ( 1 + exp(-Layer[i+1][j]) ); RyLayer[i+1][j] = RxLayer[i+1][j] * Layer[i+1][j] * (1 - Layer[i+1][j]); break; } // Default: Activation Function not supported default: { printf("[ERROR] AC Function for Layer[%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); } } } } ///////// Pearlmutter Backward Propagation ///////// // Gradient Initialisation // Calculating R{} Gradient of KL w.r.t. output values from the final layer, i.e. R{d(KL)/d(mean_i)} for (size_t i=0; i<ActionSpaceDim; ++i) { RGLayer[NumLayers-1][i] = RyLayer[NumLayers-1][i] / Std[i] / Std[i]; } // Backward Propagation for (size_t i=NumLayers-1; i>0; --i) { size_t CurrLayerSize = LayerSize[i]; size_t PrevLayerSize = LayerSize[i-1]; size_t j, k; // Propagate from Layer[i] to Layer[i-1] #pragma omp parallel for private(j) shared(Layer, RGLayer, RGB) schedule(static) for (j=0; j<CurrLayerSize; ++j) { // Calculating R{} Gradient of KL w.r.t. pre-activated values in Layer[i], i.e. R{d(KL)/d(x_i)} // Differentiate the activation function switch (AcFunc[i]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function: tanh' = 1 - tanh^2 case 't': {RGLayer[i][j] = (1-Layer[i][j]*Layer[i][j])*RGLayer[i][j]; break;} // sigmoid Activation Function: sigmoid' = sigmoid * (1 - sigmoid) case 's': {RGLayer[i][j] = RGLayer[i][j]*Layer[i][j]*(1-Layer[i][j]); break;} // Default: Activation Function not supported default: { fprintf(stderr, "[ERROR] AC Function for Layer [%zu] is %c. Unsupported.\n", i, AcFunc[i]); } } // The R{} derivative w.r.t to Bias is the same as that w.r.t. the pre-activated value RGB[i-1][j] = RGLayer[i][j]; } // Calculate the R{} derivative w.r.t. to Weight and the output values from Layer[i] #pragma omp parallel for private(j,k) shared(Layer, RGLayer, W, RGW) schedule(static) for (j=0; j<PrevLayerSize; ++j) { double temp = 0; for (k=0; k<CurrLayerSize; ++k) { // The R{} Derivative w.r.t. to the weight from Neuron #j in Layer[i-1] to Neuron #k in Layer[i] RGW[i-1][j*CurrLayerSize+k] = Layer[i-1][j] * RGLayer[i][k]; // Accumulate the Gradient from Neuron #k in Layer[i] to Neuron #j in Layer[i-1] temp += W[i-1][j*CurrLayerSize+k] * RGLayer[i][k]; } RGLayer[i-1][j] = temp; } } // Accumulate the Fisher-Vector Product to z pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGW[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { z[pos] += RGB[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { z[pos] += 2 * PGLogStd[k]; pos++; } } // End of iteration over current sample // Averaging Fisher Vector Product over the samples and apply CG Damping #pragma omp parallel for for (size_t i=0; i<pos; ++i) { z[i] = z[i] / (double)NumSamples + CG_Damping * x[i]; } // Now z holds the Fisher Vector Product, x holds stepdir double shs = 0; #pragma omp parallel for reduction (+:shs) for (size_t i=0; i<NumParams; ++i) { shs += z[i] * x[i]; } shs = shs * 0.5; printf("shs: %.14f\n", shs); // Lagrange Multiplier (lm in Python code) double lm = sqrt(shs / MaxKL); // Compute the 2-norm of the Policy Gradient double gnorm = 0; for (size_t i=0; i<NumParams; ++i) { gnorm += b[i] * b[i]; } gnorm = sqrt(gnorm); printf("lagrange multiplier: %.14f, gnorm: %.14f\n", lm, gnorm); // Full Step #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { fullstep[i] = x[i] / lm; } // Inner product of Negative Policy Gradient -g and Step Direction double neggdotstepdir = 0; #pragma omp parallel for reduction (+:neggdotstepdir) for (size_t i=0; i<NumParams; ++i) { neggdotstepdir += b[i] * x[i]; } //////////////////// Line Search //////////////////// // Init theta to x // If Line Search is unsuccessful, theta remains as x for (size_t i=0; i<NumParams; ++i) theta[i] = x[i]; // Expected Improve Rate Line Search = slope dy/dx at initial point double expected_improve_rate = neggdotstepdir / lm; // Temporarily Save the Model Parameters in x // The x refers to the x in linesearch function in Python code // Note: Although the name is the same, the x here has nothing to do with the x in Conjugate Gradient // Copy the Model Parameters to x pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { x[pos] = W[i][j*nextLayerDim+k]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { x[pos] = B[i][k]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { x[pos] = LogStd[k]; pos++; } // Surrogate Loss of the current Model parameters = -Avg(Advantage) double fval = 0; #pragma omp parallel for reduction (+:fval) for (size_t i=0; i<NumSamples; ++i) { fval += Advantage[i]; } fval = -fval / (double) NumSamples; printf("fval before %.14e\n", fval); // Backtracking Line Search for (size_t i=0; i<MaxBackTracks; ++i) { // Step Fraction double stepfrac = pow(0.5, (double)i); // x New #pragma omp parallel for for (size_t i=0; i<NumParams; ++i) { xnew[i] = x[i] + stepfrac * fullstep[i]; } ///////// Compute Surrogate Loss ///////// // Init W, B, LogStd from xnew pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { W[i][j*nextLayerDim+k] = xnew[pos]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { B[i][k] = xnew[pos]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { LogStd[k] = xnew[pos]; pos++; } // Init Surrogate Loss to 0 double surr = 0; for (size_t iter=0; iter<NumSamples; iter++) { ///////// Ordinary Forward Propagation ///////// // Assign Input Values for (size_t i=0; i<ObservSpaceDim; ++i) Layer[0][i] = Observ[iter*ObservSpaceDim+i]; // Forward Propagation for (size_t i=0; i<NumLayers-1; ++i) { // Propagate from Layer[i] to Layer[i+1] for (size_t j=0; j<LayerSize[i+1]; ++j) { // Calculating pre-activated value for item[j] in next layer Layer[i+1][j] = B[i][j]; for (size_t k=0; k<LayerSize[i]; ++k) { // From Neuron #k in Layer[i] to Neuron #j in Layer[i+1] Layer[i+1][j] += Layer[i][k] * W[i][k*LayerSize[i+1]+j]; } // Apply Activation Function switch (AcFunc[i+1]) { // Linear Activation Function: Ac(x) = (x) case 'l': {break;} // tanh() Activation Function case 't': {Layer[i+1][j] = tanh(Layer[i+1][j]); break;} // sigmoid Activation Function case 's': {Layer[i+1][j] = 1.0/(1+exp(-Layer[i+1][j])); break;} // Default: Activation Function not supported default: { printf("[ERROR] Activation Function for Layer [%zu] is %c. Unsupported.\n", i+1, AcFunc[i+1]); return -1; } } } } // Surrogate Loss Calculation // LoglikelihoodDifference = logp_i - oldlogp_i // Here, logp_i is derived from xnew, oldlogp_i is derived from x (Mean in the simulation data) double LoglikelihoodDifference = 0; for (size_t i=0; i<ActionSpaceDim; ++i) { double temp_x = (Action[iter*ActionSpaceDim+i] - Mean[iter*ActionSpaceDim+i]) / Std[i]; double temp_xnew = (Action[iter*ActionSpaceDim+i] - Layer[NumLayers-1][i]) / exp(LogStd[i]); LoglikelihoodDifference += temp_x*temp_x - temp_xnew*temp_xnew + log(Std[i]) - LogStd[i]; } LoglikelihoodDifference = LoglikelihoodDifference * 0.5; // Accumulate Surrogate Loss surr += exp(LoglikelihoodDifference) * Advantage[iter]; } // Average Surrogate Loss over the samples to get newfval double newfval = -surr / (double) NumSamples; // Improvement in terms of Surrogate Loss double actual_improve = fval - newfval; // Expected Improvement double expected_improve = expected_improve_rate * stepfrac; // Improvement Ratio double ratio = actual_improve / expected_improve; printf("a/e/r %.14f / %.14f / %.14f\n", actual_improve, expected_improve, ratio); // Check breaking condition - has Line Search succeeded? if ( (ratio > AcceptRatio) && (actual_improve > 0) ) { // If Line Search is successful, update parameters and quit for (size_t i=0; i<NumParams; ++i) theta[i] = xnew[i]; break; } } // End of Line Search // Update Model from theta pos = 0; for (size_t i=0; i<NumLayers-1; ++i) { size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { W[i][j*nextLayerDim+k] = theta[pos]; pos++; } } for (size_t k=0; k<nextLayerDim; ++k) { B[i][k] = theta[pos]; pos++; } } for (size_t k=0; k<ActionSpaceDim; ++k) { LogStd[k] = theta[pos]; pos++; } //////////////////// Save Training Result //////////////////// // Save training result EVERY 100 Iteration as well as in the Last Iteration if(iter%100==0 || iter==(NumIter-1)) { // Generate Result File Name char ResultFileName[30]; strcpy(ResultFileName, ResultFile); char suffix[10]; sprintf(suffix, "%03d.txt", iter); strcat(ResultFileName, suffix); // Open Result File to write Weights, Bias and LogStd FILE *ResultFilePointer = fopen(ResultFileName, "w"); if (ResultFilePointer==NULL) { fprintf(stderr, "[ERROR] Cannot open Result File [%s]. \n", ResultFileName); return -1; } // Write Weights and Bias to file for (size_t i=0; i<NumLayers-1; ++i) { // Weights W[i]: from Layer[i] to Layer[i+1] size_t curLayerDim = LayerSize[i]; size_t nextLayerDim = LayerSize[i+1]; for (size_t j=0; j<curLayerDim;++j) { for (size_t k=0; k<nextLayerDim; ++k) { fprintf(ResultFilePointer, "%.14f\n", W[i][j*nextLayerDim+k]); } } // Bias B[i]: from Layer[i] to Layer[i+1] for (size_t k=0; k<nextLayerDim; ++k) { fprintf(ResultFilePointer, "%.14f\n", B[i][k]); } } // LogStd for (size_t k=0; k<ActionSpaceDim; ++k) { fprintf(ResultFilePointer, "%.14f\n", LogStd[k]); } // Close Result File fclose(ResultFilePointer); } } // Training Finished // Toc gettimeofday(&tv2, NULL); double runtimeS = ((tv2.tv_sec-tv1.tv_sec) * (double)1E6 + (tv2.tv_usec-tv1.tv_usec)) / (double)1E6; //////////////////// Clean Up //////////////////// // Clean-Up L-BFGS lbfgs_free(LBFGS_x); // Model: Weight & Bias, Gradient of Weight & Bias, Policy Gradient of Weight & Bias, R{} Gradient of Weight & Bias for (size_t i=0; i<NumLayers-1; ++i) { free(W[i]); free(B[i]); free(GW[i]); free(GB[i]); free(PGW[i]); free(PGB[i]); free(RGW[i]); free(RGB[i]); } // Model: LogStd, Gradient of LogStd, Policy Gradient of LogStd, R{} Gradient of LogStd free(LogStd); free(GLogStd); free(PGLogStd); free(RGLogStd); // Baseline: Weight & Bias, Gradient of Weight & Bias for (size_t i=0; i<NumLayers-1; ++i) { free(WBase[i]); free(BBase[i]); free(GWBase[i]); free(GBBase[i]); } // Forward and Backward Propagation for (size_t i=0; i<NumLayers; ++i) { // Model: Ordinary Forward and Backward Propagation free(Layer[i]); free(GLayer[i]); // Model: Pearlmutter Forward and Backward Propagation free(RxLayer[i]); free(RyLayer[i]); free(RGLayer[i]); // Baseline: Ordinary Forward and Backward Propagation free(LayerBase[i]); free(GLayerBase[i]); } // Conjugate Gradient free(b); free(p); free(r); free(x); free(z); // Line Search free(fullstep); free(xnew); free(theta); // MuJoCo: Observation, Action and Observation Filtering free(ob); free(ac); free(obMean); free(obVar); // Simulation Data and Advantage Calculation free(Observ); free(Mean); free(Std); free(Action); free(Reward); free(Return); free(Baseline); free(Advantage); return runtimeS; }